A platform for community discussion. Free, open, simple.
FEATURE: improve chat search result ranking with server-side match quality (#37031)
Régis Hanol32215213bc13
diff --git a/plugins/chat/app/serializers/chat/chatables_serializer.rb b/plugins/chat/app/serializers/chat/chatables_serializer.rbindex 73b03922596..1434b559121 100644--- a/plugins/chat/app/serializers/chat/chatables_serializer.rb+++ b/plugins/chat/app/serializers/chat/chatables_serializer.rb@@ -13,13 +13,9 @@ module Chat{identifier: "u-#{user.id}",model:- ::Chat::ChatableUserSerializer.new(- user,- scope: scope,- root: false,- include_status: true,- ),+ ::Chat::ChatableUserSerializer.new(user, scope:, root: false, include_status: true),type: "user",+ match_quality: user.match_quality,}end.as_json@@ -30,8 +26,9 @@ module Chat.map do |group|{identifier: "g-#{group.id}",- model: ::Chat::ChatableGroupSerializer.new(group, scope: scope, root: false),+ model: ::Chat::ChatableGroupSerializer.new(group, scope:, root: false),type: "group",+ match_quality: group.match_quality,}end.as_json@@ -40,16 +37,12 @@ module Chatdef direct_message_channels(object.direct_message_channels || []).map do |channel|+ membership = channel_membership(channel.id){identifier: "c-#{channel.id}",type: "channel",- model:- ::Chat::ChannelSerializer.new(- channel,- scope: scope,- root: false,- membership: channel_membership(channel.id),- ),+ model: ::Chat::ChannelSerializer.new(channel, scope:, root: false, membership:),+ match_quality: channel.match_quality,}end.as_json@@ -58,16 +51,12 @@ module Chatdef category_channels(object.category_channels || []).map do |channel|+ membership = channel_membership(channel.id){identifier: "c-#{channel.id}",type: "channel",- model:- ::Chat::ChannelSerializer.new(- channel,- scope: scope,- root: false,- membership: channel_membership(channel.id),- ),+ model: ::Chat::ChannelSerializer.new(channel, scope:, root: false, membership:),+ match_quality: channel.match_quality,}end.as_jsondiff --git a/plugins/chat/app/services/chat/search_chatable.rb b/plugins/chat/app/services/chat/search_chatable.rbindex b3e68f043b7..03fb5c08629 100644--- a/plugins/chat/app/services/chat/search_chatable.rb+++ b/plugins/chat/app/services/chat/search_chatable.rb@@ -1,10 +1,15 @@# frozen_string_literal: truemodule Chat- # Returns a list of chatables (users, groups ,category channels, direct message channels) that can be chatted with.+ # Searches for chatables (users, groups, category channels, direct message channels).+ #+ # Results include a `match_quality` field for ranking:+ # - MATCH_QUALITY_EXACT (1): name/username equals search term+ # - MATCH_QUALITY_PREFIX (2): name/username starts with search term+ # - MATCH_QUALITY_PARTIAL (3): name/username contains search term## @example- # Chat::SearchChatable.call(params: { term: "@bob" }, guardian: guardian)+ # Chat::SearchChatable.call(params: { term: "bob" }, guardian: guardian)#class SearchChatableinclude Service::Base@@ -25,7 +30,7 @@ module Chatattribute :include_direct_message_channels, :boolean, default: trueattribute :excluded_memberships_channel_id, :integer- after_validation { self.term = term&.downcase&.strip&.gsub(/^[@#]+/, "") }+ after_validation { self.term = term&.downcase&.strip&.sub(/\A[@#]+/, "") }endmodel :memberships, optional: true@@ -76,7 +81,7 @@ module Chatallowed_bot_user_ids =DiscoursePluginRegistry.apply_modifier(:chat_allowed_bot_user_ids, [], guardian)- user_search = user_search.real(allowed_bot_user_ids: allowed_bot_user_ids)+ user_search = user_search.real(allowed_bot_user_ids:)user_search = user_search.includes(:user_option)if params.excluded_memberships_channel_id@@ -87,20 +92,55 @@ module Chat)end- user_search+ filter_term = params.term.to_s+ like_term = User.sanitize_sql_like(filter_term)+ escaped_exact = User.connection.quote(filter_term)+ escaped_prefix = User.connection.quote("#{like_term}%")++ select_sql = <<~SQL+ users.*,+ CASE+ WHEN users.username_lower = #{escaped_exact} THEN #{ChannelFetcher::MATCH_QUALITY_EXACT}+ WHEN users.username_lower LIKE #{escaped_prefix} THEN #{ChannelFetcher::MATCH_QUALITY_PREFIX}+ ELSE #{ChannelFetcher::MATCH_QUALITY_PARTIAL}+ END AS match_quality+ SQL++ # need to `reorder` to override the ordering applied in `UserSearch#search`+ user_search.select(select_sql).reorder("match_quality ASC, users.username_lower ASC")enddef search_groups(params, guardian)# NOTE: Do NOT eager load users here (e.g. `.includes(users: ...)`).# Groups can have 100k+ members and loading them causes request timeouts.# The serializer uses SQL COUNT queries instead.+ filter_term = params.term.to_s+ like_term = Group.sanitize_sql_like(filter_term)+ escaped_exact = Group.connection.quote(filter_term)+ escaped_prefix = Group.connection.quote("#{like_term}%")++ select_sql = <<~SQL+ groups.*,+ CASE+ WHEN LOWER(groups.name) = #{escaped_exact} THEN #{ChannelFetcher::MATCH_QUALITY_EXACT}+ WHEN LOWER(groups.name) LIKE #{escaped_prefix} THEN #{ChannelFetcher::MATCH_QUALITY_PREFIX}+ ELSE #{ChannelFetcher::MATCH_QUALITY_PARTIAL}+ END AS match_quality+ SQL++ where_sql = <<~SQL+ LOWER(groups.name) = :exact+ OR LOWER(groups.name) LIKE :prefix+ OR LOWER(groups.name) LIKE :partial+ OR LOWER(groups.full_name) LIKE :partial+ SQL+Group.visible_groups(guardian.user).members_visible_groups(guardian.user)- .where(- "groups.name ILIKE :term_like OR groups.full_name ILIKE :term_like",- term_like: "%#{params.term}%",- )+ .where(where_sql, exact: filter_term, prefix: "#{like_term}%", partial: "%#{like_term}%")+ .select(select_sql)+ .order("match_quality ASC, groups.name ASC").limit(SEARCH_RESULT_LIMIT)end@@ -110,7 +150,6 @@ module Chatstatus: :open,filter: params.term,filter_on_category_name: false,- match_filter_on_starts_with: false,limit: SEARCH_RESULT_LIMIT,)end@@ -121,7 +160,6 @@ module Chatguardian.user.id,guardian,filter: params.term,- match_filter_on_starts_with: false,limit: SEARCH_RESULT_LIMIT,) || []diff --git a/plugins/chat/assets/javascripts/discourse/components/chat/message-creator/lib/chatables-loader.js b/plugins/chat/assets/javascripts/discourse/components/chat/message-creator/lib/chatables-loader.jsindex fca38ec76b9..6bbae1be05b 100644--- a/plugins/chat/assets/javascripts/discourse/components/chat/message-creator/lib/chatables-loader.js+++ b/plugins/chat/assets/javascripts/discourse/components/chat/message-creator/lib/chatables-loader.js@@ -3,70 +3,53 @@ import { service } from "@ember/service";import { ajax } from "discourse/lib/ajax";import { popupAjaxError } from "discourse/lib/ajax-error";import { bind } from "discourse/lib/decorators";+import { MATCH_QUALITY_PARTIAL } from "discourse/plugins/chat/discourse/lib/chat-constants";import ChatChatable from "discourse/plugins/chat/discourse/models/chat-chatable";const MAX_RESULTS = 10;-const MATCH_PRIORITY = {- EXACT: 0,- PREFIX: 1,- PARTIAL: 2,-};-const TYPE_PRIORITY = {- CHANNEL: 0,- ENABLED: 1,- DISABLED: 2,+ USER: 0,+ DM_CHANNEL: 1,+ CATEGORY_CHANNEL: 2,+ GROUP: 3,};-function getChatatableName(chatable) {- switch (chatable.type) {- case "user":- return chatable.model.username?.toLowerCase();- case "group":- return chatable.model.name?.toLowerCase();- case "channel":- return (- chatable.model.slug?.toLowerCase() ||- chatable.model.title?.toLowerCase()- );- default:- return "";- }-}--function matchPriority(chatable, term) {- const name = getChatatableName(chatable);- const lowerTerm = term.toLowerCase();-- if (name === lowerTerm) {- return MATCH_PRIORITY.EXACT;- }- if (name.startsWith(lowerTerm)) {- return MATCH_PRIORITY.PREFIX;- }- return MATCH_PRIORITY.PARTIAL;-}-function typePriority(chatable) {- if (chatable.type === "channel") {- return TYPE_PRIORITY.CHANNEL;+ if (chatable.type === "user") {+ return TYPE_PRIORITY.USER;+ }+ if (chatable.type === "group") {+ return TYPE_PRIORITY.GROUP;}- if (chatable.enabled) {- return TYPE_PRIORITY.ENABLED;+ if (chatable.model?.chatableType === "DirectMessage") {+ return TYPE_PRIORITY.DM_CHANNEL;}- return TYPE_PRIORITY.DISABLED;+ return TYPE_PRIORITY.CATEGORY_CHANNEL;}-export function sortChatables(chatables, term) {+export function sortChatables(chatables) {return chatables.sort((a, b) => {- const matchA = matchPriority(a, term);- const matchB = matchPriority(b, term);+ // Primary: match quality (from server, lower is better)+ const matchA = a.matchQuality ?? MATCH_QUALITY_PARTIAL;+ const matchB = b.matchQuality ?? MATCH_QUALITY_PARTIAL;if (matchA !== matchB) {return matchA - matchB;}- return typePriority(a) - typePriority(b);+ // Secondary: type priority (users > DM channels > category channels > groups)+ const typeA = typePriority(a);+ const typeB = typePriority(b);+ if (typeA !== typeB) {+ return typeA - typeB;+ }++ // Tertiary: enabled before disabled (applies to users and groups)+ if (a.enabled !== b.enabled) {+ return a.enabled ? -1 : 1;+ }++ return 0;});}@@ -131,7 +114,7 @@ export default class ChatablesLoader {return chatable;});- return sortChatables(chatables, term).slice(0, MAX_RESULTS);+ return sortChatables(chatables).slice(0, MAX_RESULTS);} catch (e) {popupAjaxError(e);}diff --git a/plugins/chat/assets/javascripts/discourse/lib/chat-constants.js b/plugins/chat/assets/javascripts/discourse/lib/chat-constants.jsindex 43335b36376..c8cffe3c18d 100644--- a/plugins/chat/assets/javascripts/discourse/lib/chat-constants.js+++ b/plugins/chat/assets/javascripts/discourse/lib/chat-constants.js@@ -43,3 +43,6 @@ export const CHAT_QUICK_REACTION_TYPE_CUSTOM = "custom";export const CHAT_SEPARATE_SIDEBAR_MODE_ALWAYS = "always";export const CHAT_SEPARATE_SIDEBAR_MODE_FULLSCREEN = "fullscreen";export const CHAT_SEPARATE_SIDEBAR_MODE_NEVER = "never";+export const MATCH_QUALITY_EXACT = 1;+export const MATCH_QUALITY_PREFIX = 2;+export const MATCH_QUALITY_PARTIAL = 3;diff --git a/plugins/chat/assets/javascripts/discourse/models/chat-chatable.js b/plugins/chat/assets/javascripts/discourse/models/chat-chatable.jsindex f2a58c6c782..3c350536b25 100644--- a/plugins/chat/assets/javascripts/discourse/models/chat-chatable.js+++ b/plugins/chat/assets/javascripts/discourse/models/chat-chatable.js@@ -2,6 +2,7 @@ import { tracked } from "@glimmer/tracking";import Category from "discourse/models/category";import Group from "discourse/models/group";import User from "discourse/models/user";+import { MATCH_QUALITY_PARTIAL } from "discourse/plugins/chat/discourse/lib/chat-constants";import ChatChannel from "discourse/plugins/chat/discourse/models/chat-channel";export default class ChatChatable {@@ -38,10 +39,12 @@ export default class ChatChatable {@tracked model;@tracked enabled = true;@tracked tracking;+ @tracked matchQuality = MATCH_QUALITY_PARTIAL;constructor(args = {}) {this.identifier = args.identifier;this.type = args.type;+ this.matchQuality = args.match_quality ?? MATCH_QUALITY_PARTIAL;switch (this.type) {case "channel":diff --git a/plugins/chat/lib/chat/channel_fetcher.rb b/plugins/chat/lib/chat/channel_fetcher.rbindex 153733de2c5..bb21fe41150 100644--- a/plugins/chat/lib/chat/channel_fetcher.rb+++ b/plugins/chat/lib/chat/channel_fetcher.rb@@ -7,19 +7,24 @@ module Chat# NOTE: this should always be > than `DIRECT_MESSAGE_CHANNELS_LIMIT` in `chat-channel-manager.js`MAX_DM_CHANNEL_RESULTS = 75+ # Match quality constants for search ranking (lower is better)+ MATCH_QUALITY_EXACT = 1+ MATCH_QUALITY_PREFIX = 2+ MATCH_QUALITY_PARTIAL = 3+def self.structured(guardian, include_threads: false)memberships = Chat::ChannelMembershipManager.all_for_user(guardian.user)public_channels = secured_public_channels(guardian, status: :open, following: true)direct_message_channels = secured_direct_message_channels(guardian.user.id, guardian){- public_channels: public_channels,- direct_message_channels: direct_message_channels,- memberships: memberships,+ public_channels:,+ direct_message_channels:,+ memberships:,tracking:tracking_state(public_channels.map(&:id) + direct_message_channels.map(&:id),guardian,- include_threads: include_threads,+ include_threads:,),}end@@ -30,13 +35,11 @@ module Chatreturn DB.query_single(allowed_channel_ids_sql) if !followingDB.query_single(<<~SQL, user_id: guardian.user.id)- SELECT chat_channel_id- FROM user_chat_channel_memberships- WHERE user_chat_channel_memberships.user_id = :user_id- AND user_chat_channel_memberships.chat_channel_id IN (- #{allowed_channel_ids_sql}- )- SQL+ SELECT chat_channel_id+ FROM user_chat_channel_memberships+ WHERE user_chat_channel_memberships.user_id = :user_id+ AND user_chat_channel_memberships.chat_channel_id IN (#{allowed_channel_ids_sql})+ SQLenddef self.generate_allowed_channel_ids_sql(guardian, exclude_dm_channels: false)@@ -48,7 +51,9 @@ module Chat).select("chat_channels.id").to_sql+dm_channel_sql = ""+if !exclude_dm_channelsdm_channel_sql = <<~SQLUNION@@ -69,10 +74,10 @@ module Chatend<<~SQL- -- secured category chat channels- #{category_channel_sql}- #{dm_channel_sql}- SQL+ -- secured category chat channels+ #{category_channel_sql}+ #{dm_channel_sql}+ SQLenddef self.secured_public_channel_slug_lookup(guardian, slugs)@@ -82,7 +87,7 @@ module Chat.with_categories.where(chatable_type: Chat::Channel.public_channel_chatable_types).where("chat_channels.id IN (#{allowed_channel_ids})")- .where("chat_channels.slug IN (:slugs)", slugs: slugs)+ .where("chat_channels.slug IN (:slugs)", slugs:)enddef self.secured_public_channel_search(guardian, options = {})@@ -123,21 +128,59 @@ module Chatendif options[:filter].present?- category_filter =- (options[:filter_on_category_name] ? "OR categories.name ILIKE :filter" : "")+ filter_term = options[:filter].downcase+ like_term = Chat::Channel.sanitize_sql_like(filter_term)++ if options.key?(:match_filter_on_starts_with)+ filter_sql = options[:match_filter_on_starts_with] ? "#{like_term}%" : "%#{like_term}%"+ category_filter =+ (options[:filter_on_category_name] ? "OR categories.name ILIKE :filter" : "")- sql =- "chat_channels.name ILIKE :filter OR chat_channels.slug ILIKE :filter #{category_filter}"- if options[:match_filter_on_starts_with]- filter_sql = "#{options[:filter].downcase}%"+ channels =+ channels.where(+ "chat_channels.name ILIKE :filter OR chat_channels.slug ILIKE :filter #{category_filter}",+ filter: filter_sql,+ )++ channels = channels.select("chat_channels.*, #{MATCH_QUALITY_PARTIAL} AS match_quality")+ channels = channels.order("chat_channels.name ASC, categories.name ASC")else- filter_sql = "%#{options[:filter].downcase}%"- end+ escaped_exact = Chat::Channel.connection.quote(filter_term)+ escaped_prefix = Chat::Channel.connection.quote("#{like_term}%")+ category_filter =+ (options[:filter_on_category_name] ? "OR categories.name ILIKE :partial" : "")- channels =- channels.where(sql, filter: filter_sql).order(- "chat_channels.name ASC, categories.name ASC",- )+ channels =+ channels.where(+ <<~SQL,+ LOWER(chat_channels.name) = :exact+ OR LOWER(chat_channels.name) LIKE :prefix+ OR LOWER(chat_channels.name) LIKE :partial+ OR LOWER(chat_channels.slug) = :exact+ OR LOWER(chat_channels.slug) LIKE :prefix+ OR LOWER(chat_channels.slug) LIKE :partial+ #{category_filter}+ SQL+ exact: filter_term,+ prefix: "#{like_term}%",+ partial: "%#{like_term}%",+ )++ select_sql = <<~SQL+ chat_channels.*,+ CASE+ WHEN LOWER(chat_channels.name) = #{escaped_exact} OR LOWER(chat_channels.slug) = #{escaped_exact} THEN #{MATCH_QUALITY_EXACT}+ WHEN LOWER(chat_channels.name) LIKE #{escaped_prefix} OR LOWER(chat_channels.slug) LIKE #{escaped_prefix} THEN #{MATCH_QUALITY_PREFIX}+ ELSE #{MATCH_QUALITY_PARTIAL}+ END AS match_quality+ SQL++ channels = channels.select(select_sql)+ channels =+ channels.order("match_quality ASC, chat_channels.name ASC, categories.name ASC")+ end+ else+ channels = channels.select("chat_channels.*, #{MATCH_QUALITY_PARTIAL} AS match_quality")endif options.key?(:slugs)@@ -205,7 +248,7 @@ module Chat.joins("INNER JOIN direct_message_users ON direct_message_users.direct_message_channel_id = direct_message_channels.id",)- .where("direct_message_users.user_id = :user_id", user_id: user_id)+ .where("direct_message_users.user_id = :user_id", user_id:)query =Chat::Channel@@ -222,21 +265,45 @@ module Chatquery = query.includes(chatable: [{ users: :user_status }]) if SiteSetting.enable_user_statusif options[:filter]- if options[:match_filter_on_starts_with]- filter_sql = "#{options[:filter].downcase}%"- else- filter_sql = "%#{options[:filter].downcase}%"- end+ filter_term = options[:filter].downcase+ like_term = Chat::Channel.sanitize_sql_like(filter_term)+ escaped_exact = Chat::Channel.connection.quote(filter_term)+ escaped_prefix = Chat::Channel.connection.quote("#{like_term}%")query =query.joins(user_chat_channel_memberships: :user).where(- "chat_channels.name ILIKE :filter OR chat_channels.slug ILIKE :filter OR users.username ILIKE :filter",- filter: filter_sql,+ <<~SQL,+ users.username_lower = :exact+ OR users.username_lower LIKE :prefix+ OR users.username_lower LIKE :partial+ OR LOWER(chat_channels.name) LIKE :partial+ OR LOWER(chat_channels.slug) LIKE :partial+ SQL+ exact: filter_term,+ prefix: "#{like_term}%",+ partial: "%#{like_term}%",)++ # MIN() gives us the best match among all participants+ # If ANY participant is an exact match, match_quality = MATCH_QUALITY_EXACT+ select_sql = <<~SQL+ chat_channels.*,+ MIN(+ CASE+ WHEN users.username_lower = #{escaped_exact} THEN #{MATCH_QUALITY_EXACT}+ WHEN users.username_lower LIKE #{escaped_prefix} THEN #{MATCH_QUALITY_PREFIX}+ ELSE #{MATCH_QUALITY_PARTIAL}+ END+ ) AS match_quality+ SQL++ query = query.select(select_sql)+ else+ query = query.select("chat_channels.*, #{MATCH_QUALITY_PARTIAL} AS match_quality")endif options.key?(:following)- following_params = { user_id: user_id }+ following_params = { user_id: }following_params[:following] = options[:following] if options[:following].present?query =query.joins(:user_chat_channel_memberships).where(@@ -244,11 +311,13 @@ module Chat)end- query =- query- .limit(MAX_DM_CHANNEL_RESULTS)- .order("last_message.created_at DESC NULLS LAST")- .group("chat_channels.id", "last_message.id")+ query = query.limit(MAX_DM_CHANNEL_RESULTS).group("chat_channels.id", "last_message.id")++ if options[:filter]+ query = query.order("match_quality ASC, last_message.created_at DESC NULLS LAST")+ else+ query = query.order("last_message.created_at DESC NULLS LAST")+ endchannels = query.to_a@@ -300,6 +369,7 @@ module Chatraise Discourse::NotFound if chat_channel.blank?raise Discourse::InvalidAccess if !guardian.can_join_chat_channel?(chat_channel)+chat_channelendenddiff --git a/plugins/chat/lib/chat/channel_hashtag_data_source.rb b/plugins/chat/lib/chat/channel_hashtag_data_source.rbindex b230f482635..4ac7cc58733 100644--- a/plugins/chat/lib/chat/channel_hashtag_data_source.rb+++ b/plugins/chat/lib/chat/channel_hashtag_data_source.rb@@ -58,7 +58,6 @@ module Chatguardian,filter: term,limit: limit,- exclude_dm_channels: true,match_filter_on_starts_with:condition == HashtagAutocompleteService.search_conditions[:starts_with],)diff --git a/plugins/chat/spec/lib/chat/channel_fetcher_spec.rb b/plugins/chat/spec/lib/chat/channel_fetcher_spec.rbindex 54467a88104..91785e2afbc 100644--- a/plugins/chat/spec/lib/chat/channel_fetcher_spec.rb+++ b/plugins/chat/spec/lib/chat/channel_fetcher_spec.rb@@ -229,6 +229,46 @@ describe Chat::ChannelFetcher do).to match_array([category_channel.id])end+ context "with match_quality when filtering" do+ fab!(:exact_channel) { Fabricate(:category_channel, name: "dev") }+ fab!(:prefix_channel) { Fabricate(:category_channel, name: "devops") }+ fab!(:partial_channel) { Fabricate(:category_channel, name: "mydev") }++ it "assigns correct match quality values" do+ channels = described_class.secured_public_channel_search(guardian, filter: "dev")++ expect(channels.find { |c| c.name == "dev" }.match_quality).to eq(+ described_class::MATCH_QUALITY_EXACT,+ )+ expect(channels.find { |c| c.name == "devops" }.match_quality).to eq(+ described_class::MATCH_QUALITY_PREFIX,+ )+ expect(channels.find { |c| c.name == "mydev" }.match_quality).to eq(+ described_class::MATCH_QUALITY_PARTIAL,+ )+ end++ it "orders by match quality" do+ channels =+ described_class+ .secured_public_channel_search(guardian, filter: "dev")+ .select { |c| c.name.include?("dev") }+ expect(channels.map(&:name)).to eq(%w[dev devops mydev])+ end++ it "only returns prefix matches when match_filter_on_starts_with is true" do+ channels =+ described_class.secured_public_channel_search(+ guardian,+ filter: "dev",+ match_filter_on_starts_with: true,+ )++ channel_names = channels.select { |c| c.name.include?("dev") }.map(&:name)+ expect(channel_names).to contain_exactly("dev", "devops")+ end+ end+it "can filter by an array of slugs" doexpect(described_class.secured_public_channels(guardian, slugs: ["support"]).map(&:id),@@ -474,6 +514,63 @@ describe Chat::ChannelFetcher do)endend++ context "with match_quality when filtering" do+ fab!(:david) { Fabricate(:user, username: "david") }+ fab!(:davidb) { Fabricate(:user, username: "davidb") }+ fab!(:mydavid) { Fabricate(:user, username: "mydavid") }++ fab!(:exact_dm_channel) { Fabricate(:direct_message_channel, users: [user1, david]) }+ fab!(:prefix_dm_channel) { Fabricate(:direct_message_channel, users: [user1, davidb]) }+ fab!(:partial_dm_channel) { Fabricate(:direct_message_channel, users: [user1, mydavid]) }++ it "assigns correct match quality based on participant usernames" do+ channels =+ described_class.secured_direct_message_channels_search(+ user1.id,+ guardian,+ filter: "david",+ )++ expect(channels.find { |c| c.id == exact_dm_channel.id }.match_quality).to eq(+ described_class::MATCH_QUALITY_EXACT,+ )+ expect(channels.find { |c| c.id == prefix_dm_channel.id }.match_quality).to eq(+ described_class::MATCH_QUALITY_PREFIX,+ )+ expect(channels.find { |c| c.id == partial_dm_channel.id }.match_quality).to eq(+ described_class::MATCH_QUALITY_PARTIAL,+ )+ end++ it "orders by match quality" do+ channels =+ described_class.secured_direct_message_channels_search(+ user1.id,+ guardian,+ filter: "david",+ )++ expect(channels.map(&:id)).to eq(+ [exact_dm_channel.id, prefix_dm_channel.id, partial_dm_channel.id],+ )+ end++ it "uses the best match quality among all participants" do+ mixed_channel = Fabricate(:direct_message_channel, users: [user1, david, mydavid])++ channels =+ described_class.secured_direct_message_channels_search(+ user1.id,+ guardian,+ filter: "david",+ )++ expect(channels.find { |c| c.id == mixed_channel.id }.match_quality).to eq(+ described_class::MATCH_QUALITY_EXACT,+ )+ end+ endenddescribe ".unreads_total" dodiff --git a/plugins/chat/spec/serializer/chat/chatables_serializer_spec.rb b/plugins/chat/spec/serializer/chat/chatables_serializer_spec.rbindex f4487d5cfd1..254c815dede 100644--- a/plugins/chat/spec/serializer/chat/chatables_serializer_spec.rb+++ b/plugins/chat/spec/serializer/chat/chatables_serializer_spec.rb@@ -1,9 +1,15 @@# frozen_string_literal: truedescribe Chat::ChatablesSerializer do- context "with status" do- fab!(:user_1, :user)+ fab!(:user_1, :user)+ let(:scope) { Guardian.new(Fabricate(:user)) }++ before do+ user_1.define_singleton_method(:match_quality) { Chat::ChannelFetcher::MATCH_QUALITY_PARTIAL }+ end++ describe "user status" dobefore doSiteSetting.enable_user_status = trueuser_1.set_status!("test", ":cat:")@@ -11,11 +17,7 @@ describe Chat::ChatablesSerializer doit "includes status" doserializer =- described_class.new(- OpenStruct.new({ users: [user_1] }),- scope: Guardian.new(Fabricate(:user)),- root: false,- )+ described_class.new(OpenStruct.new(users: [user_1], memberships: []), scope:, root: false)expect(serializer.users[0]["model"][:status]).to be_presentend@@ -23,13 +25,9 @@ describe Chat::ChatablesSerializer docontext "with hidden profile" dobefore { user_1.user_option.update!(hide_profile: true) }- it "doesn’t include status" do+ it "doesn't include status" doserializer =- described_class.new(- OpenStruct.new({ users: [user_1] }),- scope: Guardian.new(Fabricate(:user)),- root: false,- )+ described_class.new(OpenStruct.new(users: [user_1], memberships: []), scope:, root: false)expect(serializer.users[0]["model"][:status]).to be_blankenddiff --git a/plugins/chat/spec/services/chat/search_chatable_spec.rb b/plugins/chat/spec/services/chat/search_chatable_spec.rbindex fa3ecfe8041..4a0e4b6cac4 100644--- a/plugins/chat/spec/services/chat/search_chatable_spec.rb+++ b/plugins/chat/spec/services/chat/search_chatable_spec.rb@@ -75,6 +75,28 @@ RSpec.describe Chat::SearchChatable doexpect(result.users).to contain_exactly(sam)end+ context "with match_quality" do+ fab!(:david) { Fabricate(:user, username: "david") }+ fab!(:davidb) { Fabricate(:user, username: "davidb") }++ before { params[:term] = "david" }++ it "assigns correct match quality values" do+ users = result.users+ expect(users.find { |u| u.username == "david" }.match_quality).to eq(+ Chat::ChannelFetcher::MATCH_QUALITY_EXACT,+ )+ expect(users.find { |u| u.username == "davidb" }.match_quality).to eq(+ Chat::ChannelFetcher::MATCH_QUALITY_PREFIX,+ )+ end++ it "orders users by match quality" do+ users = result.users.select { |u| u.username.start_with?("david") }+ expect(users.map(&:username)).to eq(%w[david davidb])+ end+ end+it "can filter users with a membership to a specific channel" doparams[:excluded_memberships_channel_id] = channel_1.id@@ -159,6 +181,32 @@ RSpec.describe Chat::SearchChatable doexpect(result.groups).to_not include(hidden_group)expect(result.groups).to_not include(hidden_members_group)end++ context "with match_quality" do+ fab!(:dev_group) { Fabricate(:group, name: "dev") }+ fab!(:devops_group) { Fabricate(:group, name: "devops") }+ fab!(:mydev_group) { Fabricate(:group, name: "mydev") }++ before { params[:term] = "dev" }++ it "assigns correct match quality values" do+ groups = result.groups+ expect(groups.find { |g| g.name == "dev" }.match_quality).to eq(+ Chat::ChannelFetcher::MATCH_QUALITY_EXACT,+ )+ expect(groups.find { |g| g.name == "devops" }.match_quality).to eq(+ Chat::ChannelFetcher::MATCH_QUALITY_PREFIX,+ )+ expect(groups.find { |g| g.name == "mydev" }.match_quality).to eq(+ Chat::ChannelFetcher::MATCH_QUALITY_PARTIAL,+ )+ end++ it "orders groups by match quality then name" do+ groups = result.groups.select { |g| g.name.include?("dev") }+ expect(groups.map(&:name)).to eq(%w[dev devops mydev])+ end+ endendcontext "when not including groups" do@@ -212,7 +260,7 @@ RSpec.describe Chat::SearchChatable doexpect(result.direct_message_channels).to contain_exactly(channel_2, channel_3, channel_5)end- it "doesn’t fetches inaccessible direct message channels" do+ it "doesn't fetch inaccessible direct message channels" doexpect(result.direct_message_channels).to_not include(channel_4)enddiff --git a/plugins/chat/test/javascripts/unit/lib/chatables-loader-test.js b/plugins/chat/test/javascripts/unit/lib/chatables-loader-test.jsindex cb9ee574803..ea7733edde5 100644--- a/plugins/chat/test/javascripts/unit/lib/chatables-loader-test.js+++ b/plugins/chat/test/javascripts/unit/lib/chatables-loader-test.js@@ -1,146 +1,257 @@import { module, test } from "qunit";import { sortChatables } from "discourse/plugins/chat/discourse/components/chat/message-creator/lib/chatables-loader";+import {+ MATCH_QUALITY_EXACT,+ MATCH_QUALITY_PARTIAL,+ MATCH_QUALITY_PREFIX,+} from "discourse/plugins/chat/discourse/lib/chat-constants";import ChatChatable from "discourse/plugins/chat/discourse/models/chat-chatable";module("Discourse Chat | Unit | lib | chatables-loader", function () {- function createUserChatable(username, has_chat_enabled = true) {+ function createUserChatable(+ username,+ { has_chat_enabled = true, match_quality = MATCH_QUALITY_PARTIAL } = {}+ ) {return ChatChatable.create({type: "user",identifier: `u-${username}`,model: { id: Math.random(), username, has_chat_enabled },+ match_quality,});}- function createGroupChatable(name, can_chat = true) {+ function createGroupChatable(+ name,+ { can_chat = true, match_quality = MATCH_QUALITY_PARTIAL } = {}+ ) {return ChatChatable.create({type: "group",identifier: `g-${name}`,model: { id: Math.random(), name, can_chat },+ match_quality,});}- function createChannelChatable(title, slug = null) {+ function createDMChannelChatable(+ title,+ { match_quality = MATCH_QUALITY_PARTIAL } = {}+ ) {return ChatChatable.create({type: "channel",identifier: `c-${title}`,- model: { id: Math.random(), title, slug: slug || title.toLowerCase() },+ model: {+ id: Math.random(),+ title,+ slug: title.toLowerCase(),+ chatable_type: "DirectMessage",+ },+ match_quality,});}- test("exact matches come first", function (assert) {+ function createCategoryChannelChatable(+ title,+ { match_quality = MATCH_QUALITY_PARTIAL } = {}+ ) {+ return ChatChatable.create({+ type: "channel",+ identifier: `c-${title}`,+ model: {+ id: Math.random(),+ title,+ slug: title.toLowerCase(),+ chatable_type: "Category",+ },+ match_quality,+ });+ }++ test("users come before DM channels", function (assert) {const chatables = [- createUserChatable("developer"),- createUserChatable("dev"),- createUserChatable("devops"),+ createDMChannelChatable("david-chat", {+ match_quality: MATCH_QUALITY_EXACT,+ }),+ createUserChatable("david", { match_quality: MATCH_QUALITY_EXACT }),];- const sorted = sortChatables(chatables, "dev");- assert.strictEqual(sorted[0].model.username, "dev");+ const sorted = sortChatables(chatables);+ assert.strictEqual(sorted[0].type, "user");+ assert.strictEqual(sorted[1].type, "channel");+ });++ test("DM channels come before category channels", function (assert) {+ const chatables = [+ createCategoryChannelChatable("dev", {+ match_quality: MATCH_QUALITY_EXACT,+ }),+ createDMChannelChatable("dev-chat", {+ match_quality: MATCH_QUALITY_EXACT,+ }),+ ];++ const sorted = sortChatables(chatables);+ assert.strictEqual(sorted[0].model.chatableType, "DirectMessage");+ assert.strictEqual(sorted[1].model.chatableType, "Category");});- test("channels come before users with same match quality", function (assert) {+ test("category channels come before groups", function (assert) {const chatables = [- createUserChatable("dev"),- createChannelChatable("Dev", "dev"),+ createGroupChatable("developers", { match_quality: MATCH_QUALITY_EXACT }),+ createCategoryChannelChatable("dev", {+ match_quality: MATCH_QUALITY_EXACT,+ }),];- const sorted = sortChatables(chatables, "dev");+ const sorted = sortChatables(chatables);assert.strictEqual(sorted[0].type, "channel");- assert.strictEqual(sorted[1].type, "user");+ assert.strictEqual(sorted[1].type, "group");});- test("enabled users come before disabled users", function (assert) {+ test("exact matches come before prefix matches within same type", function (assert) {const chatables = [- createUserChatable("developer", false),- createUserChatable("devops", true),+ createUserChatable("developer", { match_quality: MATCH_QUALITY_PREFIX }),+ createUserChatable("dev", { match_quality: MATCH_QUALITY_EXACT }),+ createUserChatable("devops", { match_quality: MATCH_QUALITY_PREFIX }),];- const sorted = sortChatables(chatables, "dev");+ const sorted = sortChatables(chatables);+ assert.strictEqual(sorted[0].model.username, "dev");+ });++ test("enabled users come before disabled users with same match quality", function (assert) {+ const chatables = [+ createUserChatable("developer", {+ has_chat_enabled: false,+ match_quality: MATCH_QUALITY_EXACT,+ }),+ createUserChatable("devops", {+ has_chat_enabled: true,+ match_quality: MATCH_QUALITY_EXACT,+ }),+ ];++ const sorted = sortChatables(chatables);assert.strictEqual(sorted[0].model.username, "devops");assert.strictEqual(sorted[1].model.username, "developer");});- test("starts-with matches come before contains matches", function (assert) {+ test("chattable groups come before non-chattable groups with same match quality", function (assert) {const chatables = [- createUserChatable("mydev"),- createUserChatable("developer"),+ createGroupChatable("large-group", {+ can_chat: false,+ match_quality: MATCH_QUALITY_EXACT,+ }),+ createGroupChatable("small-group", {+ can_chat: true,+ match_quality: MATCH_QUALITY_EXACT,+ }),];- const sorted = sortChatables(chatables, "dev");+ const sorted = sortChatables(chatables);+ assert.strictEqual(sorted[0].model.name, "small-group");+ assert.strictEqual(sorted[1].model.name, "large-group");+ });++ test("prefix matches come before partial matches", function (assert) {+ const chatables = [+ createUserChatable("mydev", { match_quality: MATCH_QUALITY_PARTIAL }),+ createUserChatable("developer", { match_quality: MATCH_QUALITY_PREFIX }),+ ];++ const sorted = sortChatables(chatables);assert.strictEqual(sorted[0].model.username, "developer");assert.strictEqual(sorted[1].model.username, "mydev");});- test("full prioritization order", function (assert) {+ test("full prioritization order: match_quality > type > enabled", function (assert) {const chatables = [- createUserChatable("developer", false),- createUserChatable("devhelper", true),- createChannelChatable("Dev Talk", "dev-talk"),- createUserChatable("dev", true),- createChannelChatable("Dev", "dev"),- createGroupChatable("developers", true),- createUserChatable("superdev", false),+ createGroupChatable("developers", {+ match_quality: MATCH_QUALITY_PREFIX,+ }),+ createUserChatable("dev", {+ has_chat_enabled: true,+ match_quality: MATCH_QUALITY_EXACT,+ }),+ createUserChatable("dev-disabled", {+ has_chat_enabled: false,+ match_quality: MATCH_QUALITY_EXACT,+ }),+ createUserChatable("devhelper", {+ has_chat_enabled: true,+ match_quality: MATCH_QUALITY_PREFIX,+ }),+ createDMChannelChatable("dev-chat", {+ match_quality: MATCH_QUALITY_EXACT,+ }),+ createCategoryChannelChatable("dev-category", {+ match_quality: MATCH_QUALITY_EXACT,+ }),];- const sorted = sortChatables(chatables, "dev");+ const sorted = sortChatables(chatables);- const firstChannelName = sorted[0].model.slug ?? sorted[0].model.title;- assert.strictEqual(firstChannelName, "dev", "exact match channel first");assert.strictEqual(- sorted[1].model.username,+ sorted[0].model.username,"dev",- "exact match enabled user second"+ "exact match enabled user first");- assert.strictEqual(sorted[2].type, "channel", "starts-with channel third");assert.strictEqual(- sorted[3].model.username,- "devhelper",- "starts-with enabled user"+ sorted[1].model.username,+ "dev-disabled",+ "exact match disabled user second");assert.strictEqual(- sorted[4].model.name,- "developers",- "starts-with enabled group"+ sorted[2].model.chatableType,+ "DirectMessage",+ "exact match DM channel third");assert.strictEqual(- sorted[5].model.username,- "developer",- "starts-with disabled user"+ sorted[3].model.chatableType,+ "Category",+ "exact match category channel fourth");assert.strictEqual(- sorted[6].model.username,- "superdev",- "contains disabled user last"+ sorted[4].model.username,+ "devhelper",+ "prefix match user fifth");+ assert.strictEqual(sorted[5].type, "group", "prefix match group last");});- test("case insensitive matching", function (assert) {+ test("exact match group comes before prefix match user", function (assert) {const chatables = [- createUserChatable("DEV"),- createUserChatable("Dev"),- createUserChatable("dev"),+ createUserChatable("devs", {+ has_chat_enabled: true,+ match_quality: MATCH_QUALITY_PREFIX,+ }),+ createGroupChatable("dev", {+ can_chat: true,+ match_quality: MATCH_QUALITY_EXACT,+ }),];- const sorted = sortChatables(chatables, "DEV");-- assert.strictEqual(sorted.length, 3);- sorted.forEach((chatable) => {- assert.strictEqual(- chatable.model.username.toLowerCase(),- "dev",- `${chatable.model.username} should match`- );- });+ const sorted = sortChatables(chatables);+ assert.strictEqual(sorted[0].type, "group");+ assert.strictEqual(sorted[1].type, "user");});- test("disabled groups come after enabled users", function (assert) {+ test("match quality determines order within same type", function (assert) {const chatables = [- createGroupChatable("devs", false),- createUserChatable("devs", true),+ createDMChannelChatable("davidb-chat", {+ match_quality: MATCH_QUALITY_PREFIX,+ }),+ createDMChannelChatable("david-chat", {+ match_quality: MATCH_QUALITY_EXACT,+ }),+ createDMChannelChatable("cvx-david", {+ match_quality: MATCH_QUALITY_EXACT,+ }),];- const sorted = sortChatables(chatables, "devs");- assert.strictEqual(sorted[0].type, "user");- assert.strictEqual(sorted[1].type, "group");+ const sorted = sortChatables(chatables);+ assert.strictEqual(sorted[0].matchQuality, MATCH_QUALITY_EXACT);+ assert.strictEqual(sorted[1].matchQuality, MATCH_QUALITY_EXACT);+ assert.strictEqual(sorted[2].matchQuality, MATCH_QUALITY_PREFIX);+ assert.strictEqual(sorted[2].model.title, "davidb-chat");});});