Skip to content

A platform for community discussion. Free, open, simple.

FEATURE: Add category creation and real category editing to AI bot tools (#42799)

Gabriel Grubba2de0e3f963b9
diff --git a/db/structure.sql b/db/structure.sql
index 68f0991c181..44146dd0b44 100644
--- a/db/structure.sql
+++ b/db/structure.sql
@@ -23361,6 +23361,7 @@ INSERT INTO "schema_migrations" (version) VALUES
('20260824091843'),
('20260824072257'),
('20260824051214'),
+('20260821210543'),
('20260821164114'),
('20260820171539'),
('20260820143851'),
diff --git a/plugins/discourse-ai/config/locales/server.en.yml b/plugins/discourse-ai/config/locales/server.en.yml
index 39b2fe2db91..1274b258503 100644
--- a/plugins/discourse-ai/config/locales/server.en.yml
+++ b/plugins/discourse-ai/config/locales/server.en.yml
@@ -710,7 +710,9 @@ en:
delete_topic: "Delete topic"
edit_post: "Edit post"
edit_tags: "Edit tags"
+ create_category: "Create category"
edit_category: "Edit category"
+ change_topic_category: "Change topic category"
set_topic_timer: "Set topic timer"
set_slow_mode: "Set slow mode"
move_posts: "Move posts"
@@ -764,7 +766,9 @@ en:
delete_topic: "Delete a topic"
edit_post: "Edit the content of a post"
edit_tags: "Edit the tags on a topic"
- edit_category: "Move a topic to a different category"
+ 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"
set_topic_timer: "Set a timer on a topic to close, open, delete, or bump it"
set_slow_mode: "Enable or disable slow mode on a topic"
move_posts: "Move posts to a new or existing topic"
@@ -817,7 +821,9 @@ en:
delete_topic: "Deleting topic %{topic_id} (deleted: %{deleted})"
edit_post: "Editing post %{post_id}"
edit_tags: "Editing tags on topic %{topic_id}: %{tags}"
- edit_category: "Moving topic %{topic_id} to category %{category_id}"
+ create_category: "Creating category '%{name}'"
+ edit_category: "Editing category %{category_id} (%{fields})"
+ change_topic_category: "Moving topic %{topic_id} to category %{category_id}"
set_topic_timer: "Setting %{timer_type} timer on topic %{topic_id} (%{duration_hours}h)"
set_slow_mode: "Setting slow mode on topic %{topic_id} (%{slow_mode_seconds}s)"
move_posts: "Moving posts %{post_ids} from topic %{topic_id}"
@@ -946,7 +952,23 @@ en:
tagging_disabled: "Tagging is not enabled on this site."
success: "Tags updated successfully."
+ create_category:
+ errors:
+ no_name: "A name is required to create a category."
+ not_allowed: "You are not allowed to create categories."
+ parent_not_found: "Parent category not found."
+ no_reason: "A reason is required to create a category."
+ success: "Category '%{name}' created successfully."
+
edit_category:
+ errors:
+ not_found: "Category not found."
+ not_allowed: "You are not allowed to edit this category."
+ nothing_to_edit: "At least one of name, description, color, or text_color must be provided."
+ no_reason: "A reason is required to edit a category."
+ success: "Category '%{name}' updated successfully."
+
+ change_topic_category:
errors:
not_found: "Topic not found."
not_allowed: "You are not allowed to move this topic."
diff --git a/plugins/discourse-ai/db/migrate/20260821210543_rename_edit_category_tool_to_change_topic_category.rb b/plugins/discourse-ai/db/migrate/20260821210543_rename_edit_category_tool_to_change_topic_category.rb
new file mode 100644
index 00000000000..54a4046fa49
--- /dev/null
+++ b/plugins/discourse-ai/db/migrate/20260821210543_rename_edit_category_tool_to_change_topic_category.rb
@@ -0,0 +1,45 @@
+# frozen_string_literal: true
+
+class RenameEditCategoryToolToChangeTopicCategory < ActiveRecord::Migration[8.0]
+ # The EditCategory tool used to move a topic to a different category; that
+ # behavior now lives in ChangeTopicCategory while EditCategory edits the category
+ # itself. Renaming the stored entry keeps existing agents doing what they
+ # were configured to do.
+ def up
+ DB
+ .query("SELECT id, tools FROM ai_agents WHERE tools::text LIKE '%EditCategory%'")
+ .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?("ChangeTopicCategory")
+
+ renamed =
+ tools.map do |tool|
+ if tool.is_a?(Array) && tool.first == "EditCategory"
+ ["ChangeTopicCategory", *tool.drop(1)]
+ elsif tool == "EditCategory"
+ "ChangeTopicCategory"
+ 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; their stored parameters
+ # (topic_id/category_id/reason) are the change_topic_category signature.
+ execute "UPDATE ai_tool_actions SET tool_name = 'change_topic_category' WHERE tool_name = 'edit_category'"
+ end
+
+ def down
+ raise ActiveRecord::IrreversibleMigration
+ end
+end
diff --git a/plugins/discourse-ai/lib/agents/agent.rb b/plugins/discourse-ai/lib/agents/agent.rb
index 019af8570eb..7d401173c82 100644
--- a/plugins/discourse-ai/lib/agents/agent.rb
+++ b/plugins/discourse-ai/lib/agents/agent.rb
@@ -116,7 +116,9 @@ module DiscourseAi
Tools::LockPost,
Tools::DeleteTopic,
Tools::EditPost,
+ Tools::CreateCategory,
Tools::EditCategory,
+ Tools::ChangeTopicCategory,
Tools::SetTopicTimer,
Tools::SetSlowMode,
Tools::MovePosts,
diff --git a/plugins/discourse-ai/lib/agents/discourse_admin_assistant.rb b/plugins/discourse-ai/lib/agents/discourse_admin_assistant.rb
index aae2be2121d..abbd960d4db 100644
--- a/plugins/discourse-ai/lib/agents/discourse_admin_assistant.rb
+++ b/plugins/discourse-ai/lib/agents/discourse_admin_assistant.rb
@@ -30,7 +30,9 @@ module DiscourseAi
Tools::UnlistTopic,
Tools::DeleteTopic,
Tools::EditPost,
+ Tools::CreateCategory,
Tools::EditCategory,
+ Tools::ChangeTopicCategory,
Tools::EditTags,
Tools::MovePosts,
Tools::SuspendUser,
diff --git a/plugins/discourse-ai/lib/agents/tools/change_topic_category.rb b/plugins/discourse-ai/lib/agents/tools/change_topic_category.rb
new file mode 100644
index 00000000000..7232586b4bd
--- /dev/null
+++ b/plugins/discourse-ai/lib/agents/tools/change_topic_category.rb
@@ -0,0 +1,126 @@
+# frozen_string_literal: true
+
+module DiscourseAi
+ module Agents
+ module Tools
+ class ChangeTopicCategory < Tool
+ def self.signature
+ {
+ name: name,
+ description: "Moves a topic to a different category.",
+ parameters: [
+ {
+ name: "topic_id",
+ description: "The ID of the topic to move",
+ type: "integer",
+ required: true,
+ },
+ {
+ name: "category_id",
+ description: "The ID of the target category",
+ type: "integer",
+ required: true,
+ },
+ {
+ name: "reason",
+ description: "Short explanation of why the topic is being moved",
+ type: "string",
+ required: true,
+ },
+ {
+ name: "public_edit_reason",
+ description: "Whether the reason should be visible in the post's revision history",
+ type: "boolean",
+ },
+ ],
+ }
+ end
+
+ def self.name
+ "change_topic_category"
+ end
+
+ def self.requires_approval?
+ true
+ end
+
+ def self.attribute_to_approver?
+ true
+ end
+
+ def invoke
+ if (error = validation_error)
+ return error
+ end
+ perform_move
+ end
+
+ def validation_error
+ if topic.blank? || topic.first_post.blank?
+ return(
+ error_response(I18n.t("discourse_ai.ai_bot.change_topic_category.errors.not_found"))
+ )
+ end
+
+ if category.blank?
+ return(
+ error_response(
+ I18n.t("discourse_ai.ai_bot.change_topic_category.errors.category_not_found"),
+ )
+ )
+ end
+
+ if reason.blank?
+ return(
+ error_response(I18n.t("discourse_ai.ai_bot.change_topic_category.errors.no_reason"))
+ )
+ end
+
+ nil
+ end
+
+ def description_args
+ { topic_id: parameters[:topic_id], category_id: parameters[:category_id] }
+ end
+
+ private
+
+ def topic
+ @topic ||= Topic.find_by(id: parameters[:topic_id])
+ end
+
+ def category
+ @category ||= Category.find_by(id: parameters[:category_id])
+ end
+
+ def perform_move
+ if !guardian.can_edit_topic?(topic)
+ return(
+ error_response(I18n.t("discourse_ai.ai_bot.change_topic_category.errors.not_allowed"))
+ )
+ end
+
+ revisor = PostRevisor.new(topic.first_post, topic)
+ result =
+ revisor.revise!(
+ guardian.user,
+ { category_id: category.id }.tap do |f|
+ f[:edit_reason] = reason if !!parameters[:public_edit_reason]
+ end,
+ )
+
+ if result
+ {
+ status: "success",
+ message: I18n.t("discourse_ai.ai_bot.change_topic_category.success"),
+ }
+ else
+ error_response(
+ I18n.t("discourse_ai.ai_bot.change_topic_category.errors.revision_failed"),
+ )
+ end
+ end
+ end
+ end
+ end
+end
diff --git a/plugins/discourse-ai/lib/agents/tools/create_category.rb b/plugins/discourse-ai/lib/agents/tools/create_category.rb
new file mode 100644
index 00000000000..1d64019c373
--- /dev/null
+++ b/plugins/discourse-ai/lib/agents/tools/create_category.rb
@@ -0,0 +1,151 @@
+# frozen_string_literal: true
+
+module DiscourseAi
+ module Agents
+ module Tools
+ class CreateCategory < Tool
+ def self.signature
+ {
+ name: name,
+ description:
+ "Creates a new category. Create parent categories before their subcategories, and use list_categories to find parent category IDs.",
+ parameters: [
+ {
+ name: "name",
+ description: "The display name for the new category",
+ type: "string",
+ required: true,
+ },
+ {
+ name: "description",
+ description: "A description for the new category",
+ type: "string",
+ },
+ {
+ name: "parent_category_id",
+ description: "The ID of the parent category, when creating a subcategory",
+ type: "integer",
+ },
+ {
+ name: "color",
+ description:
+ "The background color, as a 6 digit hex code (e.g. 0088CC). Defaults to the site default when omitted.",
+ type: "string",
+ },
+ {
+ name: "text_color",
+ description: "The text color, as a 6 digit hex code (e.g. FFFFFF)",
+ type: "string",
+ },
+ {
+ name: "reason",
+ description: "Short explanation of why the category is being created",
+ type: "string",
+ required: true,
+ },
+ ],
+ }
+ end
+
+ def self.name
+ "create_category"
+ 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 parameters[:name].blank?
+ return error_response(I18n.t("discourse_ai.ai_bot.create_category.errors.no_name"))
+ end
+
+ if parameters[:parent_category_id].present? && parent_category.blank?
+ return(
+ error_response(I18n.t("discourse_ai.ai_bot.create_category.errors.parent_not_found"))
+ )
+ end
+
+ if parameters[:description].present? &&
+ parameters[:description].size > CategoriesController::MAX_DESCRIPTION_PARAM_LENGTH
+ return(
+ error_response(
+ I18n.t(
+ "category.errors.description_too_long",
+ count: CategoriesController::MAX_DESCRIPTION_PARAM_LENGTH,
+ ),
+ )
+ )
+ end
+
+ if reason.blank?
+ return error_response(I18n.t("discourse_ai.ai_bot.create_category.errors.no_reason"))
+ end
+
+ # Model validations (duplicate name, name length, color format) run
+ # against the unsaved candidate so an invalid request is rejected
+ # before it is queued for approval.
+ candidate = Category.new(category_attributes)
+ return error_response(candidate.errors.full_messages.to_sentence) if !candidate.valid?
+
+ nil
+ end
+
+ def description_args
+ { name: parameters[:name] }
+ end
+
+ private
+
+ def parent_category
+ @parent_category ||= Category.find_by(id: parameters[:parent_category_id])
+ end
+
+ def category_attributes
+ attributes = {
+ name: parameters[:name],
+ description: parameters[:description].presence,
+ parent_category_id: parent_category&.id,
+ user: guardian.user,
+ }
+ %i[color text_color].each do |param|
+ value = parameters[param]
+ attributes[param] = value.to_s.delete_prefix("#") if value.present?
+ end
+ attributes
+ end
+
+ def perform_create
+ if !guardian.can_create_category?
+ return error_response(I18n.t("discourse_ai.ai_bot.create_category.errors.not_allowed"))
+ end
+
+ category = Category.new(category_attributes)
+
+ if category.save
+ StaffActionLogger.new(guardian.user).log_category_creation(category)
+ {
+ status: "success",
+ category_id: category.id,
+ url: category.url,
+ message: I18n.t("discourse_ai.ai_bot.create_category.success", name: category.name),
+ }
+ else
+ error_response(category.errors.full_messages.to_sentence)
+ end
+ end
+ end
+ end
+ end
+end
diff --git a/plugins/discourse-ai/lib/agents/tools/edit_category.rb b/plugins/discourse-ai/lib/agents/tools/edit_category.rb
index 8371d757f32..4eb98ae1f22 100644
--- a/plugins/discourse-ai/lib/agents/tools/edit_category.rb
+++ b/plugins/discourse-ai/lib/agents/tools/edit_category.rb
@@ -4,33 +4,46 @@ module DiscourseAi
module Agents
module Tools
class EditCategory < Tool
+ EDITABLE_PARAMS = %i[name description color text_color].freeze
+
def self.signature
{
name: name,
- description: "Moves a topic to a different category.",
+ description:
+ "Edits an existing category's name, description, or colors. At least one editable field must be provided.",
parameters: [
{
- name: "topic_id",
- description: "The ID of the topic to move",
+ name: "category_id",
+ description: "The ID of the category to edit",
type: "integer",
required: true,
},
{
- name: "category_id",
- description: "The ID of the target category",
- type: "integer",
- required: true,
+ name: "name",
+ description: "The new display name for the category",
+ type: "string",
},
{
- name: "reason",
- description: "Short explanation of why the topic is being moved",
+ name: "description",
+ description:
+ "The new description for the category. Pass an empty string to clear the existing description.",
+ type: "string",
+ },
+ {
+ name: "color",
+ description: "The new background color, as a 6 digit hex code (e.g. 0088CC)",
type: "string",
- required: true,
},
{
- name: "public_edit_reason",
- description: "Whether the reason should be visible in the post's revision history",
- type: "boolean",
+ name: "text_color",
+ description: "The new text color, as a 6 digit hex code (e.g. FFFFFF)",
+ type: "string",
+ },
+ {
+ name: "reason",
+ description: "Short explanation of why the category is being edited",
+ type: "string",
+ required: true,
},
],
}
@@ -44,20 +57,25 @@ module DiscourseAi
true
end
+ def self.attribute_to_approver?
+ true
+ end
+
def invoke
- topic = Topic.find_by(id: parameters[:topic_id])
- if !topic
- return error_response(I18n.t("discourse_ai.ai_bot.edit_category.errors.not_found"))
+ if (error = validation_error)
+ return error
end
+ perform_edit
+ end
- if !guardian.can_edit_topic?(topic)
- return error_response(I18n.t("discourse_ai.ai_bot.edit_category.errors.not_allowed"))
+ def validation_error
+ if category.blank?
+ return error_response(I18n.t("discourse_ai.ai_bot.edit_category.errors.not_found"))
end
- category = Category.find_by(id: parameters[:category_id])
- if !category
+ if changes.blank?
return(
- error_response(I18n.t("discourse_ai.ai_bot.edit_category.errors.category_not_found"))
+ error_response(I18n.t("discourse_ai.ai_bot.edit_category.errors.nothing_to_edit"))
)
end
@@ -65,29 +83,69 @@ module DiscourseAi
return error_response(I18n.t("discourse_ai.ai_bot.edit_category.errors.no_reason"))
end
- first_post = topic.first_post
- if !first_post
- return error_response(I18n.t("discourse_ai.ai_bot.edit_category.errors.not_found"))
+ if (error = invalid_changes_error)
+ return error
end
- revisor = PostRevisor.new(first_post, topic)
- result =
- revisor.revise!(
- acting_user,
- { category_id: category.id }.tap do |f|
- f[:edit_reason] = reason if !!parameters[:public_edit_reason]
- end,
- )
-
- if result
- { status: "success", message: I18n.t("discourse_ai.ai_bot.edit_category.success") }
- else
- error_response(I18n.t("discourse_ai.ai_bot.edit_category.errors.revision_failed"))
- end
+ nil
end
def description_args
- { topic_id: parameters[:topic_id], category_id: parameters[:category_id] }
+ { category_id: parameters[:category_id], fields: changes.keys.join(", ") }
+ end
+
+ private
+
+ def category
+ @category ||= Category.find_by(id: parameters[:category_id])
+ end
+
+ def changes
+ @changes ||=
+ EDITABLE_PARAMS
+ .filter_map do |param|
+ value = parameters[param]
+ if param == :description
+ # An explicitly provided empty description clears it.
+ next if value.nil?
+ else
+ next if value.blank?
+ end
+ value = value.to_s.delete_prefix("#") if %i[color text_color].include?(param)
+ [param, value]
+ end
+ .to_h
+ end
+
+ # Runs the model validations against the unsaved changes so an invalid
+ # request is rejected before it is queued for approval, instead of
+ # producing a review item that could only fail.
+ def invalid_changes_error
+ category.assign_attributes(changes)
+ error = error_response(category.errors.full_messages.to_sentence) if !category.valid?
+ category.restore_attributes
+ error
+ end
+
+ def perform_edit
+ if !guardian.can_edit_category?(category)
+ return error_response(I18n.t("discourse_ai.ai_bot.edit_category.errors.not_allowed"))
+ end
+
+ if category.update(changes)
+ StaffActionLogger.new(guardian.user).log_category_settings_change(
+ category,
+ changes.stringify_keys,
+ old_permissions: {
+ },
+ )
+ {
+ status: "success",
+ message: I18n.t("discourse_ai.ai_bot.edit_category.success", name: category.name),
+ }
+ else
+ error_response(category.errors.full_messages.to_sentence)
+ end
end
end
end
diff --git a/plugins/discourse-ai/spec/lib/agents/discourse_admin_assistant_spec.rb b/plugins/discourse-ai/spec/lib/agents/discourse_admin_assistant_spec.rb
index 3bafcdfe457..4e47a4ac817 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
@@ -24,7 +24,9 @@ RSpec.describe DiscourseAi::Agents::DiscourseAdminAssistant do
DiscourseAi::Agents::Tools::UnlistTopic,
DiscourseAi::Agents::Tools::DeleteTopic,
DiscourseAi::Agents::Tools::EditPost,
+ DiscourseAi::Agents::Tools::CreateCategory,
DiscourseAi::Agents::Tools::EditCategory,
+ DiscourseAi::Agents::Tools::ChangeTopicCategory,
DiscourseAi::Agents::Tools::EditTags,
DiscourseAi::Agents::Tools::MovePosts,
DiscourseAi::Agents::Tools::SuspendUser,
diff --git a/plugins/discourse-ai/spec/lib/agents/tools/change_topic_category_spec.rb b/plugins/discourse-ai/spec/lib/agents/tools/change_topic_category_spec.rb
new file mode 100644
index 00000000000..2855f79a5f3
--- /dev/null
+++ b/plugins/discourse-ai/spec/lib/agents/tools/change_topic_category_spec.rb
@@ -0,0 +1,98 @@
+# frozen_string_literal: true
+
+RSpec.describe DiscourseAi::Agents::Tools::ChangeTopicCategory 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!(:post)
+ fab!(:category)
+ fab!(:target_category, :category)
+
+ before do
+ enable_current_plugin
+ SiteSetting.ai_bot_enabled = true
+ end
+
+ def tool(params = nil, **kwargs)
+ params ||= kwargs
+ described_class.new(params, bot_user: bot_user, llm: llm, context: context)
+ end
+
+ let(:context) { DiscourseAi::Agents::BotContext.new }
+
+ it "moves the topic to a different category" do
+ topic = post.topic
+ topic.update!(category: category)
+
+ result = tool(topic_id: topic.id, category_id: target_category.id, reason: "Better fit").invoke
+
+ expect(result[:status]).to eq("success")
+ expect(topic.reload.category_id).to eq(target_category.id)
+ expect(post.reload.edit_reason).to be_nil
+ end
+
+ it "sets a public edit reason when public_edit_reason is true" do
+ topic = post.topic
+ topic.update!(category: category)
+
+ result =
+ tool(
+ topic_id: topic.id,
+ category_id: target_category.id,
+ reason: "Better fit",
+ public_edit_reason: true,
+ ).invoke
+
+ expect(result[:status]).to eq("success")
+ expect(post.reload.edit_reason).to eq("Better fit")
+ end
+
+ it "returns an error when topic is not found" do
+ result = tool(topic_id: -1, category_id: target_category.id, reason: "Test").invoke
+
+ expect(result[:status]).to eq("error")
+ end
+
+ it "rejects missing topics, categories, and reasons before queueing for approval" do
+ expect(
+ tool(topic_id: -1, category_id: target_category.id, reason: "Test").validation_error,
+ ).to be_present
+ expect(
+ tool(topic_id: post.topic_id, category_id: -1, reason: "Test").validation_error,
+ ).to be_present
+ expect(
+ tool(topic_id: post.topic_id, category_id: target_category.id, reason: " ").validation_error,
+ ).to be_present
+ expect(
+ tool(topic_id: post.topic_id, category_id: target_category.id, reason: "Ok").validation_error,
+ ).to be_nil
+ end
+
+ it "returns an error when category is not found" do
+ result = tool(topic_id: post.topic_id, category_id: -1, reason: "Test").invoke
+
+ expect(result[:status]).to eq("error")
+ end
+
+ it "returns an error when reason is blank" do
+ result = tool(topic_id: post.topic_id, category_id: target_category.id, reason: " ").invoke
+
+ expect(result[:status]).to eq("error")
+ 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(
+ { topic_id: post.topic_id, category_id: target_category.id, 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")
+ end
+end
diff --git a/plugins/discourse-ai/spec/lib/agents/tools/create_category_spec.rb b/plugins/discourse-ai/spec/lib/agents/tools/create_category_spec.rb
new file mode 100644
index 00000000000..66bfcc4c6f9
--- /dev/null
+++ b/plugins/discourse-ai/spec/lib/agents/tools/create_category_spec.rb
@@ -0,0 +1,120 @@
+# frozen_string_literal: true
+
+RSpec.describe DiscourseAi::Agents::Tools::CreateCategory 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
+ 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 category with a description and returns its id and url" do
+ result =
+ tool(name: "What we do", description: "All about our mission", reason: "Site setup").invoke
+
+ expect(result[:status]).to eq("success")
+
+ category = Category.find(result[:category_id])
+ expect(category.name).to eq("What we do")
+ expect(category.user_id).to eq(admin.id)
+ expect(category.description).to include("All about our mission")
+ expect(result[:url]).to eq(category.url)
+ end
+
+ it "creates a subcategory under the given parent" do
+ parent = Fabricate(:category)
+
+ result =
+ tool(name: "How to use the forum", parent_category_id: parent.id, reason: "Setup").invoke
+
+ expect(result[:status]).to eq("success")
+ expect(Category.find(result[:category_id]).parent_category_id).to eq(parent.id)
+ end
+
+ it "applies custom colors, stripping a leading # from hex codes" do
+ result = tool(name: "Colorful", color: "#AA2211", text_color: "EEEEEE", reason: "Setup").invoke
+
+ expect(result[:status]).to eq("success")
+ category = Category.find(result[:category_id])
+ expect(category.color).to eq("AA2211")
+ expect(category.text_color).to eq("EEEEEE")
+ end
+
+ it "logs a staff action attributed to the context user" do
+ expect { tool(name: "Audited", reason: "Audit trail").invoke }.to change {
+ UserHistory.where(
+ acting_user_id: admin.id,
+ action: UserHistory.actions[:create_category],
+ ).count
+ }.by(1)
+ end
+
+ it "returns an error when the description is too long" do
+ result = tool(name: "Long desc", description: "a" * 1001, reason: "Test").invoke
+
+ expect(result[:status]).to eq("error")
+ expect(Category.exists?(name: "Long desc")).to eq(false)
+ end
+
+ it "returns an error when name is blank" do
+ result = tool(name: " ", reason: "Test").invoke
+
+ expect(result[:status]).to eq("error")
+ end
+
+ it "returns an error when the parent category is not found" do
+ result = tool(name: "Orphan", parent_category_id: -1, reason: "Test").invoke
+
+ expect(result[:status]).to eq("error")
+ expect(result[:error]).to include("Parent category not found")
+ 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 "rejects a duplicate name before it can be queued for approval" do
+ Fabricate(:category, name: "Duplicate")
+
+ tool_instance = tool(name: "Duplicate", reason: "Test")
+
+ expect(tool_instance.validation_error).to be_present
+ expect(tool_instance.invoke[:status]).to eq("error")
+ end
+
+ it "rejects an invalid color before it can be queued for approval" do
+ error = tool(name: "Bad color", color: "nope", reason: "Test").validation_error
+
+ expect(error).to be_present
+ expect(Category.exists?(name: "Bad color")).to eq(false)
+ 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(Category.exists?(name: "Nope")).to eq(false)
+ end
+end
diff --git a/plugins/discourse-ai/spec/lib/agents/tools/edit_category_spec.rb b/plugins/discourse-ai/spec/lib/agents/tools/edit_category_spec.rb
index e4a417b3480..e9c4efdc2c1 100644
--- a/plugins/discourse-ai/spec/lib/agents/tools/edit_category_spec.rb
+++ b/plugins/discourse-ai/spec/lib/agents/tools/edit_category_spec.rb
@@ -4,65 +4,123 @@ RSpec.describe DiscourseAi::Agents::Tools::EditCategory 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!(:post)
+ fab!(:admin)
fab!(:category)
- fab!(:target_category, :category)
before do
enable_current_plugin
SiteSetting.ai_bot_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
- let(:context) { DiscourseAi::Agents::BotContext.new }
-
- it "moves the topic to a different category" do
- topic = post.topic
- topic.update!(category: category)
-
- result = tool(topic_id: topic.id, category_id: target_category.id, reason: "Better fit").invoke
+ it "updates the category's name and colors" do
+ result =
+ tool(
+ category_id: category.id,
+ name: "Renamed category",
+ color: "#FF0000",
+ text_color: "000000",
+ reason: "Rebranding",
+ ).invoke
expect(result[:status]).to eq("success")
- expect(topic.reload.category_id).to eq(target_category.id)
- expect(post.reload.edit_reason).to be_nil
+ category.reload
+ expect(category.name).to eq("Renamed category")
+ expect(category.color).to eq("FF0000")
+ expect(category.text_color).to eq("000000")
end
- it "sets a public edit reason when public_edit_reason is true" do
- topic = post.topic
- topic.update!(category: category)
+ it "updates the category description and its definition topic" do
+ category_with_definition = Fabricate(:category_with_definition)
result =
tool(
- topic_id: topic.id,
- category_id: target_category.id,
- reason: "Better fit",
- public_edit_reason: true,
+ category_id: category_with_definition.id,
+ description: "A brand new description",
+ reason: "Test",
).invoke
expect(result[:status]).to eq("success")
- expect(post.reload.edit_reason).to eq("Better fit")
+ category_with_definition.reload
+ expect(category_with_definition.description).to include("A brand new description")
+ expect(category_with_definition.topic.first_post.reload.raw).to eq("A brand new description")
+ end
+
+ it "clears the description when an empty string is provided" do
+ category_with_definition = Fabricate(:category_with_definition)
+ tool(
+ category_id: category_with_definition.id,
+ description: "Something old",
+ reason: "Setup",
+ ).invoke
+
+ result = tool(category_id: category_with_definition.id, description: "", reason: "Clean").invoke
+
+ expect(result[:status]).to eq("success")
+ expect(category_with_definition.reload.description).to be_blank
end
- it "returns an error when topic is not found" do
- result = tool(topic_id: -1, category_id: target_category.id, reason: "Test").invoke
+ it "rejects invalid changes before they can be queued for approval" do
+ error = tool(category_id: category.id, color: "not-a-color", reason: "Test").validation_error
+
+ expect(error).to be_present
+ expect(error[:status]).to eq("error")
+ expect(category.reload.color).not_to eq("not-a-color")
+ end
+
+ it "logs a staff action attributed to the context user" do
+ expect {
+ tool(category_id: category.id, name: "Audited name", reason: "Audit trail").invoke
+ }.to change {
+ UserHistory.where(
+ acting_user_id: admin.id,
+ action: UserHistory.actions[:change_category_settings],
+ ).count
+ }.by(1)
+ end
+
+ it "logs a staff action for a description-only edit" do
+ expect {
+ tool(category_id: category.id, description: "Audited description", reason: "Audit").invoke
+ }.to change {
+ UserHistory.where(
+ acting_user_id: admin.id,
+ action: UserHistory.actions[:change_category_settings],
+ subject: "description",
+ ).count
+ }.by(1)
+ end
+
+ it "returns an error when the category is not found" do
+ result = tool(category_id: -1, name: "New name", reason: "Test").invoke
expect(result[:status]).to eq("error")
end
- it "returns an error when category is not found" do
- result = tool(topic_id: post.topic_id, category_id: -1, reason: "Test").invoke
+ it "returns an error when no editable field is provided" do
+ result = tool(category_id: category.id, reason: "Test").invoke
expect(result[:status]).to eq("error")
+ expect(result[:error]).to include("At least one")
end
it "returns an error when reason is blank" do
- result = tool(topic_id: post.topic_id, category_id: target_category.id, reason: " ").invoke
+ result = tool(category_id: category.id, name: "New name", reason: " ").invoke
+
+ expect(result[:status]).to eq("error")
+ end
+
+ it "returns an error when the new values are invalid" do
+ result = tool(category_id: category.id, color: "not-a-color", reason: "Test").invoke
expect(result[:status]).to eq("error")
+ expect(category.reload.color).not_to eq("not-a-color")
end
it "returns an error when context user lacks permission" do
@@ -70,7 +128,7 @@ RSpec.describe DiscourseAi::Agents::Tools::EditCategory do
ctx = DiscourseAi::Agents::BotContext.new(user: regular_user)
t =
described_class.new(
- { topic_id: post.topic_id, category_id: target_category.id, reason: "test" },
+ { category_id: category.id, name: "Nope", reason: "test" },
bot_user: bot_user,
llm: llm,
context: ctx,
@@ -79,5 +137,6 @@ RSpec.describe DiscourseAi::Agents::Tools::EditCategory do
expect(result[:status]).to eq("error")
expect(result[:error]).to include("not allowed")
+ expect(category.reload.name).not_to eq("Nope")
end
end
diff --git a/plugins/discourse-ai/spec/migrations/rename_edit_category_tool_to_change_topic_category_spec.rb b/plugins/discourse-ai/spec/migrations/rename_edit_category_tool_to_change_topic_category_spec.rb
new file mode 100644
index 00000000000..a593ddafae3
--- /dev/null
+++ b/plugins/discourse-ai/spec/migrations/rename_edit_category_tool_to_change_topic_category_spec.rb
@@ -0,0 +1,76 @@
+# frozen_string_literal: true
+
+require Rails.root.join(
+ "plugins/discourse-ai/db/migrate/20260821210543_rename_edit_category_tool_to_change_topic_category.rb",
+ )
+
+RSpec.describe RenameEditCategoryToolToChangeTopicCategory 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 EditCategory entries while preserving options and other tools" do
+ DB.exec(
+ "UPDATE ai_agents SET tools = :tools WHERE id = :id",
+ tools: [["EditCategory", { "option" => "x" }, true], ["CloseTopic", nil, false]].to_json,
+ id: agent.id,
+ )
+
+ described_class.new.up
+
+ expect(stored_tools(agent.id)).to eq(
+ [["ChangeTopicCategory", { "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[EditCategory CloseTopic].to_json,
+ id: agent.id,
+ )
+
+ described_class.new.up
+
+ expect(stored_tools(agent.id)).to eq(%w[ChangeTopicCategory 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_category', '{}', :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_category")
+ end
+
+ it "leaves agents that already have ChangeTopicCategory untouched" do
+ tools = [["EditCategory", nil, false], ["ChangeTopicCategory", 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