A platform for community discussion. Free, open, simple.
FEATURE: fallback to filter in search tool (#36948)
Sam7c268cdec69c
diff --git a/plugins/discourse-ai/lib/personas/tools/search.rb b/plugins/discourse-ai/lib/personas/tools/search.rbindex 8516912aa80..317a82d1fdf 100644--- a/plugins/discourse-ai/lib/personas/tools/search.rb+++ b/plugins/discourse-ai/lib/personas/tools/search.rb@@ -6,8 +6,6 @@ module DiscourseAiclass Search < Toolattr_reader :last_query- MIN_SEMANTIC_RESULTS = 5-class << selfdef signature{@@ -135,17 +133,22 @@ module DiscourseAi)@last_num_results = results[:rows]&.length || 0+ @last_filter_query = results[:filter_query]resultsendprotecteddef description_args- {- count: @last_num_results || 0,- query: @last_query || "",- url: "#{Discourse.base_path}/search?q=#{CGI.escape(@last_query || "")}",- }+ # Use /filter when we fell back to TopicsFilter, otherwise use /search+ url =+ if @last_filter_query.present?+ "#{Discourse.base_path}/filter?q=#{CGI.escape(@last_filter_query)}"+ else+ "#{Discourse.base_path}/search?q=#{CGI.escape(@last_query || "")}"+ end++ { count: @last_num_results || 0, query: @last_query || "", url: url }endprivatediff --git a/plugins/discourse-ai/lib/utils/search.rb b/plugins/discourse-ai/lib/utils/search.rbindex 70edac2839e..c1c88036810 100644--- a/plugins/discourse-ai/lib/utils/search.rb+++ b/plugins/discourse-ai/lib/utils/search.rb@@ -3,6 +3,9 @@module DiscourseAimodule Utilsclass Search+ # arbitrary but we need something safe here+ MAX_RESULTS_LIMIT = 200+def self.perform_search(search_query: nil,category: nil,@@ -18,6 +21,28 @@ module DiscourseAicurrent_user: nil,result_style: :compact)+ max_results = max_results.to_i+ raise ArgumentError, "max_results must be a positive integer" if max_results <= 0+ max_results = MAX_RESULTS_LIMIT if max_results > MAX_RESULTS_LIMIT++ if search_query.blank? &&+ has_any_filter?(category, user, order, tags, before, after, status)+ return(+ fallback_to_filter(+ category:,+ user:,+ order:,+ tags:,+ before:,+ after:,+ status:,+ max_results:,+ current_user:,+ result_style:,+ )+ )+ end+search_terms = []search_terms << search_query.strip if search_query.present?@@ -40,16 +65,16 @@ module DiscourseAireturn({args: {- search_query: search_query,- category: category,- user: user,- order: order,- max_posts: max_posts,- tags: tags,- before: before,- after: after,- status: status,- max_results: max_results,+ search_query:,+ category:,+ user:,+ order:,+ max_posts:,+ tags:,+ before:,+ after:,+ status:,+ max_results:,}.compact,rows: [],instruction: I18n.t("invalid_access"),@@ -97,55 +122,178 @@ module DiscourseAiendend- hidden_tags = nil-# Construct search_args hash for consistent return formatsearch_args = {- search_query: search_query,- category: category,- user: user,- order: order,- max_posts: max_posts,- tags: tags,- before: before,- after: after,- status: status,- max_results: max_results,+ search_query:,+ category:,+ user:,+ order:,+ max_posts:,+ tags:,+ before:,+ after:,+ status:,+ max_results:,}.compactif posts.blank?{ args: search_args, rows: [], instruction: "nothing was found, expand your search" }else+ hidden_tags = DiscourseTagging.hidden_tag_names if SiteSetting.tagging_enabledformat_results(posts, args: search_args, result_style: result_style) do |post|- category_names = [- post.topic.category&.parent_category&.name,- post.topic.category&.name,- ].compact.join(" > ")- row = {- title: post.topic.title,- url: Discourse.base_path + post.url,- username: post.user&.username,- excerpt: post.excerpt,- created: post.created_at,- category: category_names,- likes: post.like_count,- topic_views: post.topic.views,- topic_likes: post.topic.like_count,- topic_replies: post.topic.posts_count - 1,- }+ format_row(topic: post.topic, post:, hidden_tags:)+ end+ end+ end++ def self.order_to_filter_syntax(order)+ case order&.to_s+ when "latest", "latest_topic"+ "order:activity"+ when "oldest"+ "order:created-asc"+ when "views"+ "order:views"+ when "likes"+ "order:likes"+ end+ end++ def self.has_any_filter?(category, user, order, tags, before, after, status)+ [category, user, order, tags, before, after, status].any?(&:present?)+ end++ def self.fallback_to_filter(+ category:,+ user:,+ order:,+ tags:,+ before:,+ after:,+ status:,+ max_results:,+ current_user:,+ result_style:+ )+ guardian = Guardian.new(current_user)++ query_parts = []+ query_parts << "category:#{category}" if category.present?+ if order.present? && order_to_filter_syntax(order)+ query_parts << order_to_filter_syntax(order)+ end+ query_parts << "tags:#{tags}" if tags.present?+ query_parts << "users:#{user}" if user.present?+ query_parts << "created-before:#{before}" if before.present?+ query_parts << "created-after:#{after}" if after.present?+ query_parts << "status:#{status}" if status.present?- if SiteSetting.tagging_enabled- hidden_tags ||= DiscourseTagging.hidden_tag_names- tags = post.topic.tags.map(&:name) - hidden_tags- row[:tags] = tags.join(", ") if tags.present?+ return empty_results if query_parts.blank?++ scope = TopicQuery.new(guardian.user).latest_results(skip_ordering: true)+ filter = TopicsFilter.new(guardian:, scope: scope)+ topics = filter.filter_from_query_string(query_parts.join(" "))++ # may be uneeded with goldiloader+ topics = topics.includes(:category, :user)+ topics = topics.includes(:tags) if SiteSetting.tagging_enabled+ topics = topics.limit(max_results)++ format_filter_results(+ topics,+ query_string: query_parts.join(" "),+ result_style:,+ category:,+ user:,+ order:,+ tags:,+ before:,+ after:,+ status:,+ max_results:,+ )+ end++ def self.format_filter_results(+ topics,+ query_string:,+ result_style:,+ category:,+ user:,+ order:,+ tags:,+ before:,+ after:,+ status:,+ max_results:+ )+ search_args = {+ category:,+ user:,+ order:,+ tags:,+ before:,+ after:,+ status:,+ max_results:,+ }.compact++ if topics.blank?+ {+ args: search_args,+ rows: [],+ instruction: "nothing was found, expand your search",+ filter_query: query_string,+ }+ else+ hidden_tags = DiscourseTagging.hidden_tag_names if SiteSetting.tagging_enabled+ result =+ format_results(topics, args: search_args, result_style: result_style) do |topic|+ format_row(topic: topic, hidden_tags:)end+ result[:filter_query] = query_string+ result+ end+ end- row- end+ def self.empty_results+ { args: {}, rows: [], instruction: "nothing was found, expand your search" }+ end++ def self.format_row(topic:, post: nil, hidden_tags: nil)+ row = {+ title: topic.title,+ # this is deliberate, we don't want to repeat https://example.com/ in every result, but we need subfolder+ url: Discourse.base_path + (post ? post.url : topic.relative_url),+ username: post ? post.user&.username : topic.user&.username,+ excerpt: post ? post.excerpt : topic.excerpt,+ created: post ? post.created_at : topic.created_at,+ category: category_breadcrumb(topic.category),+ likes: post ? post.like_count : topic.like_count,+ topic_views: topic.views,+ topic_likes: topic.like_count,+ # deliberate - we don't want the number of "replies" in the Discourse sense, this is total number or replies to topic+ topic_replies: topic.posts_count - 1,+ }++ if SiteSetting.tagging_enabled+ hidden_tags ||= DiscourseTagging.hidden_tag_names+ tag_names = visible_tag_names(topic.tags, hidden_tags)+ row[:tags] = tag_names if tag_namesend++ rowend- private+ def self.category_breadcrumb(category)+ [category&.parent_category&.name, category&.name].compact.join(" > ")+ end++ def self.visible_tag_names(tags, hidden_tags)+ return nil unless SiteSetting.tagging_enabled && tags.present?+ visible = tags.map(&:name) - hidden_tags+ visible.presence&.join(", ")+ enddef self.format_results(rows, args: nil, result_style:)rows = rows&.map { |row| yield row } if block_given?diff --git a/plugins/discourse-ai/spec/lib/personas/tools/search_spec.rb b/plugins/discourse-ai/spec/lib/personas/tools/search_spec.rbindex 7ca61581879..139b808f10e 100644--- a/plugins/discourse-ai/spec/lib/personas/tools/search_spec.rb+++ b/plugins/discourse-ai/spec/lib/personas/tools/search_spec.rb@@ -103,6 +103,31 @@ RSpec.describe DiscourseAi::Personas::Tools::Search doexpect(results[:rows]).to eq([])end+ it "uses /filter URL for filter-only queries" do+ Fabricate(:post, topic: topic_with_tags)++ search = described_class.new({ order: "latest" }, bot_user: bot_user, llm: llm)+ search.invoke(&progress_blk)++ description_args = search.send(:description_args)+ expect(description_args[:url]).to eq("/filter?q=order%3Aactivity")+ end++ it "uses /search URL for queries with search terms" do+ post1 = Fabricate(:post, topic: topic_with_tags)++ search =+ described_class.new(+ { search_query: post1.raw, order: "latest" },+ bot_user: bot_user,+ llm: llm,+ )+ search.invoke(&progress_blk)++ description_args = search.send(:description_args)+ expect(description_args[:url]).to eq("/search?q=Hello+world+order%3Alatest")+ end+describe "semantic search" dolet(:query) { "this is an expanded search" }@@ -168,10 +193,14 @@ RSpec.describe DiscourseAi::Personas::Tools::Search dopost1 = Fabricate(:post, topic: topic_with_tags)search =- described_class.new({ limit: 1, user: post1.user.username }, bot_user: bot_user, llm: llm)+ described_class.new(+ { search_query: post1.raw, limit: 1, user: post1.user.username },+ bot_user: bot_user,+ llm:,+ )results = search.invoke(&progress_blk)- expect(results[:rows].to_s).to include("/subfolder" + post1.url)+ expect(results[:rows].to_s).to include("/subfolder#{post1.url}")endit "passes on all search params" do@@ -196,7 +225,12 @@ RSpec.describe DiscourseAi::Personas::Tools::Search doit "returns rich topic information" dopost1 = Fabricate(:post, like_count: 1, topic: topic_with_tags)- search = described_class.new({ user: post1.user.username }, bot_user: bot_user, llm: llm)+ search =+ described_class.new(+ { search_query: post1.raw, user: post1.user.username },+ bot_user: bot_user,+ llm: llm,+ )post1.topic.update!(views: 100, posts_count: 2, like_count: 10)results = search.invoke(&progress_blk)diff --git a/plugins/discourse-ai/spec/lib/utils/search_spec.rb b/plugins/discourse-ai/spec/lib/utils/search_spec.rbindex cd4bdf3d186..f824368c95c 100644--- a/plugins/discourse-ai/spec/lib/utils/search_spec.rb+++ b/plugins/discourse-ai/spec/lib/utils/search_spec.rb@@ -72,8 +72,7 @@ RSpec.describe DiscourseAi::Utils::Search doresults = described_class.perform_search(search_query: private_post.raw, current_user: user)expect(results[:rows].length).to eq(0)- # Add user to group with access- GroupUser.create!(group: group, user: user)+ group.add(user)# Now should find the private postresults =@@ -219,5 +218,120 @@ RSpec.describe DiscourseAi::Utils::Search doexpect(results[:args]).to include(search_params)end++ context "with filter-only queries (no search term)" do+ fab!(:topic1) do+ Fabricate(:topic, category: category, views: 100, like_count: 10, bumped_at: 1.day.ago)+ end+ fab!(:topic2) do+ Fabricate(:topic, category: category, views: 50, like_count: 20, bumped_at: 1.hour.ago)+ end+ fab!(:topic3) { Fabricate(:topic, tags: [tag_funny]) }+ fab!(:post1) { Fabricate(:post, topic: topic1) }+ fab!(:post2) { Fabricate(:post, topic: topic2) }+ fab!(:post3) { Fabricate(:post, topic: topic3) }++ it "returns topics with order:latest filter only (uses TopicsFilter fallback)" do+ results = described_class.perform_search(order: "latest", current_user: admin)++ expect(results[:rows]).to be_present+ expect(results[:args][:order]).to eq("latest")++ url_index = results[:column_names].index("url")+ topic_urls = results[:rows].map { |row| row[url_index] }++ expected_urls = [topic3.relative_url, topic2.relative_url, topic1.relative_url]++ # keep only topics we expect (ignore any other fabricated topics)+ topic_urls &= expected_urls++ expect(topic_urls).to eq(expected_urls)+ end++ it "returns topics filtered by category with order" do+ results =+ described_class.perform_search(+ category: category.slug,+ order: "views",+ current_user: admin,+ )++ expect(results[:rows]).to be_present++ url_index = results[:column_names].index("url")+ topic_urls = results[:rows].map { |row| row[url_index] }++ expected_urls =+ Topic.order("views desc, bumped_at desc").where(category: category).map(&:relative_url)+ expect(topic_urls).to eq(expected_urls)+ end++ it "returns topics filtered by tags" do+ results = described_class.perform_search(tags: tag_funny.name, current_user: admin)++ expect(results[:rows]).to be_present++ url_index = results[:column_names].index("url")+ topic_urls = results[:rows].map { |row| row[url_index] }+ expect(topic_urls).to contain_exactly(topic_with_tags.relative_url, topic3.relative_url)+ end++ it "returns topics filtered by user" do+ results = described_class.perform_search(user: post1.user.username, current_user: admin)++ url_index = results[:column_names].index("url")+ topic_urls = results[:rows].map { |row| row[url_index] }++ expect(topic_urls).to contain_exactly(topic1.relative_url)+ end++ it "returns empty results when no filters are provided and no search query" do+ results = described_class.perform_search(current_user: admin)++ expect(results[:rows]).to eq([])+ end++ it "respects category permissions" do+ private_topic = Fabricate(:topic, category: private_category)+ Fabricate(:post, topic: private_topic)++ results = described_class.perform_search(order: "latest", current_user: user)+ url_index = results[:column_names].index("url")+ topic_urls = results[:rows].map { |row| row[url_index] }.join+ expect(topic_urls).not_to include("/t/#{private_topic.slug}/#{private_topic.id}")++ GroupUser.create!(group: group, user: user)+ results = described_class.perform_search(order: "latest", current_user: user)+ url_index = results[:column_names].index("url")+ topic_urls = results[:rows].map { |row| row[url_index] }.join+ expect(topic_urls).to include("/t/#{private_topic.slug}/#{private_topic.id}")+ end++ it "returns correct result structure for filter-only queries with category" do+ results =+ described_class.perform_search(+ category: category.slug,+ order: "latest",+ current_user: admin,+ )++ expect(results).to have_key(:args)+ expect(results).to have_key(:rows)+ expect(results).to have_key(:column_names)+ expect(results[:column_names]).to include("title", "url", "username", "category")+ end++ it "respects max_results for filter-only queries" do+ results =+ described_class.perform_search(+ category: category.slug,+ order: "latest",+ max_results: 1,+ current_user: admin,+ )++ expect(results[:rows].length).to be <= 1+ end+ endendend