Skip to content

[Due for payment 2026-06-02] [$250] Chat-Draft message cannot be send after reopening the chat #90859

Closed

Description

@mitarachim

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


Version Number: 9.3.75-0
Reproducible in staging?: Yes
Reproducible in production?: Yes
If this was caught during regression testing, add the test name, ID and link from BrowserStack: https://test-management.browserstack.com/projects/2219752/folder/13176910/test-cases/41237484
Email or phone of affected tester (no customers): N/A
Issue reported by: Applause Internal Team
Bug source: Exploratory - Significant User Experience Deterioration
Device used: MacBook Air 15.7.4 Chrome, iPhone 15 iOS 26.4.2
App Component: Chat Report View

Action Performed:

  1. Sign in to ND
  2. Navigate to any chat
  3. Type something in the compose box, do not send the message
  4. Navigate to a different chat, then back to the chat with a draft message
  5. Click Send button

Expected Result:

Draft message is sent successfully

Actual Result:

Draft message cannot be send, nothing happens after clicking Send button (or Enter), if user navigated away from the chat, then back

Workaround:

Unknown

Platforms:

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

Screenshots/Videos

Bug7155465_1778881444641.Draft.mp4

View all open jobs on GitHub

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

Activity

  1. added
    BugSomething is broken. Auto assigns a BugZero manager.
    and removed on May 22, 2026
  2. MelvinBot commented on May 22, 2026

    @MelvinBot
    Contributor

    Proposal

    What is the root cause of that problem?

    After the "new editing model" refactor (PR #76741), submitDraftAndClearComposer gates sending on debouncedCommentMaxLengthValidation?.flush():

    if (isSendDisabled || !debouncedCommentMaxLengthValidation?.flush()) {
        return;
    }

    Lodash flush() returns undefined when the debounced function was never invoked. !undefined is true, so the send silently aborts.

    When navigating back to a chat with a draft, SilentCommentUpdater skips calling updateComment on first mount because usePrevious initializes its ref with the current value, so prevReportId === reportID and prevCommentProp === comment — the guard at line 47 returns early. The validation debounce is never invoked, so flush() returns undefined, and pressing Send does nothing.

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

    In useDebouncedCommentMaxLengthValidation.ts:45, the debounce instance is created fresh every render without memoization. It should be wrapped in a useRef (or useMemo) so the same instance persists across renders. Additionally, the submitDraftAndClearComposer guard should be made safe against a never-invoked debounce — e.g., treat undefined from flush() as a pass (the text hasn't exceeded max length if validation was never triggered), or eagerly invoke the validation when the draft is loaded.

    What alternative solutions did you explore? (Optional)

    An alternative would be to fix SilentCommentUpdater to always call updateComment on mount (e.g., by initializing usePrevious with undefined for reportID). However, that only addresses one path — any re-render that creates a new debounce instance after SilentCommentUpdater syncs would reintroduce the bug. Stabilizing the debounce instance is the more robust fix.

    Investigation details

    Data flow of the bug:

    1. User types in chat A → updateComment() → debouncedCommentMaxLengthValidation(text) invoked on debounce instance
    2. User navigates away → draft saved to Onyx
    3. User navigates back → ComposerProvider mounts, reads draft from Onyx, text state shows "hello"
    4. useDebouncedCommentMaxLengthValidation creates a new lodash debounce instance (never called)
    5. SilentCommentUpdater effect fires but skips sync — usePrevious returns current values on first render, so all guards pass and updateComment is never called
    6. User sees draft text, isSendDisabled is false (button looks enabled)
    7. User clicks Send → submitDraftAndClearComposer() → flush() on the never-invoked instance → returns undefined
    8. !undefined === true → early return → message silently not sent

    Secondary concern: useDebounce.ts:32-33 cancels (rather than flushes) pending saves on unmount, which could lose drafts if the user navigates away within the debounce window.

    Possibly related: #91149 (message displayed in compose box after opening a new chat — may share draft restoration logic)


    Next Steps for Contributor+ team: Reply with @MelvinBot implement this to create a draft PR, @MelvinBot <your feedback> to refine this analysis, or explain why you are rejecting Melvin's proposal.

  3. added
    ExternalAdded to denote the issue can be worked on by a contributor
    on May 22, 2026
  4. added
    Help WantedApply this label when an issue is open to proposals by contributors
    on May 22, 2026
  5. wildan-m commented on May 22, 2026

    @wildan-m
    Contributor

    Proposal

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

    After typing a draft message in a chat, navigating to a different chat, and then navigating back to the original chat, clicking the Send button (or pressing Enter) does nothing — the visible draft message is not sent. This regressed with the recent composer editing refactor that shipped in 9.3.75-0.

    What is the root cause of that problem?

    submitDraftAndClearComposer in useComposerSubmit gates message sending on the return value of debouncedCommentMaxLengthValidation.flush():

    const submitDraftAndClearComposer = () => {
    if (isSendDisabled || !debouncedCommentMaxLengthValidation?.flush()) {
    return;
    }

    The debouncedCommentMaxLengthValidation function is created inside useDebouncedCommentMaxLengthValidation by calling lodashDebounce inline on every render, with no useMemo or useRef to preserve the instance:

    const debouncedCommentMaxLengthValidation = lodashDebounce(validateMaxLength, CONST.TIMING.COMMENT_LENGTH_DEBOUNCE_TIME, {leading: true});

    Because ComposerProvider re-renders on every keystroke (it owns the text state) and on every other state change in its subtree, each render replaces the debounced function with a fresh closure that has its internal result and timerId reset to undefined. Lodash's flush() for a debounced function that has never been invoked returns undefined (verified via direct test against the installed lodash: _.debounce(fn, 1500, {leading: true}).flush() returns undefined before any call).

    When the user re-opens a chat that already has a draft, the draft text is restored from Onyx via SilentCommentUpdater, but the user has not typed in the current ComposerProvider instance after the most recent re-render. The current debounce instance therefore has result === undefined, so !debouncedCommentMaxLengthValidation?.flush() evaluates to true, and submitDraftAndClearComposer returns early before reaching clearComposer(). Since the actual addComment call is wired through clearComposer() → clearWorklet → input clear() → onClear → validateAndSubmitDraft, the message is never submitted and the Send button silently does nothing.

    The same fault path explains why pressing Enter also does nothing in the reopened-chat scenario: onEnterKeyPress is the same submitDraftAndClearComposer function.

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

    In src/pages/inbox/report/ReportActionCompose/useDebouncedCommentMaxLengthValidation.ts, wrap the lodashDebounce(...) call in useMemo so the same debounced instance is reused across renders, keyed by the inputs that actually change the validation behavior (reportID and isEditing). Also wrap validateMaxLength in useCallback with the matching dependencies so the memoized debounce always closes over an up-to-date validator without being recreated.

    Preserving the debounce instance across renders restores the intended semantics of flush() in submitDraftAndClearComposer:

    • When the user has typed at least once in the current ComposerProvider lifetime, the leading-edge invocation has run and cached result === true (assuming the comment is not over the limit), so flush() returns true and the send proceeds.
    • When the user has not typed but is sending a restored draft, the onValueChange path triggered by SilentCommentUpdater's updateComment(comment) calls the debounced validator on the leading edge during the restore, populating result on the persistent instance. Subsequent re-renders no longer wipe that value, so flush() on Send correctly returns true.

    We should also add a cleanup that calls debouncedCommentMaxLengthValidation.cancel() when the component unmounts (or when the memo dependencies change and a new instance is created), so any pending trailing invocation on the previous instance is dropped instead of firing after the component is gone.

    Compare branch: https://github.com/Expensify/App/compare/main...wildan-m:App:wildan/90859-fix-restored-draft-send?expand=1

    What alternative solutions did you explore? (Optional)

    An alternative is to drop the flush() check from submitDraftAndClearComposer and rely on isSendDisabled (which already includes isExceedingMaxLength via React state) plus an unconditional debouncedCommentMaxLengthValidation?.flush() call afterward purely for its side effect of forcing a pending validation to run. This works because {leading: true} ensures the very first validation per debounce window runs synchronously and sets state, so by the time the user can click Send, isExceedingMaxLength is already accurate. However, it slightly weakens the guarantee in the "paste-then-immediately-send within the 1500 ms debounce wait" edge case, where a trailing validation might still be scheduled. Memoizing the debounce keeps the original gating logic intact while fixing the regression, so it is preferable.

  6. melvin-bot commented on May 22, 2026

    @melvin-bot

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

  7. KJ21-ENG commented on May 22, 2026

    @KJ21-ENG
    Contributor

    🚨 Edited by proposal-police: This proposal was edited at 2026-05-22 17:00:45 UTC.

    Proposal

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

    After a user types a chat draft, leaves that chat, and returns, the draft is restored in the composer but pressing Send or Enter does not post it.

    What is the root cause of that problem?

    The normal send path treats the return value of the debounced max-length validator as a required submit-time validation result.

    In useComposerSubmit, submitDraftAndClearComposer() returns before doing anything else when debouncedCommentMaxLengthValidation.flush() is falsy:

    const submitDraftAndClearComposer = () => {
    if (isSendDisabled || !debouncedCommentMaxLengthValidation?.flush()) {
    return;
    }

    That validator is a lodash debounce around validateMaxLength():

    function validateMaxLength(value: string) {
    const taskCommentMatch = value?.match(CONST.REGEX.TASK_TITLE_WITH_OPTIONAL_SHORT_MENTION);
    // Only apply task-title validation when composing (not when editing an existing message)
    if (!isEditing && taskCommentMatch) {
    const title = taskCommentMatch?.[3] ? taskCommentMatch[3].trim().replaceAll('\n', ' ') : '';
    const exceeded = title ? title.length > CONST.TITLE_CHARACTER_LIMIT : false;
    setIsTaskTitle(exceeded);
    setExceededMaxLength(exceeded ? CONST.TITLE_CHARACTER_LIMIT : null);
    return !exceeded;
    }
    const exceeded = getCommentLength(value, {reportID}) > CONST.MAX_COMMENT_LENGTH;
    setIsTaskTitle(false);
    setExceededMaxLength(exceeded ? CONST.MAX_COMMENT_LENGTH : null);
    return !exceeded;
    }
    const debouncedCommentMaxLengthValidation = lodashDebounce(validateMaxLength, CONST.TIMING.COMMENT_LENGTH_DEBOUNCE_TIME, {leading: true});

    For a restored draft, the composer text can be initialized directly from REPORT_DRAFT_COMMENT in ComposerProvider:

    const getInitialText = () => {
    return draftComment ?? '';
    };
    const textRef = useRef<string>(getInitialText());
    const [text, setTextState] = useState(getInitialText);

    That makes isSendDisabled false because the restored text is non-empty:

    const isDraftCommentEmpty = !text || !!text.match(CONST.REGEX.EMPTY_COMMENT);
    const isSubmittingDraftCommentDisabled = isBlockedFromConcierge || isExceedingMaxLength || isDraftCommentEmpty;
    const isSendDisabled = !isEditingInComposer && isSubmittingDraftCommentDisabled;

    But this restore path does not invoke ComposerInput.onValueChange(), which is where the debounced validator normally gets called while typing:

    const onValueChange = (v: string) => {
    if (v.length === 0 && isComposerFullSize) {
    setIsComposerFullSize(reportID, false);
    }
    debouncedCommentMaxLengthValidation?.(v);
    };

    On web/iOS, SilentCommentUpdater also skips its first effect because usePrevious() initializes previous values to the current values, so the first restored-draft render is treated as unchanged and does not call updateComment(comment):

    const [comment = '', commentResult] = useOnyx(`${ONYXKEYS.COLLECTION.REPORT_DRAFT_COMMENT}${reportID}`);
    const prevCommentProp = usePrevious(comment);
    const prevReportId = usePrevious(reportID);
    const {preferredLocale} = useLocalize();
    const prevPreferredLocale = usePrevious(preferredLocale);
    useEffect(() => {
    if (isLoadingOnyxValue(commentResult)) {
    return;
    }
    // Skip sync when transitioning to a preexisting report
    // This prevents overwriting the just-saved draft with an empty string
    if (isTransitioningToPreExistingReport.current && reportID !== prevReportId) {
    onTransitionToPreExistingReportComplete();
    return;
    }
    // Value state does not have the same value as comment props when the comment gets changed from another tab.
    // In this case, we should synchronize the value between tabs.
    const shouldSyncComment = prevCommentProp !== comment && value !== comment && !isCommentPendingSaved.current;
    // As the report IDs change, make sure to update the composer comment as we need to make sure
    // we do not show incorrect data in there (ie. draft of message from other report).
    if (preferredLocale === prevPreferredLocale && reportID === prevReportId && !shouldSyncComment) {
    return;
    }
    updateComment(comment ?? '');
    }, [

    export default function usePrevious<T>(value: T): T {
    const ref = useRef<T>(value);
    useEffect(() => {
    ref.current = value;
    }, [value]);
    return ref.current;

    So the composer can show a valid draft while the current debounced validator has never been invoked. In that state, lodash flush() returns undefined, !flush() is true, and Send/Enter exit before clearComposer(), onClear, or addComment() can run.

    This also explains the platform split: Android SilentCommentUpdater calls updateComment(comment) on mount, which can invoke the normal value-change path there:

    function SilentCommentUpdater({updateComment, reportID}: SilentCommentUpdaterProps) {
    const [comment = ''] = useOnyx(`${ONYXKEYS.COLLECTION.REPORT_DRAFT_COMMENT}${reportID}`);
    useEffect(() => {
    updateComment(comment);
    // eslint-disable-next-line react-hooks/exhaustive-deps -- We need to run this on mount
    }, []);

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

    Submit should synchronously validate the current composer text instead of depending on whether a debounced typing callback happened to run earlier.

    1. Update useDebouncedCommentMaxLengthValidation to expose a non-debounced validator, for example validateCommentMaxLength(value: string), using the same task-title/comment-length logic that currently lives inside validateMaxLength().
    2. Keep the debounced wrapper for live typing feedback from ComposerInput.onValueChange(). While touching this hook, memoize/cancel the debounced function so render churn does not reset its internal state or leave stale timers, but do not use debounce state as the submit source of truth.
    3. Add the synchronous validator to the composer send context and use it in useComposerSubmit against textRef.current:
    const currentDraft = textRef.current ?? '';
    
    if (isSendDisabled || !validateCommentMaxLength(currentDraft)) {
        return;
    }

    Then keep the existing edit/full-size/clear flow. The important part is that a restored draft is validated from the canonical composer text before the send path can return.

    1. Pass the same synchronous validator to useEditMessage and use it in publishDraft(draftMessage) instead of debouncedCommentMaxLengthValidation.flush(), so restored edit drafts are not vulnerable to the same never-invoked-debounce case.

    This keeps the current live max-length UX while making Send validate the actual message that is visible in the composer.

    What alternative solutions did you explore? (Optional)

    Memoizing only the lodash debounce is not enough by itself. A restored draft can still mount with no onValueChange() call on web/iOS, so the memoized instance may still have no result for flush().

    Changing the guard to treat flush() === undefined as valid would unblock the repro, but it would also rely on stale isExceedingMaxLength state for an over-limit restored draft. A submit-time validator handles both the normal restored draft and the over-limit restored draft.

    Forcing SilentCommentUpdater to sync on mount would prime the validator indirectly, but it keeps submit correctness coupled to a platform-specific draft-sync side effect. Validation belongs in the submit path.

    The clear/worklet path is downstream of this bug. On the failing path, execution returns at the flush() guard before clearComposer() is called, so changing onClear or the UI-thread clear event would not fix this repro.

    What specific scenarios should we cover in automated tests?

    Add a regression test that seeds ${ONYXKEYS.COLLECTION.REPORT_DRAFT_COMMENT}${reportID} with a non-empty draft, renders the composer for that report, does not fire a change event, presses Send or triggers Enter, and verifies addComment is called once with the restored draft and the draft is cleared.

    Also cover a restored draft over the max length to verify the synchronous submit-time validator blocks it, and cover the edit-draft submit path if there is already test coverage around publishDraft().

  8. changed the title [-]Chat-Draft message cannot be send after reopening the chat[/-] [+][$250] Chat-Draft message cannot be send after reopening the chat[/+] on May 22, 2026
  9. 22 remaining items

  10. melvin-bot commented on May 26, 2026

    @melvin-bot

    The solution for this issue has been 🚀 deployed to production 🚀 in version 9.3.82-3 and is now subject to a 7-day regression period 📆. Here is the list of pull requests that resolve this issue:

    If no regressions arise, payment will be issued on 2026-06-02. 🎊

    For reference, here are some details about the assignees on this issue:

    • @bernhardoj requires payment through NewDot Manual Requests
  11. melvin-bot commented on May 26, 2026

    @melvin-bot

    @bernhardoj The PR fixing this issue has been merged! The following checklist (instructions) will need to be completed before the issue can be closed. Please copy/paste the BugZero Checklist from here into a new comment on this GH and complete it. If you have the K2 extension, you can simply click: [this button]

  12. bernhardoj commented on May 27, 2026

    @bernhardoj
    Contributor

    BugZero Checklist:

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

      Link to the comment on the PR: https://github.com/Expensify/App/pull/90516/changes#r3308400420
      Link to the comment on the Issue: Not sure which one is the issue

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

      Link to discussion: N/A

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

    This was caught on an existing regression test, so no need for a new one.

  13. added
    Awaiting PaymentAuto-added when associated PR is deployed to production
    and removed on May 27, 2026
  14. melvin-bot commented on Jun 1, 2026

    @melvin-bot

    Triggered auto assignment to @mallenexpensify (Awaiting Payment)

  15. melvin-bot commented on Jun 1, 2026

    @melvin-bot

    Payment Summary

    Upwork Job

    BugZero Checklist (@mallenexpensify)

    • I have verified the correct assignees and roles are listed above and updated the necessary manual offers
    • I have verified that there are no duplicate or incorrect contracts on Upwork for this job (https://www.upwork.com/ab/applicants/2057864744968219675/hired)
    • I have verified the PR was not reverted
    • I have applied any discounts due to bugs/regressions introduced by this PR
    • I have paid out the Upwork contracts or cancelled the ones that are incorrect
    • I have verified the payment summary above is correct
  16. mallenexpensify commented on Jun 3, 2026

    @mallenexpensify
    Contributor

    Payment Summary

    Contributor+: @bernhardoj due $250 via NewDot

  17. flaviadefaria commented on Jun 16, 2026

    @flaviadefaria
    Contributor

    Approved: @bernhardoj due $250 via NewDot

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

Metadata

Metadata

Labels

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

Type

No type

Projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions