A platform for community discussion. Free, open, simple.
FIX: Respect category tag restrictions when suggesting tags (#40545)
Régis Hanol64603110aebd
diff --git a/frontend/discourse/app/components/modal/move-to-topic.gjs b/frontend/discourse/app/components/modal/move-to-topic.gjsindex f581fdb8bcd..95bef1a96a4 100644--- a/frontend/discourse/app/components/modal/move-to-topic.gjs+++ b/frontend/discourse/app/components/modal/move-to-topic.gjs@@ -433,6 +433,7 @@ export default class MoveToTopic extends Component {updateTags=this.updateTagstags=this.tags+ categoryId=this.categoryId}}/></div>diff --git a/plugins/discourse-ai/app/controllers/discourse_ai/ai_helper/assistant_controller.rb b/plugins/discourse-ai/app/controllers/discourse_ai/ai_helper/assistant_controller.rbindex 6295eba3ab4..fa2b6115c7c 100644--- a/plugins/discourse-ai/app/controllers/discourse_ai/ai_helper/assistant_controller.rb+++ b/plugins/discourse-ai/app/controllers/discourse_ai/ai_helper/assistant_controller.rb@@ -100,10 +100,14 @@ module DiscourseAiif params[:topic_id]topic = Topic.find_by(id: params[:topic_id])guardian.ensure_can_see!(topic)- opts = { topic_id: topic.id }+ opts = { topic_id: topic.id, category: topic.category, selected_tag_ids: topic.tag_ids }elseinput = get_text_param!- opts = { text: input }+ opts = {+ text: input,+ category: suggestible_category,+ selected_tag_ids: selected_tag_ids_param,+ }endrender json: DiscourseAi::AiHelper::SemanticCategorizer.new(current_user, opts).tags,@@ -290,6 +294,15 @@ module DiscourseAiparams[:post_id].tap { |t| raise Discourse::InvalidParameters.new(:post_id) if t.blank? }end+ def suggestible_category+ return if params[:category_id].blank?+ Category.where(id: params[:category_id]).where(id: guardian.allowed_category_ids).first+ end++ def selected_tag_ids_param+ Tag.where_name(Array(params[:selected_tags]).first(100)).pluck(:id)+ end+def rate_limiter_performed!action_rate_limit = RATE_LIMITS[action_name] || RATE_LIMITS["default"]RateLimiter.new(diff --git a/plugins/discourse-ai/assets/javascripts/discourse/components/ai-split-topic-suggester.gjs b/plugins/discourse-ai/assets/javascripts/discourse/components/ai-split-topic-suggester.gjsindex 9e50e2f051a..739e1c31e0e 100644--- a/plugins/discourse-ai/assets/javascripts/discourse/components/ai-split-topic-suggester.gjs+++ b/plugins/discourse-ai/assets/javascripts/discourse/components/ai-split-topic-suggester.gjs@@ -11,6 +11,7 @@ import { uniqueItemsFromArray } from "discourse/lib/array-tools";import { eq } from "discourse/truth-helpers";import DButton from "discourse/ui-kit/d-button";import dCategoryBadge from "discourse/ui-kit/helpers/d-category-badge";+import { tagSuggestionParams } from "../lib/ai-helper-suggestions";export default class AiSplitTopicSuggester extends Component {@service site;@@ -40,9 +41,18 @@ export default class AiSplitTopicSuggester extends Component {this.loading = true;+ const data = { text: this.input };++ if (this.args.mode === this.SUGGESTION_TYPES.tag) {+ Object.assign(+ data,+ tagSuggestionParams(this.args.categoryId, this.args.currentValue)+ );+ }+ajax(`/discourse-ai/ai-helper/${this.args.mode}`, {method: "POST",- data: { text: this.input },+ data,}).then((result) => {if (this.args.mode === this.SUGGESTION_TYPES.title) {diff --git a/plugins/discourse-ai/assets/javascripts/discourse/components/suggestion-menus/ai-tag-suggester.gjs b/plugins/discourse-ai/assets/javascripts/discourse/components/suggestion-menus/ai-tag-suggester.gjsindex 1f0295cc1f3..8353698e12a 100644--- a/plugins/discourse-ai/assets/javascripts/discourse/components/suggestion-menus/ai-tag-suggester.gjs+++ b/plugins/discourse-ai/assets/javascripts/discourse/components/suggestion-menus/ai-tag-suggester.gjs@@ -14,6 +14,7 @@ import { i18n } from "discourse-i18n";import {MIN_CHARACTER_COUNT,showSuggestionsError,+ tagSuggestionParams,} from "../../lib/ai-helper-suggestions";export default class AiTagSuggester extends Component {@@ -71,6 +72,10 @@ export default class AiTagSuggester extends Component {if (this.content) {data.text = this.content;+ Object.assign(+ data,+ tagSuggestionParams(this.model?.categoryId, this.model?.get("tags"))+ );} else {data.topic_id = this.args.buffered.content.id;}diff --git a/plugins/discourse-ai/assets/javascripts/discourse/connectors/split-new-topic-tag-after/ai-tag-suggestion.gjs b/plugins/discourse-ai/assets/javascripts/discourse/connectors/split-new-topic-tag-after/ai-tag-suggestion.gjsindex e3b7cecd2b2..238d801d995 100644--- a/plugins/discourse-ai/assets/javascripts/discourse/connectors/split-new-topic-tag-after/ai-tag-suggestion.gjs+++ b/plugins/discourse-ai/assets/javascripts/discourse/connectors/split-new-topic-tag-after/ai-tag-suggestion.gjs@@ -17,6 +17,7 @@ export default class AiTagSuggestion extends Component {@mode="suggest_tags"@updateAction={{@outletArgs.updateTags}}@currentValue={{@outletArgs.tags}}+ @categoryId={{@outletArgs.categoryId}}/>{{/if}}</template>diff --git a/plugins/discourse-ai/assets/javascripts/discourse/lib/ai-helper-suggestions.js b/plugins/discourse-ai/assets/javascripts/discourse/lib/ai-helper-suggestions.jsindex 91da8f7c6c5..57c1d393f3b 100644--- a/plugins/discourse-ai/assets/javascripts/discourse/lib/ai-helper-suggestions.js+++ b/plugins/discourse-ai/assets/javascripts/discourse/lib/ai-helper-suggestions.js@@ -4,6 +4,27 @@ import { i18n } from "discourse-i18n";export const MIN_CHARACTER_COUNT = 40;+function tagNames(tags) {+ return (tags ?? [])+ .map((tag) => (typeof tag === "string" ? tag : tag?.name))+ .filter(Boolean);+}++export function tagSuggestionParams(categoryId, tags) {+ const params = {};++ if (categoryId) {+ params.category_id = categoryId;+ }++ const selectedTags = tagNames(tags);+ if (selectedTags.length) {+ params.selected_tags = selectedTags;+ }++ return params;+}+export function showSuggestionsError(context, reloadFn) {const toasts = getOwner(context).lookup("service:toasts");diff --git a/plugins/discourse-ai/lib/ai_helper/semantic_categorizer.rb b/plugins/discourse-ai/lib/ai_helper/semantic_categorizer.rbindex a5c0656a82a..6807152c7c2 100644--- a/plugins/discourse-ai/lib/ai_helper/semantic_categorizer.rb+++ b/plugins/discourse-ai/lib/ai_helper/semantic_categorizer.rb@@ -8,6 +8,8 @@ module DiscourseAi@vector = DiscourseAi::Embeddings::Vector.instance@schema = DiscourseAi::Embeddings::Schema.for(Topic)@topic_id = opts[:topic_id]+ @category = opts[:category]+ @selected_tag_ids = opts[:selected_tag_ids]enddef categories@@ -87,6 +89,7 @@ module DiscourseAi.group_by { |c| c[:name] }.map { |name, scores| { name: name, score: scores.sum { |s| s[:score] } } }.sort_by { |c| -c[:score] }+ .then { reject_tags_disallowed_in_category(it) }.take(7).then do |tags|models = Tag.where(name: tags.map { it[:name] }).index_by(&:name)@@ -102,6 +105,25 @@ module DiscourseAiprivate+ def reject_tags_disallowed_in_category(candidates)+ return candidates if candidates.empty?++ allowed_names =+ DiscourseTagging+ .filter_allowed_tags(+ @user.guardian,+ category: @category,+ selected_tag_ids: @selected_tag_ids,+ for_topic: true,+ only_tag_names: candidates.map { |c| c[:name] },+ limit: nil,+ )+ .map(&:name)+ .to_set++ candidates.select { |c| allowed_names.include?(c[:name]) }+ end+def nearest_neighbors(limit: 50)if @topic_idtarget = Topic.find_by(id: @topic_id)diff --git a/plugins/discourse-ai/spec/lib/modules/ai_helper/semantic_categorizer_spec.rb b/plugins/discourse-ai/spec/lib/modules/ai_helper/semantic_categorizer_spec.rbindex af2d3d72ced..75637aa0d6a 100644--- a/plugins/discourse-ai/spec/lib/modules/ai_helper/semantic_categorizer_spec.rb+++ b/plugins/discourse-ai/spec/lib/modules/ai_helper/semantic_categorizer_spec.rb@@ -56,4 +56,67 @@ RSpec.describe DiscourseAi::AiHelper::SemanticCategorizer docategorizer.tagsexpect(inner_vector.vdef.pg_function).to eq("<=>")end++ def seed_candidate_tagged_with(tag)+ topic = Fabricate(:topic)+ Fabricate(:topic_tag, topic:, tag:)+ vector.generate_representation_from(topic)+ end++ describe "category tag restrictions" do+ fab!(:restricted_tag, :tag)+ fab!(:allowed_tag, :tag)++ fab!(:restricted_category) { Fabricate(:category, allowed_tags: [allowed_tag.name]) }++ before do+ seed_candidate_tagged_with(restricted_tag)+ seed_candidate_tagged_with(allowed_tag)+ end++ it "does not suggest a tag the selected category disallows" do+ suggested =+ described_class+ .new(user, { text: "hello", category: restricted_category })+ .tags+ .map { |t| t[:name] }++ expect(suggested).to include(allowed_tag.name)+ expect(suggested).not_to include(restricted_tag.name)+ end++ it "suggests the tag in a category that allows it" do+ permissive_category = Fabricate(:category, allow_global_tags: true)++ suggested =+ described_class+ .new(user, { text: "hello", category: permissive_category })+ .tags+ .map { |t| t[:name] }++ expect(suggested).to include(restricted_tag.name)+ end+ end++ describe "one tag per group restrictions" do+ fab!(:selected_tag, :tag)+ fab!(:sibling_tag, :tag)+ fab!(:tag_group) do+ Fabricate(:tag_group, tags: [selected_tag, sibling_tag], one_per_topic: true)+ end++ before { seed_candidate_tagged_with(sibling_tag) }++ it "excludes a one-per-topic group sibling once a member is selected" do+ without_selection = described_class.new(user, { text: "hello" }).tags.map { |t| t[:name] }+ expect(without_selection).to include(sibling_tag.name)++ with_selection =+ described_class+ .new(user, { text: "hello", selected_tag_ids: [selected_tag.id] })+ .tags+ .map { |t| t[:name] }+ expect(with_selection).not_to include(sibling_tag.name)+ end+ endenddiff --git a/plugins/discourse-ai/spec/requests/ai_helper/assistant_controller_spec.rb b/plugins/discourse-ai/spec/requests/ai_helper/assistant_controller_spec.rbindex e645a88f2f1..b0a3720a57c 100644--- a/plugins/discourse-ai/spec/requests/ai_helper/assistant_controller_spec.rb+++ b/plugins/discourse-ai/spec/requests/ai_helper/assistant_controller_spec.rb@@ -874,6 +874,39 @@ RSpec.describe DiscourseAi::AiHelper::AssistantController doexpect(response.status).to eq(403)endend++ context "when the selected category restricts tags" do+ fab!(:allowed_tag, :tag)+ fab!(:restricted_tag, :tag)+ fab!(:restricted_category) { Fabricate(:category, allowed_tags: [allowed_tag.name]) }+ fab!(:topic)++ before do+ Fabricate(:topic_tag, topic:, tag: allowed_tag)+ Fabricate(:topic_tag, topic:, tag: restricted_tag)++ WebMock.stub_request(:post, embedding_definition.url).to_return(+ status: 200,+ body: JSON.dump([[0.0038493] * embedding_definition.dimensions]),+ )++ DiscourseAi::Embeddings::Vector.instance.generate_representation_from(topic)+ end++ it "does not suggest tags the category disallows" do+ post "/discourse-ai/ai-helper/suggest_tags",+ params: {+ text: "hello",+ category_id: restricted_category.id,+ }++ expect(response.status).to eq(200)++ suggested = response.parsed_body["assistant"].map { |t| t["name"] }+ expect(suggested).to include(allowed_tag.name)+ expect(suggested).not_to include(restricted_tag.name)+ end+ endenddescribe "#semantic_categories" do