[$250] [Sentry: APP-PPW] TrackExpense submits empty draft expense and returns 666 (Missing currency)
Problem
APP-PPW reports Expense API Error: TrackExpense returned 666.
- Impact: 1 user, 24 events.
- Platform: web, Chrome on Windows.
- Release:
[email protected]. - Route:
/search(Search_Root). - First seen: 2026-11-28 02:07 UTC.
Production logs show an empty expense submitted alongside a populated expense. The empty request omits currency and amount and has blank merchant/date/comment with no receipt. Auth returns 402 Missing currency, which PHP wraps as 666. This does not establish loss of the populated expense.
First-party frames
src/libs/actions/OnyxUpdates.ts:160βtrackExpenseApiErrorsrc/libs/telemetry/trackExpenseCreationError.ts:145βSentry.captureMessage
Likely cause
useOptimisticDraftTransactions includes every truthy draft when multiple drafts exist. useTrackExpenseSubmission submits each without validating currency or draft completeness.
A leftover partial draft is the suspected trigger; its origin has not been reproduced.
Suggested fix
Skip or clean up unintended partial drafts before submission, while preserving legitimate receipt-only scan drafts. Add regression coverage for a valid expense submitted while a partial draft exists.
Upwork Automation - Do Not Edit
- Upwork Job URL: https://www.upwork.com/jobs/~022127208736416002640
- Upwork Job ID: 2127208736416002640
- Last Price Increase: 2026-12-01
Issue Owner
Current Issue Owner: @Eskalifer1
Triggered auto assignment to Contributor-plus team member for initial proposal review - @Eskalifer1 (External)
Job added to Upwork: https://www.upwork.com/jobs/~022127208736416002640
Proposal
Please re-state the problem that we are trying to solve in this issue.
On web, when more than one draft transaction exists in Onyx, tracking an expense can also submit a leftover empty draft (no amount, currency, merchant, date or receipt) as its own TrackExpense request. Auth rejects that request with 402 Missing currency, which is wrapped as 666 and reported as an expense API error.
What is the root cause of that problem?
The submit path does not check whether a draft is complete. In current main:
src/hooks/useOptimisticDraftTransactions.tsswitches to everyTRANSACTION_DRAFTvalue as soon as there is more than one, and the only filter it applies is truthiness:
A stale or partial draft object therefore counts as a real item.const allTransactions = optimisticTransactions && optimisticTransactions.length > 1 ? optimisticTransactions : [transaction]; const transactions = allTransactions.filter((value): value is Transaction => !!value);useConfirmationTransactionPagershows it, and it is passed down astransactions.- In
useTrackExpenseSubmission.ts,trackExpense()loops overtransactions.entries()and callstrackExpenseIOUActionsfor each item. Its upfront checks cover only the participant and, for CATEGORIZE/SHARE/SUBMIT, the linked tracked expense. Nothing checks currency or completeness, so the empty draft goes out withcurrency: undefined.
What I could not confirm: where the partial draft comes from in the first place. Like the issue says, I have not reproduced its creation and won't claim a specific origin. One detail that may be relevant: 24 events from a single user suggests the stub survives the cleanup that runs after a submit. That cleanup removes draftTransactionIDs, which validTransactionDraftIDsSelector builds from each draft's transactionID field, not from its Onyx key. So a stub written under a transactionsDraft_<id> key without its own transactionID (for example, a late Onyx.merge into a draft that was already removed) would never be cleaned up. That is a hypothesis to verify, not a proven cause.
What changes do you think we should make in order to solve the problem?
- Add one shared helper, for example
isUsableDraftTransaction(draft)inTransactionUtils. It returns false only for real empty shells, which means all of the following are missing: a currency, a non-zero amount, a receipt (receipt?.source, or a receipt file in progress), and atransactionID. This criterion is deliberately narrow, so receipt-only SmartScan drafts (amount 0, filled in later) and distance/per-diem drafts are kept. - Filter in
useOptimisticDraftTransactionswith that helper before thelength > 1check. Then one valid draft plus one empty shell falls back to the single-transaction path, and the empty shell no longer shows as an extra page on the confirmation pager. I'd check the other callers (the scan components,useParticipantSubmission,useReportPickerActions) so their behavior only changes for empty shells. - Guard at submit time. In
useTrackExpenseSubmission.trackExpense(), and in the matching loop inuseRequestMoneySubmissionthat reads the sametransactions, skip any item that fails the helper andLog.warnits key/transactionID. This is defense in depth, and the log will show where these drafts come from. - Make cleanup remove the shell. Pass the skipped drafts' Onyx keys (or derive
draftTransactionIDsfrom the collection keys rather thandraft.transactionID) socleanupAfterExpenseCreate/removeDraftTransactionsByIDsactually removes them and they don't come back on the next confirmation. - Tests
useOptimisticDraftTransactions: (a) one valid draft plus one empty draft returns only the valid one, (b) one valid draft plus one receipt-only scan draft returns both, (c) two valid drafts return both.- In the existing
tests/unit/hooks/useTrackExpenseSubmission.test.ts, assert thattrackExpenseis called exactly once when a valid expense is submitted while an empty draft exists. This is the regression case the issue asks for.
What alternative solutions did you explore? (Optional)
- Validating only inside
trackExpenseIOUActions. This stops the API error, but the empty draft still shows up as an extra row/page on the confirmation screen and is never cleaned up, so the hook-level filter is the better fix. - Defaulting a missing currency (for example, to the user's local currency). I rejected this because it would quietly create a junk $0 expense instead of dropping the stub.
AI disclosure: I used AI-assisted tooling to investigate the code and draft this proposal, and I reviewed it myself against current main. I'll write and test the implementation myself if I'm assigned.
π£ @mathewtimeus-collab! π£ 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>
Proposal
Please re-state the problem that we are trying to solve in this issue.
On web (seen on /search), submitting a TrackExpense flow when multiple entries exist in ONYXKEYS.COLLECTION.TRANSACTION_DRAFT can submit a leftover empty partial draft alongside the real expense (missing currency and amount, blank merchant/date/comment, no receipt). Auth rejects the empty request with 402 Missing currency, which PHP wraps as 666 (APP-PPW), and a single user hit this repeatedly across submissions.
What is the root cause of that problem?
Three linked gaps allow partial/placeholder drafts in COLLECTION.TRANSACTION_DRAFT to survive cleanup and enter TrackExpense:
- Unintended drafts live in
COLLECTION.TRANSACTION_DRAFTand can evaderemoveDraftTransactionsByIDscleanup:/searchbulk edit (initBulkEditDraftTransactioninsrc/libs/actions/IOU/BulkEdit.ts) writes{transactionID: CONST.IOU.OPTIMISTIC_BULK_EDIT_TRANSACTION_ID, selectedTransactionIDs}intoCOLLECTION.TRANSACTION_DRAFTwith nocurrency/amount/receipt.- Delayed
Onyx.mergeupdates (such as receipt failure resets or flag setters after a draft removal) can also leave entries withoutdraft.transactionID. - In
src/selectors/TransactionDraft.ts,validTransactionDraftIDsSelectorreadsdraft.transactionIDinstead of falling back to the Onyx key suffix (transactionsDraft_<id>). When a partial draft lacksdraft.transactionID, the selector returnsundefined, soremoveDraftTransactionsByIDsnever removestransactionsDraft_<id>and the stub persists across subsequent expense creations.
useOptimisticDraftTransactionscheckslength > 1before validating drafts (src/hooks/useOptimisticDraftTransactions.ts):- As soon as one valid draft and one partial or bulk-edit draft coexist,
optimisticTransactions.length > 1becomes true and only filters truthiness (Boolean), passing the partial draft to the confirmation list and submission hook.
- As soon as one valid draft and one partial or bulk-edit draft coexist,
useTrackExpenseSubmissioniterates and submits unvalidated drafts (src/pages/iou/request/step/confirmation/submission/useTrackExpenseSubmission.ts):trackExpense()loops throughtransactions.entries()without skipping partial drafts lacking bothcurrencyand a validreceipt, forwarding them straight intotrackExpenseIOUActions.
What changes do you think we should make in order to solve the problem?
- Centralize draft validity and fix ID selection in
src/selectors/TransactionDraft.ts:- Export
isValidTransactionDraft(draft, receipt?): returnsfalseif!draft?.transactionIDordraft.transactionID === CONST.IOU.OPTIMISTIC_BULK_EDIT_TRANSACTION_ID; otherwise returnstruewhen the draft has a non-emptycurrencyOR a valid attached receipt (checking bothreceiptFiles[id],draft.receiptnon-empty properties,hasReceiptSource, andhasReceipt, while rejecting cleared empty receipt objects like{source: '', filename: '', type: ''}). This keeps legitimate receipt-only SmartScan drafts (amount: 0, filled later or scanned server-side) intact. - Update
validTransactionDraftIDsSelectorto readObject.entries(drafts ?? {})and fall back to theONYXKEYS.COLLECTION.TRANSACTION_DRAFTkey suffix whendraft.transactionIDis missing so cleanup removes orphaned stubs. - Update
validTransactionDraftsSelectorto skip entries withoutdraft.transactionIDorCONST.IOU.OPTIMISTIC_BULK_EDIT_TRANSACTION_ID.
- Export
- Filter before the multi-draft check in
src/hooks/useOptimisticDraftTransactions.ts:- Filter
optimisticTransactionsviaisValidTransactionDraftbefore testingvalidOptimisticTransactions.length > 1, so one valid draft plus one leftover partial/bulk-edit draft cleanly falls back to[transaction].
- Filter
- Guard and clean up skipped drafts in
src/pages/iou/request/step/confirmation/submission/useTrackExpenseSubmission.ts:- Partition
transactionsusingisValidTransactionDraft(item, receiptFiles[item.transactionID])intosubmittableTransactionsandskippedDraftTransactionIDs. Return early ifsubmittableTransactions.length === 0. - Use
submittableTransactionsfor the linked-tracked check,shouldDeferAutoSubmitForBatchItem, thetrackExpenseIOUActionsloop, andperformPostBatchCleanup({transactions: submittableTransactions, ...}). - Merge
skippedDraftTransactionIDsintocleanupDraftTransactionIDspassed totrackExpenseIOUActionsandperformPostBatchCleanupso skipped stubs are cleaned up on completion, and ensure legitimate receipt-only scan drafts missing currency/amount safely default toamount: item.amount ?? 0andcurrentUserLocalCurrency.
- Partition
- Tests:
- Add
tests/unit/selectors/TransactionDraftTest.tsandtests/unit/hooks/useOptimisticDraftTransactions.test.ts. - Extend
tests/unit/hooks/useTrackExpenseSubmission.test.tswith regression cases covering: a populated expense alongside an empty partial draft (asserts 1 call and cleanup of both IDs), a bulk-edit placeholder draft, receipt-only scan drafts without currency, and an all-partial batch no-op.
- Add
What alternative solutions did you explore? (Optional)
- Defaulting missing
currencyunconditionally intrackExpense()would still turn empty partial stubs into unintended$0expenses. - Filtering only inside
useTrackExpenseSubmissionwould still expose empty stubs as extra confirmation pager entries if multiple drafts are loaded; sharingisValidTransactionDraftacross the hook and submission path addresses both layers cleanly.
π£ @ryancooper312! π£ 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>
Proposal
Please re-state the problem that we are trying to solve in this issue.
When submitting a tracked expense via TrackExpense on the confirmation step, an unintended empty/partial draft transaction (missing currency and amount, with blank merchant/created/comment and no receipt) can be submitted alongside a populated expense. Auth rejects the empty request with 402 Missing currency, wrapped by PHP as a 666 error (Sentry: APP-PPW).
What is the root cause of that problem?
- In
useOptimisticDraftTransactions.ts, whenever more than one entry exists inONYXKEYS.COLLECTION.TRANSACTION_DRAFT, every truthy object (!!value) is returned without checking whether the draft is actually populated or valid:
A stale/partial leftover draft in Onyx therefore enters theconst allTransactions = optimisticTransactions && optimisticTransactions.length > 1 ? optimisticTransactions : [transaction]; const transactions = allTransactions.filter((value): value is Transaction => !!value);transactionsarray passed into the confirmation step (useConfirmationTransactionPager.ts). - In
useTrackExpenseSubmission.ts,trackExpenseiterates directly over every item intransactions(L182) and passesitem.currency,item.amount,item.merchant,item.created, andreceiptFiles[item.transactionID]directly totrackExpenseIOUActions(L212-L292) without filtering out incomplete/empty drafts that lack a validcurrencyor expense payload.
What changes do you think we should make in order to solve the problem?
-
Add a pure, reusable draft-validation helper (e.g.,
isValidTrackExpenseDraftinsrc/pages/iou/request/step/confirmation/submission/utils/) that distinguishes submittable tracked expense drafts from empty/partial leftover drafts while explicitly preserving legitimate receipt-only SmartScan drafts:- A draft is invalid/empty and should be skipped if:
!item.currency(sinceTrackExpensestrictly requirescurrencyand returns402 Missing currencywithout it), OR- It has no receipt (
!receiptFiles[item.transactionID] && !hasReceipt(item)) and no populated core expense fields (item.amount === undefined && !item.merchant && !item.created && !item.comment?.comment?.trim()).
- A legitimate receipt-only scan draft (which has
receiptFiles[item.transactionID]orhasReceipt(item)and a validcurrency, even whenamount === 0andmerchant/commentare empty) passes validation and is preserved.
function isValidTrackExpenseDraft(item: Transaction, receiptFiles: Record<string, Receipt>): boolean { if (!item.currency) { return false; } const hasAttachedReceipt = !!receiptFiles[item.transactionID] || hasReceipt(item); if (hasAttachedReceipt) { return true; } const hasExpenseDetails = item.amount !== undefined || !!item.merchant?.trim() || !!item.created || !!item.comment?.comment?.trim(); return hasExpenseDetails; } - A draft is invalid/empty and should be skipped if:
-
Filter out and clean up unintended partial drafts upfront in
useTrackExpenseSubmission.ts:- Partition
transactionsat the start oftrackExpenseintovalidTransactionsandinvalidTransactionsusingisValidTrackExpenseDraft(item, receiptFiles). - If
validTransactions.length === 0, remove any leftoverinvalidTransactionsfrom Onyx draft storage (removeDraftTransaction/removeDraftTransactions) and return early without issuing anyTrackExpenseAPI call. - Run
requiresLinkedTracked, the submissionfor (const [index, item] of validTransactions.entries())loop, andshouldDeferAutoSubmitForBatchItem(index < validTransactions.length - 1) exclusively againstvalidTransactionsβ this also prevents a trailing empty draft from falsely settinghasNextItem: trueand deferring auto-submit on the last valid expense. - Ensure
invalidTransactionsare also cleaned up in Onyx alongsidevalidTransactions(viaperformPostBatchCleanupreceiving the fulltransactionslist or explicitly clearing skipped draft IDs) so the stale partial draft does not persist into subsequent submissions.
- Partition
What specific scenarios should we cover in automated tests to prevent reintroducing this issue in the future?
Add unit / regression tests (e.g., in tests/unit/useTrackExpenseSubmissionTest.ts or alongside existing confirmation submission tests) covering:
- Valid expense + empty partial draft in
transactions: Only the valid expense invokestrackExpenseIOUActions, the empty draft (missingcurrency/amount/receipt) is skipped and cleaned up from draft storage, andshouldDeferAutoSubmitForBatchItemtreats the valid expense as the last item (hasNextItem: false). - Legitimate receipt-only SmartScan draft: A draft with
currency+ attached receipt (receiptFiles[transactionID]oritem.receipt.source) andamount: 0, blankmerchant/commentIS submitted normally. - Only empty/partial draft(s) present:
trackExpenseIOUActionsis not called at all, and the stray partial draft is cleaned up. - Multiple valid expenses (mixed manual + receipt-only scan) + leftover partial draft: Both valid expenses submit cleanly while the partial draft is skipped and purged.
What alternative solutions did you explore? (Optional)
- Filtering inside
useOptimisticDraftTransactionsdirectly: Considered filtering incomplete drafts insideuseOptimisticDraftTransactions, which is shared across intermediate IOU creation steps. However, drafts may legitimately be partially populated during earlier wizard steps before reaching confirmation, so filtering globally there risks breaking intermediate flows. Filtering and purging stale partial drafts at submission time inuseTrackExpenseSubmission(with a reusable helper that can also be shared byuseRequestMoneySubmissionif needed) is tightly scoped, safe, and directly cleans up stale Onyx drafts.
π£ @StoneFancyX! π£ 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/~0155f07601958509cf
β Contributor details stored successfully. Thank you for contributing to Expensify!
Proposal
Please re-state the problem that we are trying to solve in this issue.
When submitting a tracked expense via TrackExpense on the confirmation step, an unintended empty/partial draft transaction (missing currency and amount, with blank merchant/created/comment and no receipt) can be submitted alongside a populated expense. Auth rejects the empty request with 402 Missing currency, wrapped by PHP as a 666 error (Sentry: APP-PPW).
What is the root cause of that problem?
- In
useOptimisticDraftTransactions.ts, whenever more than one entry exists inONYXKEYS.COLLECTION.TRANSACTION_DRAFT, every truthy object (!!value) is returned without checking whether the draft is actually populated or valid:
A stale/partial leftover draft in Onyx therefore enters theconst allTransactions = optimisticTransactions && optimisticTransactions.length > 1 ? optimisticTransactions : [transaction]; const transactions = allTransactions.filter((value): value is Transaction => !!value);transactionsarray passed into the confirmation step (useConfirmationTransactionPager.ts). - In
useTrackExpenseSubmission.ts,trackExpenseiterates directly over every item intransactions(L182) and passesitem.currency,item.amount,item.merchant,item.created, andreceiptFiles[item.transactionID]directly totrackExpenseIOUActions(L212-L292) without filtering out incomplete/empty drafts that lack a validcurrencyor expense payload.
What changes do you think we should make in order to solve the problem?
-
Add a pure, reusable draft-validation helper (e.g.,
isValidTrackExpenseDraftinsrc/pages/iou/request/step/confirmation/submission/utils/) that distinguishes submittable tracked expense drafts from empty/partial leftover drafts while explicitly preserving legitimate receipt-only SmartScan drafts:- A draft is invalid/empty and should be skipped if:
!item.currency(sinceTrackExpensestrictly requirescurrencyand returns402 Missing currencywithout it), OR- It has no receipt (
!receiptFiles[item.transactionID] && !hasReceipt(item)) and no populated core expense fields (item.amount === undefined && !item.merchant && !item.created && !item.comment?.comment?.trim()).
- A legitimate receipt-only scan draft (which has
receiptFiles[item.transactionID]orhasReceipt(item)and a validcurrency, even whenamount === 0andmerchant/commentare empty) passes validation and is preserved.
function isValidTrackExpenseDraft(item: Transaction, receiptFiles: Record<string, Receipt>): boolean { if (!item.currency) { return false; } const hasAttachedReceipt = !!receiptFiles[item.transactionID] || hasReceipt(item); if (hasAttachedReceipt) { return true; } const hasExpenseDetails = item.amount !== undefined || !!item.merchant?.trim() || !!item.created || !!item.comment?.comment?.trim(); return hasExpenseDetails; } - A draft is invalid/empty and should be skipped if:
-
Filter out and clean up unintended partial drafts upfront in
useTrackExpenseSubmission.ts:- Partition
transactionsat the start oftrackExpenseintovalidTransactionsandinvalidTransactionsusingisValidTrackExpenseDraft(item, receiptFiles). - If
validTransactions.length === 0, remove any leftoverinvalidTransactionsfrom Onyx draft storage (removeDraftTransaction/removeDraftTransactions) and return early without issuing anyTrackExpenseAPI call. - Run
requiresLinkedTracked, the submissionfor (const [index, item] of validTransactions.entries())loop, andshouldDeferAutoSubmitForBatchItem(index < validTransactions.length - 1) exclusively againstvalidTransactionsβ this also prevents a trailing empty draft from falsely settinghasNextItem: trueand deferring auto-submit on the last valid expense. - Ensure
invalidTransactionsare also cleaned up in Onyx alongsidevalidTransactions(viaperformPostBatchCleanupreceiving the fulltransactionslist or explicitly clearing skipped draft IDs) so the stale partial draft does not persist into subsequent submissions.
- Partition
What specific scenarios should we cover in automated tests to prevent reintroducing this issue in the future?
Add unit / regression tests (e.g., in tests/unit/useTrackExpenseSubmissionTest.ts or alongside existing confirmation submission tests) covering:
- Valid expense + empty partial draft in
transactions: Only the valid expense invokestrackExpenseIOUActions, the empty draft (missingcurrency/amount/receipt) is skipped and cleaned up from draft storage, andshouldDeferAutoSubmitForBatchItemtreats the valid expense as the last item (hasNextItem: false). - Legitimate receipt-only SmartScan draft: A draft with
currency+ attached receipt (receiptFiles[transactionID]oritem.receipt.source) andamount: 0, blankmerchant/commentIS submitted normally. - Only empty/partial draft(s) present:
trackExpenseIOUActionsis not called at all, and the stray partial draft is cleaned up. - Multiple valid expenses (mixed manual + receipt-only scan) + leftover partial draft: Both valid expenses submit cleanly while the partial draft is skipped and purged.
What alternative solutions did you explore? (Optional)
- Filtering inside
useOptimisticDraftTransactionsdirectly: Considered filtering incomplete drafts insideuseOptimisticDraftTransactions, which is shared across intermediate IOU creation steps. However, drafts may legitimately be partially populated during earlier wizard steps before reaching confirmation, so filtering globally there risks breaking intermediate flows. Filtering and purging stale partial drafts at submission time inuseTrackExpenseSubmission(with a reusable helper that can also be shared byuseRequestMoneySubmissionif needed) is tightly scoped, safe, and directly cleans up stale Onyx drafts.
Contributor details Your Expensify account email: [email protected] Upwork Profile Link: https://www.upwork.com/freelancers/~01a25f60a005b11ebf
β Contributor details stored successfully. Thank you for contributing to Expensify!
Withdrawing my proposal here as I won't be able to take this on β please feel free to proceed with other contributors. Thanks!
@MelvinBot post proposal for this issue
Proposal
What is the root cause of that problem?
The confirmation flow treats the entire draft collection as one expense batch whenever multiple drafts exist, filtering only falsy values. An empty draft therefore joins the populated expense.
Track submission then submits every batch item without validating currency. The empty itemβs missing fields reach TrackExpense, consistent with the Missing currency response documented in this issue.
The empty draftβs origin remains unverified. This proposal addresses its admission into submission, not a confirmed draft-creation race.
Code evidence
- useOptimisticDraftTransactions.ts:15β23: expands the collection into the batch.
- useTrackExpenseSubmission.ts:146β241: iterates every item and forwards its amount and currency.
- TrackExpense.ts:3038β3060: constructs API parameters without supplying missing currency.
What changes do you think we should make in order to solve the problem?
- Partition drafts at confirmation, not throughout the wizard. Exclude only additional drafts matching the reported empty shape: absent amount/currency, blank merchant/date/comment, and no receipt or other expense payload. Preserve the initial/current draft, zero amounts, receipt-bearing drafts, distance/per-diem data, and unfamiliar fields rather than assuming they are disposable.
- Validate before submission or dismissal. If a retained draft lacks required currency, stop before any writes, preserve the drafts, and surface a recoverable validation error. Do not silently discard meaningful expenses or invent currency.
- Use the retained batch consistently for the pager, submission loop, final-item auto-submit handling, and post-submit metadata.
- Clean up by actual storage keys. After successful submission, remove submitted drafts and excluded empty extras using captured collection-key IDsβnot potentially missing embedded IDs. Do not delete drafts during rendering or failed validation.
Implementation locations and regression tests
Use the confirmation-specific useConfirmationTransactionPager.ts:25β36, leaving intermediate wizard consumers unchanged.
Validation must also precede the dismissal path in SubmitExpenseOrchestrator.tsx:478β484.
The existing cleanup selector trusts embedded IDs: TransactionDraft.ts:13β19.
Regression coverage:
- Valid expense plus empty extra, in either order: exactly one submission.
- Empty extra with/without embedded ID: correct storage-key cleanup.
- Receipt-only scans, zero/negative amounts, distance and per-diem drafts remain intact.
- Meaningful missing-currency draft: no writes, dismissal, or cleanup.
- Two valid expenses plus empty extra: correct final-item auto-submit behavior.
What alternative solutions did you explore? (Optional)
- Global completeness filtering: risks hiding legitimately incomplete wizard drafts.
- Defaulting missing currency: masks malformed input and can create unintended expenses.
- Submission-loop-only filtering: leaves the pager, batch bookkeeping, and cleanup inconsistent.
Confidence: Medium; code-supported mechanism, without a reproduced origin for the production draft.
Next Steps for Contributor+ team:
To accept: @MelvinBot implement [this](https://github.com/Expensify/App/issues/108281) to create a draft PR.
To refine: @MelvinBot <your feedback>
To reject: Explain why you are rejecting Melvin's proposal.
@MelvinBot Do you have likely steps to repro this one? Try to find them
π€ Web test steps verification results: β fail
Both candidate scenarios require same-account two-tab orchestration, which the available browser-testing tool does not support. Neither was executed; these are code-supported candidate steps, not confirmed reproductions.
| Step | Status |
|---|---|
Candidate 1: introduce bulk edit after preparing an expense1. Open two browser tabs signed into the same account.2. In tab A, prepare a valid manual personal expense and leave confirmation open. 3. In tab B, select two editable expenses in Search and choose Edit multiple. 4. Leave that panel open without changing anything. 5. Return to A and submit. Check for an extra pager item and a second TrackExpense request missing amount/currency. Why plausible: opening bulk edit writes an amount/currency-free placeholder into the shared draft collection; its cleanup runs on panel unmount. See BulkEdit.ts:944β968. Not verified: cross-tab propagation, submission, or error. |
β |
Candidate 2: recreate an ID-less draft from a still-open bulk editor β strongest match for repeated failures1. In tab B, open Edit multiple for two expenses.2. In tab A, start a new personal expense and reach confirmation. Starting this flow should clear Bβs original draft. 3. Return to B without reopening its panel. Type a character into Merchant, then erase it completely. Do not save or dismiss. 4. Return to A and submit. 5. Create another expense to check whether the empty extra persists. Why plausible: the merchant handler merges into the bulk-edit key without restoring transactionID, potentially recreating it as an empty-merchant shell. Cleanup reads embedded IDs rather than storage keys, so that shell could survive. See SearchEditMultiplePage.tsx:319β325 and TransactionDraft.ts:13β19. Not verified: whether the cleared editor remains interactive or produces the reported request. |
β |
I was not able to repro this one. I think this is happening in one tab and we already have 60 events in a couple of days. I'm gonna open it for external contributors, maybe someone will find reliable steps to reproduce this one.
Note for contributors: In order for your proposal to be selected you should be able to repro the bug and add steps to reproduce
π¨ Edited by proposal-police: This proposal was edited at 2026-12-01 19:20:09 UTC.
Proposal
Please re-state the problem that we are trying to solve in this issue.
When an expense is created, a second, empty "expense" can be sent with it: TrackExpense with no amount, currency, merchant, date, comment or receipt. The server rejects it with 402 Missing currency (666). We need the confirmation step to send only the expenses the user is actually creating, keep real receipt-only scan drafts working, and stop leftover drafts from building up in the first place.
What is the root cause of that problem?
The confirmation step decides what to send from the whole draft collection. If more than one draft exists, it takes every truthy one:
https://github.com/Expensify/App/blob/11696bb3c5afb092f27d7e0c6053c4f30874be63/src/hooks/useOptimisticDraftTransactions.ts#L15-L24
https://github.com/Expensify/App/blob/11696bb3c5afb092f27d7e0c6053c4f30874be63/src/pages/iou/request/step/confirmation/submission/useTrackExpenseSubmission.ts#L182
So any draft that isn't part of this expense becomes a second request. There are two ways such a draft ends up in the collection.
1. Bulk edit keeps its own draft in the same collection. Search > select > Edit multiple stores {transactionID: 'optimisticBulkEditTransactionID', selectedTransactionIDs} as a transaction draft. That is exactly the empty request in the logs: no amount, currency, merchant, date, comment or receipt.
https://github.com/Expensify/App/blob/11696bb3c5afb092f27d7e0c6053c4f30874be63/src/libs/actions/IOU/BulkEdit.ts#L950-L962
It's only removed in the bulk edit page's unmount cleanup:
https://github.com/Expensify/App/blob/11696bb3c5afb092f27d7e0c6053c4f30874be63/src/pages/Search/SearchEditMultiple/SearchEditMultiplePage.tsx#L224-L228
Its value has a matching transactionID, so clearMoneyRequest also removes it the next time an expense is started. That means a copy left by a closed tab can't reach a submit. It reaches one when it's created while an expense flow is already open: Onyx keeps tabs in sync on web, so opening Edit multiple in a second tab while the confirmation page is open in the first adds it to the first tab's list. The issue's route is /search, which is where bulk edit lives.
2. Leftover drafts can't be cleaned up when their value has no transactionID. Starting a new expense clears the old drafts using IDs from this selector:
https://github.com/Expensify/App/blob/11696bb3c5afb092f27d7e0c6053c4f30874be63/src/selectors/TransactionDraft.ts#L13-L19
It reads draft.transactionID from the value, not the Onyx key. Actions write into drafts with Onyx.merge (there are 32 such calls under src/libs/actions). A merge that lands after a draft was removed recreates the key with only the merged fields and no transactionID. For that draft the selector returns undefined, so clearMoneyRequest removes transactionsDraft_undefined, and the real key survives every future cleanup:
https://github.com/Expensify/App/blob/11696bb3c5afb092f27d7e0c6053c4f30874be63/src/libs/actions/TransactionEdit.ts#L117-L132
From then on, every expense flow sees "more than one draft" and sends that leftover too. That fits 24 events from one user: the leftover is still there on every submit.
useOptimisticDraftTransactions is shared by the confirmation pager, participant selection, the report picker and the submission, so the same leftover also shows up and gets sent in the Submit and Split paths, not only Track.
What changes do you think we should make in order to solve the problem?
Fix it on both sides: never treat a non-expense draft as part of the expense, and make sure every leftover can actually be cleaned up.
- One definition of "a draft of this expense flow", in
src/selectors/TransactionDraft.ts, built from the Onyx key:
/** A draft belongs to an expense flow when it's stored under its own transactionID. Bulk edit's draft and fragments recreated by a late merge don't. */
function isExpenseFlowDraft(key: string, draft: OnyxEntry<Transaction>): draft is Transaction {
const transactionID = key.replace(ONYXKEYS.COLLECTION.TRANSACTION_DRAFT, '');
return !!draft && draft.transactionID === transactionID && transactionID !== CONST.IOU.OPTIMISTIC_BULK_EDIT_TRANSACTION_ID;
}
-
useTransactionDraftValuesreturns onlyisExpenseFlowDraftentries. SouseOptimisticDraftTransactionsfalls back to the current transaction when the only "other" draft is bulk edit's or a fragment, and all seven callers (confirmation pager, participant selection, participant submission, report picker and the three scan components) see the same correct list. -
Cleanup by key, so nothing can get stuck.
validTransactionDraftIDsSelectorreturns the key suffix of every draft, instead ofdraft.transactionID:
const validTransactionDraftIDsSelector = (drafts: OnyxCollection<Transaction>): string[] =>
Object.entries(drafts ?? {}).reduce<string[]>((acc, [key, draft]) => {
const transactionID = key.replace(ONYXKEYS.COLLECTION.TRANSACTION_DRAFT, '');
if (draft) {
acc.push(transactionID);
}
return acc;
}, []);
startMoneyRequest / initMoneyRequest and the post-submit cleanup already remove every ID this returns, so a fragment is now deleted the next time any expense is started or created. validTransactionDraftsSelector gets the same key-based change.
Bulk edit's draft stays in the cleanup list, as it is today, so a copy left by a closed tab is still removed the next time an expense is started. It's only kept out of the list of expenses to show and send.
- Last guard before the request. Before the submission loop, drop a transaction with no
currencyand log it, instead of sending a request the server will reject. It's filtered before the loop, not skipped inside it, sonextTransaction/hasNextItemfor auto-submit deferral are computed on the list that is really sent:
const submittableTransactions = transactions.filter((item) => {
if (item.currency) {
return true;
}
Log.warn('[useTrackExpenseSubmission] Skipped a draft without currency', {transactionID: item.transactionID});
return false;
});
for (const [index, item] of submittableTransactions.entries()) {
const shouldDeferAutoSubmit = shouldDeferAutoSubmitForBatchItem({
nextTransaction: submittableTransactions.at(index + 1),
hasNextItem: index < submittableTransactions.length - 1,
Every real draft gets a currency from initMoneyRequest (overrideCurrency ?? policy outputCurrency ?? personal outputCurrency ?? USD), including receipt-only scan drafts, so this never skips a real expense. It only stops a malformed one if a third source ever appears. useRequestMoneySubmission is the only other submission hook that loops over this transactions list, so it gets the same guard.
Other places and why they are not broken
- Multi-receipt scan drafts are created by
buildOptimisticTransactionAndCreateDraftunder their owntransactionIDwith a currency, so they still count as "more than one draft" and are all submitted. - Receipt-only scan drafts have a currency from
initMoneyRequest, so the guard in step 4 leaves them alone. - Bulk edit itself reads and writes its draft by its fixed key, which none of these changes touch. Its cleanup works the same as today.
- The default draft
1is stored under its own ID, so it passesisExpenseFlowDraft.initMoneyRequeststill keeps it throughshouldExcludeInitialTransaction. startMoneyRequestsets{isFromFloatingActionButton}on draft1beforeinitMoneyRequestfills it. Until then that value has notransactionID, so it isn't counted as a second expense, which is correct. The key-based cleanup still removes it.
Tests
TransactionDraftselectors: a draft whose value has notransactionIDis returned by key, so it can be cleaned up; normal drafts are unchanged;isExpenseFlowDraftis false for bulk edit's draft and for a fragment.useOptimisticDraftTransactions: draft1+ bulk edit draft gives[transaction]; draft1+ a fragment withouttransactionIDgives[transaction]; two real scan drafts give both.useTrackExpenseSubmission(extending its existing test): a populated expense + bulk edit draft makes onetrackExpensecall; a populated expense + a currency-less transaction makes one call and logs; two receipt-only scan drafts make two calls.- Cleanup: after
startMoneyRequest, a fragment key withouttransactionIDis gone.
Manual check on web:
- In tab A, start a tracked expense and stop on the confirmation page.
- In tab B, select expenses in Search > Edit multiple.
- Back in tab A, submit. Only one
TrackExpenseshould be sent, with no666. - Repeat with two receipts dropped onto Search. Two expenses should be sent.
What alternative solutions did you explore? (Optional)
- Only filter drafts without currency at submit. It hides the symptom, but the leftover stays in storage forever, keeps showing up in the confirmation pager and report picker, and grows with every new fragment.
- Skip drafts without
transactionIDin the selectors. That filters them out, but it also means they can never be cleaned up, because cleanup works from the same IDs. - Move bulk edit's draft to its own Onyx key. It's cleaner long term, but it touches every bulk edit page and action. Excluding its fixed ID gives the same safety with a much smaller change.