App icon indicating copy to clipboard operation
App copied to clipboard

[$250] Marking a chat as unread doesn't stick — client immediately re-reads it, and other clients never see the change

Open melvin-bot[bot] opened this issue 2 months ago • 132 comments

If you haven’t already, check out our contributing guidelines for onboarding and email [email protected] to request to join our Slack channel!


Version Number: latest production Platform: iOS (bug 1), Desktop (bug 2)

Action Performed:

  1. On iOS, long-press a chat in the LHN and choose Mark as unread.
  2. Repeat on a second chat.
  3. Open the desktop app (already signed in, session left open) and look at the LHN.

Expected Result: Both chats stay unread on iOS, and the desktop app shows them as unread.

Actual Result: Two separate failures:

Bug 1 — the marking client immediately re-marks the chat as read. On iOS, MarkAsUnread rolled lastReadTime back correctly, but ~3 seconds later the same client fired ReadNewestAction and pushed lastReadTime forward again, silently undoing the mark. The user had to mark the chat unread a second time before it stuck. This looks like the report screen still being mounted/focused after the LHN action, so the "you're viewing this report" read-receipt fires and clobbers the unread state.

Bug 2 — other clients never learn about the unread state. Server-side both chats were correctly unread. The desktop client then ran ReconnectApp twice, ~40 minutes later, both times sending the same updateIDFrom cursor — millions of updates behind the unread writes. The cursor never advanced, so desktop kept rendering stale state and showed both chats as read. Desktop never sent OpenReport or ReadNewestAction, so it did not re-mark them read — it simply never received the update.

Workaround: Mark the chat unread a second time (bug 1). Fully reload the desktop app (bug 2).


Reported by @mallenexpensify via DM with MelvinBot.

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

melvin-bot[bot] avatar Sep 15 '26 16:09 melvin-bot[bot]

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

melvin-bot[bot] avatar Sep 15 '26 20:09 melvin-bot[bot]

Unable to auto-create job on Upwork. The BZ team member should create it manually for this issue.

melvin-bot[bot] avatar Sep 15 '26 20:09 melvin-bot[bot]

@eh2077 tag me if you don't think this is frontend. Thx

mallenexpensify avatar Sep 15 '26 20:09 mallenexpensify

Proposal

What is the root cause of that problem?

These are two unrelated bugs. Bug 1 is a frontend bug with a clear root cause. Bug 2 is not fixable in this repo.

Bug 1 — the marking client re-reads the chat.

markCommentAsUnread rolls lastReadTime back to just before the action (src/libs/actions/Report/index.ts:3268). That makes the report genuinely unread — which is exactly what the auto-read effect in useMarkAsRead is looking for:

There is no "the user deliberately marked this unread" flag anywhere in the hook. Nothing distinguishes "this report has new messages, auto-read it" from "the user just asked for this to be unread."

Why iOS is worse: Visibility.hasFocus() is hardcoded to true on native (index.native.ts:9) versus document.hasFocus() on web, which deletes the second half of the guard at useMarkAsRead.ts:202. And isVisible is AppState === 'active' on native, so control centre, banners and app-switcher peeks each toggle a dependency of the effect.

Bug 2 — other clients never get the update.

The client cannot fix this itself. lastUpdateIDAppliedToClient has exactly one writer, and it only advances when the server's response carries a lastUpdateID greater than the current cursor (OnyxUpdates.ts:204-207). There is no gap-size threshold and no automatic fallback to a full reconnect — I looked for one and it does not exist. So if the server stops advancing the cursor, the client re-sends the same updateIDFrom forever, which matches the reported behaviour precisely: two reconnects, identical cursor, no movement, stale UI.

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

Bug 1 (fix here): make a deliberate mark-as-unread win over the automatic read receipt. Either:

  1. Record the moment of the user's mark-as-unread and have handleReportChangeMarkAsRead refuse to auto-read a report whose unread state came from that action rather than from a new message, or
  2. Make readNewestAction refuse to move lastReadTime backwards past a pending MarkAsUnread for the same report.

Option 2 matches an invariant the codebase already states elsewhere — SequentialQueue.ts already says "Marking a message unread must always win", but that guard only applies to requests that were initiated offline, so it does nothing for this online flow. Extending it is likely the smallest correct change.

Passing shouldRequireScreenFocus: true from ReportActionsList would help in the narrow layout, but it is not sufficient on its own — in the wide layout the report screen is the focused route while the user interacts with the LHN, so the focus check still passes.

Bug 2 (do not fix here): the root cause is server-side, in what the backend returns for a ReconnectApp whose updateIDFrom is far behind. That code is not in this repository, so I'm not proposing a change for it. This needs to be escalated to an internal engineer to check what the reconnect handler returns for a cursor that old. I'd suggest splitting it into its own issue so bug 1 isn't blocked behind it.

What alternative solutions did you explore?

Alternatives considered, evidence, and verification notes

Alternatives for bug 1

  • Add lastReadTime to the effect's dependency array. Rejected — it makes the clobber fire immediately instead of after 3 seconds. The dependency list is deliberately narrow; the comment at useMarkAsRead.ts:216 explains why.
  • Unmount the report screen when the LHN context menu opens. Rejected — covered split screens are deliberately frozen rather than unmounted, and the platform-level hasFocus()/AppState triggers do not require the screen to be visible anyway.

Two other unguarded paths reach readNewestAction after a mark-as-unread

Worth confirming a fix closes all three, not just the first:

  1. The app-visibility effect at useMarkAsRead.ts:261. The userActiveSince bump that markCommentAsUnread triggers is meant to protect this path, but it is only consulted when lastMessageTime.current is non-null — which it isn't in this flow — so the code falls back to the rolled-back lastReadTime and the guard is bypassed.
  2. The viewability replay through completeSkippedMarkAsRead. Separately, readActionSkippedRef is set at :213 but cleared only inside markNewestActionAsRead, so the app-visibility read at :261 can leave it stuck armed. That looks like a real latent bug on its own.

The comment at useMarkAsRead.ts:221-222 already names this exact bug class for a sibling case that was patched — the LHN variant wasn't.

What I did not pin down

I could not determine which dependency flipped at the ~3 second mark in the reporter's session. All three paths above are live and unguarded, and only logs from that device would discriminate. The fix should not depend on knowing which one fired.

I am not blaming a specific PR. The missing guard has been there since the hook was created, so this is not a recent regression, and I'm not recommending a revert.

Verification attempt: I tried to reproduce bug 1 on web, but couldn't drive it — "Mark as unread" in the LHN is only reachable via right-click/long-press, and both gestures are unsupported by the automation in this environment. So the analysis above rests on code reading, not a live repro. Bug 2 would need production logs — specifically whether those two ReconnectApp responses carried a lastUpdateID at all, which is the single data point that confirms the server-side attribution.

Possibly related issues


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


view run · no recording available

MelvinBot avatar Sep 15 '26 20:09 MelvinBot

checking

eh2077 avatar Sep 18 '26 12:09 eh2077

@eh2077 I tried to debug this. I think melvin's solution doesn't work even though RCA makes sense.

Make readNewestAction refuse to move lastReadTime backwards past a pending MarkAsUnread for the same report.

MarkAsUnread request is already gone from the queue 4s before the re-read fires. A sticky flag has the opposite problem, it also blocks auto-read for a message that arrives while your looking at the chat.

mukhrr avatar Sep 18 '26 13:09 mukhrr

@eh2077 Uh oh! This issue is overdue by 2 days. Don't forget to update your issues!

melvin-bot[bot] avatar Sep 21 '26 21:09 melvin-bot[bot]

I think it's frontend issue as it's not reproducible on web browser but I need more time to troubleshoot on iOS app to examine melvin's proposal.

eh2077 avatar Sep 22 '26 15:09 eh2077

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

melvin-bot[bot] avatar Sep 25 '26 21:09 melvin-bot[bot]

I can't reproduce this issue on iOS app, @mukhrr are you still able reproduce it?

eh2077 avatar Sep 29 '26 16:09 eh2077

@eh2077 this issue was created 2 weeks ago. Are we close to approving a proposal? If not, what's blocking us from getting this issue assigned? Don't hesitate to create a thread in #expensify-open-source to align faster in real time. Thanks!

melvin-bot[bot] avatar Sep 29 '26 21:09 melvin-bot[bot]

I can't reproduce this issue on iOS app, @mukhrr are you still able reproduce it?

@eh2077 yes I am able to reproduce on both weba nd ios

https://github.com/user-attachments/assets/c74b5328-c227-40d3-890d-62f7a94e65fd

https://github.com/user-attachments/assets/e52283ca-bb84-4034-a773-b54b8d19295e

mukhrr avatar Sep 30 '26 03:09 mukhrr

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

melvin-bot[bot] avatar Oct 02 '26 23:10 melvin-bot[bot]

@eh2077 Uh oh! This issue is overdue by 2 days. Don't forget to update your issues!

melvin-bot[bot] avatar Oct 03 '26 01:10 melvin-bot[bot]

@eh2077 Still overdue 6 days?! Let's take care of this!

melvin-bot[bot] avatar Oct 06 '26 22:10 melvin-bot[bot]

hmm, I can't reproduce it, asked for someone to take over in slack

https://github.com/user-attachments/assets/7a1c7dde-0478-4f6f-bf8e-b2543297f73a

eh2077 avatar Oct 07 '26 13:10 eh2077

@eh2077 @mallenexpensify I'm unable to reproduce it with the given flow, but I can reproduce it when I blur and refocus the Chrome browser on desktop. Is this a bug?

https://github.com/user-attachments/assets/b4c4a344-ccac-4d88-b100-ed3a2aabd9cb

dmkt9 avatar Oct 07 '26 13:10 dmkt9

@eh2077

I reproduced bug 1 on dev web and iOS. I also tested a fix for it, using the same steps on both platforms.

Repro

  • Web (wide layout): open a chat that has a message from someone else, then use Mark as unread in the LHN. lastReadTime moves back to 2026-09-28 10:39:25.589. Click into another app and back: ReadNewestAction is sent 10 ms after the window focus event, and lastReadTime becomes 2026-10-08 08:49:36.979. The browser tab stays visible the whole time, so focus alone triggers it.
  • iOS: inside the chat, long-press a message from someone else and choose Mark as unread. Send the app to the background and resume it: lastReadTime becomes 2026-10-08 09:11:53.920, and the chat drops out of Unread.

Root cause

The existing RCA here is right that nothing remembers the user's choice. markCommentAsUnread rolls lastReadTime back and emits unreadAction_<reportID>, but useMarkAsRead only uses that event to reset userActiveSince:

https://github.com/Expensify/App/blob/07d3cc09834a2fb5235dd9083ea2b8e90d412316/src/hooks/useMarkAsRead.ts#L166-L168

Two auto-read passes then read the report back. A fix has to cover both:

  1. Window focus (web/desktop). appFocusCount re-runs handleAppVisibilityMarkAsRead on every window focus. On a focus-only pass lastMessageTime is null, so the comparison falls back to the rolled-back lastReadTime. The message that was just marked unread then counts as new:

https://github.com/Expensify/App/blob/07d3cc09834a2fb5235dd9083ea2b8e90d412316/src/hooks/useMarkAsRead.ts#L267-L283

  1. App resume (iOS). isVisible is a dependency of the report-change effect, and Visibility.hasFocus() is always true on native. isUnread is now true, so line 225 reads the report:

https://github.com/Expensify/App/blob/07d3cc09834a2fb5235dd9083ea2b8e90d412316/src/hooks/useMarkAsRead.ts#L217-L241

Blocking readNewestAction while MarkAsUnread is pending does not help: the request has already left the queue when the re-read fires. A sticky "manually unread" flag has the opposite problem, because it would also block reading a new message that arrives while the user is looking. Gating on report.manuallyMarkedUnreadReportActionID does not work either: I measured it as null after Mark as unread from the LHN.

Fix

When unreadAction_ fires, remember the report's lastVisibleActionCreated. Then skip both auto-read passes while that value has not changed:

+    const handleUnreadAction = useEffectEvent(() => {
+        userActiveSince.current = DateUtils.getDBTime();
+        markedUnreadLastVisibleActionCreated.current = report?.lastVisibleActionCreated;
+    });
+
+    const isKeptUnreadByUser = () => !!markedUnreadLastVisibleActionCreated.current && markedUnreadLastVisibleActionCreated.current === report?.lastVisibleActionCreated;
...
-        const subscription = DeviceEventEmitter.addListener(`unreadAction_${reportID}`, () => {
-            userActiveSince.current = DateUtils.getDBTime();
-        });
+        const subscription = DeviceEventEmitter.addListener(`unreadAction_${reportID}`, () => handleUnreadAction());
...
-        if (shouldRequireScreenFocus && !isFocused) {
+        if ((shouldRequireScreenFocus && !isFocused) || isKeptUnreadByUser()) {
...
-        if (reportID !== getScopeReportID(scopeKey)) {
+        if (reportID !== getScopeReportID(scopeKey) || isKeptUnreadByUser()) {
  • When a new message arrives, lastVisibleActionCreated changes, the gate turns off and auto-read works as before.
  • The initial read on open and the explicit markNewestActionAsRead (scrolling to the bottom) are untouched.

Tested with the change

  • Web: two blur/focus cycles and a return from a hidden tab. No ReadNewestAction is sent, and lastReadTime stays 2026-09-28 10:39:25.589.
  • iOS: two background/resume cycles. The LHN row stays bold and labelled "Unread".
  • Neighbour: reopening the chat still marks it read on both platforms.
  • Revert: after git stash, the bug comes back on both platforms.

Bug 2 looks backend to me. The client only advances updateIDFrom when the ReconnectApp response carries a newer lastUpdateID, so a cursor that never moves comes from that response.

yusufdeveloper2903 avatar Oct 08 '26 09:10 yusufdeveloper2903

@eh2077 Huh... This is 4 days overdue. Who can take care of this?

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

@eh2077 this issue is now 4 weeks old, please consider:

  • Finding a contributor to fix the bug
  • Closing the issue if BZ has been unable to add the issue to a VIP or Wave project
  • If you have any questions, don't hesitate to start a discussion in #expensify-open-source

Thanks!

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