Skip to content

fix(Channel): guard render-phase channel.getConfig() against disconnected channels - #3257

Open
oliverlaz wants to merge 2 commits into
masterfrom
fix/disconnected-channel-getconfig
Open

fix(Channel): guard render-phase channel.getConfig() against disconnected channels#3257
oliverlaz wants to merge 2 commits into
masterfrom
fix/disconnected-channel-getconfig

Conversation

@oliverlaz

@oliverlaz oliverlaz commented Aug 5, 2026

Copy link
Copy Markdown
Member

🎯 Goal

Fixes: #3254

ChannelInner called channel.getConfig() directly in the component body. That call throws You can't use a channel after client.disconnect() was called once the channel is disconnected β€” which happens when the current user is removed from a channel or the channel is deleted. The flag is flipped by an async WS event while <Channel> is still mounted, so the throw landed in the render phase and tore down the surrounding subtree.

Same failure class as #2393 and #3248.

πŸ›  Implementation details

Added an internal getChannelConfig(channel) helper that returns undefined for a disconnected channel instead of calling getConfig(), and applied it everywhere the config was read during render or in an effect:

  • Channel.tsx β€” the reported crash. Now also a lazy useState initializer, so the call no longer re-runs on every render.
  • AttachmentSelector.tsx and useMessageComposerCommands.ts
  • useMarkRead.ts

handleEvent in Channel.tsx also early-returns for a disconnected channel, and the composer skips draft creation on unmount.

loadMoreNewer picked up the channel.disconnected guard that loadMore already had β€” without it, scrolling to the bottom of a disconnected channel still queried a dead channel on every attempt (caught by the existing try/catch, so only log noise and a redundant dispatch).

Fixing Channel alone is not enough: the crash relocates to AttachmentSelector once ChannelInner stops throwing and its subtree starts rendering.

undefined is already part of getConfig()'s return type, so degradation is graceful β€” no read events, no commands, and the attachment selector renders nothing instead of crashing.

Overlaps with #3249, which adds the same if (messageComposer.channel.disconnected) return; line along with a more complete treatment of that effect (.catch() on createDraft(), a drafts-enabled check, and preventClearingOnUnmount). #3249 should own that effect β€” the line is kept here only so this PR stays independently mergeable. Whoever merges second should drop the duplicate.

9 tests added, each verified to fail against the unfixed code first.

🎨 UI Changes

None.

…cted channels

ChannelInner evaluated channel.getConfig() as an eager useState argument, which
throws "You can't use a channel after client.disconnect() was called" once the
channel is disconnected (current user removed / channel deleted). The throw
happened during render, tearing down the surrounding subtree.

Add an internal getChannelConfig() guard, apply it at every render-phase call
site, use a lazy initializer so it no longer re-runs on every render, and
early-return from handleEvent for a disconnected channel.

Fixing Channel alone is not enough: the crash relocates to AttachmentSelector
once ChannelInner stops throwing and its subtree renders.

Closes #3254
@coderabbitai

coderabbitai Bot commented Aug 5, 2026

Copy link
Copy Markdown

Review Change Stack

πŸ“ Walkthrough

Walkthrough

The PR adds a shared disconnected-channel configuration guard. Channel rendering, events, and pagination avoid unsafe access. Composer and read-state flows skip operations that require an active client. Regression tests cover these paths.

Changes

Disconnected channel safety

Layer / File(s) Summary
Safe channel configuration access
src/utils/getChannelConfig.ts, src/utils/__tests__/getChannelConfig.test.ts
Adds getChannelConfig, which returns undefined for disconnected channels and otherwise calls channel.getConfig().
Channel render and event guards
src/components/Channel/Channel.tsx, src/components/Channel/__tests__/Channel.test.tsx
Uses the shared helper during initialization. Disconnected events and newer-message pagination return early. Tests cover rerenders, initial state, pagination, and event handling.
Composer and message-list guards
src/components/MessageComposer/..., src/components/MessageList/hooks/...
Uses the shared helper for attachment actions, commands, and read-event support. Composer cleanup skips draft operations when disconnected. Tests cover each path.

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

Suggested reviewers: arnautov-anton

πŸš₯ Pre-merge checks | βœ… 5
βœ… Passed checks (5 passed)
Check name Status Explanation
Linked Issues check βœ… Passed The changes satisfy issue #3254 by guarding disconnected channels and using a lazy initializer to prevent render-phase crashes.
Out of Scope Changes check βœ… Passed The additional guards address the same disconnected-channel failure class and are supported by the stated objectives and regression tests.
Docstring Coverage βœ… Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
Title check βœ… Passed The title clearly identifies the fix for render-phase getConfig calls on disconnected channels.
Description check βœ… Passed The description includes the required goal, implementation details, and UI changes sections with sufficient detail.
✨ Finishing Touches
πŸ“ Generate docstrings
  • Create stacked PR
  • Commit on current branch
πŸ§ͺ Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch fix/disconnected-channel-getconfig

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.

@github-actions

github-actions Bot commented Aug 5, 2026

Copy link
Copy Markdown

Size Change: +739 B (+0.08%)

Total Size: 885 kB

πŸ“¦ View Changed
Filename Size Change
dist/cjs/channel-detail.js 23.3 kB -2 B (-0.01%)
dist/cjs/emojis.js 2.65 kB -1 B (-0.04%)
dist/cjs/index.js 293 kB +25 B (+0.01%)
dist/cjs/ReactPlayerWrapper.js 545 B -1 B (-0.18%)
dist/cjs/useChannelHeaderOnlineStatus.js 41.2 kB -1 B (0%)
dist/cjs/useMessageComposerController.js 1.01 kB -1 B (-0.1%)
dist/cjs/useNotificationApi.js 58.3 kB +361 B (+0.62%)
dist/es/channel-detail.mjs 22.7 kB -2 B (-0.01%)
dist/es/emojis.mjs 2.58 kB -1 B (-0.04%)
dist/es/index.mjs 290 kB +6 B (0%)
dist/es/useChannelHeaderOnlineStatus.mjs 40.6 kB -1 B (0%)
dist/es/useNotificationApi.mjs 57.1 kB +357 B (+0.63%)
ℹ️ View Unchanged
Filename Size
dist/cjs/audioProcessing.js 1.74 kB
dist/cjs/mp3-encoder.js 814 B
dist/css/channel-detail.css 2.84 kB
dist/css/emoji-picker.css 178 B
dist/css/emoji-replacement.css 456 B
dist/css/index.css 41.4 kB
dist/es/audioProcessing.mjs 1.65 kB
dist/es/mp3-encoder.mjs 768 B
dist/es/ReactPlayerWrapper.mjs 485 B
dist/es/useMessageComposerController.mjs 936 B

compressed-size-action

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Actionable comments posted: 1

πŸ€– 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/components/MessageComposer/MessageComposer.tsx`:
- Around line 98-105: Recheck messageComposer.channel.disconnected inside the
finally callback before calling messageComposer.clear(), while preserving the
existing early return before createDraft(). Add a test covering an unresolved
createDraft(), unmounting and disconnecting the channel, then resolving the
draft and verifying clear() is not called.
πŸͺ„ 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: defaults

Review profile: CHILL

Plan: Pro Plus

Run ID: 8dfb987f-5afb-479d-a989-5f3fb44ef7e7

πŸ“₯ Commits

Reviewing files that changed from the base of the PR and between 13b3f13 and 36d2a37.

πŸ“’ Files selected for processing (12)
  • src/components/Channel/Channel.tsx
  • src/components/Channel/__tests__/Channel.test.tsx
  • src/components/MessageComposer/AttachmentSelector/AttachmentSelector.tsx
  • src/components/MessageComposer/MessageComposer.tsx
  • src/components/MessageComposer/__tests__/AttachmentSelector.test.tsx
  • src/components/MessageComposer/__tests__/MessageInput.test.tsx
  • src/components/MessageComposer/hooks/__tests__/useMessageComposerCommands.test.tsx
  • src/components/MessageComposer/hooks/useMessageComposerCommands.ts
  • src/components/MessageList/hooks/__tests__/useMarkRead.test.tsx
  • src/components/MessageList/hooks/useMarkRead.ts
  • src/utils/__tests__/getChannelConfig.test.ts
  • src/utils/getChannelConfig.ts

Comment on lines +98 to 105
// A disconnected channel (current user removed / channel deleted) cannot
// accept a draft, and neither createDraft() nor clear() are safe to call:
// both reach channel.getConfig(), which throws "You can't use a channel
// after client.disconnect() was called". The composer is going away with
// the channel, so there is nothing left worth persisting or resetting.
if (messageComposer.channel.disconnected) return;

messageComposer.createDraft().finally(() => messageComposer.clear());

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🩺 Stability & Availability | 🟠 Major | ⚑ Quick win

Recheck disconnection before clear().

Line 103 only protects the start of cleanup. A WebSocket event can disconnect the channel while createDraft() is pending. The finally callback then calls messageComposer.clear(), which reaches channel.getConfig() after client.disconnect() and can throw.

Recheck messageComposer.channel.disconnected inside finally. Add a test that leaves createDraft() pending, unmounts, disconnects the channel, resolves the draft promise, and verifies that clear() is not called.

Proposed fix
-      messageComposer.createDraft().finally(() => messageComposer.clear());
+      void messageComposer.createDraft().finally(() => {
+        if (!messageComposer.channel.disconnected) {
+          messageComposer.clear();
+        }
+      });
πŸ“ Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
// A disconnected channel (current user removed / channel deleted) cannot
// accept a draft, and neither createDraft() nor clear() are safe to call:
// both reach channel.getConfig(), which throws "You can't use a channel
// after client.disconnect() was called". The composer is going away with
// the channel, so there is nothing left worth persisting or resetting.
if (messageComposer.channel.disconnected) return;
messageComposer.createDraft().finally(() => messageComposer.clear());
// A disconnected channel (current user removed / channel deleted) cannot
// accept a draft, and neither createDraft() nor clear() are safe to call:
// both reach channel.getConfig(), which throws "You can't use a channel
// after client.disconnect() was called". The composer is going away with
// the channel, so there is nothing left worth persisting or resetting.
if (messageComposer.channel.disconnected) return;
void messageComposer.createDraft().finally(() => {
if (!messageComposer.channel.disconnected) {
messageComposer.clear();
}
});
πŸ€– 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/components/MessageComposer/MessageComposer.tsx` around lines 98 - 105,
Recheck messageComposer.channel.disconnected inside the finally callback before
calling messageComposer.clear(), while preserving the existing early return
before createDraft(). Add a test covering an unresolved createDraft(),
unmounting and disconnecting the channel, then resolving the draft and verifying
clear() is not called.

@codecov

codecov Bot commented Aug 5, 2026

Copy link
Copy Markdown

Codecov Report

βœ… All modified and coverable lines are covered by tests.
βœ… Project coverage is 85.18%. Comparing base (1b8fa34) to head (36d2a37).
⚠️ Report is 2 commits behind head on master.

Additional details and impacted files
@@            Coverage Diff             @@
##           master    #3257      +/-   ##
==========================================
- Coverage   85.21%   85.18%   -0.03%     
==========================================
  Files         507      509       +2     
  Lines       15957    15971      +14     
  Branches     5029     5033       +4     
==========================================
+ Hits        13597    13605       +8     
- Misses       2360     2366       +6     

β˜” View full report in Codecov by Harness.
πŸ“’ Have feedback on the report? Share it here.

πŸš€ New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • πŸ“¦ JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

loadMore already short-circuits on channel.disconnected, but loadMoreNewer
checked only online.current / navigator.onLine / hasNext and went on to call
channel.query(), which throws for a disconnected channel. The existing
try/catch swallowed it into a console.warn plus a spurious
setLoadingMoreNewer dispatch on every scroll-to-bottom.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

2 participants