A platform for community discussion. Free, open, simple.
FEATURE: Add tag creation and tag editing to AI bot tools (#42801)
Gabriel Grubbaf1a073270cb1
diff --git a/config/locales/client.en.yml b/config/locales/client.en.ymlindex cdaf66c538b..616478966ce 100644--- a/config/locales/client.en.yml+++ b/config/locales/client.en.yml@@ -9157,6 +9157,7 @@ en:deleted_tag: "deleted tag"update_directory_columns: "update directory columns"deleted_unused_tags: "deleted unused tags"+ created_tag: "created tag"renamed_tag: "renamed tag"revoke_email: "revoke email"lock_trust_level: "lock trust level"diff --git a/db/structure.sql b/db/structure.sqlindex 44146dd0b44..5b15010f40d 100644--- a/db/structure.sql+++ b/db/structure.sql@@ -23361,6 +23361,7 @@ INSERT INTO "schema_migrations" (version) VALUES('20260824091843'),('20260824072257'),('20260824051214'),+('20260821210913'),('20260821210543'),('20260821164114'),('20260820171539'),diff --git a/plugins/discourse-ai/app/models/reviewable_ai_tool_action.rb b/plugins/discourse-ai/app/models/reviewable_ai_tool_action.rbindex 8436e56732f..21aff7eeae5 100644--- a/plugins/discourse-ai/app/models/reviewable_ai_tool_action.rb+++ b/plugins/discourse-ai/app/models/reviewable_ai_tool_action.rb@@ -48,7 +48,7 @@ class ReviewableAiToolAction < Reviewablecontext.user = performed_by if tool_class.attribute_to_approver?# Suppress automation re-triggers caused by the tool's side effects- # (e.g. edit_tags → topic_tags_changed → automation fires again → loop).+ # (e.g. change_topic_tags → topic_tags_changed → automation fires again → loop).result =if defined?(DiscourseAutomation)DiscourseAutomation.suppress_triggers { tool.invoke }diff --git a/plugins/discourse-ai/config/locales/server.en.yml b/plugins/discourse-ai/config/locales/server.en.ymlindex 1274b258503..fbcf0555364 100644--- a/plugins/discourse-ai/config/locales/server.en.yml+++ b/plugins/discourse-ai/config/locales/server.en.yml@@ -709,7 +709,9 @@ en:lock_post: "Lock post"delete_topic: "Delete topic"edit_post: "Edit post"- edit_tags: "Edit tags"+ change_topic_tags: "Edit topic tags"+ create_tag: "Create tag"+ edit_tag: "Edit tag"create_category: "Create category"edit_category: "Edit category"change_topic_category: "Change topic category"@@ -765,7 +767,9 @@ en:lock_post: "Lock or unlock a post"delete_topic: "Delete a topic"edit_post: "Edit the content of a post"- edit_tags: "Edit the tags on a topic"+ change_topic_tags: "Edit the tags on a topic"+ create_tag: "Create a new tag"+ edit_tag: "Rename a tag or change its description"create_category: "Create a new category"edit_category: "Edit an existing category's name, description, or colors"change_topic_category: "Move a topic to a different category"@@ -820,7 +824,9 @@ en:lock_post: "Locking post %{post_id} (locked: %{locked})"delete_topic: "Deleting topic %{topic_id} (deleted: %{deleted})"edit_post: "Editing post %{post_id}"- edit_tags: "Editing tags on topic %{topic_id}: %{tags}"+ change_topic_tags: "Editing tags on topic %{topic_id}: %{tags}"+ create_tag: "Creating tag '%{name}'"+ edit_tag: "Editing tag '%{name}' (%{fields})"create_category: "Creating category '%{name}'"edit_category: "Editing category %{category_id} (%{fields})"change_topic_category: "Moving topic %{topic_id} to category %{category_id}"@@ -944,7 +950,7 @@ en:revision_failed: "Failed to revise the post."success: "Post edited successfully."- edit_tags:+ change_topic_tags:errors:not_found: "Topic not found."not_allowed: "You are not allowed to edit tags on this topic."@@ -952,6 +958,25 @@ en:tagging_disabled: "Tagging is not enabled on this site."success: "Tags updated successfully."+ create_tag:+ errors:+ tagging_disabled: "Tagging is not enabled on this site."+ no_name: "A name is required to create a tag."+ already_exists: "A tag named '%{name}' already exists."+ not_allowed: "You are not allowed to create tags."+ no_reason: "A reason is required to create a tag."+ success: "Tag '%{name}' created successfully."++ edit_tag:+ errors:+ tagging_disabled: "Tagging is not enabled on this site."+ not_found: "Tag not found."+ not_allowed: "You are not allowed to edit this tag."+ nothing_to_edit: "Either new_name or description must be provided."+ invalid_new_name: "'%{name}' is not a valid tag name."+ no_reason: "A reason is required to edit a tag."+ success: "Tag '%{name}' updated successfully."+create_category:errors:no_name: "A name is required to create a category."diff --git a/plugins/discourse-ai/db/migrate/20260821210913_rename_edit_tags_tool_to_change_topic_tags.rb b/plugins/discourse-ai/db/migrate/20260821210913_rename_edit_tags_tool_to_change_topic_tags.rbnew file mode 100644index 00000000000..1fc88ed7b88--- /dev/null+++ b/plugins/discourse-ai/db/migrate/20260821210913_rename_edit_tags_tool_to_change_topic_tags.rb@@ -0,0 +1,44 @@+# frozen_string_literal: true++class RenameEditTagsToolToChangeTopicTags < ActiveRecord::Migration[8.0]+ # The tool that tags a topic was renamed from EditTags to ChangeTopicTags to+ # distinguish it from the new EditTag tool that edits a tag itself. Rename+ # the stored entry so existing agents keep the tool.+ def up+ DB+ .query("SELECT id, tools FROM ai_agents WHERE tools::text LIKE '%EditTags%'")+ .each do |row|+ tools = row.tools.is_a?(String) ? JSON.parse(row.tools) : row.tools+ next if !tools.is_a?(Array)++ names = tools.map { |tool| tool.is_a?(Array) ? tool.first : tool }+ next if names.include?("ChangeTopicTags")++ renamed =+ tools.map do |tool|+ if tool.is_a?(Array) && tool.first == "EditTags"+ ["ChangeTopicTags", *tool.drop(1)]+ elsif tool == "EditTags"+ "ChangeTopicTags"+ else+ tool+ end+ end+ next if renamed == tools++ DB.exec(+ "UPDATE ai_agents SET tools = :tools WHERE id = :id",+ tools: renamed.to_json,+ id: row.id,+ )+ end++ # Pending approval actions replay by tool name; the parameters are+ # unchanged by the rename.+ execute "UPDATE ai_tool_actions SET tool_name = 'change_topic_tags' WHERE tool_name = 'edit_tags'"+ end++ def down+ raise ActiveRecord::IrreversibleMigration+ end+enddiff --git a/plugins/discourse-ai/lib/agents/agent.rb b/plugins/discourse-ai/lib/agents/agent.rbindex 7d401173c82..a939edf9b93 100644--- a/plugins/discourse-ai/lib/agents/agent.rb+++ b/plugins/discourse-ai/lib/agents/agent.rb@@ -151,7 +151,9 @@ module DiscourseAiif SiteSetting.tagging_enabledtools << Tools::ListTags- tools << Tools::EditTags+ tools << Tools::CreateTag+ tools << Tools::EditTag+ tools << Tools::ChangeTopicTagsend# Image generation tools - use custom UI-configured toolsdiff --git a/plugins/discourse-ai/lib/agents/discourse_admin_assistant.rb b/plugins/discourse-ai/lib/agents/discourse_admin_assistant.rbindex abbd960d4db..3f0efc8eeed 100644--- a/plugins/discourse-ai/lib/agents/discourse_admin_assistant.rb+++ b/plugins/discourse-ai/lib/agents/discourse_admin_assistant.rb@@ -33,7 +33,9 @@ module DiscourseAiTools::CreateCategory,Tools::EditCategory,Tools::ChangeTopicCategory,- Tools::EditTags,+ Tools::CreateTag,+ Tools::EditTag,+ Tools::ChangeTopicTags,Tools::MovePosts,Tools::SuspendUser,Tools::SilenceUser,diff --git a/plugins/discourse-ai/lib/agents/tools/edit_tags.rb b/plugins/discourse-ai/lib/agents/tools/change_topic_tags.rbsimilarity index 67%rename from plugins/discourse-ai/lib/agents/tools/edit_tags.rbrename to plugins/discourse-ai/lib/agents/tools/change_topic_tags.rbindex d0ea4beac32..344cdebb129 100644--- a/plugins/discourse-ai/lib/agents/tools/edit_tags.rb+++ b/plugins/discourse-ai/lib/agents/tools/change_topic_tags.rb@@ -3,11 +3,12 @@module DiscourseAimodule Agentsmodule Tools- class EditTags < Tool+ class ChangeTopicTags < Tooldef self.signature{name: name,- description: "Adds tags to a topic. By default appends to existing tags.",+ description:+ "Adds, replaces, or removes tags on a topic. By default appends the given tags to the existing ones; with replace set, the given list becomes the topic's complete tag set and any omitted tag is removed.",parameters: [{name: "topic_id",@@ -17,7 +18,8 @@ module DiscourseAi},{name: "tags",- description: "Array of tag names to add to the topic",+ description:+ "Array of tag names to apply. In replace mode this is the topic's full resulting tag list",type: "array",item_type: "string",required: true,@@ -44,7 +46,7 @@ module DiscourseAienddef self.name- "edit_tags"+ "change_topic_tags"enddef self.requires_approval?@@ -53,18 +55,26 @@ module DiscourseAidef invokeif !SiteSetting.tagging_enabled- return error_response(I18n.t("discourse_ai.ai_bot.edit_tags.errors.tagging_disabled"))+ return(+ error_response(+ I18n.t("discourse_ai.ai_bot.change_topic_tags.errors.tagging_disabled"),+ )+ )endtopic = Topic.find_by(id: parameters[:topic_id])- return error_response(I18n.t("discourse_ai.ai_bot.edit_tags.errors.not_found")) if !topic+ if !topic+ return error_response(I18n.t("discourse_ai.ai_bot.change_topic_tags.errors.not_found"))+ endif !guardian.can_edit_tags?(topic)- return error_response(I18n.t("discourse_ai.ai_bot.edit_tags.errors.not_allowed"))+ return(+ error_response(I18n.t("discourse_ai.ai_bot.change_topic_tags.errors.not_allowed"))+ )endif reason.blank?- return error_response(I18n.t("discourse_ai.ai_bot.edit_tags.errors.no_reason"))+ return error_response(I18n.t("discourse_ai.ai_bot.change_topic_tags.errors.no_reason"))endtag_names = parameters[:tags] || []@@ -75,14 +85,14 @@ module DiscourseAifirst_post = topic.first_postif !first_post- return error_response(I18n.t("discourse_ai.ai_bot.edit_tags.errors.not_found"))+ return error_response(I18n.t("discourse_ai.ai_bot.change_topic_tags.errors.not_found"))endrevisor = PostRevisor.new(first_post, topic)result = revisor.revise!(acting_user, fields)if result- { status: "success", message: I18n.t("discourse_ai.ai_bot.edit_tags.success") }+ { status: "success", message: I18n.t("discourse_ai.ai_bot.change_topic_tags.success") }elseerror_response(topic.errors.full_messages.join(", "))enddiff --git a/plugins/discourse-ai/lib/agents/tools/create_tag.rb b/plugins/discourse-ai/lib/agents/tools/create_tag.rbnew file mode 100644index 00000000000..295531bf5d7--- /dev/null+++ b/plugins/discourse-ai/lib/agents/tools/create_tag.rb@@ -0,0 +1,114 @@+# frozen_string_literal: true++module DiscourseAi+ module Agents+ module Tools+ class CreateTag < Tool+ def self.signature+ {+ name: name,+ description:+ "Creates a new tag without applying it to any topic. Use change_topic_tags to apply tags to a topic.",+ parameters: [+ {+ name: "name",+ description: "The name for the new tag",+ type: "string",+ required: true,+ },+ {+ name: "description",+ description: "A short description for the new tag",+ type: "string",+ },+ {+ name: "reason",+ description: "Short explanation of why the tag is being created",+ type: "string",+ required: true,+ },+ ],+ }+ end++ def self.name+ "create_tag"+ end++ def self.requires_approval?+ true+ end++ def self.attribute_to_approver?+ true+ end++ def invoke+ if (error = validation_error)+ return error+ end+ perform_create+ end++ def validation_error+ if !SiteSetting.tagging_enabled+ return(error_response(I18n.t("discourse_ai.ai_bot.create_tag.errors.tagging_disabled")))+ end++ if clean_name.blank?+ return error_response(I18n.t("discourse_ai.ai_bot.create_tag.errors.no_name"))+ end++ # Before the existence check, so unauthorized users cannot probe+ # hidden tag names.+ if !guardian.can_admin_tags?+ return error_response(I18n.t("discourse_ai.ai_bot.create_tag.errors.not_allowed"))+ end++ if Tag.where_name(clean_name).exists?+ return(+ error_response(+ I18n.t("discourse_ai.ai_bot.create_tag.errors.already_exists", name: clean_name),+ )+ )+ end++ if reason.blank?+ return error_response(I18n.t("discourse_ai.ai_bot.create_tag.errors.no_reason"))+ end++ nil+ end++ def description_args+ { name: clean_name.presence || parameters[:name] }+ end++ private++ def clean_name+ @clean_name ||= DiscourseTagging.clean_tag(parameters[:name].to_s)+ end++ def perform_create+ if !guardian.can_admin_tags?+ return error_response(I18n.t("discourse_ai.ai_bot.create_tag.errors.not_allowed"))+ end++ tag = Tag.new(name: clean_name, description: parameters[:description].presence)++ if tag.save+ StaffActionLogger.new(guardian.user).log_custom("created_tag", subject: tag.name)+ {+ status: "success",+ tag_name: tag.name,+ message: I18n.t("discourse_ai.ai_bot.create_tag.success", name: tag.name),+ }+ else+ error_response(tag.errors.full_messages.to_sentence)+ end+ end+ end+ end+ end+enddiff --git a/plugins/discourse-ai/lib/agents/tools/edit_tag.rb b/plugins/discourse-ai/lib/agents/tools/edit_tag.rbnew file mode 100644index 00000000000..ce842e7d741--- /dev/null+++ b/plugins/discourse-ai/lib/agents/tools/edit_tag.rb@@ -0,0 +1,141 @@+# frozen_string_literal: true++module DiscourseAi+ module Agents+ module Tools+ class EditTag < Tool+ def self.signature+ {+ name: name,+ description:+ "Renames an existing tag or changes its description. This edits the tag itself everywhere it is used; use change_topic_tags to change which tags are on a topic.",+ parameters: [+ {+ name: "name",+ description: "The current name of the tag to edit",+ type: "string",+ required: true,+ },+ { name: "new_name", description: "The new name for the tag", type: "string" },+ {+ name: "description",+ description:+ "The new description for the tag. Pass an empty string to clear the existing description.",+ type: "string",+ },+ {+ name: "reason",+ description: "Short explanation of why the tag is being edited",+ type: "string",+ required: true,+ },+ ],+ }+ end++ def self.name+ "edit_tag"+ end++ def self.requires_approval?+ true+ end++ def self.attribute_to_approver?+ true+ end++ def invoke+ if (error = validation_error)+ return error+ end+ perform_edit+ end++ def validation_error+ if !SiteSetting.tagging_enabled+ return error_response(I18n.t("discourse_ai.ai_bot.edit_tag.errors.tagging_disabled"))+ end++ # Invisible tags report not-found so their names cannot be probed.+ if tag.blank? || !guardian.can_see_tag?(tag)+ return error_response(I18n.t("discourse_ai.ai_bot.edit_tag.errors.not_found"))+ end++ if parameters[:new_name].blank? && !description_provided?+ return error_response(I18n.t("discourse_ai.ai_bot.edit_tag.errors.nothing_to_edit"))+ end++ if parameters[:new_name].present? && clean_new_name.blank?+ return(+ error_response(+ I18n.t(+ "discourse_ai.ai_bot.edit_tag.errors.invalid_new_name",+ name: parameters[:new_name],+ ),+ )+ )+ end++ if reason.blank?+ return error_response(I18n.t("discourse_ai.ai_bot.edit_tag.errors.no_reason"))+ end++ nil+ end++ def description_args+ { name: parameters[:name], fields: changed_fields.join(", ") }+ end++ private++ def tag+ @tag ||= Tag.where_name(parameters[:name].to_s).first+ end++ def clean_new_name+ @clean_new_name ||= DiscourseTagging.clean_tag(parameters[:new_name].to_s)+ end++ def description_provided?+ !parameters[:description].nil?+ end++ def changed_fields+ fields = []+ fields << "name → #{clean_new_name}" if parameters[:new_name].present?+ fields << "description" if description_provided?+ fields+ end++ def perform_edit+ if !guardian.can_edit_tag?(tag)+ return error_response(I18n.t("discourse_ai.ai_bot.edit_tag.errors.not_allowed"))+ end++ previous_name = tag.name+ tag.name = clean_new_name if parameters[:new_name].present?+ tag.description = parameters[:description].presence if description_provided?++ if tag.save+ if tag.name != previous_name+ StaffActionLogger.new(guardian.user).log_custom(+ "renamed_tag",+ previous_value: previous_name,+ new_value: tag.name,+ )+ end+ {+ status: "success",+ tag_name: tag.name,+ message: I18n.t("discourse_ai.ai_bot.edit_tag.success", name: tag.name),+ }+ else+ error_response(tag.errors.full_messages.to_sentence)+ end+ end+ end+ end+ end+enddiff --git a/plugins/discourse-ai/spec/lib/agents/discourse_admin_assistant_spec.rb b/plugins/discourse-ai/spec/lib/agents/discourse_admin_assistant_spec.rbindex 4e47a4ac817..33782323b71 100644--- a/plugins/discourse-ai/spec/lib/agents/discourse_admin_assistant_spec.rb+++ b/plugins/discourse-ai/spec/lib/agents/discourse_admin_assistant_spec.rb@@ -27,7 +27,9 @@ RSpec.describe DiscourseAi::Agents::DiscourseAdminAssistant doDiscourseAi::Agents::Tools::CreateCategory,DiscourseAi::Agents::Tools::EditCategory,DiscourseAi::Agents::Tools::ChangeTopicCategory,- DiscourseAi::Agents::Tools::EditTags,+ DiscourseAi::Agents::Tools::CreateTag,+ DiscourseAi::Agents::Tools::EditTag,+ DiscourseAi::Agents::Tools::ChangeTopicTags,DiscourseAi::Agents::Tools::MovePosts,DiscourseAi::Agents::Tools::SuspendUser,DiscourseAi::Agents::Tools::SilenceUser,diff --git a/plugins/discourse-ai/spec/lib/agents/tools/edit_tags_spec.rb b/plugins/discourse-ai/spec/lib/agents/tools/change_topic_tags_spec.rbsimilarity index 98%rename from plugins/discourse-ai/spec/lib/agents/tools/edit_tags_spec.rbrename to plugins/discourse-ai/spec/lib/agents/tools/change_topic_tags_spec.rbindex fd5438b5c1e..9bb5e3da2f7 100644--- a/plugins/discourse-ai/spec/lib/agents/tools/edit_tags_spec.rb+++ b/plugins/discourse-ai/spec/lib/agents/tools/change_topic_tags_spec.rb@@ -1,6 +1,6 @@# frozen_string_literal: true-RSpec.describe DiscourseAi::Agents::Tools::EditTags do+RSpec.describe DiscourseAi::Agents::Tools::ChangeTopicTags dofab!(:llm_model)let(:bot_user) { DiscourseAi::AiBot::EntryPoint.find_user_from_model(llm_model.name) }let(:llm) { DiscourseAi::Completions::Llm.proxy(llm_model) }diff --git a/plugins/discourse-ai/spec/lib/agents/tools/create_tag_spec.rb b/plugins/discourse-ai/spec/lib/agents/tools/create_tag_spec.rbnew file mode 100644index 00000000000..fec1f5d2b33--- /dev/null+++ b/plugins/discourse-ai/spec/lib/agents/tools/create_tag_spec.rb@@ -0,0 +1,110 @@+# frozen_string_literal: true++RSpec.describe DiscourseAi::Agents::Tools::CreateTag do+ fab!(:llm_model)+ let(:bot_user) { DiscourseAi::AiBot::EntryPoint.find_user_from_model(llm_model.name) }+ let(:llm) { DiscourseAi::Completions::Llm.proxy(llm_model) }+ fab!(:admin)++ before do+ enable_current_plugin+ SiteSetting.ai_bot_enabled = true+ SiteSetting.tagging_enabled = true+ end++ let(:context) { DiscourseAi::Agents::BotContext.new(user: admin) }++ def tool(params = nil, **kwargs)+ params ||= kwargs+ described_class.new(params, bot_user: bot_user, llm: llm, context: context)+ end++ it "creates a tag with a description" do+ result =+ tool(name: "release-notes", description: "Release announcements", reason: "Setup").invoke++ expect(result[:status]).to eq("success")+ tag = Tag.find_by_name("release-notes")+ expect(tag).to be_present+ expect(tag.description).to eq("Release announcements")+ expect(result[:tag_name]).to eq("release-notes")+ end++ it "cleans the tag name like manual tag creation does" do+ result = tool(name: "Release Notes!", reason: "Setup").invoke++ expect(result[:status]).to eq("success")+ expect(result[:tag_name]).to eq("release-notes")+ end++ it "logs a staff action attributed to the context user" do+ expect { tool(name: "audited-tag", reason: "Audit trail").invoke }.to change {+ UserHistory.where(acting_user_id: admin.id, custom_type: "created_tag").count+ }.by(1)+ end++ it "returns an error when the tag already exists" do+ Fabricate(:tag, name: "duplicate")++ result = tool(name: "Duplicate", reason: "Test").invoke++ expect(result[:status]).to eq("error")+ expect(result[:error]).to include("already exists")+ end++ it "returns an error when the name is blank" do+ result = tool(name: " ", reason: "Test").invoke++ expect(result[:status]).to eq("error")+ end++ it "returns an error when reason is blank" do+ result = tool(name: "no-reason", reason: " ").invoke++ expect(result[:status]).to eq("error")+ end++ it "returns an error when tagging is disabled" do+ SiteSetting.tagging_enabled = false++ result = tool(name: "some-tag", reason: "Test").invoke++ expect(result[:status]).to eq("error")+ expect(Tag.exists?(name: "some-tag")).to eq(false)+ end++ it "does not reveal whether a tag exists to users lacking permission" do+ Fabricate(:tag, name: "hidden-existing")+ regular_user = Fabricate(:user, trust_level: TrustLevel[0])+ ctx = DiscourseAi::Agents::BotContext.new(user: regular_user)+ t =+ described_class.new(+ { name: "hidden-existing", reason: "test" },+ bot_user: bot_user,+ llm: llm,+ context: ctx,+ )+ result = t.invoke++ expect(result[:status]).to eq("error")+ expect(result[:error]).to include("not allowed")+ expect(result[:error]).not_to include("already exists")+ end++ it "returns an error when context user lacks permission" do+ regular_user = Fabricate(:user, trust_level: TrustLevel[0])+ ctx = DiscourseAi::Agents::BotContext.new(user: regular_user)+ t =+ described_class.new(+ { name: "nope", reason: "test" },+ bot_user: bot_user,+ llm: llm,+ context: ctx,+ )+ result = t.invoke++ expect(result[:status]).to eq("error")+ expect(result[:error]).to include("not allowed")+ expect(Tag.exists?(name: "nope")).to eq(false)+ end+enddiff --git a/plugins/discourse-ai/spec/lib/agents/tools/edit_tag_spec.rb b/plugins/discourse-ai/spec/lib/agents/tools/edit_tag_spec.rbnew file mode 100644index 00000000000..93b9ac6837d--- /dev/null+++ b/plugins/discourse-ai/spec/lib/agents/tools/edit_tag_spec.rb@@ -0,0 +1,126 @@+# frozen_string_literal: true++RSpec.describe DiscourseAi::Agents::Tools::EditTag do+ fab!(:llm_model)+ let(:bot_user) { DiscourseAi::AiBot::EntryPoint.find_user_from_model(llm_model.name) }+ let(:llm) { DiscourseAi::Completions::Llm.proxy(llm_model) }+ fab!(:admin)+ fab!(:tag) { Fabricate(:tag, name: "old-name") }++ before do+ enable_current_plugin+ SiteSetting.ai_bot_enabled = true+ SiteSetting.tagging_enabled = true+ end++ let(:context) { DiscourseAi::Agents::BotContext.new(user: admin) }++ def tool(params = nil, **kwargs)+ params ||= kwargs+ described_class.new(params, bot_user: bot_user, llm: llm, context: context)+ end++ it "renames the tag and logs a staff action attributed to the context user" do+ result = tool(name: "old-name", new_name: "new-name", reason: "Rebranding").invoke++ expect(result[:status]).to eq("success")+ expect(tag.reload.name).to eq("new-name")+ expect(UserHistory.where(acting_user_id: admin.id, custom_type: "renamed_tag").count).to eq(1)+ end++ it "updates the tag description without logging a rename" do+ result = tool(name: "old-name", description: "A better description", reason: "Test").invoke++ expect(result[:status]).to eq("success")+ expect(tag.reload.description).to eq("A better description")+ expect(UserHistory.where(custom_type: "renamed_tag").count).to eq(0)+ end++ it "clears the description when an empty string is provided" do+ tag.update!(description: "Something old")++ result = tool(name: "old-name", description: "", reason: "Cleanup").invoke++ expect(result[:status]).to eq("success")+ expect(tag.reload.description).to be_nil+ end++ it "rejects a new name that normalizes to nothing" do+ result = tool(name: "old-name", new_name: "!!!", reason: "Test").invoke++ expect(result[:status]).to eq("error")+ expect(result[:error]).to include("not a valid tag name")+ expect(tag.reload.name).to eq("old-name")+ end++ it "finds the tag case-insensitively" do+ result = tool(name: "OLD-NAME", description: "Found it", reason: "Test").invoke++ expect(result[:status]).to eq("success")+ expect(tag.reload.description).to eq("Found it")+ end++ it "returns an error when the tag is not found" do+ result = tool(name: "missing", new_name: "whatever", reason: "Test").invoke++ expect(result[:status]).to eq("error")+ end++ it "returns an error when neither new_name nor description is provided" do+ result = tool(name: "old-name", reason: "Test").invoke++ expect(result[:status]).to eq("error")+ expect(result[:error]).to include("new_name or description")+ end++ it "returns an error when reason is blank" do+ result = tool(name: "old-name", new_name: "new-name", reason: " ").invoke++ expect(result[:status]).to eq("error")+ end++ it "returns an error when renaming to an existing tag's name" do+ Fabricate(:tag, name: "taken")++ result = tool(name: "old-name", new_name: "taken", reason: "Test").invoke++ expect(result[:status]).to eq("error")+ expect(tag.reload.name).to eq("old-name")+ end++ it "reports invisible tags as not found" do+ hidden_tag = Fabricate(:tag, name: "staff-only")+ Fabricate(:tag_group, permissions: { "staff" => 1 }, tag_names: [hidden_tag.name])+ regular_user = Fabricate(:user, trust_level: TrustLevel[0])+ ctx = DiscourseAi::Agents::BotContext.new(user: regular_user)+ t =+ described_class.new(+ { name: hidden_tag.name, new_name: "found-you", reason: "test" },+ bot_user: bot_user,+ llm: llm,+ context: ctx,+ )+ result = t.invoke++ expect(result[:status]).to eq("error")+ expect(result[:error]).to include("not found")+ expect(hidden_tag.reload.name).to eq("staff-only")+ end++ it "returns an error when context user lacks permission" do+ regular_user = Fabricate(:user, trust_level: TrustLevel[0])+ ctx = DiscourseAi::Agents::BotContext.new(user: regular_user)+ t =+ described_class.new(+ { name: "old-name", new_name: "nope", reason: "test" },+ bot_user: bot_user,+ llm: llm,+ context: ctx,+ )+ result = t.invoke++ expect(result[:status]).to eq("error")+ expect(result[:error]).to include("not allowed")+ expect(tag.reload.name).to eq("old-name")+ end+enddiff --git a/plugins/discourse-ai/spec/migrations/rename_edit_tags_tool_to_change_topic_tags_spec.rb b/plugins/discourse-ai/spec/migrations/rename_edit_tags_tool_to_change_topic_tags_spec.rbnew file mode 100644index 00000000000..3b40d667b64--- /dev/null+++ b/plugins/discourse-ai/spec/migrations/rename_edit_tags_tool_to_change_topic_tags_spec.rb@@ -0,0 +1,76 @@+# frozen_string_literal: true++require Rails.root.join(+ "plugins/discourse-ai/db/migrate/20260821210913_rename_edit_tags_tool_to_change_topic_tags.rb",+ )++RSpec.describe RenameEditTagsToolToChangeTopicTags do+ fab!(:agent, :ai_agent)++ before do+ enable_current_plugin+ @original_verbose = ActiveRecord::Migration.verbose+ ActiveRecord::Migration.verbose = false+ end++ after { ActiveRecord::Migration.verbose = @original_verbose }++ def stored_tools(id)+ value = DB.query_single("SELECT tools FROM ai_agents WHERE id = ?", id).first+ value.is_a?(String) ? JSON.parse(value) : value+ end++ it "renames EditTags entries while preserving options and other tools" do+ DB.exec(+ "UPDATE ai_agents SET tools = :tools WHERE id = :id",+ tools: [["EditTags", { "option" => "x" }, true], ["CloseTopic", nil, false]].to_json,+ id: agent.id,+ )++ described_class.new.up++ expect(stored_tools(agent.id)).to eq(+ [["ChangeTopicTags", { "option" => "x" }, true], ["CloseTopic", nil, false]],+ )+ end++ it "renames bare string entries" do+ DB.exec(+ "UPDATE ai_agents SET tools = :tools WHERE id = :id",+ tools: %w[EditTags CloseTopic].to_json,+ id: agent.id,+ )++ described_class.new.up++ expect(stored_tools(agent.id)).to eq(%w[ChangeTopicTags CloseTopic])+ end++ it "renames pending tool approval actions so they stay replayable" do+ action_id =+ DB.query_single(+ "INSERT INTO ai_tool_actions (tool_name, tool_parameters, ai_agent_id, bot_user_id, created_at, updated_at)+ VALUES ('edit_tags', '{}', :agent_id, -1, NOW(), NOW()) RETURNING id",+ agent_id: agent.id,+ ).first++ described_class.new.up++ expect(+ DB.query_single("SELECT tool_name FROM ai_tool_actions WHERE id = ?", action_id).first,+ ).to eq("change_topic_tags")+ end++ it "leaves agents that already have ChangeTopicTags untouched" do+ tools = [["EditTags", nil, false], ["ChangeTopicTags", nil, false]]+ DB.exec(+ "UPDATE ai_agents SET tools = :tools WHERE id = :id",+ tools: tools.to_json,+ id: agent.id,+ )++ described_class.new.up++ expect(stored_tools(agent.id)).to eq(tools)+ end+end