App icon indicating copy to clipboard operation
App copied to clipboard

[$175] Workflows- Page loads endlessly when open workflows/approvals/new in Dew Workspace

Open applause-bot[bot] opened this issue 2 weeks ago • 25 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?: Yes Reproducible in production?: Yes If this was caught during regression testing, add the test name, ID and link from BrowserStack: https://github.com/Expensify/App/pull/104490 Email or phone of affected tester (no customers): [email protected] Issue reported by: Applause Internal Team Bug source: Pull Request QA execution Device used: Windows 11 Chrome App Component: Workspace Settings

Action Performed:

Preconditions: Use [email protected] and PR53494 workspace - This account and workspace is Dew and Hide people is off

  1. Open https://staging.new.expensify.com/
  2. Go to Dew workpaces
  3. Go to Workflows
  4. Open the URL with ending /workflows/approvals/new
  5. If crashed, reload the page

Expected Result:

Create new approval form should be displayed

Actual Result:

Page crashes first, if reloads the page load endlessly

Workaround:

Unknown

Platforms:

  • [x] Android: App
  • [ ] Android: mWeb Chrome
  • [x] iOS: App
  • [ ] iOS: mWeb Safari
  • [ ] iOS: mWeb Chrome
  • [x] Windows: Chrome
  • [ ] MacOS: Chrome Safari

Screenshots/Videos

https://github.com/user-attachments/assets/dee677fe-6a19-45c6-ad15-b22f991524f6

Bug7313093_1794565447740!staging.new.expensify.com-1794564940057.txt

View all open jobs on GitHub

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

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

applause-bot[bot] avatar Nov 13 '26 15:11 applause-bot[bot]

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

https://platform.applause.com/services/links/v1/external/a73eed977aae9b325a489619074f800ebaad83ffbdee355d4b5e76404a551e69

applause-bot[bot] avatar Nov 13 '26 15:11 applause-bot[bot]

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

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

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

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

Proposal

What is the root cause of that problem?

Medium confidence for the endless loading; the initial crash remains unconfirmed.

Opening /workflows/approvals/new directly bypasses the approval wizard’s draft initialization. When no draft exists, the create screen displays a spinner but never initializes the missing state, so loading cannot finish. This path is accessible on DEW workspaces when Hide people is off.

Supporting evidence and limitations

Limitation: The attachment contains neither the original fatal exception nor the draft’s contents. An absent draft explains the spinner, not the preceding crash. No browser reproduction was performed.

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

For the missing-draft loading defect, initialize a complete creation draft on direct entry after state hydration and access checks. Derive the available members and used approvers as normal creation does, and preserve any existing in-progress draft.

Use isInitialFlow: false for this fallback, matching the existing direct-create entry from WorkspaceMemberDetailsPage.tsx:260–279.

Add regression coverage for direct entry and reload without a draft, existing-draft preservation, and DEW with Hide people both off and on.

Before claiming the entire issue resolved: capture the original exception stack and pre-crash draft shape.

What alternative solutions did you explore? (Optional)

Redirecting to the approval wizard would avoid the spinner, but would not meet the stated expectation of displaying the creation form.

Related issue: Editing approval workflows on DEW workspaces optimistically drops Dynamic External mode concerns save-time state updates, not this route-entry initialization defect.


Next Steps for Contributor+ team: To accept: @MelvinBot implement [this](https://github.com/Expensify/App/issues/106869) 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 15:11 MelvinBot

Proposal

What is the root cause of that problem?

There are two interrelated root causes explaining both the initial crash and the subsequent endless loading on reload:

  1. The Endless Loading Spinner on Direct Entry / Reload:

    • When a user directly opens or reloads workspaces/:policyID/workflows/approvals/new (ROUTES.ts:1820), the route renders WorkspaceWorkflowsApprovalsCreatePage.tsx (WorkspaceWorkflowsApprovalsCreatePage.tsx:44).
    • In DEW workspaces where dynamicExternalWorkflowHidePeople is false ("Hide people is off"), shouldHideDynamicExternalWorkflowPeople(policy) returns false (workflows.ts:82–84), so the page bypasses FullPageNotFoundView.
    • However, WorkspaceWorkflowsApprovalsCreatePage expects an existing approvalWorkflow draft in Onyx (ONYXKEYS.APPROVAL_WORKFLOW). In normal wizard flows, this draft is seeded by predecessor screens (WorkflowsApprovalsTab.tsx:184 or WorkspaceMemberDetailsPage.tsx:263).
    • On direct URL entry or browser reload, approvalWorkflow is null/undefined. Lines 133–137 of WorkspaceWorkflowsApprovalsCreatePage.tsx:
      {!approvalWorkflow && (
          <View style={[styles.flex1, styles.fullScreenLoading]}>
              <ActivityIndicator size={CONST.ACTIVITY_INDICATOR_SIZE.LARGE} />
          </View>
      )}
      
      Because the component does not initialize a missing draft or fetch it from an API, it stays on the full-screen loading spinner indefinitely.
  2. The Preceding Crash:

    • In ApprovalWorkflowEditor.tsx (ApprovalWorkflowEditor.tsx:56, 95, 207), the component assumes approvalWorkflow.approvers and approvalWorkflow.members are always defined arrays:
      • Line 56: const approverCount = approvalWorkflow.approvers.length;
      • Line 95: sortAlphabetically(approvalWorkflow.members, ...)
      • Line 207: approvalWorkflow.approvers.map(...)
    • If an interrupted or partial draft exists in Onyx without these keys, direct navigation triggers an unhandled TypeError: Cannot read properties of undefined (reading 'length').

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

  1. Auto-initialize Fallback Creation Draft on Direct Entry in WorkspaceWorkflowsApprovalsCreatePage.tsx: Import useApprovalWorkflows and INITIAL_APPROVAL_WORKFLOW:

    import useApprovalWorkflows from '@hooks/useApprovalWorkflows';
    import {INITIAL_APPROVAL_WORKFLOW} from '@libs/WorkflowUtils';
    import {clearApprovalWorkflow, setApprovalWorkflow} from '@userActions/Workflow';
    

    Derive availableMembers and usedApproverEmails using useApprovalWorkflows(policy), and add a useEffect that initializes the draft once policy is loaded and access checks pass:

    const {availableMembers, usedApproverEmails} = useApprovalWorkflows(policy);
    
    useEffect(() => {
        if (approvalWorkflow || !policy || isLoadingReportData || shouldShowNotFoundView) {
            return;
        }
    
        setApprovalWorkflow({
            ...INITIAL_APPROVAL_WORKFLOW,
            isInitialFlow: false,
            availableMembers,
            usedApproverEmails,
        });
    }, [approvalWorkflow, policy, isLoadingReportData, shouldShowNotFoundView, availableMembers, usedApproverEmails]);
    

    This matches the direct-create entry pattern in WorkspaceMemberDetailsPage.tsx:263–269, allowing the create screen to immediately render ApprovalWorkflowEditor on direct entry or reload.

  2. Clean Up Creation Draft on Flow Exit: In WorkspaceWorkflowsApprovalsCreatePage.tsx, clear the draft when unmounting if the creation was not completed or saved, preventing stale drafts from lingering in Onyx:

    useEffect(() => {
        return () => {
            clearApprovalWorkflow();
        };
    }, []);
    
  3. Defensive Guarding in ApprovalWorkflowEditor.tsx: In src/pages/workspace/workflows/approvals/ApprovalWorkflowEditor.tsx, safeguard against undefined arrays:

    const approvers = approvalWorkflow.approvers ?? [];
    const approverCount = approvers.length;
    const sortedMembers = approvalWorkflow.isDefault ? [] : sortAlphabetically(approvalWorkflow.members ?? [], 'displayName', localeCompare);
    

    And iterate over approvers.map on line 207. This eliminates any possible crash if a draft is partially formed.


What alternative solutions did you explore? (Optional)

  1. Redirecting to DYNAMIC_ROUTES.WORKSPACE_WORKFLOWS_APPROVALS_EXPENSES_FROM when approvalWorkflow is missing: Discarded because users or deep links specifically targeting /workflows/approvals/new expect to land on the approval creation screen (just as WorkspaceMemberDetailsPage navigates directly to /new). Redirecting breaks direct navigation and reloading.
  2. Showing an error or not-found view when approvalWorkflow is absent: Discarded because /workflows/approvals/new is a valid, shareable workspace route, and showing an error on browser reload provides poor UX. Auto-initializing the draft is consistent with WorkspaceWorkflowsApprovalsEditPage.tsx:218–220.

Contributor details

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

kevinjosh10 avatar Nov 13 '26 16:11 kevinjosh10

Proposal

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

On a Dynamic External Workflow (DEW) workspace with Hide people turned off (dynamicExternalWorkflowHidePeople: false), opening /workspaces/<policyID>/workflows/approvals/new directly via URL/deep link (as in QA Step 6 of PR #104490) or reloading the page causes WorkspaceWorkflowsApprovalsCreatePage either to crash when a partial ONYXKEYS.APPROVAL_WORKFLOW fragment exists in Onyx or to remain stuck indefinitely on a full-screen loading spinner instead of rendering the approval workflow creation form.

What is the root cause of that problem?

There are three interacting root causes across draft initialization, render-time validation, and draft cleanup:

  1. Missing direct-entry draft initialization in WorkspaceWorkflowsApprovalsCreatePage (endless loading spinner):

  2. Unseeded Onyx.merge writes & synchronous first-render crash in ApprovalWorkflowEditor:

    • ONYXKEYS.APPROVAL_WORKFLOW is persisted in IndexedDB (ONYXKEYS.ts:774, not listed in ramOnlyKeys in src/setup/index.ts). Four actions in Workflow.ts—setApprovalWorkflowMembers (L637), clearApprovalWorkflowApprovers (L722), setApprovalWorkflowIsInitialFlow (L728), and validateApprovalWorkflow (L854)—call Onyx.merge(ONYXKEYS.APPROVAL_WORKFLOW, ...) without ensuring a base draft exists. If a partial object lacking approvers, members, or usedApproverEmails is present, !!approvalWorkflow in WorkspaceWorkflowsApprovalsCreatePage.tsx:109 evaluates to true on the initial render before any useEffect runs, mounting ApprovalWorkflowEditor.tsx and throwing synchronously at approvalWorkflow.approvers.length (L56), sortAlphabetically(approvalWorkflow.members, ...) (L95), or approvalWorkflow.usedApproverEmails.some(...) (L212). (On a fresh staging deploy, lazy-loading the WorkspaceWorkflowsApprovalsCreatePage chunk across a bundle rollout can also trigger GenericErrorPage once before a reload exposes the missing-draft spinner.)
  3. Stale EDIT drafts and un-cleared rules-based CREATE drafts lingering in ONYXKEYS.APPROVAL_WORKFLOW:

    • WorkspaceWorkflowsApprovalsEditPage does not clear ONYXKEYS.APPROVAL_WORKFLOW when dismissed via Back/backdrop (which is why WorkflowsApprovalsTab.tsx:401-402 and WorkspaceMemberDetailsPage.tsx:244-245 explicitly call clearApprovalWorkflow() before navigating).
    • Similarly, while legacy createApprovalWorkflow, updateApprovalWorkflow, and removeApprovalWorkflow clear ONYXKEYS.APPROVAL_WORKFLOW in optimisticData (Workflow.ts:116-120, 225-229, 300-304), the rules-based actions createApprovalWorkflowRules, updateApprovalWorkflowRules, and removeApprovalWorkflowRules (Workflow.ts:361-392, 429-473, 538-563) never clear ONYXKEYS.APPROVAL_WORKFLOW.
    • As a result, a naive if (approvalWorkflow) return; check on direct entry to /workflows/approvals/new will mistakenly render a stale action: 'edit' session (hiding the create header, locking "Expenses from" to "Everyone" when isDefault: true, and routing sub-page backTo to WORKSPACE_WORKFLOWS_APPROVALS_EDIT at ApprovalWorkflowEditor.tsx:157-159) or re-populate an already-saved rule-based workflow.

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

  1. Validate hasValidCreateDraft for both rendering and fallback initialization in src/pages/workspace/workflows/approvals/WorkspaceWorkflowsApprovalsCreatePage.tsx:

    • Derive availableMembers and usedApproverEmails via useApprovalWorkflows(policy) and check that approvalWorkflow is a complete CREATE draft before rendering ApprovalWorkflowEditor or skipping initialization:
      const {availableMembers, usedApproverEmails} = useApprovalWorkflows(policy);
      
      const hasValidCreateDraft =
          approvalWorkflow?.action === CONST.APPROVAL_WORKFLOW.ACTION.CREATE &&
          Array.isArray(approvalWorkflow.members) &&
          Array.isArray(approvalWorkflow.approvers) &&
          Array.isArray(approvalWorkflow.usedApproverEmails);
      
      useEffect(() => {
          if (hasValidCreateDraft || isEmptyObject(policy) || shouldShowNotFoundView) {
              return;
          }
      
          setApprovalWorkflow({
              ...INITIAL_APPROVAL_WORKFLOW,
              isInitialFlow: false,
              availableMembers,
              usedApproverEmails,
          });
      }, [hasValidCreateDraft, policy, shouldShowNotFoundView, availableMembers, usedApproverEmails]);
      
    • Gate the JSX on hasValidCreateDraft ({hasValidCreateDraft ? (<>...</>) : (<View style={[styles.flex1, styles.fullScreenLoading]}><ActivityIndicator size={CONST.ACTIVITY_INDICATOR_SIZE.LARGE} /></View>)}) so partial Onyx.merge fragments or stale EDIT drafts never mount ApprovalWorkflowEditor on the first render before useEffect runs.
    • Do not block the useEffect on isLoadingReportData: once !isEmptyObject(policy) holds in Onyx (matching WorkspaceWorkflowsApprovalsEditPage.tsx:83, 197-226), the form initializes immediately even while offline or during a background ReconnectApp.
  2. Clear abandoned drafts on explicit modal dismiss in WorkspaceWorkflowsApprovalsCreatePage.tsx (without an unmount useEffect):

    • Update HeaderWithBackButton's onBackButtonPress (L107) to clear the draft when dismissing the modal:
      onBackButtonPress={() => {
          clearApprovalWorkflow();
          Navigation.dismissModal();
      }}
      
    • Do not clear ONYXKEYS.APPROVAL_WORKFLOW in an unconditional unmount useEffect(() => () => clearApprovalWorkflow(), []):
      • Under React <StrictMode> / USE_ACTIVITY_SCREEN_STRICT_MODE_IN_DEV (enabled on dev/staging), simulated unmount + remount on initial mount would wipe wizard-seeded (ExpensesFrom -> Approver -> CreatePage) and member-profile-seeded (WorkspaceMemberDetailsPage) drafts.
      • During wizard creation, browser/hardware Back from CreatePage pops back to ApproverPage (see WorkspaceWorkflowsApprovalsApprovalLimitPage.tsx:148-150), where the in-progress draft must stay intact.
  3. Clear ONYXKEYS.APPROVAL_WORKFLOW in rules-based workflow save/remove actions in src/libs/actions/Workflow.ts:

    • Call clearApprovalWorkflow() in createApprovalWorkflowRules (L384), updateApprovalWorkflowRules (L472), and removeApprovalWorkflowRules (L561) to match legacy createApprovalWorkflow / updateApprovalWorkflow / removeApprovalWorkflow (L116-120, L225-229, L300-304), ensuring saved rule-based workflows do not stay in ONYXKEYS.APPROVAL_WORKFLOW and pre-fill a later direct /workflows/approvals/new visit. (Keep this in Workflow.ts rather than ApprovalWorkflowRulesOnyxData.ts, which is also used by HR integration actions.)
  4. Add regression tests in tests/ui/WorkspaceWorkflowsApprovalsCreatePageTest.tsx and tests/actions/WorkflowTest.ts:

    • Direct entry / reload on WorkspaceWorkflowsApprovalsCreatePage with ONYXKEYS.APPROVAL_WORKFLOW unset (null) on a DEW workspace (approvalMode: CONST.POLICY.APPROVAL_MODE.DYNAMICEXTERNAL, dynamicExternalWorkflowHidePeople: false) seeds INITIAL_APPROVAL_WORKFLOW with isInitialFlow: false and renders ApprovalWorkflowEditor.
    • Direct entry when ONYXKEYS.APPROVAL_WORKFLOW holds a stale EDIT draft or partial object replaces it cleanly without throwing.
    • DEW workspace with dynamicExternalWorkflowHidePeople: true renders FullPageNotFoundView without seeding a draft.
    • createApprovalWorkflowRules clears ONYXKEYS.APPROVAL_WORKFLOW on save.

What alternative solutions did you explore? (Optional)

  • Redirecting /workflows/approvals/new to DYNAMIC_ROUTES.WORKSPACE_WORKFLOWS_APPROVALS_EXPENSES_FROM when approvalWorkflow is absent: Rejected because /workflows/approvals/new is a direct shareable route expected to display the creation form (consistent with WorkspaceMemberDetailsPage's direct isInitialFlow: false entry and PR #104490 Step 6), and redirecting would break browser reloads on the confirm page.
  • Clearing ONYXKEYS.APPROVAL_WORKFLOW on component unmount: Rejected because USE_ACTIVITY_SCREEN_STRICT_MODE_IN_DEV / <Activity> cleanup cycles and hardware/browser Back navigation to ApproverPage would wipe active creation drafts.

cocvn157 avatar Nov 13 '26 17:11 cocvn157

@Krishna2323 Can you please confirm whether it is a regression from https://github.com/Expensify/App/pull/104490 before I proceed here?

parasharrajat avatar Nov 14 '26 10:11 parasharrajat

https://github.com/user-attachments/assets/eaf31c0c-2562-4a6f-839b-60f3719d0ff9

Proposal

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

Opening /workspaces/<policyID>/workflows/approvals/new directly on a DEW workspace with Hide people off can leave the creation page loading indefinitely. The report also describes a crash before reloading.

What is the root cause of that problem?

Normal navigation creates an approval draft before opening the confirmation page. Direct URL entry bypasses that initialization. WorkspaceWorkflowsApprovalsCreatePage reads ONYXKEYS.APPROVAL_WORKFLOW and shows a spinner when it is absent, but nothing on the page creates the missing draft.

The page also treats any existing draft as ready for ApprovalWorkflowEditor. A partial draft containing only isInitialFlow crashes when the editor reads approvers.length. I reproduced that mechanism in a wrapped-page test; I have not confirmed that this was the reporter's exact pre-crash state.

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

Initialize and check the draft in WorkspaceWorkflowsApprovalsCreatePage before rendering the editor:

  1. Use INITIAL_APPROVAL_WORKFLOW and the existing useApprovalWorkflows(policy) member and approver data when a draft is missing. Fill missing fields in partial drafts while retaining existing selections.
  2. Start a fresh CREATE draft when a stale EDIT draft remains. For an unfinished initial flow, preserve members and approvers and set isInitialFlow to false, matching confirmation-page navigation.
  3. Render the editor once the required draft fields exist. Keep the existing access checks, including the Hide people restriction. Allow initialization from a cached policy while report data is still loading.

This overlaps with the draft-initialization approach in earlier proposals. The candidate also handles an abandoned initial-flow draft without losing its selections. It changes the create page and its existing test file.

What alternative solutions did you explore? (Optional)

Clearing the draft on every unmount could discard selections during wizard navigation or development remounts. Adding empty-array fallbacks only inside the editor would avoid some crashes but leave the missing-draft spinner unresolved.

Tests and results

The baseline regression run reproduced the missing-draft spinner and partial-draft crash. With the fix, all nine tests in the wrapped-page suite pass. Coverage includes missing and partial drafts, stale EDIT drafts, initial-flow normalization with selections preserved, cached policy loading, Hide people, and existing workflow creation behavior.

Type checking, lint, React Compiler, spelling, and whitespace checks passed.

The video shows three checks in the patched web build: direct entry without a draft, reload with the saved draft, and direct entry with a partial draft containing only isInitialFlow. All three rendered the confirmation form with the required draft fields and no captured page errors. The recording uses a synthetic local DEW policy with API calls blocked. A live DEW staging workspace and native devices have not been tested.

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

Proposal

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

On a Dynamic External Workflow (DEW) workspace with Hide people off, opening /workspaces/:policyID/workflows/approvals/new directly (or reloading that URL) should show the create-approval form. Instead the page can throw on first open, and after a reload it stays on a full-screen spinner.

This was found during QA of PR #104490, but that PR only preserves approvalMode on DEW saves/imports. It does not change how this route is initialized. The same gap exists on non-DEW workspaces; QA hit it on DEW because that is the workspace they were already testing, and Hide people being off is what allows the route to render at all.

What is the root cause of that problem?

WorkspaceWorkflowsApprovalsCreatePage never creates an approval-workflow draft, and it treats any truthy value in ONYXKEYS.APPROVAL_WORKFLOW as ready for the editor.

The route is a normal deep link:

    WORKSPACE_WORKFLOWS_APPROVALS_NEW: {
        route: 'workspaces/:policyID/workflows/approvals/new',
        getRoute: (policyID: string) => `workspaces/${policyID}/workflows/approvals/new` as const,
    },

It is registered in src/libs/Navigation/linkingConfig/config.ts (lines 1114–1116) and as a workflows RHP in src/libs/Navigation/linkingConfig/RELATIONS/WORKSPACE_TO_RHP.ts (line 51).

On a DEW workspace, the page is hidden only when Hide people is on:

function shouldHideDynamicExternalWorkflowPeople(policy: OnyxEntry<Policy>): boolean {
    return hasDynamicExternalWorkflow(policy) && !!policy?.dynamicExternalWorkflowHidePeople;
}

With Hide people off, shouldShowNotFoundView is false and the page renders. It then branches only on whether a draft already exists:

                    {!!approvalWorkflow && (
                        <>
                            <ApprovalWorkflowEditor
                                approvalWorkflow={approvalWorkflow}
                                policy={policy}
                                policyID={route.params.policyID}
                                ref={formRef}
                            />
                            // ...submit footer...
                        </>
                    )}
                    {!approvalWorkflow && (
                        <View style={[styles.flex1, styles.fullScreenLoading]}>
                            <ActivityIndicator size={CONST.ACTIVITY_INDICATOR_SIZE.LARGE} />
                        </View>
                    )}

Nothing on this page seeds ONYXKEYS.APPROVAL_WORKFLOW. The usual create path does that before navigation, from WorkflowsApprovalsTab (lines 184–188) or WorkspaceMemberDetailsPage (lines 264–270). The edit page also initializes its own draft (WorkspaceWorkflowsApprovalsEditPage.tsx, lines 196–226). Direct entry and reload skip those predecessors, so approvalWorkflow stays null and the spinner never finishes. That matches the attached log: the indicator is shown for longer than expected after OpenPolicyWorkflowsPage has already returned 200, with no request still in flight.

This is also why existing tests miss it: tests/ui/WorkspaceWorkflowsApprovalsCreatePageTest.tsx (lines 75–81) always writes a complete draft before render.

The first-open crash is a second gap in the same branch. !!approvalWorkflow is true for any leftover object, including a partial Onyx.merge fragment or a stale action: 'edit' session. ApprovalWorkflowEditor then assumes the required arrays are present:

    const approverCount = approvalWorkflow.approvers.length;
    const sortedMembers = approvalWorkflow.isDefault ? [] : sortAlphabetically(approvalWorkflow.members, 'displayName', localeCompare);
                        !shouldUseApprovalWorkflowRules && !errorText && approvalWorkflow.usedApproverEmails.some((approverEmail) => approverEmail === approver?.email);

ONYXKEYS.APPROVAL_WORKFLOW is persisted (it is not in ramOnlyKeys in src/setup/index.ts). Several writers also call Onyx.merge without a base draft (setApprovalWorkflowMembers at line 637, clearApprovalWorkflowApprovers at lines 722–723, setApprovalWorkflowIsInitialFlow at lines 727–728, and validateApprovalWorkflow at line 854 of src/libs/actions/Workflow.ts). A merge into a missing key leaves a truthy object that is missing approvers / members / usedApproverEmails, which throws on the first render, before any useEffect can repair it.

I have not seen the reporter's pre-crash draft in the public attachments, so I am not claiming that this was definitely the first exception. It is the only crash path in this screen that the code clearly supports, and the page should not mount the editor until the draft is a complete CREATE workflow.

A related stale-draft problem: legacy createApprovalWorkflow / updateApprovalWorkflow / removeApprovalWorkflow set ONYXKEYS.APPROVAL_WORKFLOW to null in their optimistic data (Workflow.ts, lines 115–120, 224–229, 299–304), but createApprovalWorkflowRules, updateApprovalWorkflowRules, and removeApprovalWorkflowRules (lines 361–392, 429–473, 538–563) never clear it. The create page also does not clear the draft itself after a rules-based save. A later visit to /workflows/approvals/new can therefore reuse an already-saved session rather than start a new one.

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

All of the user-facing fix belongs in src/pages/workspace/workflows/approvals/WorkspaceWorkflowsApprovalsCreatePage.tsx.

  1. Only render the editor for a complete CREATE draft. Derive availableMembers and usedApproverEmails with useApprovalWorkflows(policy), and gate both the editor and the initialization skip on something like:
const hasValidCreateDraft =
    approvalWorkflow?.action === CONST.APPROVAL_WORKFLOW.ACTION.CREATE &&
    Array.isArray(approvalWorkflow.members) &&
    Array.isArray(approvalWorkflow.approvers) &&
    Array.isArray(approvalWorkflow.usedApproverEmails);

Show the existing spinner until that is true, so a partial merge or a leftover EDIT draft cannot mount ApprovalWorkflowEditor on the first paint.

  1. Initialize a fallback CREATE draft on direct entry or reload. After the policy is present and shouldShowNotFoundView is false, if the draft is missing, incomplete, or still in EDIT mode, call setApprovalWorkflow with INITIAL_APPROVAL_WORKFLOW from src/libs/WorkflowUtils.ts, plus availableMembers, usedApproverEmails, and isInitialFlow: false.

isInitialFlow: false is required, not optional. It is what WorkspaceMemberDetailsPage already does when it jumps straight to this page (lines 261–270). The default on INITIAL_APPROVAL_WORKFLOW is true, and DynamicWorkspaceWorkflowsApprovalsExpensesFromPage clears the whole draft on unmount while that flag is set (lines 468–472). If a user opens "Expenses from" from the confirm form and we left isInitialFlow true, leaving that sub-page would wipe the draft and put them back on the spinner.

Do not wait on isLoadingReportData. withPolicyAndFullscreenLoading already covers the empty-policy loading case. Once !isEmptyObject(policy), the form can be built from the cached policy, including while offline, which is how the edit page initializes (lines 196–226). Do not seed a draft when Hide people is on, the user cannot write approvals, or the policy is invalid.

  1. Preserve in-progress CREATE selections. If a leftover draft is already action: 'create' but incomplete, or it is still an initial-flow draft, keep any members / approvers already chosen, fill the missing arrays from INITIAL_APPROVAL_WORKFLOW, and set isInitialFlow to false. If a stale EDIT draft is present, replace it with a fresh CREATE draft. After a valid CREATE draft exists, update only availableMembers and usedApproverEmails when those derived lists change (for example when personal details arrive after a hard reload), without resetting the user's selections.

  2. Clear the draft only when the create modal is dismissed, by wrapping the existing HeaderWithBackButton handler:

onBackButtonPress={() => {
    clearApprovalWorkflow();
    Navigation.dismissModal();
}}

Do not clear ONYXKEYS.APPROVAL_WORKFLOW in an unmount useEffect. Navigating from this page to the Approver or Expenses from screens unmounts it, and a cleanup there would delete the draft those screens need. React Strict Mode remounts in dev/staging would do the same.

  1. Clear the draft from the rules-based save/remove actions in src/libs/actions/Workflow.ts: call clearApprovalWorkflow() from createApprovalWorkflowRules, updateApprovalWorkflowRules, and removeApprovalWorkflowRules, so they match the legacy actions. Keep that in Workflow.ts, not in ApprovalWorkflowRulesOnyxData.ts, which is also used by HR import paths.

I would not rely on optional chaining inside ApprovalWorkflowEditor as the fix. Empty-array fallbacks can hide a throw, but they leave the missing-draft spinner in place and can hide a bad draft instead of replacing it.

What specific scenarios should we cover in automated tests to prevent reintroducing this issue in the future?

In tests/ui/WorkspaceWorkflowsApprovalsCreatePageTest.tsx:

  • Direct entry / reload with ONYXKEYS.APPROVAL_WORKFLOW unset, on a DEW workspace (approvalMode: CONST.POLICY.APPROVAL_MODE.DYNAMICEXTERNAL, dynamicExternalWorkflowHidePeople: false), seeds INITIAL_APPROVAL_WORKFLOW with isInitialFlow: false and renders ApprovalWorkflowEditor.
  • The same direct-entry path works on a non-DEW Control workspace, since the missing initialization is not DEW-specific.
  • A partial draft (for example only {isInitialFlow: true}) does not throw, becomes a complete CREATE draft, and keeps any members or approvers already present.
  • A stale EDIT draft is replaced with a fresh CREATE draft (action: 'create', empty members/approvers, isInitialFlow: false).
  • An unfinished initial-flow CREATE draft keeps its members and approvers and has isInitialFlow set to false.
  • A DEW workspace with dynamicExternalWorkflowHidePeople: true shows FullPageNotFoundView and does not seed a draft.
  • Existing behavior still holds: a workflow that includes every workspace member is created as the default one.

In tests/actions/WorkflowTest.ts:

  • createApprovalWorkflowRules (and the update/remove rules helpers) clear ONYXKEYS.APPROVAL_WORKFLOW on save.

What alternative solutions did you explore? (Optional)

  • Redirect /workflows/approvals/new to the Expenses from step when the draft is missing. Rejected because the expected result is the create form itself, and this is already a supported direct entry from WorkspaceMemberDetailsPage.
  • Clear the draft on unmount. Rejected because leaving this page for a sub-page, or a Strict Mode remount, would wipe an in-progress draft.
  • Guard only inside ApprovalWorkflowEditor. Rejected because it does not fix the endless spinner, and it would still render a stale EDIT session as if it were a new workflow.
  • Show a not-found or error view when the draft is missing. Rejected because this is a valid, shareable workspace route; the form should be created, not blocked.

PawanOzha avatar Nov 15 '26 03:11 PawanOzha

📣 @PawanOzha! 📣 Hey, it seems we don’t have your contributor details yet! You'll only have to do this once, and this is how we'll hire you on Upwork. Please follow these steps:

  1. Make sure you've read and understood the contributing guidelines.
  2. Get the email address used to login to your Expensify account. If you don't already have an Expensify account, create one here. If you have multiple accounts (e.g. one for testing), please use your main account email.
  3. Get the link to your Upwork profile. It's necessary because we only pay via Upwork. You can access it by logging in, and then clicking on your name. It'll look like this. If you don't already have an account, sign up for one here.
  4. Copy the format below and paste it in a comment on this issue. Replace the placeholder text with your actual details. Screen Shot 2022-11-16 at 4 42 54 PM Format:
Contributor details
Your Expensify account email: <REPLACE EMAIL HERE>
Upwork Profile Link: <REPLACE LINK HERE>

melvin-bot[bot] avatar Nov 15 '26 03:11 melvin-bot[bot]

Contributor details

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

PawanOzha avatar Nov 15 '26 03:11 PawanOzha

⚠️ Invalid email. Please make sure to create an Expensify account with this email first here.

melvin-bot[bot] avatar Nov 15 '26 03:11 melvin-bot[bot]

Contributor details Your Expensify account email: [email protected] Upwork Profile Link: https://www.upwork.com/freelancers/~01e1700af765e4270c

PawanOzha avatar Nov 15 '26 04:11 PawanOzha

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

melvin-bot[bot] avatar Nov 15 '26 04:11 melvin-bot[bot]

Proposal

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

On a Dynamic External Workflow (DEW) workspace with Hide people turned off (dynamicExternalWorkflowHidePeople: false), opening /workspaces/:policyID/workflows/approvals/new directly via URL/deep link or reloading the page causes WorkspaceWorkflowsApprovalsCreatePage either to crash on initial render (if a partial or stale ONYXKEYS.APPROVAL_WORKFLOW draft is persisted in IndexedDB) or to stay stuck indefinitely on a full-screen loading spinner instead of rendering the approval workflow creation form.

What is the root cause of that problem?

  1. No fallback draft initialization on direct entry / reload (src/pages/workspace/workflows/approvals/WorkspaceWorkflowsApprovalsCreatePage.tsx:48, 109-137):
    • ROUTES.WORKSPACE_WORKFLOWS_APPROVALS_NEW (workspaces/:policyID/workflows/approvals/new) is registered as a direct RHP deep link (src/libs/Navigation/linkingConfig/config.ts:1114-1116, WORKSPACE_TO_RHP.ts:51). When shouldHideDynamicExternalWorkflowPeople(policy) is false (src/libs/PolicyUtils/workflows.ts:82-84), FullPageNotFoundView allows rendering.
    • However, WorkspaceWorkflowsApprovalsCreatePage assumes ONYXKEYS.APPROVAL_WORKFLOW was already initialized by WorkflowsApprovalsTab.tsx:184-188 or WorkspaceMemberDetailsPage.tsx:263-269. When opened directly or reloaded without a draft, !approvalWorkflow renders <ActivityIndicator /> (lines 133-137) forever because no useEffect initializes INITIAL_APPROVAL_WORKFLOW.
  2. Persisted partial Onyx.merge fragments & stale EDIT / rules-based drafts crash or corrupt the first render (src/libs/actions/Workflow.ts, ApprovalWorkflowEditor.tsx):
    • ONYXKEYS.APPROVAL_WORKFLOW is persisted in IndexedDB (src/ONYXKEYS.ts:774, not in ramOnlyKeys). Actions such as setApprovalWorkflowMembers (Workflow.ts:637), clearApprovalWorkflowApprovers (L722), setApprovalWorkflowIsInitialFlow (L728), and validateApprovalWorkflow (L854) call Onyx.merge(ONYXKEYS.APPROVAL_WORKFLOW, ...) without checking for a base draft.
    • Because WorkspaceWorkflowsApprovalsCreatePage.tsx:109 gates ApprovalWorkflowEditor only on !!approvalWorkflow, any partial object mounts ApprovalWorkflowEditor on the very first render (before any useEffect can run) and throws TypeError when reading approvalWorkflow.approvers.length (ApprovalWorkflowEditor.tsx:63), sortAlphabetically(approvalWorkflow.members, ...) (L102), or approvalWorkflow.usedApproverEmails.some(...) (L235).
    • Additionally, createApprovalWorkflowRules (Workflow.ts:361-392), updateApprovalWorkflowRules (L429-473), and removeApprovalWorkflowRules (L538-563) do not clear ONYXKEYS.APPROVAL_WORKFLOW (unlike legacy createApprovalWorkflow at L116-120), and WorkspaceWorkflowsApprovalsEditPage leaves action: 'edit' drafts in Onyx when dismissed via Back.

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

  1. Gate rendering and fallback initialization on a complete CREATE draft in src/pages/workspace/workflows/approvals/WorkspaceWorkflowsApprovalsCreatePage.tsx:
    • Use useApprovalWorkflows(policy) to compute availableMembers and usedApproverEmails.
    • Define a strict completeness guard:
      const {availableMembers, usedApproverEmails} = useApprovalWorkflows(policy);
      
      const hasValidCreateDraft =
          approvalWorkflow?.action === CONST.APPROVAL_WORKFLOW.ACTION.CREATE &&
          Array.isArray(approvalWorkflow.members) &&
          Array.isArray(approvalWorkflow.approvers) &&
          Array.isArray(approvalWorkflow.usedApproverEmails);
      
    • Seed or normalize the draft in a useEffect once !isEmptyObject(policy) and !shouldShowNotFoundView (preserving any existing members/approvers on a partial CREATE draft and forcing isInitialFlow: false so DynamicWorkspaceWorkflowsApprovalsExpensesFromPage.tsx:468-472 does not wipe the draft on sub-page unmount):
      useEffect(() => {
          if (hasValidCreateDraft || isEmptyObject(policy) || shouldShowNotFoundView) {
              return;
          }
          const isPartialCreateDraft = approvalWorkflow?.action === CONST.APPROVAL_WORKFLOW.ACTION.CREATE;
          setApprovalWorkflow({
              ...INITIAL_APPROVAL_WORKFLOW,
              members: isPartialCreateDraft && Array.isArray(approvalWorkflow?.members) ? approvalWorkflow.members : INITIAL_APPROVAL_WORKFLOW.members,
              approvers: isPartialCreateDraft && Array.isArray(approvalWorkflow?.approvers) ? approvalWorkflow.approvers : INITIAL_APPROVAL_WORKFLOW.approvers,
              isInitialFlow: false,
              availableMembers,
              usedApproverEmails,
          });
      }, [hasValidCreateDraft, approvalWorkflow, policy, shouldShowNotFoundView, availableMembers, usedApproverEmails]);
      
    • Replace {!!approvalWorkflow && ...} / {!approvalWorkflow && ...} (lines 109-137) with {hasValidCreateDraft ? (...) : (<View style={[styles.flex1, styles.fullScreenLoading]}><ActivityIndicator size={CONST.ACTIVITY_INDICATOR_SIZE.LARGE} /></View>)}.
  2. Clear the draft on modal dismiss in WorkspaceWorkflowsApprovalsCreatePage.tsx and on rules-based workflow actions in src/libs/actions/Workflow.ts:
    • In WorkspaceWorkflowsApprovalsCreatePage.tsx:107, update HeaderWithBackButton's onBackButtonPress to call clearApprovalWorkflow() before Navigation.dismissModal() (avoiding an unmount useEffect that would wipe the draft when navigating to ExpensesFrom / Approver sub-pages or under React StrictMode).
    • In src/libs/actions/Workflow.ts, call clearApprovalWorkflow() in createApprovalWorkflowRules, updateApprovalWorkflowRules, and removeApprovalWorkflowRules.
  3. Add unit tests in tests/ui/WorkspaceWorkflowsApprovalsCreatePageTest.tsx and tests/actions/WorkflowTest.ts:
    • Verify direct entry with ONYXKEYS.APPROVAL_WORKFLOW unset (null), with a partial fragment, and with a stale EDIT draft on a DEW workspace (dynamicExternalWorkflowHidePeople: false and true).

What alternative solutions did you explore? (Optional)

  • Clearing ONYXKEYS.APPROVAL_WORKFLOW in an unmount useEffect: Discarded because navigating to sub-pages (ExpensesFrom / Approver) or <StrictMode> remounts would wipe an active creation draft.
  • Redirecting /workflows/approvals/new to ExpensesFrom: Discarded because /workflows/approvals/new is a valid direct entry route (used by WorkspaceMemberDetailsPage) and reloading should keep the user on the creation form.

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

@parasharrajat Uh oh! This issue is overdue by 2 days. Don't forget to update your issues!

@parasharrajat Eep! 4 days overdue now. Issues have feelings too...

@parasharrajat Now this issue is 8 days overdue. Are you sure this should be a Daily? Feel free to change it!

Getting help internally to set DEW workspace...

parasharrajat avatar Nov 24 '26 09:11 parasharrajat

@parasharrajat this issue was created 2 weeks ago. Are we close to approving a proposal? If not, what's blocking us from getting this issue assigned? Don't hesitate to create a thread in #expensify-open-source to align faster in real time. Thanks!