App icon indicating copy to clipboard operation
App copied to clipboard

[Due for payment 2026-11-19] [$175] Web - Chat - Composer doesn't regain focus after closing a modal once a message has been edited

Open MelvinBot opened this issue 1 month ago • 35 comments

Action Performed

  1. Open the app in a desktop browser.
  2. Go to any chat.
  3. Send a message.
  4. Click the chat header to open a modal, then close it. Verify that the composer automatically regains focus.
  5. Right-click the message > Edit comment > Cancel or Save.
  6. Click the chat header again to open the modal, then close it.
  7. Notice that the composer doesn't regain focus.

Expected Result

The composer should automatically regain focus after the modal is closed.

Actual Result

The composer doesn't regain focus after the modal is closed.

Platforms

  • [x] Web (desktop browser)

Reproducible on staging. Not caused by [LegendList 4/9] fix: stabilize composer focus and scroll notifications.

Video

https://github.com/user-attachments/assets/c256d19c-38c4-4353-a522-7593a07a3e2e

Context

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

MelvinBot avatar Oct 27 '26 08:10 MelvinBot

@MelvinBot submit a proposal

dmkt9 avatar Oct 27 '26 09:10 dmkt9

Proposal

What is the root cause of that problem?

The edit composer leaves the INPUT_FOCUSED Onyx flag set to true after it unmounts.

  1. When the edit composer gets focus, composerFocusKeepFocusOn sets INPUT_FOCUSED to true (InputFocus/index.web.ts:17-20, called from ReportActionItemMessageEdit.tsx:172-174).
  2. Cancel or Save unmounts the edit composer. Its unmount cleanup never resets the flag (ReportActionItemMessageEdit.tsx:176-190).
  3. The main composer is then focused in code, not by a click (useEditComposerToggle.ts:97-100). The flag is only cleared on a real click, so it stays true.
  4. When the modal closes, the main composer's refocus effect sees editFocused === true. It assumes an edit composer still owns focus, so it clears the flag and returns without calling focus(true) (ComposerWithSuggestions.tsx:934-938). The effect runs again after the flag changes, but by then the "modal just closed" check at line 930 no longer passes.

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

In the unmount cleanup of ReportActionItemMessageEdit, call inputFocusChange(false) before the existing early return. Once the edit composer is gone, it can't own focus, so the flag must not block the main composer.

inputFocusChange does nothing on native, so this only changes web.

Related cleanup (optional)

The same cleanup compares editComposerRef.current with composerRef.current. The inline ref callback sets composerRef.current to null during unmount, before the cleanup runs. So the check always returns early, and ReportActionComposeFocusManager.clear(true) never runs. Capture composerRef.current in a local variable when the effect runs and compare against that.

What alternative solutions did you explore? (Optional)

Clear INPUT_FOCUSED in the main composer's handleFocus when editFocused is true. Then any focus on the main composer resets the flag, not just a click. This is broader and may affect the case where an edit composer is still mounted.

Verification notes

This analysis comes from reading the code at 1279b3e. I haven't confirmed it in a browser. To check, log editFocused, prevIsFocused and prevIsModalVisible in the refocus effect after Cancel → open the header → close.


Next Steps for Contributor+ team: To accept: @MelvinBot implement [this](https://github.com/Expensify/App/issues/105111) to create a draft PR. To refine: @MelvinBot <your feedback> To reject: Explain why you are rejecting Melvin's proposal.


view run

MelvinBot avatar Oct 27 '26 09:10 MelvinBot

Current assignee @dmkt9 is eligible for the External assigner, not assigning anyone new.

melvin-bot[bot] avatar Oct 27 '26 09:10 melvin-bot[bot]

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

melvin-bot[bot] avatar Oct 27 '26 09:10 melvin-bot[bot]

Proposal

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

On desktop web, closing the chat header modal reportedly restores composer focus until a message has been edited. After either Cancel or Save, closing the same modal leaves the composer unfocused.

Audit verdict: MelvinBot’s diagnosis is plausible, but the supplied proposal does not meet the required empirical evidence standard. No independently verified replacement fix can be claimed from the available material.

What is the root cause of that problem?

The supplied analysis describes this causal chain at commit 1279b3ec2ad3146701258198311177793ab9cb42:

  1. Editing sets INPUT_FOCUSED to true through InputFocus/index.web.ts, lines 17–20, called from ReportActionItemMessageEdit.tsx, lines 172–174.
  2. The edit component’s cleanup allegedly leaves that flag unchanged at ReportActionItemMessageEdit.tsx, lines 176–190.
  3. Programmatic main-composer focus at useEditComposerToggle.ts, lines 97–100, allegedly does not clear it.
  4. The modal-close effect consumes the stale flag and returns before focusing at ComposerWithSuggestions.tsx, lines 930–938.

These are supplied source references, not independently verified findings. GitHub retrieval failed, no Expensify checkout was found locally, and no browser or Jest reproduction was executed. Consequently, the actual root cause remains unconfirmed.

The decisive missing evidence is a trace showing that the editor has disappeared, INPUT_FOCUSED remains true, and the subsequent modal-close transition takes the early-return branch without calling focus(true).

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

The smallest candidate remains MelvinBot’s proposed insertion in src/pages/inbox/report/ReportActionItemMessageEdit.tsx, inside the cited cleanup block and before its existing early return:

inputFocusChange(false);

This is a conditional candidate, not a verified, apply-ready diff. The surrounding source, existing import, effect dependencies, and platform implementation could not be inspected; inventing their exact contents would undermine this audit.

Before accepting that insertion, verify:

  • Cleanup timing: Determine whether the cleanup also runs on dependency changes while the editor remains mounted. “Cleanup” does not necessarily mean “editor permanently removed.”
  • Focus ownership: Determine whether an outgoing editor can clear the shared flag after another editor has acquired focus.
  • Update ordering: Exercise the real Onyx update path and confirm that the modal-close effect observes the reset.
  • Platform behavior: Verify the claimed native no-op implementation rather than treating it as established.

If those checks pass, retain the one-line behavior change and any necessary import adjustment. There is no evidence here justifying a broader refactor.

What alternative solutions did you explore? (Optional)

MelvinBot’s proposal should be refined, not dismissed with invented defects. Its explicit admission of no browser verification prevents acceptance under the requested evidence standard. It does not prove that its proposed fix is incorrect.

The ownership and cleanup-timing cases above are unresolved regression risks, not demonstrated failures.

The optional ref-capture change also needs separate justification. Making ReportActionComposeFocusManager.clear(true) execute changes behavior beyond resetting INPUT_FOCUSED. The supplied material does not establish that this is necessary or safe.

Clearing the flag in the main composer’s handleFocus affects every programmatic focus event. That wider scope requires evidence that it preserves active-editor behavior.

Finally, the one-line cleanup reset is already MelvinBot’s proposal. Presenting it as an original competing solution creates a direct duplication risk. Neither originality nor “the only safe production-grade fix” is supported.

What automated tests can you add to prevent this from re-occurring?

Add a web Jest integration test using the real editor cleanup, main-composer modal-close effect, and Onyx subscriptions. Suggested parameterized case:

it.each(['cancel', 'save'] as const)(
    'restores composer focus after %s and a subsequent header-modal close',
    async (action) => {
        // Render the report with both composer paths and real Onyx subscriptions.
        // Open and close the header modal; verify baseline composer focus.
        // Enter message editing and focus the edit input.
        // Perform the selected Cancel or Save action.
        // Wait for the editor to disappear and Onyx updates to settle.
        // Open and close the header modal without clicking the main composer.
        // Assert the main composer receives focus after this modal closes.
    },
);

This is a test specification, not an executable repository test or evidence of a passing run. The repository’s render helpers and test layout were unavailable.

The completed test must:

  • Fail on the unpatched revision and pass with the candidate change.
  • Assert focus after the second modal close; focus immediately after Cancel or Save is insufficient.
  • Preserve focus protection when an edit composer remains active.
  • Exercise editor replacement and dependency-triggered cleanup if those transitions exist.
  • Avoid mocking inputFocusChange into an implementation that bypasses Onyx.

A desktop-browser run must additionally confirm actual input focus. A mocked focus call alone cannot establish browser behavior.

No tests were run, no runtime trace was collected, and no patch was applied. Under the mandatory evidence rule, this remains an unverified proposal requiring refinement.

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

camesenin avatar Oct 27 '26 09:10 camesenin

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

melvin-bot[bot] avatar Oct 27 '26 09:10 melvin-bot[bot]

Proposal

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

On Web (wide layout), after a user edits an existing chat message (and saves with Enter or cancels with Escape), the main chat composer regains focus. However, if the user then opens any modal (such as the emoji picker or attachment menu) and closes it without selecting an item, the main chat composer fails to regain focus.

What is the root cause of that problem?

There are three interacting bugs in how web input focus state (ONYXKEYS.INPUT_FOCUSED / editFocused), cached DOM focus refs (refSave), and edit-composer unmount cleanup are managed across ReportActionItemMessageEdit.tsx, ComposerWithSuggestions.tsx, and InputFocus/index.web.ts:

  1. ONYXKEYS.INPUT_FOCUSED (editFocused) is set to true when focusing the edit composer, and is never reset when the edit composer closes or when the main composer regains focus programmatically:

    • In src/pages/inbox/report/ReportActionItemMessageEdit.tsx (lines 167–169), a useEffect runs on wide layout whenever isFocused is true and calls composerFocusKeepFocusOn(composerRef.current, isFocused, modal, onyxInputFocused).
    • In src/libs/actions/InputFocus/index.web.ts (lines 14–22), when isFocused is true, composerFocusKeepFocusOn calls inputFocusChange(true) (which merges ONYXKEYS.INPUT_FOCUSED = true) and stores the edit composer DOM node in the module-level variable refSave = ref.
    • When the user finishes editing (via Enter in publishDraft or Escape in triggerSaveOrCancel), deleteReportActionDraft removes the draft and ReportActionItemMessageEdit unmounts without resetting inputFocusChange(false).
    • Next, src/pages/inbox/report/ReportActionCompose/useEditComposerToggle.ts (lines 89–98) detects that editing ended (wasEditingRef.current && !isEditing) and calls onFocus?.() (handleEditFocus in src/pages/inbox/report/ReportActionCompose/ComposerWithSuggestions.tsx, lines 326–329), which calls focus(true) on the main composer.
    • Focusing the main composer triggers handleFocus (ComposerWithSuggestions.tsx, lines 1006–1010), which sets isFocused = true (setIsCommentEmpty / ReportActionComposeFocusManager.onComposerFocus), but does not clear ONYXKEYS.INPUT_FOCUSED (inputFocusChange(false)). In ComposerWithSuggestions.tsx (lines 738–744), inputFocusChange(false) is only called inside setShouldBlockSuggestionCalcToFalse, which is bound to onClick on the main composer (line 1043). Because focus was restored programmatically via useEditComposerToggle (or via keyboard navigation) rather than a physical mouse click on the main composer, ONYXKEYS.INPUT_FOCUSED (editFocused) remains true even while the user is actively focused in the main composer.
  2. Closing a modal checks editFocused and aborts main-composer focus restoration:

    • When a modal (such as the emoji picker) opens and then closes (prevIsModalVisible && !isModalVisible), the useEffect in src/pages/inbox/report/ReportActionCompose/ComposerWithSuggestions.tsx (lines 928–943) runs to restore focus to the main composer.
    • At lines 934–937, it checks: if (editFocused) { inputFocusChange(false); return; }
    • Because editFocused (ONYXKEYS.INPUT_FOCUSED) is still true from the earlier message edit, this branch clears ONYXKEYS.INPUT_FOCUSED and returns early instead of calling focus(true) on the main composer. Meanwhile, ReportActionItemMessageEdit is already unmounted, so nothing focuses the edit composer either—leaving neither composer focused.
  3. ReportActionItemMessageEdit's unmount cleanup fails to clear editComposerRef because its inline callback ref sets composerRef.current = null before useEffect cleanup runs:

    • In src/pages/inbox/report/ReportActionItemMessageEdit.tsx (lines 312–320), <Composer> receives an inline callback ref: ref={(el: ComposerRef | null) => { composerRef.current = el; ... }} that only updates ReportActionComposeFocusManager.editComposerRef.current = el when el !== null.
    • During unmount, React invokes callback refs with null before running useEffect cleanup functions. Thus composerRef.current becomes null while ReportActionComposeFocusManager.editComposerRef.current still points to the old ComposerRef instance.
    • When the unmount cleanup in ReportActionItemMessageEdit.tsx (lines 171–184) subsequently runs, the guard if (ReportActionComposeFocusManager.editComposerRef.current !== composerRef.current) { return; } compares the old ComposerRef against null, evaluates to true, and returns early—so ReportActionComposeFocusManager.clear(true) is never executed and editComposerRef.current remains a stale reference to the unmounted edit composer.

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

  1. Clear ONYXKEYS.INPUT_FOCUSED whenever the main composer gains focus (src/pages/inbox/report/ReportActionCompose/ComposerWithSuggestions.tsx):

    • In handleFocus (ComposerWithSuggestions.tsx, lines 1006–1010), call inputFocusChange(false) whenever editFocused is true (or unconditionally on main composer focus). This guarantees that whenever the main composer becomes the active focused input—whether via mouse click, useEditComposerToggle after saving/canceling an edit, or keyboard Tab/hotkey while an edit composer is still mounted—ONYXKEYS.INPUT_FOCUSED accurately reflects that the edit composer is no longer the focused input.
  2. Fix the unmount cleanup and ref assignment in src/pages/inbox/report/ReportActionItemMessageEdit.tsx (lines 171–184 and 312–320):

    • Extract the <Composer> ref callback into a useCallback (or capture the mounted composer instance in a local variable / ref that isn't overwritten before cleanup) so that on unmount:
      • ReportActionComposeFocusManager.clear(true) is properly called when this edit composer owned editComposerRef.current.
      • If onyxInputFocused is true (or this edit composer is the active input), call inputFocusChange(false) so ONYXKEYS.INPUT_FOCUSED is not left true after ReportActionItemMessageEdit unmounts (for example, on narrow/mobile web layouts where useEditComposerToggle does not auto-focus the main composer).
  3. Clear refSave in src/libs/actions/InputFocus/index.web.ts when inputFocusChange(false) is called or when the saved element is disconnected:

    • In src/libs/actions/InputFocus/index.web.ts (lines 10–32), reset refSave = null inside inputFocusChange(false) (or guard refSave.isConnected before calling refSave.focus()) so composerFocusKeepFocusOn never attempts to focus a detached DOM node from an unmounted edit composer.

What alternative solutions did you explore? (Optional)

  • Only calling inputFocusChange(false) in ReportActionItemMessageEdit unmount cleanup: While resetting inputFocusChange(false) on unmount fixes the case where the edit composer is closed before opening a modal, it does not fix the case where a user starts editing a message (leaving the edit box open), focuses the main composer via keyboard/shortcut, and then opens and closes a modal. Clearing inputFocusChange(false) inside the main composer's handleFocus in ComposerWithSuggestions.tsx in addition to cleaning up on ReportActionItemMessageEdit unmount handles both flows cleanly.

huhuli083-creator avatar Oct 27 '26 12:10 huhuli083-creator

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

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

melvin-bot[bot] avatar Oct 27 '26 12:10 melvin-bot[bot]

Proposal

What is the root cause of that problem?

The edit composer sets the INPUT_FOCUSED Onyx flag to true on focus (src/libs/actions/InputFocus/index.web.ts:17-20, called from src/pages/inbox/report/ReportActionItemMessageEdit.tsx:172-174), and its unmount cleanup never clears it (ReportActionItemMessageEdit.tsx:176-190). The main composer is then focused in code, not by a click (src/pages/inbox/report/ReportActionCompose/useEditComposerToggle.ts:97-100), and the flag is only cleared on a real click, so it stays true. When the modal closes, the main composer's refocus effect (src/pages/inbox/report/ReportActionCompose/ComposerWithSuggestions.tsx:934-938) sees editFocused === true, assumes an edit composer still owns focus, clears the flag and returns without calling focus(true). By the time the effect runs again, the "modal just closed" check at line 930 no longer passes, so focus is lost for good.

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

  • In useEditComposerToggle's programmatic focus path, call inputFocusChange(false) right after focusing the main composer, so the stale edit flag never reaches the modal-close effect. This fixes the trap at the consumer instead of only in one component's cleanup: any other programmatic-focus path after an edit would hit the same stale flag.
  • Keep the modal-close effect's early return for a genuinely mounted edit composer; with the stale flag cleared it will no longer trigger on a dead edit session.

What will I verify?

  • Send a message, open and close the chat-header modal, and confirm the composer regains focus.
  • Edit a message, then cancel or save, open and close the modal again, and confirm the composer regains focus.
  • Confirm edit-composer focus still works while actually editing a message.

khizzcr7 avatar Oct 27 '26 13:10 khizzcr7

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

huhuli083-creator avatar Oct 27 '26 13:10 huhuli083-creator

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

melvin-bot[bot] avatar Oct 27 '26 13:10 melvin-bot[bot]

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

huhuli083-creator avatar Oct 27 '26 13:10 huhuli083-creator

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

melvin-bot[bot] avatar Oct 27 '26 13:10 melvin-bot[bot]

Proposal

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

On Desktop Web, closing a modal (such as the chat header RHP modal) normally restores focus to the main chat composer. However, once a user edits any message and either cancels or saves the edit, opening and closing a modal no longer restores focus to the main chat composer.

What is the root cause of that problem?

  1. Focusing the edit composer sets ONYXKEYS.INPUT_FOCUSED (editFocused) to true (src/pages/inbox/report/ReportActionItemMessageEdit.tsx:172-174):
    • ReportActionItemMessageEdit runs composerFocusKeepFocusOn(composerRef.current, isFocused, modal, onyxInputFocused) (src/libs/actions/InputFocus/index.web.ts:17-20), which calls inputFocusChange(true) -> Onyx.set(ONYXKEYS.INPUT_FOCUSED, true) when the edit input is focused.
  2. Unmounting ReportActionItemMessageEdit on Cancel or Save never resets ONYXKEYS.INPUT_FOCUSED to false (src/pages/inbox/report/ReportActionItemMessageEdit.tsx:176-190):
    • Its unmount effect only calls ReportActionComposeFocusManager.clear(true) and leaves ONYXKEYS.INPUT_FOCUSED === true in Onyx (and useEditComposerToggle.ts:97-100 restores main composer focus programmatically without triggering the window click listener in ComposerWithSuggestions.tsx:524-531 that resets inputFocusChange(false)).
  3. When the next modal closes, ComposerWithSuggestions.tsx:930-939 aborts refocus because editFocused is still true:
    • In src/pages/inbox/report/ReportActionCompose/ComposerWithSuggestions.tsx:934-938:
      if (editFocused) {
          inputFocusChange(false);
          return;
      }
      focus(true);
      
    • On the render where the modal closes (prevIsModalVisible && !isModalVisible), editFocused is still true, so the effect calls inputFocusChange(false) and returns early without calling focus(true). On the subsequent render after editFocused becomes false, prevIsModalVisible is already false, so focus(true) never runs.

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

In src/pages/inbox/report/ReportActionItemMessageEdit.tsx (lines 176-190), reset inputFocusChange(false) in the unmount cleanup alongside ReportActionComposeFocusManager.clear(true) when ReportActionComposeFocusManager.editComposerRef.current === composerRef.current:

useEffect(
    () => {
        if (composerRef.current) {
            ReportActionComposeFocusManager.editComposerRef.current = composerRef.current;
        }
        return () => {
            if (ReportActionComposeFocusManager.editComposerRef.current !== composerRef.current) {
                return;
            }
            inputFocusChange(false);
            ReportActionComposeFocusManager.clear(true);
        };
    },
    [],
);

What alternative solutions did you explore?

Calling inputFocusChange(false) inside MainComposer.focus() was also considered, but cleaning up inputFocusChange(false) when ReportActionItemMessageEdit unmounts directly fixes the stale ONYXKEYS.INPUT_FOCUSED state at its source regardless of whether the main composer is refocused immediately.

weaieverything avatar Oct 27 '26 13:10 weaieverything

MelvinBot's proposal looks good to me

🎀 👀 🎀 C+

dmkt9 avatar Oct 27 '26 14:10 dmkt9

Current assignee @roryabraham is eligible for the choreEngineerContributorManagement assigner, not assigning anyone new.

melvin-bot[bot] avatar Oct 27 '26 14:10 melvin-bot[bot]

@roryabraham, @dmkt9 Whoops! This issue is 2 days overdue. Let's get this updated quick!

melvin-bot[bot] avatar Oct 30 '26 21:10 melvin-bot[bot]

@roryabraham, @dmkt9 Still overdue 6 days?! Let's take care of this!

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

@roryabraham, @dmkt9 6 days overdue. This is scarier than being forced to listen to Vogon poetry!

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

@roryabraham, @dmkt9 Still overdue 6 days?! Let's take care of this!

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