Skip to content

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

FEATURE: new unified discourse.editTopic API for custom tools (#37129)

Samdba73b33490c
diff --git a/plugins/discourse-ai/lib/ai_tool_scripts/preamble.js b/plugins/discourse-ai/lib/ai_tool_scripts/preamble.js
index f9182d7a52a..5044f171944 100644
--- a/plugins/discourse-ai/lib/ai_tool_scripts/preamble.js
+++ b/plugins/discourse-ai/lib/ai_tool_scripts/preamble.js
@@ -128,7 +128,8 @@
* discourse.getTopic(topic_id): Retrieves details for a specific topic.
* Parameters:
* topic_id (number): The ID of the topic.
- * Returns: Object (Topic details using ListableTopicSerializer structure) or null if not found/accessible.
+ * Returns: Object (Topic details using ListableTopicSerializer structure, plus `tags`, `first_post_id`,
+ * `category_id`, `category_name`, `category_slug`) or null if not found/accessible.
*
* discourse.getUser(user_id_or_username): Retrieves details for a specific user.
* Parameters:
@@ -152,14 +153,20 @@
* The sending user must have permission to post in the channel.
* Returns: { success: boolean, message_id?: number, message?: string, created_at?: string } or { error: string }
*
- * discourse.setTags(topic_id, tags, options?): Sets tags for a topic.
+ * discourse.editTopic(topic_id, updates, options?): Edits topic properties (tags, category, visibility).
* Parameters:
* topic_id (number): The ID of the topic.
- * tags (Array<string>): The list of tags to apply.
+ * updates (Object): Properties to update (all optional):
+ * tags (Array<string>): Tags to apply to the topic.
+ * category (number | string): Category ID, name, or slug.
+ * visible (boolean): true to list, false to unlist.
* options (Object, optional):
- * append (boolean): If true, tags are added to existing ones.
* username (string): The username of the user performing the action.
- * Returns: { success: boolean, tags: Array<string> }
+ * silent (boolean): Skip notifications for category changes (default: false).
+ * append (boolean): Append tags instead of replacing (default: false).
+ * Returns: { success: boolean, topic: { id, category_id, category_name, category_slug, tags, visible, visibility_reason_id } }
+ * Throws: Error if topic not found, permission denied, or operation fails.
+ * Note: `discourse.setTags(topic_id, tags, options)` is available as a backwards-compatible alias.
*
* discourse.editPost(post_id, raw, options?): Edits a post's content.
* Parameters:
diff --git a/plugins/discourse-ai/lib/personas/tool_runner.rb b/plugins/discourse-ai/lib/personas/tool_runner.rb
index 4d8e8bb80e2..aa3b4fe4ab7 100644
--- a/plugins/discourse-ai/lib/personas/tool_runner.rb
+++ b/plugins/discourse-ai/lib/personas/tool_runner.rb
@@ -47,6 +47,18 @@ module DiscourseAi
end
end
+ def resolve_category(category_id_or_name)
+ if category_id_or_name.is_a?(Integer) ||
+ category_id_or_name.to_i.to_s == category_id_or_name.to_s
+ Category.find_by(id: category_id_or_name.to_i)
+ else
+ Category
+ .where(name: category_id_or_name)
+ .or(Category.where(slug: category_id_or_name))
+ .first
+ end
+ end
+
def mini_racer_context
@mini_racer_context ||=
begin
@@ -177,20 +189,24 @@ module DiscourseAi
}
return result;
},
- setTags: function(topic_id, tags, options) {
- const result = _discourse_set_tags(topic_id, tags, options);
+ editPost: function(post_id, raw, options) {
+ const result = _discourse_edit_post(post_id, raw, options);
if (result.error) {
- return result;
+ throw new Error(result.error);
}
return result;
},
- editPost: function(post_id, raw, options) {
- const result = _discourse_edit_post(post_id, raw, options);
+ editTopic: function(topic_id, updates, options) {
+ const result = _discourse_edit_topic(topic_id, updates, options);
if (result.error) {
throw new Error(result.error);
}
return result;
},
+ // Backwards compatibility alias (undocumented)
+ setTags: function(topic_id, tags, options) {
+ return this.editTopic(topic_id, { tags: tags }, options);
+ },
};
const context = #{JSON.generate(@context.to_json)};
@@ -462,6 +478,9 @@ module DiscourseAi
)
data["tags"] = topic.tags.pluck(:name)
data["first_post_id"] = topic.first_post&.id
+ data["category_id"] = topic.category_id
+ data["category_name"] = topic.category&.name
+ data["category_slug"] = topic.category&.slug
data
end
end,
@@ -643,12 +662,7 @@ module DiscourseAi
user = resolve_user(username)
return { error: "User not found: #{username}" } if user.nil?
- category =
- if category_id.present?
- Category.find_by(id: category_id)
- else
- Category.find_by(name: category_name) || Category.find_by(slug: category_name)
- end
+ category = resolve_category(category_id.presence || category_name)
return { error: "Category not found" } if category.nil?
@@ -842,53 +856,106 @@ module DiscourseAi
)
mini_racer_context.attach(
- "_discourse_set_tags",
- ->(topic_id, tags, options) do
+ "_discourse_edit_post",
+ ->(post_id, raw, options) do
in_attached_function do
- topic = Topic.find_by(id: topic_id)
- return { error: "Topic not found" } if topic.nil?
+ post = Post.find_by(id: post_id)
+ return { error: "Post not found" } if post.nil?
options ||= {}
- append = !!options["append"]
+ edit_reason = options["edit_reason"]
username = options["username"]
user = resolve_user(username)
return { error: "User not found: #{username}" } if user.nil?
- if DiscourseTagging.tag_topic_by_names(
- topic,
- Guardian.new(user),
- tags,
- append: append,
- )
- { success: true, tags: topic.tags.pluck(:name) }
+ revisor = PostRevisor.new(post)
+ if revisor.revise!(user, { raw: raw, edit_reason: edit_reason })
+ { success: true, post_id: post.id }
else
- { error: "Failed to apply tags", details: topic.errors.full_messages }
+ { error: post.errors.full_messages.join(", ") }
end
end
end,
)
mini_racer_context.attach(
- "_discourse_edit_post",
- ->(post_id, raw, options) do
+ "_discourse_edit_topic",
+ ->(topic_id, updates, options) do
in_attached_function do
- post = Post.find_by(id: post_id)
- return { error: "Post not found" } if post.nil?
+ topic = Topic.find_by(id: topic_id)
+ return { error: "Topic not found" } if topic.nil?
+ updates ||= {}
options ||= {}
- edit_reason = options["edit_reason"]
- username = options["username"]
+ user = resolve_user(options["username"])
+ return { error: "User not found: #{options["username"]}" } if user.nil?
- user = resolve_user(username)
- return { error: "User not found: #{username}" } if user.nil?
+ guardian = Guardian.new(user)
- revisor = PostRevisor.new(post)
- if revisor.revise!(user, { raw: raw, edit_reason: edit_reason })
- { success: true, post_id: post.id }
- else
- { error: post.errors.full_messages.join(", ") }
+ # Handle category change
+ if updates.key?("category")
+ if topic.private_message?
+ return { error: "Cannot change category of private messages" }
+ end
+
+ category = resolve_category(updates["category"])
+ return { error: "Category not found" } if category.nil?
+
+ unless guardian.can_move_topic_to_category?(category.id)
+ return { error: "Permission denied" }
+ end
+
+ unless topic.change_category_to_id(category.id, silent: !!options["silent"])
+ return { error: "Failed to change category", details: topic.errors.full_messages }
+ end
end
+
+ # Handle visibility change
+ if updates.key?("visible")
+ unless guardian.can_toggle_topic_visibility?(topic)
+ return { error: "Permission denied" }
+ end
+
+ visibility_reason =
+ if updates["visible"]
+ Topic.visibility_reasons[:manually_relisted]
+ else
+ Topic.visibility_reasons[:manually_unlisted]
+ end
+
+ topic.update_status(
+ "visible",
+ updates["visible"],
+ user,
+ { visibility_reason_id: visibility_reason },
+ )
+ end
+
+ # Handle tags change
+ if updates.key?("tags")
+ unless DiscourseTagging.tag_topic_by_names(
+ topic,
+ guardian,
+ updates["tags"],
+ append: !!options["append"],
+ )
+ return { error: "Failed to apply tags", details: topic.errors.full_messages }
+ end
+ end
+
+ {
+ success: true,
+ topic: {
+ id: topic.id,
+ category_id: topic.category_id,
+ category_name: topic.category&.name,
+ category_slug: topic.category&.slug,
+ tags: topic.tags.pluck(:name),
+ visible: topic.visible,
+ visibility_reason_id: topic.visibility_reason_id,
+ },
+ }
end
end,
)
diff --git a/plugins/discourse-ai/spec/lib/personas/tool_runner_spec.rb b/plugins/discourse-ai/spec/lib/personas/tool_runner_spec.rb
index dc9926b55e4..8f542581fc6 100644
--- a/plugins/discourse-ai/spec/lib/personas/tool_runner_spec.rb
+++ b/plugins/discourse-ai/spec/lib/personas/tool_runner_spec.rb
@@ -16,6 +16,11 @@ RSpec.describe DiscourseAi::Personas::ToolRunner do
)
end
fab!(:llm_model)
+ fab!(:tag1) { Fabricate(:tag, name: "tag1") }
+ fab!(:tag2) { Fabricate(:tag, name: "tag2") }
+ fab!(:category) { Fabricate(:category, name: "Test Category", slug: "test-category") }
+ fab!(:topic) { Fabricate(:topic, category: category) }
+ fab!(:pm_topic, :private_message_topic)
let(:llm) { DiscourseAi::Completions::Llm.proxy(llm_model.id) }
before do
@@ -38,12 +43,9 @@ RSpec.describe DiscourseAi::Personas::ToolRunner do
end
it "can set tags on a topic" do
- topic = Fabricate(:topic)
- Fabricate(:tag, name: "tag1")
- Fabricate(:tag, name: "tag2")
tool.update!(
script:
- "function invoke(params) { return discourse.setTags(params.topic_id, ['tag1', 'tag2']); }",
+ "function invoke(params) { return discourse.editTopic(params.topic_id, { tags: ['tag1', 'tag2'] }); }",
)
runner =
described_class.new(
@@ -56,11 +58,11 @@ RSpec.describe DiscourseAi::Personas::ToolRunner do
)
result = runner.invoke
expect(result["success"]).to eq(true)
+ expect(result["topic"]["tags"]).to contain_exactly("tag1", "tag2")
expect(topic.reload.tags.pluck(:name)).to contain_exactly("tag1", "tag2")
end
it "can get a topic with tags and first_post_id" do
- topic = Fabricate(:topic)
Fabricate(:post, topic: topic)
tag = Fabricate(:tag, name: "test_tag")
topic.tags << tag
@@ -83,13 +85,12 @@ RSpec.describe DiscourseAi::Personas::ToolRunner do
end
it "can append tags on a topic" do
- topic = Fabricate(:topic)
old_tag = Fabricate(:tag, name: "old_tag")
topic.tags << old_tag
Fabricate(:tag, name: "new_tag")
tool.update!(
script:
- "function invoke(params) { return discourse.setTags(params.topic_id, ['new_tag'], { append: true }); }",
+ "function invoke(params) { return discourse.editTopic(params.topic_id, { tags: ['new_tag'] }, { append: true }); }",
)
runner =
described_class.new(
@@ -106,11 +107,9 @@ RSpec.describe DiscourseAi::Personas::ToolRunner do
end
it "can set tags as a specific user" do
- topic = Fabricate(:topic)
- Fabricate(:tag, name: "tag1")
tool.update!(
script:
- "function invoke(params) { return discourse.setTags(params.topic_id, ['tag1'], { username: 'system' }); }",
+ "function invoke(params) { return discourse.editTopic(params.topic_id, { tags: ['tag1'] }, { username: 'system' }); }",
)
runner =
described_class.new(
@@ -122,7 +121,8 @@ RSpec.describe DiscourseAi::Personas::ToolRunner do
tool: tool,
)
result = runner.invoke
- expect(result).to eq({ "success" => true, "tags" => ["tag1"] })
+ expect(result["success"]).to eq(true)
+ expect(result["topic"]["tags"]).to eq(["tag1"])
expect(topic.reload.tags.pluck(:name)).to contain_exactly("tag1")
end
@@ -182,5 +182,287 @@ RSpec.describe DiscourseAi::Personas::ToolRunner do
expect(prompt_options.last[:response_format]).to eq({ "type" => "json_object" })
end
end
+
+ it "can get a topic with category info" do
+ tool.update!(script: <<~JS)
+ function invoke(params) {
+ const t = discourse.getTopic(params.topic_id);
+ return {
+ category_id: t.category_id,
+ category_name: t.category_name,
+ category_slug: t.category_slug
+ };
+ }
+ JS
+ runner =
+ described_class.new(
+ parameters: {
+ topic_id: topic.id,
+ },
+ llm: llm,
+ bot_user: bot_user,
+ tool: tool,
+ )
+ result = runner.invoke
+ expect(result["category_id"]).to eq(category.id)
+ expect(result["category_name"]).to eq("Test Category")
+ expect(result["category_slug"]).to eq("test-category")
+ end
+
+ it "can set category on a topic by slug" do
+ new_category = Fabricate(:category, slug: "new-category")
+ tool.update!(script: <<~JS)
+ function invoke(params) {
+ return discourse.editTopic(params.topic_id, { category: "new-category" });
+ }
+ JS
+ runner =
+ described_class.new(
+ parameters: {
+ topic_id: topic.id,
+ },
+ llm: llm,
+ bot_user: bot_user,
+ tool: tool,
+ )
+ result = runner.invoke
+ expect(result["success"]).to eq(true)
+ expect(result["topic"]["category_id"]).to eq(new_category.id)
+ expect(topic.reload.category_id).to eq(new_category.id)
+ end
+
+ it "can set category on a topic by ID" do
+ new_category = Fabricate(:category)
+ tool.update!(script: <<~JS)
+ function invoke(params) {
+ return discourse.editTopic(params.topic_id, { category: params.category_id });
+ }
+ JS
+ runner =
+ described_class.new(
+ parameters: {
+ topic_id: topic.id,
+ category_id: new_category.id,
+ },
+ llm: llm,
+ bot_user: bot_user,
+ tool: tool,
+ )
+ result = runner.invoke
+ expect(result["success"]).to eq(true)
+ expect(result["topic"]["category_id"]).to eq(new_category.id)
+ expect(topic.reload.category_id).to eq(new_category.id)
+ end
+
+ it "returns error when setting category on private message" do
+ tool.update!(script: <<~JS)
+ function invoke(params) {
+ try {
+ return discourse.editTopic(params.topic_id, { category: params.category_id });
+ } catch(e) {
+ return { error: e.message };
+ }
+ }
+ JS
+ runner =
+ described_class.new(
+ parameters: {
+ topic_id: pm_topic.id,
+ category_id: category.id,
+ },
+ llm: llm,
+ bot_user: bot_user,
+ tool: tool,
+ )
+ result = runner.invoke
+ expect(result["error"]).to include("private")
+ end
+
+ it "can unlist a topic" do
+ tool.update!(script: <<~JS)
+ function invoke(params) {
+ return discourse.editTopic(params.topic_id, { visible: false });
+ }
+ JS
+ runner =
+ described_class.new(
+ parameters: {
+ topic_id: topic.id,
+ },
+ llm: llm,
+ bot_user: bot_user,
+ tool: tool,
+ )
+ result = runner.invoke
+ expect(result["success"]).to eq(true)
+ expect(result["topic"]["visible"]).to eq(false)
+ expect(topic.reload.visible).to eq(false)
+ expect(topic.visibility_reason_id).to eq(Topic.visibility_reasons[:manually_unlisted])
+ end
+
+ it "can relist a topic" do
+ topic.update!(visible: false)
+ tool.update!(script: <<~JS)
+ function invoke(params) {
+ return discourse.editTopic(params.topic_id, { visible: true });
+ }
+ JS
+ runner =
+ described_class.new(
+ parameters: {
+ topic_id: topic.id,
+ },
+ llm: llm,
+ bot_user: bot_user,
+ tool: tool,
+ )
+ result = runner.invoke
+ expect(result["success"]).to eq(true)
+ expect(result["topic"]["visible"]).to eq(true)
+ expect(topic.reload.visible).to eq(true)
+ expect(topic.visibility_reason_id).to eq(Topic.visibility_reasons[:manually_relisted])
+ end
+
+ it "editTopic throws error for non-existent topic" do
+ tool.update!(script: <<~JS)
+ function invoke(params) {
+ try {
+ return discourse.editTopic(999999, { tags: ['tag1'] });
+ } catch(e) {
+ return { thrown: true, message: e.message };
+ }
+ }
+ JS
+ runner = described_class.new(parameters: {}, llm: llm, bot_user: bot_user, tool: tool)
+ result = runner.invoke
+ expect(result["thrown"]).to eq(true)
+ expect(result["message"]).to include("not found")
+ end
+
+ it "can edit multiple topic properties at once" do
+ new_category = Fabricate(:category, slug: "multi-edit")
+ tool.update!(script: <<~JS)
+ function invoke(params) {
+ return discourse.editTopic(params.topic_id, {
+ category: "multi-edit",
+ tags: ['tag1', 'tag2'],
+ visible: false
+ });
+ }
+ JS
+ runner =
+ described_class.new(
+ parameters: {
+ topic_id: topic.id,
+ },
+ llm: llm,
+ bot_user: bot_user,
+ tool: tool,
+ )
+ result = runner.invoke
+ expect(result["success"]).to eq(true)
+ expect(result["topic"]["category_id"]).to eq(new_category.id)
+ expect(result["topic"]["tags"]).to contain_exactly("tag1", "tag2")
+ expect(result["topic"]["visible"]).to eq(false)
+ topic.reload
+ expect(topic.category_id).to eq(new_category.id)
+ expect(topic.tags.pluck(:name)).to contain_exactly("tag1", "tag2")
+ expect(topic.visible).to eq(false)
+ end
+
+ it "can set category on a topic by name" do
+ new_category = Fabricate(:category, name: "New Category Name", slug: "different-slug")
+ tool.update!(script: <<~JS)
+ function invoke(params) {
+ return discourse.editTopic(params.topic_id, { category: "New Category Name" });
+ }
+ JS
+ runner =
+ described_class.new(
+ parameters: {
+ topic_id: topic.id,
+ },
+ llm: llm,
+ bot_user: bot_user,
+ tool: tool,
+ )
+ result = runner.invoke
+ expect(result["success"]).to eq(true)
+ expect(result["topic"]["category_id"]).to eq(new_category.id)
+ expect(topic.reload.category_id).to eq(new_category.id)
+ end
+
+ it "returns error when user cannot move topic to category" do
+ regular_user = Fabricate(:user)
+ new_category = Fabricate(:category)
+ new_category.set_permissions(staff: :full)
+ new_category.save!
+ tool.update!(script: <<~JS)
+ function invoke(params) {
+ try {
+ return discourse.editTopic(params.topic_id, { category: params.category_id }, { username: params.username });
+ } catch(e) {
+ return { error: e.message };
+ }
+ }
+ JS
+ runner =
+ described_class.new(
+ parameters: {
+ topic_id: topic.id,
+ category_id: new_category.id,
+ username: regular_user.username,
+ },
+ llm: llm,
+ bot_user: bot_user,
+ tool: tool,
+ )
+ result = runner.invoke
+ expect(result["error"]).to include("Permission denied")
+ end
+
+ it "returns error when user cannot toggle topic visibility" do
+ regular_user = Fabricate(:user)
+ tool.update!(script: <<~JS)
+ function invoke(params) {
+ try {
+ return discourse.editTopic(params.topic_id, { visible: false }, { username: params.username });
+ } catch(e) {
+ return { error: e.message };
+ }
+ }
+ JS
+ runner =
+ described_class.new(
+ parameters: {
+ topic_id: topic.id,
+ username: regular_user.username,
+ },
+ llm: llm,
+ bot_user: bot_user,
+ tool: tool,
+ )
+ result = runner.invoke
+ expect(result["error"]).to include("Permission denied")
+ end
+
+ it "setTags alias works for backwards compatibility" do
+ tool.update!(
+ script:
+ "function invoke(params) { return discourse.setTags(params.topic_id, ['tag1', 'tag2']); }",
+ )
+ runner =
+ described_class.new(
+ parameters: {
+ topic_id: topic.id,
+ },
+ llm: llm,
+ bot_user: bot_user,
+ tool: tool,
+ )
+ result = runner.invoke
+ expect(result["success"]).to eq(true)
+ expect(topic.reload.tags.pluck(:name)).to contain_exactly("tag1", "tag2")
+ end
end
end