[$175] Workflows- Page loads endlessly when open workflows/approvals/new in Dew Workspace
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
- Open https://staging.new.expensify.com/
- Go to Dew workpaces
- Go to Workflows
- Open the URL with ending /workflows/approvals/new
- 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
Applause Internal Information Exported by: Julia Ponikarchuk Bug ID: 7313093
Upwork Automation - Do Not Edit
- Upwork Job URL: https://www.upwork.com/jobs/~022121271632517590260
- Upwork Job ID: 2121271632517590260
- Last Price Increase: 2026-11-13
Issue Owner
Current Issue Owner: @parasharrajat
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
Triggered auto assignment to Contributor-plus team member for initial proposal review - @parasharrajat (External)
Job added to Upwork: https://www.upwork.com/jobs/~022121271632517590260
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
- Normal creation initializes the draft before navigation: WorkflowsApprovalsTab.tsx:182–207.
- The destination reads that draft and renders an indefinite spinner when it is absent, without a recovery path: WorkspaceWorkflowsApprovalsCreatePage.tsx:109–137.
- DEW blocks this screen only when Hide people is enabled: workflows.ts:72–84.
- The attached browser log records a spinner exceeding 10 seconds while online and authenticated, with no queued requests. This is consistent with waiting on local state rather than a pending request.
- Existing tests always provide a complete draft, missing the direct-entry case: WorkspaceWorkflowsApprovalsCreatePageTest.tsx:75–99.
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.
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:
-
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 rendersWorkspaceWorkflowsApprovalsCreatePage.tsx(WorkspaceWorkflowsApprovalsCreatePage.tsx:44). - In DEW workspaces where
dynamicExternalWorkflowHidePeopleis false ("Hide people is off"),shouldHideDynamicExternalWorkflowPeople(policy)returnsfalse(workflows.ts:82–84), so the page bypassesFullPageNotFoundView. - However,
WorkspaceWorkflowsApprovalsCreatePageexpects an existingapprovalWorkflowdraft in Onyx (ONYXKEYS.APPROVAL_WORKFLOW). In normal wizard flows, this draft is seeded by predecessor screens (WorkflowsApprovalsTab.tsx:184orWorkspaceMemberDetailsPage.tsx:263). - On direct URL entry or browser reload,
approvalWorkflowisnull/undefined. Lines 133–137 ofWorkspaceWorkflowsApprovalsCreatePage.tsx:
Because the component does not initialize a missing draft or fetch it from an API, it stays on the full-screen loading spinner indefinitely.{!approvalWorkflow && ( <View style={[styles.flex1, styles.fullScreenLoading]}> <ActivityIndicator size={CONST.ACTIVITY_INDICATOR_SIZE.LARGE} /> </View> )}
- When a user directly opens or reloads
-
The Preceding Crash:
- In
ApprovalWorkflowEditor.tsx(ApprovalWorkflowEditor.tsx:56, 95, 207), the component assumesapprovalWorkflow.approversandapprovalWorkflow.membersare always defined arrays:- Line 56:
const approverCount = approvalWorkflow.approvers.length; - Line 95:
sortAlphabetically(approvalWorkflow.members, ...) - Line 207:
approvalWorkflow.approvers.map(...)
- Line 56:
- 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').
- In
What changes do you think we should make in order to solve the problem?
-
Auto-initialize Fallback Creation Draft on Direct Entry in
WorkspaceWorkflowsApprovalsCreatePage.tsx: ImportuseApprovalWorkflowsandINITIAL_APPROVAL_WORKFLOW:import useApprovalWorkflows from '@hooks/useApprovalWorkflows'; import {INITIAL_APPROVAL_WORKFLOW} from '@libs/WorkflowUtils'; import {clearApprovalWorkflow, setApprovalWorkflow} from '@userActions/Workflow';Derive
availableMembersandusedApproverEmailsusinguseApprovalWorkflows(policy), and add auseEffectthat initializes the draft oncepolicyis 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 renderApprovalWorkflowEditoron direct entry or reload. -
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(); }; }, []); -
Defensive Guarding in
ApprovalWorkflowEditor.tsx: Insrc/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.mapon line 207. This eliminates any possible crash if a draft is partially formed.
What alternative solutions did you explore? (Optional)
- Redirecting to
DYNAMIC_ROUTES.WORKSPACE_WORKFLOWS_APPROVALS_EXPENSES_FROMwhenapprovalWorkflowis missing: Discarded because users or deep links specifically targeting/workflows/approvals/newexpect to land on the approval creation screen (just asWorkspaceMemberDetailsPagenavigates directly to/new). Redirecting breaks direct navigation and reloading. - Showing an error or not-found view when
approvalWorkflowis absent: Discarded because/workflows/approvals/newis a valid, shareable workspace route, and showing an error on browser reload provides poor UX. Auto-initializing the draft is consistent withWorkspaceWorkflowsApprovalsEditPage.tsx:218–220.
Contributor details
Your Expensify account email: [email protected] Upwork Profile Link: https://www.upwork.com/freelancers/~0131dae36abcf59374
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:
-
Missing direct-entry draft initialization in
WorkspaceWorkflowsApprovalsCreatePage(endless loading spinner):ROUTES.WORKSPACE_WORKFLOWS_APPROVALS_NEW(workspaces/:policyID/workflows/approvals/new) is registered as a direct deep-linkable RHP route inlinkingConfig/config.ts:1114-1116andWORKSPACE_TO_RHP.ts:51. On DEW workspaces where Hide people is off,shouldHideDynamicExternalWorkflowPeople(policy)returnsfalse(workflows.ts:72-84), soFullPageNotFoundViewallows access.- However,
WorkspaceWorkflowsApprovalsCreatePage.tsx:48, 109-137assumes a predecessor screen (WorkflowsApprovalsTab.tsx:184-188orWorkspaceMemberDetailsPage.tsx:263-269) has already seededONYXKEYS.APPROVAL_WORKFLOW. UnlikeWorkspaceWorkflowsApprovalsEditPage.tsx:197-237,WorkspaceWorkflowsApprovalsCreatePagenever initializes a fallback draft whenapprovalWorkflowis absent—leaving{!approvalWorkflow && <ActivityIndicator />}spinning indefinitely (confirmed in the attached browser log:ActivityIndicator has been shown for longer than expectedon/workspaces/8D52E064C3D73B89/workflows/approvals/newafterOpenPolicyWorkflowsPagefinished with200).
-
Unseeded
Onyx.mergewrites & synchronous first-render crash inApprovalWorkflowEditor:ONYXKEYS.APPROVAL_WORKFLOWis persisted in IndexedDB (ONYXKEYS.ts:774, not listed inramOnlyKeysinsrc/setup/index.ts). Four actions inWorkflow.ts—setApprovalWorkflowMembers(L637),clearApprovalWorkflowApprovers(L722),setApprovalWorkflowIsInitialFlow(L728), andvalidateApprovalWorkflow(L854)—callOnyx.merge(ONYXKEYS.APPROVAL_WORKFLOW, ...)without ensuring a base draft exists. If a partial object lackingapprovers,members, orusedApproverEmailsis present,!!approvalWorkflowinWorkspaceWorkflowsApprovalsCreatePage.tsx:109evaluates totrueon the initial render before anyuseEffectruns, mountingApprovalWorkflowEditor.tsxand throwing synchronously atapprovalWorkflow.approvers.length(L56),sortAlphabetically(approvalWorkflow.members, ...)(L95), orapprovalWorkflow.usedApproverEmails.some(...)(L212). (On a fresh staging deploy, lazy-loading theWorkspaceWorkflowsApprovalsCreatePagechunk across a bundle rollout can also triggerGenericErrorPageonce before a reload exposes the missing-draft spinner.)
-
Stale
EDITdrafts and un-cleared rules-basedCREATEdrafts lingering inONYXKEYS.APPROVAL_WORKFLOW:WorkspaceWorkflowsApprovalsEditPagedoes not clearONYXKEYS.APPROVAL_WORKFLOWwhen dismissed via Back/backdrop (which is whyWorkflowsApprovalsTab.tsx:401-402andWorkspaceMemberDetailsPage.tsx:244-245explicitly callclearApprovalWorkflow()before navigating).- Similarly, while legacy
createApprovalWorkflow,updateApprovalWorkflow, andremoveApprovalWorkflowclearONYXKEYS.APPROVAL_WORKFLOWinoptimisticData(Workflow.ts:116-120, 225-229, 300-304), the rules-based actionscreateApprovalWorkflowRules,updateApprovalWorkflowRules, andremoveApprovalWorkflowRules(Workflow.ts:361-392, 429-473, 538-563) never clearONYXKEYS.APPROVAL_WORKFLOW. - As a result, a naive
if (approvalWorkflow) return;check on direct entry to/workflows/approvals/newwill mistakenly render a staleaction: 'edit'session (hiding the create header, locking"Expenses from"to"Everyone"whenisDefault: true, and routing sub-pagebackTotoWORKSPACE_WORKFLOWS_APPROVALS_EDITatApprovalWorkflowEditor.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?
-
Validate
hasValidCreateDraftfor both rendering and fallback initialization insrc/pages/workspace/workflows/approvals/WorkspaceWorkflowsApprovalsCreatePage.tsx:- Derive
availableMembersandusedApproverEmailsviauseApprovalWorkflows(policy)and check thatapprovalWorkflowis a completeCREATEdraft before renderingApprovalWorkflowEditoror 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 partialOnyx.mergefragments or staleEDITdrafts never mountApprovalWorkflowEditoron the first render beforeuseEffectruns. - Do not block the
useEffectonisLoadingReportData: once!isEmptyObject(policy)holds in Onyx (matchingWorkspaceWorkflowsApprovalsEditPage.tsx:83, 197-226), the form initializes immediately even while offline or during a backgroundReconnectApp.
- Derive
-
Clear abandoned drafts on explicit modal dismiss in
WorkspaceWorkflowsApprovalsCreatePage.tsx(without an unmountuseEffect):- Update
HeaderWithBackButton'sonBackButtonPress(L107) to clear the draft when dismissing the modal:onBackButtonPress={() => { clearApprovalWorkflow(); Navigation.dismissModal(); }} - Do not clear
ONYXKEYS.APPROVAL_WORKFLOWin an unconditional unmountuseEffect(() => () => 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
CreatePagepops back toApproverPage(seeWorkspaceWorkflowsApprovalsApprovalLimitPage.tsx:148-150), where the in-progress draft must stay intact.
- Under React
- Update
-
Clear
ONYXKEYS.APPROVAL_WORKFLOWin rules-based workflow save/remove actions insrc/libs/actions/Workflow.ts:- Call
clearApprovalWorkflow()increateApprovalWorkflowRules(L384),updateApprovalWorkflowRules(L472), andremoveApprovalWorkflowRules(L561) to match legacycreateApprovalWorkflow/updateApprovalWorkflow/removeApprovalWorkflow(L116-120,L225-229,L300-304), ensuring saved rule-based workflows do not stay inONYXKEYS.APPROVAL_WORKFLOWand pre-fill a later direct/workflows/approvals/newvisit. (Keep this inWorkflow.tsrather thanApprovalWorkflowRulesOnyxData.ts, which is also used by HR integration actions.)
- Call
-
Add regression tests in
tests/ui/WorkspaceWorkflowsApprovalsCreatePageTest.tsxandtests/actions/WorkflowTest.ts:- Direct entry / reload on
WorkspaceWorkflowsApprovalsCreatePagewithONYXKEYS.APPROVAL_WORKFLOWunset (null) on a DEW workspace (approvalMode: CONST.POLICY.APPROVAL_MODE.DYNAMICEXTERNAL,dynamicExternalWorkflowHidePeople: false) seedsINITIAL_APPROVAL_WORKFLOWwithisInitialFlow: falseand rendersApprovalWorkflowEditor. - Direct entry when
ONYXKEYS.APPROVAL_WORKFLOWholds a staleEDITdraft or partial object replaces it cleanly without throwing. - DEW workspace with
dynamicExternalWorkflowHidePeople: truerendersFullPageNotFoundViewwithout seeding a draft. createApprovalWorkflowRulesclearsONYXKEYS.APPROVAL_WORKFLOWon save.
- Direct entry / reload on
What alternative solutions did you explore? (Optional)
- Redirecting
/workflows/approvals/newtoDYNAMIC_ROUTES.WORKSPACE_WORKFLOWS_APPROVALS_EXPENSES_FROMwhenapprovalWorkflowis absent: Rejected because/workflows/approvals/newis a direct shareable route expected to display the creation form (consistent withWorkspaceMemberDetailsPage's directisInitialFlow: falseentry and PR#104490Step 6), and redirecting would break browser reloads on the confirm page. - Clearing
ONYXKEYS.APPROVAL_WORKFLOWon component unmount: Rejected becauseUSE_ACTIVITY_SCREEN_STRICT_MODE_IN_DEV/<Activity>cleanup cycles and hardware/browser Back navigation toApproverPagewould wipe active creation drafts.
@Krishna2323 Can you please confirm whether it is a regression from https://github.com/Expensify/App/pull/104490 before I proceed here?
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:
- Use
INITIAL_APPROVAL_WORKFLOWand the existinguseApprovalWorkflows(policy)member and approver data when a draft is missing. Fill missing fields in partial drafts while retaining existing selections. - Start a fresh CREATE draft when a stale EDIT draft remains. For an unfinished initial flow, preserve members and approvers and set
isInitialFlowto false, matching confirmation-page navigation. - 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.
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.
- Only render the editor for a complete CREATE draft. Derive
availableMembersandusedApproverEmailswithuseApprovalWorkflows(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.
- Initialize a fallback CREATE draft on direct entry or reload. After the policy is present and
shouldShowNotFoundViewis false, if the draft is missing, incomplete, or still in EDIT mode, callsetApprovalWorkflowwithINITIAL_APPROVAL_WORKFLOWfromsrc/libs/WorkflowUtils.ts, plusavailableMembers,usedApproverEmails, andisInitialFlow: 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.
-
Preserve in-progress CREATE selections. If a leftover draft is already
action: 'create'but incomplete, or it is still an initial-flow draft, keep anymembers/approversalready chosen, fill the missing arrays fromINITIAL_APPROVAL_WORKFLOW, and setisInitialFlowtofalse. If a stale EDIT draft is present, replace it with a fresh CREATE draft. After a valid CREATE draft exists, update onlyavailableMembersandusedApproverEmailswhen those derived lists change (for example when personal details arrive after a hard reload), without resetting the user's selections. -
Clear the draft only when the create modal is dismissed, by wrapping the existing
HeaderWithBackButtonhandler:
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.
- Clear the draft from the rules-based save/remove actions in
src/libs/actions/Workflow.ts: callclearApprovalWorkflow()fromcreateApprovalWorkflowRules,updateApprovalWorkflowRules, andremoveApprovalWorkflowRules, so they match the legacy actions. Keep that inWorkflow.ts, not inApprovalWorkflowRulesOnyxData.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_WORKFLOWunset, on a DEW workspace (approvalMode: CONST.POLICY.APPROVAL_MODE.DYNAMICEXTERNAL,dynamicExternalWorkflowHidePeople: false), seedsINITIAL_APPROVAL_WORKFLOWwithisInitialFlow: falseand rendersApprovalWorkflowEditor. - 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
isInitialFlowset tofalse. - A DEW workspace with
dynamicExternalWorkflowHidePeople: trueshowsFullPageNotFoundViewand 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) clearONYXKEYS.APPROVAL_WORKFLOWon save.
What alternative solutions did you explore? (Optional)
- Redirect
/workflows/approvals/newto 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 fromWorkspaceMemberDetailsPage. - 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! 📣 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:
- Make sure you've read and understood the contributing guidelines.
- 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.
- 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.
- Copy the format below and paste it in a comment on this issue. Replace the placeholder text with your actual details.
Format:
Contributor details
Your Expensify account email: <REPLACE EMAIL HERE>
Upwork Profile Link: <REPLACE LINK HERE>
Contributor details
Your Expensify account email: [email protected] Upwork Profile Link: https://www.upwork.com/freelancers/~01e1700af765e4270c
⚠️ Invalid email. Please make sure to create an Expensify account with this email first here.
Contributor details Your Expensify account email: [email protected] Upwork Profile Link: https://www.upwork.com/freelancers/~01e1700af765e4270c
✅ Contributor details stored successfully. Thank you for contributing to Expensify!
Proposal
Please re-state the problem that we are trying to solve in this issue.
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?
- 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). WhenshouldHideDynamicExternalWorkflowPeople(policy)isfalse(src/libs/PolicyUtils/workflows.ts:82-84),FullPageNotFoundViewallows rendering.- However,
WorkspaceWorkflowsApprovalsCreatePageassumesONYXKEYS.APPROVAL_WORKFLOWwas already initialized byWorkflowsApprovalsTab.tsx:184-188orWorkspaceMemberDetailsPage.tsx:263-269. When opened directly or reloaded without a draft,!approvalWorkflowrenders<ActivityIndicator />(lines 133-137) forever because nouseEffectinitializesINITIAL_APPROVAL_WORKFLOW.
- Persisted partial
Onyx.mergefragments & staleEDIT/ rules-based drafts crash or corrupt the first render (src/libs/actions/Workflow.ts,ApprovalWorkflowEditor.tsx):ONYXKEYS.APPROVAL_WORKFLOWis persisted in IndexedDB (src/ONYXKEYS.ts:774, not inramOnlyKeys). Actions such assetApprovalWorkflowMembers(Workflow.ts:637),clearApprovalWorkflowApprovers(L722),setApprovalWorkflowIsInitialFlow(L728), andvalidateApprovalWorkflow(L854) callOnyx.merge(ONYXKEYS.APPROVAL_WORKFLOW, ...)without checking for a base draft.- Because
WorkspaceWorkflowsApprovalsCreatePage.tsx:109gatesApprovalWorkflowEditoronly on!!approvalWorkflow, any partial object mountsApprovalWorkflowEditoron the very first render (before anyuseEffectcan run) and throwsTypeErrorwhen readingapprovalWorkflow.approvers.length(ApprovalWorkflowEditor.tsx:63),sortAlphabetically(approvalWorkflow.members, ...)(L102), orapprovalWorkflow.usedApproverEmails.some(...)(L235). - Additionally,
createApprovalWorkflowRules(Workflow.ts:361-392),updateApprovalWorkflowRules(L429-473), andremoveApprovalWorkflowRules(L538-563) do not clearONYXKEYS.APPROVAL_WORKFLOW(unlike legacycreateApprovalWorkflowatL116-120), andWorkspaceWorkflowsApprovalsEditPageleavesaction: 'edit'drafts in Onyx when dismissed via Back.
What changes do you think we should make in order to solve the problem?
- Gate rendering and fallback initialization on a complete
CREATEdraft insrc/pages/workspace/workflows/approvals/WorkspaceWorkflowsApprovalsCreatePage.tsx:- Use
useApprovalWorkflows(policy)to computeavailableMembersandusedApproverEmails. - 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
useEffectonce!isEmptyObject(policy)and!shouldShowNotFoundView(preserving any existingmembers/approverson a partialCREATEdraft and forcingisInitialFlow: falsesoDynamicWorkspaceWorkflowsApprovalsExpensesFromPage.tsx:468-472does 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>)}.
- Use
- Clear the draft on modal dismiss in
WorkspaceWorkflowsApprovalsCreatePage.tsxand on rules-based workflow actions insrc/libs/actions/Workflow.ts:- In
WorkspaceWorkflowsApprovalsCreatePage.tsx:107, updateHeaderWithBackButton'sonBackButtonPressto callclearApprovalWorkflow()beforeNavigation.dismissModal()(avoiding an unmountuseEffectthat would wipe the draft when navigating toExpensesFrom/Approversub-pages or under React StrictMode). - In
src/libs/actions/Workflow.ts, callclearApprovalWorkflow()increateApprovalWorkflowRules,updateApprovalWorkflowRules, andremoveApprovalWorkflowRules.
- In
- Add unit tests in
tests/ui/WorkspaceWorkflowsApprovalsCreatePageTest.tsxandtests/actions/WorkflowTest.ts:- Verify direct entry with
ONYXKEYS.APPROVAL_WORKFLOWunset (null), with a partial fragment, and with a staleEDITdraft on a DEW workspace (dynamicExternalWorkflowHidePeople: falseandtrue).
- Verify direct entry with
What alternative solutions did you explore? (Optional)
- Clearing
ONYXKEYS.APPROVAL_WORKFLOWin an unmountuseEffect: Discarded because navigating to sub-pages (ExpensesFrom/Approver) or<StrictMode>remounts would wipe an active creation draft. - Redirecting
/workflows/approvals/newtoExpensesFrom: Discarded because/workflows/approvals/newis a valid direct entry route (used byWorkspaceMemberDetailsPage) and reloading should keep the user on the creation form.
@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 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!