You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
[Due for payment 2026-09-01] [$250] Edited comment remains in composer after saving #98580
Awaiting PaymentAuto-added when associated PR is deployed to productionBugSomething is broken. Auto assigns a BugZero manager.DailyKSv2ExternalAdded to denote the issue can be worked on by a contributor
Version Number: Reproducible in staging?: Needs Reproduction Reproducible in production?: Needs Reproduction If this was caught during regression testing, add the test name, ID and link from BrowserStack: Email or phone of affected tester (no customers): Logs:https://stackoverflow.com/c/expensify/questions/4856 Expensify/Expensify Issue URL: Issue reported by:@brunovjk Slack conversation (hyperlinked to channel name): #Expensify Bugs
Action Performed:
Open any chat.
Send a message that includes an attachment link / attachment content.
Long press the sent message.
Tap Edit comment.
Edit the comment, especially the attachment link/text.
Save the edited comment.
Expected Result:
The edited comment should save, edit mode should close, and the composer should be cleared.
Actual Result:
The edited comment saves correctly in the chat, but the edited content still remains in the composer. (edited)
Workaround:
Unknown
Platforms:
Select the officially supported platforms where the issue was reproduced:
Inline "edit mode" is driven entirely by whether a persisted Onyx REPORT_ACTIONS_DRAFTS entry exists with message !== undefined (useActiveDraftReportAction.ts:85). Saving an edit runs publishDraft → deleteDraft → clearAllReportActionDrafts(), which wipes that draft and is the only thing that turns edit mode off (useEditMessage.ts:69-92).
On mobile, every keystroke while editing schedules a 1000 ms debouncedsaveReportActionDraft (ComposerWithSuggestions.tsx:553-561). If the user taps Save within ~1 s of their last edit, the clear runs first, then the still-pending debounced save fires and re-persists{message: editedText} — so useActiveDraftReportAction resolves a draft again and edit mode re-opens with the edited content still in the composer.
This is mobile/native-only (matching the iOS-only report): on wide layout the inline editor unmounts on save, which cancels its pending debounce (useDebounce.ts:37-45); the mobile ComposerWithSuggestions stays mounted, so nothing ever cancels the pending save.
Investigation details & evidence chain
User edits the message → onChangeText → updateComment(text, true) schedules debouncedSaveReportActionDraft (1000 ms) (ComposerWithSuggestions.tsx:553-561).
User taps Save → publishDraft → submitEdit(), editReportComment(...), deleteDraft() → stopEditing() + clearAllReportActionDrafts() (Report/index.ts:3529).
ComposerWithSuggestions does not unmount, so its pending debounce is never cancelled/flushed (useDebouncedSaveDraft only cancels on unmount and exposes no cancel/flush).
~1 s later the trailing debounce fires saveReportActionDraft → Onyx.setCollection re-writes {message: editedText} (Report/index.ts:3534).
useActiveDraftReportAction resolves a draft again → provider flips edit mode back ON → composer shows the edited text.
On the "attachment" detail: the race in code is not gated on attachments vs. plain text — both paths schedule the same debounced save. I could not prove attachment-specificity from static code; the most likely explanation is that the edited attachment link is committed by editReportComment normally, and the reporter simply happened to save quickly (inside the 1 s window). This part is medium confidence and worth confirming with a device repro, but it does not change the root cause. A plain-text edit saved within ~1 s should reproduce the same way on iOS.
Testing note: a web reproduction attempt could not open the "Edit comment" menu in the headless harness (no hover/right-click primitive), which is consistent with the bug being narrow-layout-only anyway.
What changes do you think we should make in order to solve the problem?
Cancel (or no-op) the composer's pending debounced saveReportActionDraft the moment editing ends, so a trailing save can't resurrect the cleared draft. Any one of:
Preferred: expose a cancel() from useDebouncedSaveDraft (it's backed by lodash debounce.cancel via useDebounce) and call it in ComposerWithSuggestions when editingState transitions out of EDITING.
Guard the debounced callback so it does not persist a draft when editingState !== EDITING.
Have deleteDraft flush/cancel the composer's pending save before clearAllReportActionDrafts().
What alternative solutions did you explore? (Optional)
Persisting the edit draft synchronously (non-debounced) on save so the clear always wins — rejected as more fragile than simply cancelling the pending save.
Next Steps for Contributor+ team: To accept:@MelvinBot implement [this](https://github.com/Expensify/App/issues/98580) to create a draft PR. To refine:@MelvinBot <your feedback> To reject: Explain why you are rejecting Melvin's proposal.
Please re-state the problem that we are trying to solve in this issue.
After an edited comment is saved on a narrow/native layout, the edit session must close exactly once and the main composer must restore its pre-edit draft. Neither a delayed edit-draft save nor a late native onChangeText event from the just-finished edit may recreate text in the composer.
This is broader than attachment markdown. Attachment-link edits make the race easy to reproduce, but the same boundary is exercised by iOS autocorrection and other native text reconciliation.
What is the root cause of that problem?
There are two independent writes crossing the edit → normal-composer boundary. Cancelling only the edit-draft debounce does not close the second race.
1. The edit lifecycle drops SUBMITTED too early
useComposerSubmit already delays edit submission by one tick to wait for native autocorrection, a mitigation introduced by #90883. It then calls publishDraft().
useEditMessage.publishDraft() currently does this synchronously:
submitEdit() → local edit state becomes SUBMITTED;
editReportComment(...);
deleteDraft() → immediately calls stopEditing() and clearAllReportActionDrafts().
Because React batches the local updates, the useful SUBMITTED barrier can collapse straight to OFF before the persisted Onyx draft has disappeared and before the native input has finished emitting events.
At that point ComposerWithSuggestions.updateComment() routes solely from the currenteditingState:
EDITING on narrow layout → save as a report-action edit draft;
anything else → save as the ordinary REPORT_DRAFT_COMMENT.
So an iOS onChangeText emitted just after Save carries the old edited value, sees editingState === OFF, and is misclassified as a brand-new normal composer draft. The edited comment is already correct in the chat, but that same text now remains in the composer. This is why merely cancelling debouncedSaveReportActionDraft does not fully fix the bug: the late event writes through debouncedSaveComment, a different writer.
The context can also briefly re-arm the edit while the Onyx clear is pending: ReportActionEditMessageContextProvider treats any still-resolved persisted draft as authoritative and turns OFF back into EDITING. Keeping SUBMITTED until the clear is observed prevents that stale snapshot from reopening the same action.
2. A pending edit-draft debounce can outlive the clear
Every narrow edit keystroke schedules debouncedSaveReportActionDraft. clearAllReportActionDrafts() can run before that trailing callback. If the callback fires afterward, it recreates the persisted edit draft and can keep/reopen the edit session.
Therefore this is a two-sided teardown race:
stale debounced edit-draft write after clear;
late native input event misrouted into the normal composer draft after local state becomes OFF.
src/pages/inbox/report/ReportActionCompose/useEditMessage.ts — SUBMITTED is immediately followed by stopEditing() + draft clear.
src/pages/inbox/report/ReportActionCompose/ComposerWithSuggestions.tsx — onChangeText always enters updateComment(), which chooses edit-vs-normal persistence from live editingState.
src/pages/inbox/report/ReportActionEditMessageContext.tsx — persisted draft resolution can re-enable editing while the clear has not propagated.
src/pages/inbox/report/useDebouncedSaveDraft.ts — exposes no cancellation/invalidation operation.
What changes do you think we should make in order to solve the problem?
Make SUBMITTED a real teardown state and invalidate the edit writer:
Separate submitted teardown from Cancel.
Cancel should continue to stop editing and clear the draft immediately.
Save should call submitEdit(), publish the edit, and clear the persisted action draft without immediately calling stopEditing().
Let ReportActionEditMessageContextProvider transition SUBMITTED → OFF only after useActiveDraftReportAction() observes that the persisted draft is gone. While state is SUBMITTED, the still-present snapshot for that same action must not turn the state back to EDITING.
Block native edit events during submitted teardown.
At the very start of ComposerWithSuggestions.updateComment() / onChangeText, if editingState === SUBMITTED, ignore the event entirely: do not call setText, do not update commentRef, and especially do not call debouncedSaveComment.
Once the draft clear is observed and state becomes OFF, useEditComposerToggle performs its existing forced restoration of the pre-edit draftComment and selection.
Invalidate the pending report-action draft debounce before clearing Onyx.
Extend useDebouncedSaveDraft with a scoped cancelPendingSave() (or generation-token invalidation) and reset isSavePending.
Invoke it for the report-action draft writer when Save/Cancel begins and when the edited action ID changes.
Do not cancel the separate normal-comment debounce; unsent normal composer text must retain its existing persistence behavior.
Preserve the existing one-tick autocorrection read.
EDITING → SUBMITTED → persisted draft absent → OFF → restore normal draft.
No event from the old edit session is allowed to become a normal draft in the middle.
What specific scenarios should we cover in automated tests to prevent reintroducing this issue in the future?
Use fake timers plus delayed Onyx/native events:
Type an edit, tap Save, then fire a late onChangeText(editedText) while state is SUBMITTED; verify it neither changes composer text nor writes REPORT_DRAFT_COMMENT.
Delay the Onyx draft clear; verify the same persisted draft cannot change SUBMITTED back to EDITING.
Resolve the clear; verify the state becomes OFF once and the original normal composer draft/selection is restored.
Leave an edit-draft debounce pending at Save, advance timers after the clear, and verify it cannot recreate the action draft.
Repeat with Cancel.
Repeat the Save race with plain text, autocorrected text, and attachment-link markdown.
Preserve a non-empty normal composer draft before editing and verify it is restored byte-for-byte.
Verify wide-layout inline editing and normal unsent-comment debounce behavior are unchanged.
What alternative solutions did you explore? (Optional)
Only cancel the action-draft debounce: incomplete; a late native event after state becomes OFF still writes the edit text through the normal-comment debounce.
Clear the visible composer again after Save: masks the UI but does not prevent the stale normal draft from being persisted.
Increase the existing setTimeout(0) delay: timing-dependent and cannot prove that all native events have arrived.
Keep editing OFF and add value comparisons: fragile for legitimate cases where the pre-edit draft equals part of the edited text. A lifecycle barrier identifies the source session instead of guessing from string equality.
@mukhrr I don't think this one falls under #97935's scope though.
It reproduces on a plain text message with no attachment at all.
The actual sequence: the last keystroke schedules debouncedSaveReportActionDraft (1000ms). Save is tapped 282ms later, so deleteDraft() runs clearAllReportActionDrafts() while that debounce is still pending. The composer is restored correctly at that point - then 524ms after the clear the trailing debounce fires, saveReportActionDraft re-persists the edit draft, and useActiveDraftReportAction resolves a draft again so the provider flips OFF -> EDITING. Edit mode re-opens with the edited text. useDebouncedSaveDraft exposes no cancel, so nothing stops it.
There is no overlap in files or implementation mechanisms, so to be fair, I think I'll remain the C+ and keep reviewing proposals here. I'd still love to see a proposal from you as well.
🚨 Edited by proposal-police: This proposal was edited at 2026-08-14 09:43:51 UTC.
Proposal
Please re-state the problem that we are trying to solve in this issue.
On narrow layout (iOS App, and any narrow client) a message is edited inside the main composer. After tapping Save the chat updates correctly, but about a second later the composer flips back into edit mode still holding the edited text.
What is the root cause of that problem?
Edit mode is not component state — it is derived entirely from a persisted REPORT_ACTIONS_DRAFTS entry whose message !== undefined (useActiveDraftReportAction.ts#L38-L49). So anything that re-writes that draft after Save re-opens the editor.
Nothing cancels the pending write. useDebouncedSaveDraft returns no canceller (L18-L39) and useDebounce only cancels when the debounced instance is re-created or the component unmounts (useDebounce.ts#L37-L45) — and the main composer never unmounts on Save. Up to a second later the trailing call re-persists {message: editedText} (Report/index.ts#L3645-L3664), the resolver sees a draft again, and the provider flips OFF → EDITING and re-seeds the composer (ReportActionEditMessageContext.tsx#L113-L123). Wide layout is safe because the editor is ReportActionItemMessageEdit, which unmounts when the draft clears (ChatMessageContent.tsx#L51).
I built a deterministic repro (narrow layout, real ReportActionCompose, real publishDraft, fake timers) and measured three things that shape the fix:
Right after Save the composer is already correct — edit mode off, composer empty, draft gone. The leftover text appears only when the trailing write lands, which matches the ordering in your trace. Neither the repro nor that trace shows the SUBMITTED → OFF lifecycle contributing, so I would leave it alone.
It is narrow-layout, not iOS. The repro reproduces with the platform mocked as web, so mWeb Chrome/Safari should be added to the affected platforms.
The stale write belongs to a finished edit session, and it can hijack a live one. Because saveReportActionDraft writes with Onyx.setCollection, a late callback replaces the whole collection. Two variants of this exist on main today, and both are worse than the reported symptom: saving and immediately editing another message, and switching straight from one edit target to another without saving — in the second one editingState never leaves EDITING, so the new edit is silently replaced by the previous message's text.
The attachment in the repro steps is not part of the mechanism: editing a link is simply a bulk change followed by an immediate Save, which lands inside the 1000 ms window every time. Plain text reproduces identically.
What changes do you think we should make in order to solve the problem?
Make the pending report-action draft save droppable, and drop it at every edit-session boundary. useDebouncedSaveDraft already tracks isSavePending, so this needs no change to useDebounce's contract — which matters because that hook has many callers, and keeping the change inside the draft-save wrapper limits the blast radius to the two writers that actually need it.
Then drop it in ComposerWithSuggestions on both boundaries — when the session ends, and when the edited action changes:
// src/pages/inbox/report/ReportActionCompose/ComposerWithSuggestions.tsx
+ useEffect(() => {+ if (editingState === CONST.REPORT_ACTION_EDIT_MESSAGE_STATE.EDITING) {+ return;+ }+ cancelSaveReportActionDraft();+ }, [editingState, cancelSaveReportActionDraft]);++ // A pending save belongs to the session that scheduled it: dropping it when the edited action changes+ // stops it from overwriting the draft of the message the user just switched to.+ useEffect(() => {+ cancelSaveReportActionDraft();+ }, [editingReportID, editingReportAction?.reportActionID, cancelSaveReportActionDraft]);
The first effect covers Save, Cancel, Escape, the confirmed empty-message deletion and navigating away, because all of them end the session through stopEditing(). The second covers moving between edit targets, which never passes through OFF.
This loses no work: the report-action writer is created with shouldExecuteOnUnmount = false, so a pending edit-draft save is already discarded on unmount today — dropping it at a session boundary is the same policy applied to the surface that never unmounts. The normal comment draft writer (debouncedSaveComment, a different Onyx key) is untouched, and so is the wide-layout editor's own instance in ReportActionItemMessageEdit.
I verified all three failure modes against the repro — Save inside the debounce window, Save followed immediately by editing another message, and switching edit targets without saving — plus the existing ReportActionComposeTest, ReportActionMessageEditLayoutTest and ReportActionItemMessageEditTest suites, which all still pass.
What specific scenarios should we cover in automated tests to prevent reintroducing this issue in the future?
Narrow layout, edit a message, Save ~300 ms after the last keystroke, then advance past the debounce: REPORT_ACTIONS_DRAFTS stays empty, edit mode stays off, composer stays cleared. Fails on main today.
Same window, but start editing a second message right after Save: the second message's draft survives and the composer keeps its text. Fails on main today.
Type in one edit, then open the edit menu on another message without saving: the pending write from the first session must not replace the second draft. Fails on main today, and is the case a plain "cancel when editing ends" guard misses.
Control: Save more than 1 s after the last keystroke — unchanged behaviour, edit mode closes.
Cancel/Escape inside the window: the discarded text must not come back.
The existing composer/edit suites keep passing — all 30 tests still pass with this change.
Implementation note for whoever writes these: waitForBatchedUpdates calls jest.runOnlyPendingTimers() under fake timers, so using it between the keystroke and Save flushes the very debounce under test and hides the bug. The test has to flush React/Onyx work without running timers in that window.
What alternative solutions did you explore? (Optional)
Cancel only when the state leaves EDITING. Measured: it closes the reported bug and the save-then-edit-another case, but not the target switch — going from one edit straight to another never passes through OFF, so the pending write survives. That is why the second effect above exists.
Guard the debounced callback on editingState !== EDITING. Measured: weaker still — by the time the trailing call fires the state is EDITING again for the new message, so the guard passes and the stale write lands.
A generation token threaded through the hook's arguments, plus an invalidator exposed on the composer ref. Same guarantee as the two effects above, but it changes the saveDraft call signature and adds ref plumbing into useEditMessage; the session boundaries are already observable in the composer, so I would keep the change local.
Keep SUBMITTED through the async clear (drop stopEditing() from the Save path). Measured: on its own it does not fix the bug — the trailing write still lands and re-arms edit mode.
Flush the pending save before clearAllReportActionDrafts(). It writes a draft we are about to delete and makes correctness depend on Onyx write ordering rather than removing the race.
Persist edit drafts synchronously. Reinstates a per-keystroke Onyx write on the exact path the debounce exists to protect.
Inline edit mode is not a piece of component state, it is derived entirely from whether a persisted REPORT_ACTIONS_DRAFTS entry exists with message !== undefined:
When the user hits Save less than CONST.TIMING.DRAFT_SAVE_DEBOUNCE_TIME (1000 ms) after their last keystroke, the order is:
publishDraft → editReportComment(...) (the message saves — which is why the chat looks right) → deleteDraft() → stopEditing() + clearAllReportActionDrafts().
ComposerWithSuggestions stays mounted, so nothing cancels the pending debounce.
The trailing call lands and re-writes {message: editedText} with Onyx.setCollection:
useActiveDraftReportAction resolves a draft again → the provider flips editingState back to EDITING and re-seeds editingMessage with the edited text. The composer is back in edit mode holding what was just saved.
Two details worth spelling out, because they are what make this real rather than theoretical:
The debounce genuinely survives.useDebounce cancels and re-creates its lodash instance whenever func identity changes, and useDebouncedSaveDraftImpl passes an inline arrow — normally that would mean a fresh (cancelled) debounce every render.
It survives because React Compiler memoizes that arrow — which is precisely what the file's own header comment says the non-generic impl exists for. So the pending trailing save really does outlive the save-and-clear.
It is narrow-layout only, matching the iOS-only report. The updateComment edit branch above is gated on shouldUseNarrowLayout, so on wide layout the main composer never schedules an edit-draft save at all; the separate ReportActionItemMessageEdit editor unmounts on save, and useDebounce's unmount cleanup cancels its pending call.
The attachment in the repro steps is not part of the mechanism — the race is content-agnostic. An attachment/link message simply makes it likely in practice: the composer holds long markdown like [url](url), the user makes one small tweak and taps Save immediately, landing well inside the 1 s window. The same thing happens on the cancel (X) path, which also runs deleteDraft.
What changes do you think we should make in order to solve the problem?
Make the pending draft save droppable, and drop it the moment editing ends.
useDebouncedSaveDraft already tracks isSavePending, so the cancel needs no new lodash plumbing and no change to useDebounce's contract (which has many other callers, and whose return value is a bare proxy function with no .cancel() to expose). Turn that ref into the gate for the trailing invocation and add a canceller:
This does not lose any work: useDebouncedSaveDraft(saveReportActionDraft) is created with shouldExecuteOnUnmount = false, so a pending edit-draft save is already discarded when the composer unmounts today. Cancelling on edit-end is consistent with that.
Tests: tests/unit/useDebouncedSaveDraftTest.ts covers the scheduled-then-cancelled trailing call (fails on current main, passes with the change), that an uncancelled save still runs, and that typing after a cancel schedules a fresh save with the newer value.
What alternative solutions did you explore? (Optional)
Guard the debounced callback on editingState !== EDITING instead of cancelling. Rejected: if the user starts editing a different message inside the 1 s window, editingState is EDITING again and the stale trailing call would happily persist the previous action's text. Cancelling is keyed to the specific pending save, so it does not have that hole.
Flush the pending save before clearAllReportActionDrafts(). Rejected: it writes a draft we are about to delete, and leaves the ordering dependent on Onyx write sequencing rather than removing the race.
Persist edit drafts synchronously (no debounce). Rejected: reinstates the per-keystroke Onyx writes the debounce exists to avoid.
Awaiting PaymentAuto-added when associated PR is deployed to productionBugSomething is broken. Auto assigns a BugZero manager.DailyKSv2ExternalAdded to denote the issue can be worked on by a contributor
Activity
MelvinBot commentedon Aug 13, 2026
Proposal
What is the root cause of that problem?
Inline "edit mode" is driven entirely by whether a persisted Onyx
REPORT_ACTIONS_DRAFTSentry exists withmessage !== undefined(useActiveDraftReportAction.ts:85). Saving an edit runspublishDraft → deleteDraft → clearAllReportActionDrafts(), which wipes that draft and is the only thing that turns edit mode off (useEditMessage.ts:69-92).On mobile, every keystroke while editing schedules a 1000 ms debounced
saveReportActionDraft(ComposerWithSuggestions.tsx:553-561). If the user taps Save within ~1 s of their last edit, the clear runs first, then the still-pending debounced save fires and re-persists{message: editedText}— souseActiveDraftReportActionresolves a draft again and edit mode re-opens with the edited content still in the composer.This is mobile/native-only (matching the iOS-only report): on wide layout the inline editor unmounts on save, which cancels its pending debounce (
useDebounce.ts:37-45); the mobileComposerWithSuggestionsstays mounted, so nothing ever cancels the pending save.Investigation details & evidence chain
onChangeText → updateComment(text, true)schedulesdebouncedSaveReportActionDraft(1000 ms) (ComposerWithSuggestions.tsx:553-561).publishDraft→submitEdit(),editReportComment(...),deleteDraft()→stopEditing()+clearAllReportActionDrafts()(Report/index.ts:3529).ComposerWithSuggestionsdoes not unmount, so its pending debounce is never cancelled/flushed (useDebouncedSaveDraftonly cancels on unmount and exposes nocancel/flush).saveReportActionDraft→Onyx.setCollectionre-writes{message: editedText}(Report/index.ts:3534).useActiveDraftReportActionresolves a draft again → provider flips edit mode back ON → composer shows the edited text.On the "attachment" detail: the race in code is not gated on attachments vs. plain text — both paths schedule the same debounced save. I could not prove attachment-specificity from static code; the most likely explanation is that the edited attachment link is committed by
editReportCommentnormally, and the reporter simply happened to save quickly (inside the 1 s window). This part is medium confidence and worth confirming with a device repro, but it does not change the root cause. A plain-text edit saved within ~1 s should reproduce the same way on iOS.Testing note: a web reproduction attempt could not open the "Edit comment" menu in the headless harness (no hover/right-click primitive), which is consistent with the bug being narrow-layout-only anyway.
What changes do you think we should make in order to solve the problem?
Cancel (or no-op) the composer's pending debounced
saveReportActionDraftthe moment editing ends, so a trailing save can't resurrect the cleared draft. Any one of:cancel()fromuseDebouncedSaveDraft(it's backed by lodashdebounce.cancelviauseDebounce) and call it inComposerWithSuggestionswheneditingStatetransitions out ofEDITING.editingState !== EDITING.deleteDraftflush/cancel the composer's pending save beforeclearAllReportActionDrafts().What alternative solutions did you explore? (Optional)
Persisting the edit draft synchronously (non-debounced) on save so the clear always wins — rejected as more fragile than simply cancelling the pending save.
Next Steps for Contributor+ team:
To accept:
@MelvinBot implement [this](https://github.com/Expensify/App/issues/98580)to create a draft PR.To refine:
@MelvinBot <your feedback>To reject: Explain why you are rejecting Melvin's proposal.
melvin-bot commentedon Aug 13, 2026
Triggered auto assignment to Contributor-plus team member for initial proposal review - @daledah (
External)melvin-bot commentedon Aug 13, 2026
Job added to Upwork: https://www.upwork.com/jobs/~022087886721054798286
mukhrr commentedon Aug 13, 2026
coming from #97935 (comment) @youssef-lr mind assigning @brunovjk and me here since we found this during PR and have more context?! thanks cc @brunovjk
melvin's solution doesnt fix it, btw
skrohan5016-coder commentedon Aug 14, 2026
Proposal
Please re-state the problem that we are trying to solve in this issue.
After an edited comment is saved on a narrow/native layout, the edit session must close exactly once and the main composer must restore its pre-edit draft. Neither a delayed edit-draft save nor a late native
onChangeTextevent from the just-finished edit may recreate text in the composer.This is broader than attachment markdown. Attachment-link edits make the race easy to reproduce, but the same boundary is exercised by iOS autocorrection and other native text reconciliation.
What is the root cause of that problem?
There are two independent writes crossing the edit → normal-composer boundary. Cancelling only the edit-draft debounce does not close the second race.
1. The edit lifecycle drops
SUBMITTEDtoo earlyuseComposerSubmitalready delays edit submission by one tick to wait for native autocorrection, a mitigation introduced by #90883. It then callspublishDraft().useEditMessage.publishDraft()currently does this synchronously:submitEdit()→ local edit state becomesSUBMITTED;editReportComment(...);deleteDraft()→ immediately callsstopEditing()andclearAllReportActionDrafts().Because React batches the local updates, the useful
SUBMITTEDbarrier can collapse straight toOFFbefore the persisted Onyx draft has disappeared and before the native input has finished emitting events.At that point
ComposerWithSuggestions.updateComment()routes solely from the currenteditingState:EDITINGon narrow layout → save as a report-action edit draft;REPORT_DRAFT_COMMENT.So an iOS
onChangeTextemitted just after Save carries the old edited value, seeseditingState === OFF, and is misclassified as a brand-new normal composer draft. The edited comment is already correct in the chat, but that same text now remains in the composer. This is why merely cancellingdebouncedSaveReportActionDraftdoes not fully fix the bug: the late event writes throughdebouncedSaveComment, a different writer.The context can also briefly re-arm the edit while the Onyx clear is pending:
ReportActionEditMessageContextProvidertreats any still-resolved persisted draft as authoritative and turnsOFFback intoEDITING. KeepingSUBMITTEDuntil the clear is observed prevents that stale snapshot from reopening the same action.2. A pending edit-draft debounce can outlive the clear
Every narrow edit keystroke schedules
debouncedSaveReportActionDraft.clearAllReportActionDrafts()can run before that trailing callback. If the callback fires afterward, it recreates the persisted edit draft and can keep/reopen the edit session.Therefore this is a two-sided teardown race:
OFF.Relevant code:
src/pages/inbox/report/ReportActionCompose/useComposerSubmit.ts— one-tick native/autocorrection submission bridge.src/pages/inbox/report/ReportActionCompose/useEditMessage.ts—SUBMITTEDis immediately followed bystopEditing()+ draft clear.src/pages/inbox/report/ReportActionCompose/ComposerWithSuggestions.tsx—onChangeTextalways entersupdateComment(), which chooses edit-vs-normal persistence from liveeditingState.src/pages/inbox/report/ReportActionEditMessageContext.tsx— persisted draft resolution can re-enable editing while the clear has not propagated.src/pages/inbox/report/useDebouncedSaveDraft.ts— exposes no cancellation/invalidation operation.What changes do you think we should make in order to solve the problem?
Make
SUBMITTEDa real teardown state and invalidate the edit writer:Separate submitted teardown from Cancel.
submitEdit(), publish the edit, and clear the persisted action draft without immediately callingstopEditing().ReportActionEditMessageContextProvidertransitionSUBMITTED → OFFonly afteruseActiveDraftReportAction()observes that the persisted draft is gone. While state isSUBMITTED, the still-present snapshot for that same action must not turn the state back toEDITING.Block native edit events during submitted teardown.
ComposerWithSuggestions.updateComment()/onChangeText, ifeditingState === SUBMITTED, ignore the event entirely: do not callsetText, do not updatecommentRef, and especially do not calldebouncedSaveComment.OFF,useEditComposerToggleperforms its existing forced restoration of the pre-editdraftCommentand selection.Invalidate the pending report-action draft debounce before clearing Onyx.
useDebouncedSaveDraftwith a scopedcancelPendingSave()(or generation-token invalidation) and resetisSavePending.Preserve the existing one-tick autocorrection read.
This gives the lifecycle a deterministic order:
EDITING → SUBMITTED → persisted draft absent → OFF → restore normal draft.No event from the old edit session is allowed to become a normal draft in the middle.
What specific scenarios should we cover in automated tests to prevent reintroducing this issue in the future?
Use fake timers plus delayed Onyx/native events:
onChangeText(editedText)while state isSUBMITTED; verify it neither changes composer text nor writesREPORT_DRAFT_COMMENT.SUBMITTEDback toEDITING.OFFonce and the original normal composer draft/selection is restored.What alternative solutions did you explore? (Optional)
OFFstill writes the edit text through the normal-comment debounce.setTimeout(0)delay: timing-dependent and cannot prove that all native events have arrived.OFFand add value comparisons: fragile for legitimate cases where the pre-edit draft equals part of the edited text. A lifecycle barrier identifies the source session instead of guessing from string equality.daledah commentedon Aug 14, 2026
@mukhrr I don't think this one falls under #97935's scope though.
It reproduces on a plain text message with no attachment at all.
The actual sequence: the last keystroke schedules
debouncedSaveReportActionDraft(1000ms). Save is tapped 282ms later, sodeleteDraft()runsclearAllReportActionDrafts()while that debounce is still pending. The composer is restored correctly at that point - then 524ms after the clear the trailing debounce fires,saveReportActionDraftre-persists the edit draft, anduseActiveDraftReportActionresolves a draft again so the provider flipsOFF -> EDITING. Edit mode re-opens with the edited text.useDebouncedSaveDraftexposes no cancel, so nothing stops it.There is no overlap in files or implementation mechanisms, so to be fair, I think I'll remain the C+ and keep reviewing proposals here. I'd still love to see a proposal from you as well.
cc @youssef-lr @brunovjk
daledah commentedon Aug 14, 2026
🆘 C+ Help Wanted
Abdulloh0109 commentedon Aug 14, 2026
🚨 Edited by proposal-police: This proposal was edited at 2026-08-14 09:43:51 UTC.
Proposal
Please re-state the problem that we are trying to solve in this issue.
On narrow layout (iOS App, and any narrow client) a message is edited inside the main composer. After tapping Save the chat updates correctly, but about a second later the composer flips back into edit mode still holding the edited text.
What is the root cause of that problem?
Edit mode is not component state — it is derived entirely from a persisted
REPORT_ACTIONS_DRAFTSentry whosemessage !== undefined(useActiveDraftReportAction.ts#L38-L49). So anything that re-writes that draft after Save re-opens the editor.On narrow layout every keystroke schedules a 1000 ms debounced
saveReportActionDraft(ComposerWithSuggestions.tsx#L553-L558, created at L289, wait at CONST#L2121). Save runspublishDraft→editReportComment(...)→deleteDraft()→stopEditing()+clearAllReportActionDrafts()(useEditMessage.ts#L86-L91).Nothing cancels the pending write.
useDebouncedSaveDraftreturns no canceller (L18-L39) anduseDebounceonly cancels when the debounced instance is re-created or the component unmounts (useDebounce.ts#L37-L45) — and the main composer never unmounts on Save. Up to a second later the trailing call re-persists{message: editedText}(Report/index.ts#L3645-L3664), the resolver sees a draft again, and the provider flipsOFF → EDITINGand re-seeds the composer (ReportActionEditMessageContext.tsx#L113-L123). Wide layout is safe because the editor isReportActionItemMessageEdit, which unmounts when the draft clears (ChatMessageContent.tsx#L51).I built a deterministic repro (narrow layout, real
ReportActionCompose, realpublishDraft, fake timers) and measured three things that shape the fix:off, composer empty, draft gone. The leftover text appears only when the trailing write lands, which matches the ordering in your trace. Neither the repro nor that trace shows theSUBMITTED → OFFlifecycle contributing, so I would leave it alone.saveReportActionDraftwrites withOnyx.setCollection, a late callback replaces the whole collection. Two variants of this exist onmaintoday, and both are worse than the reported symptom: saving and immediately editing another message, and switching straight from one edit target to another without saving — in the second oneeditingStatenever leavesEDITING, so the new edit is silently replaced by the previous message's text.The attachment in the repro steps is not part of the mechanism: editing a link is simply a bulk change followed by an immediate Save, which lands inside the 1000 ms window every time. Plain text reproduces identically.
What changes do you think we should make in order to solve the problem?
Make the pending report-action draft save droppable, and drop it at every edit-session boundary.
useDebouncedSaveDraftalready tracksisSavePending, so this needs no change touseDebounce's contract — which matters because that hook has many callers, and keeping the change inside the draft-save wrapper limits the blast radius to the two writers that actually need it.// src/pages/inbox/report/useDebouncedSaveDraft.ts const debouncedSaveDraft = useDebounce( (...args: unknown[]) => { + if (!isSavePending.current) { + return; + } saveDraftFn(...args); isSavePending.current = false; }, wait, {shouldExecuteOnUnmount}, ); + + const cancelSaveDraft = () => { + isSavePending.current = false; + };Then drop it in
ComposerWithSuggestionson both boundaries — when the session ends, and when the edited action changes:The first effect covers Save, Cancel, Escape, the confirmed empty-message deletion and navigating away, because all of them end the session through
stopEditing(). The second covers moving between edit targets, which never passes throughOFF.This loses no work: the report-action writer is created with
shouldExecuteOnUnmount = false, so a pending edit-draft save is already discarded on unmount today — dropping it at a session boundary is the same policy applied to the surface that never unmounts. The normal comment draft writer (debouncedSaveComment, a different Onyx key) is untouched, and so is the wide-layout editor's own instance inReportActionItemMessageEdit.I verified all three failure modes against the repro — Save inside the debounce window, Save followed immediately by editing another message, and switching edit targets without saving — plus the existing
ReportActionComposeTest,ReportActionMessageEditLayoutTestandReportActionItemMessageEditTestsuites, which all still pass.What specific scenarios should we cover in automated tests to prevent reintroducing this issue in the future?
REPORT_ACTIONS_DRAFTSstays empty, edit mode stays off, composer stays cleared. Fails onmaintoday.maintoday.maintoday, and is the case a plain "cancel when editing ends" guard misses.Implementation note for whoever writes these:
waitForBatchedUpdatescallsjest.runOnlyPendingTimers()under fake timers, so using it between the keystroke and Save flushes the very debounce under test and hides the bug. The test has to flush React/Onyx work without running timers in that window.What alternative solutions did you explore? (Optional)
EDITING. Measured: it closes the reported bug and the save-then-edit-another case, but not the target switch — going from one edit straight to another never passes throughOFF, so the pending write survives. That is why the second effect above exists.editingState !== EDITING. Measured: weaker still — by the time the trailing call fires the state isEDITINGagain for the new message, so the guard passes and the stale write lands.saveDraftcall signature and adds ref plumbing intouseEditMessage; the session boundaries are already observable in the composer, so I would keep the change local.SUBMITTEDthrough the async clear (dropstopEditing()from the Save path). Measured: on its own it does not fix the bug — the trailing write still lands and re-arms edit mode.clearAllReportActionDrafts(). It writes a draft we are about to delete and makes correctness depend on Onyx write ordering rather than removing the race.mukhrr commentedon Aug 14, 2026
Proposal
What is the root cause of that problem?
Inline edit mode is not a piece of component state, it is derived entirely from whether a persisted
REPORT_ACTIONS_DRAFTSentry exists withmessage !== undefined:App/src/pages/inbox/report/useActiveDraftReportAction.ts
Lines 38 to 49 in 142348e
So the only thing that closes the editor is that draft disappearing, which
deleteDraftdoes viaclearAllReportActionDrafts():App/src/pages/inbox/report/ReportActionCompose/useEditMessage.ts
Lines 50 to 63 in 142348e
On narrow layout the edit happens in the main composer, and every text change there schedules a 1000 ms debounced
saveReportActionDraft:App/src/pages/inbox/report/ReportActionCompose/ComposerWithSuggestions.tsx
Lines 553 to 561 in 142348e
When the user hits Save less than
CONST.TIMING.DRAFT_SAVE_DEBOUNCE_TIME(1000 ms) after their last keystroke, the order is:publishDraft→editReportComment(...)(the message saves — which is why the chat looks right) →deleteDraft()→stopEditing()+clearAllReportActionDrafts().ComposerWithSuggestionsstays mounted, so nothing cancels the pending debounce.{message: editedText}withOnyx.setCollection:App/src/libs/actions/Report/index.ts
Lines 3529 to 3549 in 142348e
useActiveDraftReportActionresolves a draft again → the provider flipseditingStateback toEDITINGand re-seedseditingMessagewith the edited text. The composer is back in edit mode holding what was just saved.Two details worth spelling out, because they are what make this real rather than theoretical:
The debounce genuinely survives.
useDebouncecancels and re-creates its lodash instance wheneverfuncidentity changes, anduseDebouncedSaveDraftImplpasses an inline arrow — normally that would mean a fresh (cancelled) debounce every render.App/src/hooks/useDebounce.ts
Lines 37 to 45 in 142348e
It survives because React Compiler memoizes that arrow — which is precisely what the file's own header comment says the non-generic impl exists for. So the pending trailing save really does outlive the save-and-clear.
App/src/pages/inbox/report/useDebouncedSaveDraft.ts
Lines 16 to 33 in 142348e
It is narrow-layout only, matching the iOS-only report. The
updateCommentedit branch above is gated onshouldUseNarrowLayout, so on wide layout the main composer never schedules an edit-draft save at all; the separateReportActionItemMessageEditeditor unmounts on save, anduseDebounce's unmount cleanup cancels its pending call.The attachment in the repro steps is not part of the mechanism — the race is content-agnostic. An attachment/link message simply makes it likely in practice: the composer holds long markdown like
[url](url), the user makes one small tweak and taps Save immediately, landing well inside the 1 s window. The same thing happens on the cancel (X) path, which also runsdeleteDraft.What changes do you think we should make in order to solve the problem?
Make the pending draft save droppable, and drop it the moment editing ends.
useDebouncedSaveDraftalready tracksisSavePending, so the cancel needs no new lodash plumbing and no change touseDebounce's contract (which has many other callers, and whose return value is a bare proxy function with no.cancel()to expose). Turn that ref into the gate for the trailing invocation and add a canceller:// src/pages/inbox/report/useDebouncedSaveDraft.ts const debouncedSaveDraft = useDebounce( (...args: unknown[]) => { + if (!isSavePending.current) { + return; + } saveDraftFn(...args); isSavePending.current = false; }, wait, {shouldExecuteOnUnmount}, ); + + const cancelSaveDraft = () => { + isSavePending.current = false; + };Then cancel it in
ComposerWithSuggestionsas soon as edit mode is off, which covers both save and cancel:This does not lose any work:
useDebouncedSaveDraft(saveReportActionDraft)is created withshouldExecuteOnUnmount = false, so a pending edit-draft save is already discarded when the composer unmounts today. Cancelling on edit-end is consistent with that.Tests:
tests/unit/useDebouncedSaveDraftTest.tscovers the scheduled-then-cancelled trailing call (fails on currentmain, passes with the change), that an uncancelled save still runs, and that typing after a cancel schedules a fresh save with the newer value.What alternative solutions did you explore? (Optional)
editingState !== EDITINGinstead of cancelling. Rejected: if the user starts editing a different message inside the 1 s window,editingStateisEDITINGagain and the stale trailing call would happily persist the previous action's text. Cancelling is keyed to the specific pending save, so it does not have that hole.clearAllReportActionDrafts(). Rejected: it writes a draft we are about to delete, and leaves the ordering dependent on Onyx write sequencing rather than removing the race.635593337-3d3923d1-1a0e-4e25-82ae-1da87f67c74f.mp4
REC-20260817125114.mp4
76 remaining items
melvin-bot commentedon Aug 31, 2026
Triggered auto assignment to @mallenexpensify (
Awaiting Payment)melvin-bot commentedon Aug 31, 2026
Payment Summary
Resolving PRs:
Upwork Job
BugZero Checklist (@mallenexpensify)
Abdulloh0109 commentedon Sep 3, 2026
@mallenexpensify
mallenexpensify commentedon Sep 3, 2026
Payment Summary
Contributor: @Abdulloh0109 paid $250 via Upwork
Contributor+: @daledah due $250 via NewDot
@Abdulloh0109 can you please accept the job below? Please reply here and tag me once you have.
https://www.upwork.com/jobs/~022087886721054798286
mallenexpensify commentedon Sep 4, 2026
@Abdulloh0109 paid, summary updated above. Thx.
@Abdulloh0109 reminder "Please reply here and tag me once you have." otherwise I don't know you've accepted. thx
Abdulloh0109 commentedon Sep 4, 2026
Thank you 👍
quinthar commentedon Nov 30, 2026
Approved $250 to @daledah