Skip to content

fix: eliminate unread badge dispatch storm that crashed TabBar rendering - #3437

Merged
jeanfbrito merged 1 commit into
masterfrom
fix/unread-badge-dispatch-storm
Aug 5, 2026
Merged

fix: eliminate unread badge dispatch storm that crashed TabBar rendering#3437
jeanfbrito merged 1 commit into
masterfrom
fix/unread-badge-dispatch-storm

Conversation

@jeanfbrito

@jeanfbrito jeanfbrito commented Aug 5, 2026

Copy link
Copy Markdown
Member

Summary

Root-causes and fixes the long-standing intermittent Maximum update depth exceeded storm (first reported as 119 errors within ~1 second, ~20s after startup). The trigger turned out to be data-dependent, not code-dependent — which is why it always looked random.

How it was found

After #3435 and #3436 merged, the error storm still reproduced — now deterministically, ~2s after every startup, at reduced intensity (10–14 errors). Two techniques pinned it down:

1. Build bisection. Five builds were launched under identical conditions and the error count measured after startup:

Build Errors per startup
master (#3434 + #3435 + #3436) 12–14
master without the setVersion dispatch 12
#3434 + #3435 10
#3434 only 12
4.16.0-alpha.2 baseline (no merged PRs) 12

Every build reproduced, including the untouched baseline — so no merged PR caused it. The environment had changed instead: the storm only fires when servers have unread rooms at boot. Earlier same-day runs with no unread state were consistently clean, which is also why the bug historically appeared intermittent.

2. react-dom instrumentation. Patching getRootForUpdatedFiber (locally, dev only) to print the fiber chain at the moment of the throw identified the crashing subscriber:

[LOOP-DEBUG] fiber chain: TabBar < div < TooltipProvider < Shell < I18nextProvider < ReactRedux < Provider < ErrorCatcher < App

Root cause

On webapp boot, the server fires one unread-changed-by-subscription event per room. The chain amplified each one:

  1. injected.ts recomputed and called setBadge for every event — no coalescing, no value dedupe
  2. preload/badge.ts dispatched WEBVIEW_UNREAD_CHANGED unconditionally, even for identical values
  3. the servers reducer's upsert/update minted a new array (and server object) even when the patch changed nothing
  4. every server-subscribed component re-rendered per dispatch; with enough unread rooms, React hit its nested-update limit inside TabBar and aborted

Changes

  • src/injected.ts — badge recomputes are coalesced into a single 100ms trailing-edge call, and setBadge is skipped when the resolved value is unchanged
  • src/servers/preload/badge.ts — consecutive identical badge values no longer dispatch (also covers the pre-7.8.0 Session autorun path)
  • src/servers/reducers.tsupsert/update preserve object and array identity for no-op patches, so no-op actions no longer re-render every consumer
  • src/servers/bootWatchdog.ts — the boot deadline now arms on the first committed navigation instead of on attach; webviews that legitimately never navigate (lazy or error panes) were producing false boot-deadline-exceeded reports

Validation

  • Runtime, against the live trigger: 0 errors across the startup window, versus 10–14 in six consecutive pre-fix runs under the same account state
  • npx tsc --noEmit clean, yarn lint clean
  • yarn test: 155 suites, 1666 passed, 2 skipped
  • yarn build clean (externals check passed)

Relationship to previous PRs

#3435's fixes remain valid and necessary — they reduced the storm's amplification (119 → ~12) by stabilizing subscribers. This PR removes the storm at its source. Whether the badge storm also explains the intermittent boot wedge (stuck throbber, #3436) is not yet confirmed; the boot watchdog from #3436 remains in place to capture forensic reports if a wedge recurs.

Summary by CodeRabbit

  • Bug Fixes
    • Unread badge updates are now smoother and avoid redundant refreshes during rapid event bursts.
    • Badge counts continue updating correctly when values change.
    • Boot timeout reports are avoided for panes that have not started navigation.
    • Unchanged server updates no longer trigger unnecessary refreshes.

On webapp boot the server fires one unread-changed-by-subscription event
per room. Each event dispatched a badge update to the root window's Redux
store, the servers reducer minted a new array even for no-op patches, and
every server-subscribed component re-rendered per dispatch — with unread
rooms present at startup, React aborted TabBar with 'Maximum update depth
exceeded' on every launch.

- injected.ts: coalesce badge recomputes into a 100ms trailing-edge timer
  and skip setBadge entirely when the resolved value did not change
- preload badge.ts: skip dispatching consecutive identical badge values
  (also covers the pre-7.8.0 Session autorun path)
- servers reducers: upsert/update now preserve object and array identity
  when a patch would not change any field, so no-op actions no longer
  re-render every consumer
- bootWatchdog: arm the boot deadline on the first committed navigation
  instead of on attach — webviews that legitimately never navigate (lazy
  or error panes) produced false boot-deadline-exceeded reports
@coderabbitai

coderabbitai Bot commented Aug 5, 2026

Copy link
Copy Markdown
Contributor

Review Change Stack

Walkthrough

The PR coalesces unread badge updates and suppresses unchanged dispatches. It defers boot watchdog deadlines until navigation. It also preserves server state identity for no-op updates.

Changes

Unread badge update flow

Layer / File(s) Summary
Coalesced unread badge dispatch
src/injected.ts, src/servers/preload/badge.ts
Unread events use a 100 ms trailing-edge scheduler. Aggregate counts are retained. Unchanged badge values do not dispatch again.

Boot watchdog lifecycle

Layer / File(s) Summary
Navigation-based watchdog deadline
src/servers/bootWatchdog.ts
Webview attachment no longer starts the deadline. The deadline starts after did-navigate.

Server reducer identity preservation

Layer / File(s) Summary
No-op server patching
src/servers/reducers.ts
upsert and update preserve server and array identity when patched values are unchanged.

Estimated code review effort: 3 (Moderate) | ~20 minutes

Possibly related PRs

Suggested labels: type: bug

Suggested reviewers: ggazzo

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly describes the primary fix for the unread badge dispatch storm that caused TabBar rendering failures.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

Warning

There were issues while running some tools. Please review the errors and either fix the tool's configuration or disable the tool if it's a critical failure.

🔧 ESLint

If the error stems from missing dependencies, add them to the package.json file. For unrecoverable errors (e.g., due to private dependencies), disable the tool in the CodeRabbit configuration.

ESLint install failed. For unrecoverable errors, disable the tool in CodeRabbit configuration.


Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🧹 Nitpick comments (1)
src/servers/preload/badge.ts (1)

6-18: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Add regression tests for the deduplication contract.

The adjacent test only verifies one dispatch. Add cases for the first badge value, a repeated equal value, and a changed value. Reset the module-scoped hasDispatched and lastBadge between tests so one test does not hide another.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@src/servers/preload/badge.ts` around lines 6 - 18, Add regression tests
covering setBadge’s first dispatch, suppression of a repeated equal badge, and
dispatch of a changed badge. Reset the module-scoped hasDispatched and lastBadge
state between tests so each case independently verifies the deduplication
contract.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@src/injected.ts`:
- Around line 540-541: Share badge deduplication across the event and pre-7.8
Tracker.autorun producers: route both paths through a single helper that updates
the same lastSentBadge state, or remove the local guard and rely on the shared
deduplication in preload/badge.ts. Ensure alternating badge values from either
producer are applied correctly without stale local state suppressing updates.

---

Nitpick comments:
In `@src/servers/preload/badge.ts`:
- Around line 6-18: Add regression tests covering setBadge’s first dispatch,
suppression of a repeated equal badge, and dispatch of a changed badge. Reset
the module-scoped hasDispatched and lastBadge state between tests so each case
independently verifies the deduplication contract.
🪄 Autofix

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 3b11a535-fa5e-47e3-a875-bc1cf87998fb

📥 Commits

Reviewing files that changed from the base of the PR and between a5d10ec and 564f989.

📒 Files selected for processing (4)
  • src/injected.ts
  • src/servers/bootWatchdog.ts
  • src/servers/preload/badge.ts
  • src/servers/reducers.ts
📜 Review details
⏰ Context from checks skipped due to timeout. (7)
  • GitHub Check: build (windows-latest, windows)
  • GitHub Check: build (macos-latest, mac)
  • GitHub Check: build (ubuntu-latest, linux)
  • GitHub Check: check (macos-latest)
  • GitHub Check: check (ubuntu-latest)
  • GitHub Check: check (windows-latest)
  • GitHub Check: Analyze (javascript)
🧰 Additional context used
📓 Path-based instructions (1)
**/*.{ts,tsx}

📄 CodeRabbit inference engine (AGENTS.md)

**/*.{ts,tsx}: Use TypeScript for new code unless explicitly told otherwise.
Use Fuselage components from @rocket.chat/fuselage for UI work unless the design requires something Fuselage does not provide.
Check Theme.d.ts for valid color tokens before using Fuselage colors.
Verify library props, APIs, and tokens against official docs or local .d.ts files instead of assuming.
Use React functional components with hooks.
Redux actions follow FSA shape.
Use camelCase for file names and PascalCase for components.
Prefer clear names over unnecessary comments.
Prefer editing existing files over creating new abstractions unless the new abstraction removes real complexity or matches an existing pattern.

**/*.{ts,tsx}: Use TypeScript for all new code unless explicitly told otherwise.
Use Fuselage components for all UI work; create custom components only when Fuselage lacks the required functionality.
Import Fuselage components from @rocket.chat/fuselage.
Use only valid color tokens documented by Theme.d.ts.
Use optional chaining with fallbacks for platform-specific APIs, especially Linux-only process APIs such as process.getuid(), getgid(), geteuid(), and getegid().
Use TypeScript strict mode.
Redux actions must follow the Flux Standard Action pattern.
Use camelCase for file names and PascalCase for component names.
Avoid unnecessary comments; prefer self-documenting code through clear naming.
Do not commit or push without explicit user permission.
Verify library APIs, props, tokens, and types against official documentation and .d.ts files instead of assuming they are valid.

Files:

  • src/servers/reducers.ts
  • src/servers/preload/badge.ts
  • src/servers/bootWatchdog.ts
  • src/injected.ts
🔇 Additional comments (3)
src/servers/bootWatchdog.ts (1)

212-214: LGTM!

src/injected.ts (1)

530-539: LGTM!

Also applies to: 582-595, 614-614, 623-623

src/servers/reducers.ts (1)

80-100: LGTM!

Also applies to: 110-113

Comment thread src/injected.ts
Comment on lines +540 to +541
let lastSentBadge: number | '•' | undefined;
let hasSentBadge = false;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🎯 Functional Correctness | 🟠 Major | ⚡ Quick win

Share badge deduplication state across both producers.

lastSentBadge tracks only values sent by resolveBadge. The pre-7.8 Tracker.autorun at Line [500-503] calls window.RocketChatDesktop.setBadge directly and does not update this state. If the event path sends 3, the Session path sends 0, and the event path computes 3 again, this guard returns and leaves the actual badge at 0.

Route both producers through one shared helper, or remove this second guard and rely on the shared deduplication in src/servers/preload/badge.ts.

Suggested fix
-      let lastSentBadge: number | '•' | undefined;
-      let hasSentBadge = false;
...
-        if (hasSentBadge && badge === lastSentBadge) {
-          return;
-        }
-        hasSentBadge = true;
-        lastSentBadge = badge;
         window.RocketChatDesktop.setBadge(badge);

Also applies to: 573-579

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@src/injected.ts` around lines 540 - 541, Share badge deduplication across the
event and pre-7.8 Tracker.autorun producers: route both paths through a single
helper that updates the same lastSentBadge state, or remove the local guard and
rely on the shared deduplication in preload/badge.ts. Ensure alternating badge
values from either producer are applied correctly without stale local state
suppressing updates.

@github-actions

github-actions Bot commented Aug 5, 2026

Copy link
Copy Markdown

@github-actions

github-actions Bot commented Aug 5, 2026

Copy link
Copy Markdown

@jeanfbrito
jeanfbrito merged commit aac1316 into master Aug 5, 2026
12 checks passed
@jeanfbrito
jeanfbrito deleted the fix/unread-badge-dispatch-storm branch August 5, 2026 20:35
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant