Skip to content

Improve mention suggestion search for large channels - #4213

Merged
nuno-vieira merged 12 commits into
developfrom
fix/mention-suggestions-large-channels
Aug 13, 2026
Merged

Improve mention suggestion search for large channels#4213
nuno-vieira merged 12 commits into
developfrom
fix/mention-suggestions-large-channels

Conversation

@nuno-vieira

@nuno-vieira nuno-vieira commented Aug 11, 2026

Copy link
Copy Markdown
Member

🔗 Issue Links

🎯 Goal

Fix mention suggestions in large group chats where the target member is not in ChatChannel.lastActiveMembers, and make mention search debounce/clear reliably so typing and deleting @… does not surface stale results.

📝 Summary

  • Search channel members remotely for mention suggestions when memberCount > lastActiveMembers.count
  • Add MemberSearch / MemberSearchState and use it from mention suggestion providers
  • Add debounced RoleSearch / RoleSearchController and UserGroupSearch / UserGroupSearchController
  • Add clearResults() across user, member, role, and user group search APIs (and mention providers) to cancel in-flight work and clear cached results
  • Keep empty @ from loading the full remote member list on large channels

🛠 Implementation

Large-channel member mentions
When channel.memberCount > channel.lastActiveMembers.count, mention providers route user suggestions through remote member search instead of only filtering lastActiveMembers / lastActiveWatchers. Shared logic lives in MentionSuggestionsSearch. Smaller channels keep the existing local search path.

Debounced search state
Mention providers now reuse long-lived search objects:

  • MemberSearch for channel members
  • existing UserSearch for app-wide users
  • debounced RoleSearch / UserGroupSearch (plus matching controllers) for enhanced mentions

Clearing results
clearResults() cancels pending debounced work and clears search state. MentionSuggestionsProvider.clearResults() forwards that to the underlying search objects so UI layers can drop stale suggestion state when the mention query ends.

🧪 Manual Testing Notes

  • Open a channel with 100+ members
  • Type @ followed by a member name who is not in the first 100 cached members
  • Confirm the user appears in mention suggestions
  • Delete characters back through @ to an empty composer and confirm suggestions disappear (no stale resurfacing)
  • With enhanced mentions enabled, confirm role/group suggestions still debounce while typing

☑️ Contributor Checklist

  • I have signed the Stream CLA (required)
  • This change should be manually QAed
  • Changelog is updated with client-facing changes
  • Changelog is updated with new localization keys
  • New code is covered by unit tests
  • Documentation has been updated in the docs-content repo

Summary by CodeRabbit

  • New Features

    • Added debounced user-group, role, and channel-member searches with cancellation and pagination support.
    • Added result-clearing controls across search experiences.
    • Large-channel mention searches now retrieve matching remote members when needed.
  • Bug Fixes

    • Fixed mention suggestions failing in large channels.
    • Empty searches avoid unnecessary requests, and the current user is excluded.
  • Tests

    • Expanded coverage for search behavior, clearing results, filtering, sorting, pagination, and large channels.

When a channel has more members than lastActiveMembers can hold, mention
providers now query members via MemberList instead of only filtering the
local member list.
@nuno-vieira
nuno-vieira requested a review from a team as a code owner August 11, 2026 12:03
@coderabbitai

coderabbitai Bot commented Aug 11, 2026

Copy link
Copy Markdown

Review Change Stack

Note

Reviews paused

It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro Plus

Run ID: 9e89d589-ee7a-40e1-ad3a-63d1c99e74b8

📥 Commits

Reviewing files that changed from the base of the PR and between 900c626 and 571cbb9.

📒 Files selected for processing (3)
  • TestTools/StreamChatTestTools/Mocks/StreamChat/Workers/ChannelMemberListUpdater_Mock.swift
  • Tests/StreamChatTests/Controllers/MemberController/MemberController_Tests.swift
  • Tests/StreamChatTests/Controllers/MemberListController/MemberListController_Tests.swift
🚧 Files skipped from review as they are similar to previous changes (1)
  • TestTools/StreamChatTestTools/Mocks/StreamChat/Workers/ChannelMemberListUpdater_Mock.swift

📝 Walkthrough

Walkthrough

Mention providers now use shared search logic. Large channels use remote member searches for non-empty queries. Search APIs and controllers add configurable debouncing, cancellation, and result clearing.

Changes

Mention suggestion search

Layer / File(s) Summary
Mention resolution and remote member integration
Sources/StreamChat/MentionSuggestions/*, Sources/StreamChat/StateLayer/ChatClient+Factory.swift, Tests/StreamChatTests/MentionSuggestions/*, CHANGELOG.md
Providers delegate lookups to MentionSuggestionsSearch.fetchUsers. Large channels use MemberSearch, while empty queries avoid member requests.
Remote member search state
Sources/StreamChat/StateLayer/MemberSearch*, TestTools/.../ChannelMemberListUpdater_Mock.swift, Tests/StreamChatTests/StateLayer/MemberSearch_Tests.swift, StreamChat.xcodeproj/project.pbxproj
MemberSearch adds debounced searches, pagination, cancellation, observable state, and clearing. Tests cover requests, stale results, pagination, and state resets.
Search controllers and result clearing
Sources/StreamChat/Controllers/*SearchController/*, Sources/StreamChat/StateLayer/{RoleSearch,UserGroupSearch,UserSearch}*, Tests/StreamChatTests/{Controllers,StateLayer}/*Search*
Role and user-group searches use configurable debouncing and cancellation. Controllers support delegate updates and clearResults(). User, role, and user-group states can be cleared.

Estimated code review effort: 4 (Complex) | ~45 minutes

Mergeability Score: ⚪ Minimal · up to 571cb

The PR improves large-channel mention search and stale-result clearing without any identified merge-blocking risk; it is merge-ready after normal checks and review.

Sequence Diagram(s)

sequenceDiagram
  participant MentionSuggestionsProvider
  participant MentionSuggestionsSearch
  participant MemberSearch
  participant ChannelMemberListUpdater
  MentionSuggestionsProvider->>MentionSuggestionsSearch: fetchUsers request
  MentionSuggestionsSearch->>MemberSearch: search remote channel members
  MemberSearch->>ChannelMemberListUpdater: load member query
  ChannelMemberListUpdater-->>MemberSearch: return members
  MemberSearch-->>MentionSuggestionsProvider: return filtered suggestions
Loading

Possibly related PRs

Suggested reviewers: laevandus, martinmitrevski

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 68.49% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly summarizes the main change: improving mention suggestion search for large channels.
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.
✨ Finishing Touches 💡 1
📝 Generate docstrings 💡
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch fix/mention-suggestions-large-channels

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

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 `@Sources/StreamChat/MentionSuggestions/MentionSuggestionsSearch.swift`:
- Around line 85-87: Update the mentionAllAppUsers branch in
MentionSuggestionsSearch to filter the result of userSearch.search(query:) and
exclude the user whose ID matches currentUserId before returning it. Preserve
all other app-wide results, and add coverage for an app-wide response containing
the current user.
🪄 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: f04d3e39-3f6d-436e-b2a9-977910970a1d

📥 Commits

Reviewing files that changed from the base of the PR and between ef5cf6d and 9de4e03.

📒 Files selected for processing (6)
  • Sources/StreamChat/MentionSuggestions/DefaultMentionSuggestionsProvider.swift
  • Sources/StreamChat/MentionSuggestions/EnhancedMentionSuggestionsProvider.swift
  • Sources/StreamChat/MentionSuggestions/MentionSuggestionsSearch.swift
  • Tests/StreamChatTests/MentionSuggestions/DefaultMentionSuggestionsProvider_Tests.swift
  • Tests/StreamChatTests/MentionSuggestions/EnhancedMentionSuggestionsProvider_Tests.swift
  • Tests/StreamChatTests/MentionSuggestions/MentionSuggestionsSearch_Tests.swift

public let mentionAllAppUsers: Bool

private let userSearch: UserSearch
private let makeMemberList: @Sendable (ChannelMemberListQuery) -> MemberList

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.

why's it a closure and not a member list?

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

This is because we need to create a MemberList object per query. At the moment we do not have a MemberSearch object, like now we do with ChannelSearch. It could make sense to do it now 🤔 WDYT? Or do it in a seperate PR

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.

What about just adding state later version? We should start moving towards async-await more.

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.

Then we have nice set of these. Channel, messages, member. Also the add members view in contact info vould benefit from debounce supported MemberSearch.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

This is the state layer; the provider only uses the state layer, actually. But yeah, at the moment we don't have MemberSearch. But if we want to add it in this PR, I can do it

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

@laevandus @martinmitrevski I've updated the PR to include MemberSearch. Also, I added debouncing support for the other providers (Role Search and Group Search). While I was at it, I also added the missing GroupSearchCOntroller that was missing. (Why not)

Introduce a reusable state-layer search API matching UserSearch and
ChannelSearch, and route large-channel mention suggestions through it
instead of creating a MemberList per keystroke.
Match UserSearch/ChannelSearch so role mention typing cancels in-flight
work and debounces short queries instead of hitting the API each keystroke.
Introduce a delegate-based search controller parallel to RoleSearchController,
and apply the same dynamic debounce/cancel behavior to UserGroupSearch for
group mention typing.
Cancel in-flight searches and clear cached results when a mention query ends, so superseded responses cannot resurface stale suggestions.
@nuno-vieira nuno-vieira changed the title Search channel members remotely in large group mention suggestions Improve mention suggestion search for large channels Aug 12, 2026

@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: 4

🤖 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
`@Sources/StreamChat/Controllers/RoleSearchController/RoleSearchController.swift`:
- Around line 100-107: In RoleSearchController.swift
(Sources/StreamChat/Controllers/RoleSearchController/RoleSearchController.swift#L100-L107),
add a request generation before scheduling each search, invalidate it in
clearResults(), and gate fetch results so only the current generation may update
roles, notify the delegate, or invoke completion; apply the same guard in
UserGroupSearchController.swift
(Sources/StreamChat/Controllers/UserGroupSearchController/UserGroupSearchController.swift#L91-L98).
Add controlled stale-completion tests in RoleSearchController_Tests.swift
(Tests/StreamChatTests/Controllers/RoleSearchController/RoleSearchController_Tests.swift#L117-L130)
and UserGroupSearchController_Tests.swift
(Tests/StreamChatTests/Controllers/UserGroupSearchController/UserGroupSearchController_Tests.swift#L129-L144)
covering an old request completing after a newer search and after
clearResults().

In `@Sources/StreamChat/StateLayer/MemberSearchState.swift`:
- Around line 42-44: Require a non-nil current query before MemberSearchState
applies completed results, update
Sources/StreamChat/StateLayer/MemberSearch.swift:97-101 so clearResults
invalidates or cancels in-flight pagination, and update
Sources/StreamChat/StateLayer/UserSearchState.swift:27-31 to reject responses
received after clearing; add tests covering pagination followed by clearResults
and verify both states remain empty.

In `@StreamChat.xcodeproj/project.pbxproj`:
- Line 869: Remove both UserGroupSearchController_Tests.swift and
MemberSearch_Tests.swift from the membershipExceptions entries in
StreamChat.xcodeproj/project.pbxproj: update the entries at lines 869-869 and
969-969 so neither test file is excluded from the StreamChatTests target.

In
`@TestTools/StreamChatTestTools/Mocks/StreamChat/Workers/ChannelMemberListUpdater_Mock.swift`:
- Around line 17-23: Update cleanUp() in the mock to reset load_query_called to
the default no-op closure { _ in } alongside the other load callback state,
ensuring subsequent tests cannot invoke a callback captured by an earlier
expectation.
🪄 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: b9474660-a51a-4387-b968-f06a763a911f

📥 Commits

Reviewing files that changed from the base of the PR and between 9cf0be5 and 900c626.

📒 Files selected for processing (24)
  • CHANGELOG.md
  • Sources/StreamChat/Controllers/RoleSearchController/RoleSearchController.swift
  • Sources/StreamChat/Controllers/UserGroupSearchController/UserGroupSearchController.swift
  • Sources/StreamChat/MentionSuggestions/DefaultMentionSuggestionsProvider.swift
  • Sources/StreamChat/MentionSuggestions/EnhancedMentionSuggestionsProvider.swift
  • Sources/StreamChat/MentionSuggestions/MentionSuggestionsProvider.swift
  • Sources/StreamChat/MentionSuggestions/MentionSuggestionsSearch.swift
  • Sources/StreamChat/StateLayer/ChatClient+Factory.swift
  • Sources/StreamChat/StateLayer/MemberSearch.swift
  • Sources/StreamChat/StateLayer/MemberSearchState.swift
  • Sources/StreamChat/StateLayer/RoleSearch.swift
  • Sources/StreamChat/StateLayer/RoleSearchState.swift
  • Sources/StreamChat/StateLayer/UserGroupSearch.swift
  • Sources/StreamChat/StateLayer/UserGroupSearchState.swift
  • Sources/StreamChat/StateLayer/UserSearch.swift
  • Sources/StreamChat/StateLayer/UserSearchState.swift
  • StreamChat.xcodeproj/project.pbxproj
  • TestTools/StreamChatTestTools/Mocks/StreamChat/Workers/ChannelMemberListUpdater_Mock.swift
  • Tests/StreamChatTests/Controllers/RoleSearchController/RoleSearchController_Tests.swift
  • Tests/StreamChatTests/Controllers/UserGroupSearchController/UserGroupSearchController_Tests.swift
  • Tests/StreamChatTests/StateLayer/MemberSearch_Tests.swift
  • Tests/StreamChatTests/StateLayer/RoleSearch_Tests.swift
  • Tests/StreamChatTests/StateLayer/UserGroupSearch_Tests.swift
  • Tests/StreamChatTests/StateLayer/UserSearch_Tests.swift
🚧 Files skipped from review as they are similar to previous changes (2)
  • Sources/StreamChat/MentionSuggestions/MentionSuggestionsSearch.swift
  • Sources/StreamChat/MentionSuggestions/EnhancedMentionSuggestionsProvider.swift

Comment thread Sources/StreamChat/StateLayer/MemberSearchState.swift
Comment thread StreamChat.xcodeproj/project.pbxproj
@github-actions

Copy link
Copy Markdown
1 Warning
⚠️ Big PR

Generated by 🚫 Danger

Clear retained load completions from the mock so MemberController and MemberListController can deallocate after synchronize completes.

@laevandus laevandus 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.

✅ Verified that mentioning users not in the last active members works now. I am OK adding the additional controller as well.

@github-actions

Copy link
Copy Markdown

Public Interface

+ public class MemberSearch: @unchecked Sendable  
+ 
+   @MainActor public var state: MemberSearchState
+   
+ 
+   @discardableResult public func search(text: String,in cid: ChannelId)async throws -> [ChatChannelMember]
+   @discardableResult public func search(query: ChannelMemberListQuery)async throws -> [ChatChannelMember]
+   @discardableResult public func loadMoreMembers(limit: Int? = nil)async throws -> [ChatChannelMember]
+   public func clearResults()async

+ public extension UserGroupSearchControllerDelegate

+ @MainActor public final class MemberSearchState: ObservableObject  
+ 
+   @Published public internal var query: ChannelMemberListQuery?
+   @Published public internal var members: [ChatChannelMember]

+ public class UserGroupSearchController: DataController, DelegateCallable, DataStoreProvider, @unchecked Sendable  
+ 
+   public let client: ChatClient
+   public private var userGroups: [UserGroup]
+   public weak var delegate: UserGroupSearchControllerDelegate?
+   
+ 
+   public func searchUserGroups(text: String,teamId: String? = nil,completion: (@MainActor (Result<[UserGroup], Error>) -> Void)? = nil)
+   public func searchUserGroups(query: UserGroupSearchQuery,completion: (@MainActor (Result<[UserGroup], Error>) -> Void)? = nil)
+   public func clearResults()

+ public protocol UserGroupSearchControllerDelegate: DataControllerStateDelegate



 public final class DefaultMentionSuggestionsProvider: MentionSuggestionsProvider, Sendable  
+   public func clearResults()async

 public final class EnhancedMentionSuggestionsProvider: MentionSuggestionsProvider, Sendable  
+   public func clearResults()async

 public class UserSearch: @unchecked Sendable  
+   public func clearResults()async

 public class RoleSearch: @unchecked Sendable  
+   public func clearResults()async

 public class RoleSearchController: DataController, DelegateCallable, DataStoreProvider, @unchecked Sendable  
+   public func clearResults()

 public class UserGroupSearch: @unchecked Sendable  
+   public func clearResults()async

@Stream-SDK-Bot

Copy link
Copy Markdown
Collaborator

SDK Size

title develop branch diff status
StreamChat 7.35 MB 7.4 MB +45 KB 🟢
StreamChatUI 3.29 MB 3.29 MB 0 KB 🟢
StreamChatCommonUI 1.0 MB 1.0 MB 0 KB 🟢

@Stream-SDK-Bot

Copy link
Copy Markdown
Collaborator

StreamChat XCSize

Object Diff (bytes)
RoleSearchController.o +19469
MessageSearchController.o -17445
MemberSearch.o +8037
UserGroupSearchController.o +5311
ChannelSearch.o +5082
Show 21 more objects
Object Diff (bytes)
MemberSearchState.o +4934
ChannelRepository.o +4898
DefaultMentionSuggestionsProvider.o -4656
EnhancedMentionSuggestionsProvider.o +3420
MentionSuggestionsSearch.o +2978
UserGroupSearch.o +2428
RoleSearch.o +2359
SearchDebouncer.o +2036
GroupedChannelListLinker.o +1048
ChannelController.o +586
UploadConfig.o +488
ChannelListPayload.o +368
UserSearch.o +156
ChatClient+Factory.o +132
ReadStateHandler.o +128
PollsEvents.o -104
ChannelSearchController.o -72
ChannelMemberListUpdater.o +72
UserUpdater.o +72
AttachmentDownloader.o +68
UserGroupsRepository.o +52

@Stream-SDK-Bot

Copy link
Copy Markdown
Collaborator

StreamChatUI XCSize

Object Diff (bytes)
ChatChannelVC.o +360
ChatMessageListVC.o -112

@sonarqubecloud

Copy link
Copy Markdown

@nuno-vieira
nuno-vieira enabled auto-merge (squash) August 13, 2026 17:16
@nuno-vieira
nuno-vieira merged commit 8263bdd into develop Aug 13, 2026
20 checks passed
@nuno-vieira
nuno-vieira deleted the fix/mention-suggestions-large-channels branch August 13, 2026 17:20
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants