Skip to content

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

FEATURE: flag_post tool and triage integration (#36942)

Roman Rizzid6e47f1f6c0f
diff --git a/plugins/discourse-ai/assets/javascripts/discourse/components/ai-persona-tool-options.gjs b/plugins/discourse-ai/assets/javascripts/discourse/components/ai-persona-tool-options.gjs
index db568b92764..9dbc8e7cce4 100644
--- a/plugins/discourse-ai/assets/javascripts/discourse/components/ai-persona-tool-options.gjs
+++ b/plugins/discourse-ai/assets/javascripts/discourse/components/ai-persona-tool-options.gjs
@@ -91,6 +91,8 @@ export default class AiPersonaToolOptions extends Component {
</field.Custom>
{{else if (eq optionMeta.type "boolean")}}
<field.Checkbox />
+ {{else if (eq optionMeta.type "text")}}
+ <field.Textarea />
{{else}}
<field.Input />
{{/if}}
diff --git a/plugins/discourse-ai/config/locales/server.en.yml b/plugins/discourse-ai/config/locales/server.en.yml
index 99e51417678..db3ddbe74ef 100644
--- a/plugins/discourse-ai/config/locales/server.en.yml
+++ b/plugins/discourse-ai/config/locales/server.en.yml
@@ -505,6 +505,10 @@ en:
base_query:
name: "Base Search Query"
description: "Base query to use when searching. Example: '#urgent' will prepend '#urgent' to the search query and only include topics with the urgent category or tag."
+ flag_post:
+ flag_type:
+ name: "Flag Type"
+ description: "Controls whether the post is reviewed, hidden, deleted, or treated as spam."
tool_summary:
read_artifact: "Read a web artifact"
update_artifact: "Update a web artifact"
@@ -516,6 +520,7 @@ en:
github_pull_request_diff: "GitHub pull request diff"
random_picker: "Random Picker"
categories: "List categories"
+ flag_post: "Flag post"
search: "Search"
tags: "List tags"
time: "Time"
@@ -544,6 +549,7 @@ en:
github_pull_request_diff: "Retrieve a GitHub pull request diff"
random_picker: "Pick a random number or a random element of a list"
categories: "List all publicly visible categories on the forum"
+ flag_post: "Flag the current post for staff review"
search: "Search all public topics on the forum"
tags: "List all tags on the forum"
time: "Find time in various time zones"
@@ -570,6 +576,7 @@ en:
github_pull_request_diff: "<a href='%{url}'>%{repo} %{pull_id}</a>"
github_file_content: "Retrieved content of %{file_paths} from %{repo_name}@%{branch}"
random_picker: "Picking from %{options}, picked: %{result}"
+ flag_post: "Flagging post %{post_id} (verdict: %{verdict})"
read: "Reading: <a href='%{url}'>%{title}</a>"
time: "Time in %{timezone} is %{time}"
summarize: "Summarized <a href='%{url}'>%{title}</a>"
@@ -608,6 +615,16 @@ en:
title: "Discovery conversation: Search for %{query}"
raw: "In my search for %{query}, you showed me the following information:\n\n%{context}\n\nLet's continue the conversation."
+ flag_post:
+ errors:
+ no_context: "No post context available for flagging."
+ no_reason: "A reason is required to flag a post."
+ invalid_flag_type: "Invalid flag type."
+ skipped: "Verdict was false; no flag was created."
+ already_flagged: "Post is already flagged for review."
+ flagged: "Post flagged for review."
+ reason: "AI bot flagged this post.\n\nReason: %{reason}"
+
summarization:
configuration_hint:
one: "Configure the `%{setting}` setting first."
@@ -697,4 +714,3 @@ en:
custom_tool_exists:
one: "Custom tool with the name %{names} already exists."
other: "Custom tools with the names %{names} already exist."
-
diff --git a/plugins/discourse-ai/discourse_automation/llm_persona_triage.rb b/plugins/discourse-ai/discourse_automation/llm_persona_triage.rb
index cbe6c1ae8b7..684803e1c6c 100644
--- a/plugins/discourse-ai/discourse_automation/llm_persona_triage.rb
+++ b/plugins/discourse-ai/discourse_automation/llm_persona_triage.rb
@@ -45,6 +45,7 @@ if defined?(DiscourseAutomation)
whisper: whisper,
automation: self.automation,
silent_mode: silent_mode,
+ action: context["action"],
)
rescue => e
Discourse.warn_exception(
diff --git a/plugins/discourse-ai/lib/ai_bot/playground.rb b/plugins/discourse-ai/lib/ai_bot/playground.rb
index c53d0b8a054..249b016ff90 100644
--- a/plugins/discourse-ai/lib/ai_bot/playground.rb
+++ b/plugins/discourse-ai/lib/ai_bot/playground.rb
@@ -192,7 +192,8 @@ module DiscourseAi
auto_set_title: false,
silent_mode: false,
feature_name: nil,
- attributed_user: nil
+ attributed_user: nil,
+ feature_context: nil
)
ai_persona = AiPersona.find_by(id: persona_id)
raise Discourse::InvalidParameters.new(:persona_id) if !ai_persona
@@ -214,6 +215,7 @@ module DiscourseAi
silent_mode: silent_mode,
feature_name: feature_name,
attributed_user: attributed_user,
+ feature_context: feature_context,
)
rescue => e
if Rails.env.test?
@@ -423,6 +425,7 @@ module DiscourseAi
existing_reply_post: nil,
cancel_manager: nil,
attributed_user: nil,
+ feature_context: nil,
&blk
)
# this is a multithreading issue
@@ -459,6 +462,7 @@ module DiscourseAi
user: attributed_user,
custom_instructions: custom_instructions,
feature_name: feature_name,
+ feature_context: feature_context,
messages:
DiscourseAi::Completions::PromptMessagesBuilder.messages_from_post(
post,
diff --git a/plugins/discourse-ai/lib/automation/llm_persona_triage.rb b/plugins/discourse-ai/lib/automation/llm_persona_triage.rb
index 2bde15509ba..bd5a29d73f9 100644
--- a/plugins/discourse-ai/lib/automation/llm_persona_triage.rb
+++ b/plugins/discourse-ai/lib/automation/llm_persona_triage.rb
@@ -2,7 +2,14 @@
module DiscourseAi
module Automation
module LlmPersonaTriage
- def self.handle(post:, persona_id:, whisper: false, silent_mode: false, automation: nil)
+ def self.handle(
+ post:,
+ persona_id:,
+ whisper: false,
+ silent_mode: false,
+ automation: nil,
+ action: nil
+ )
DiscourseAi::AiBot::Playground.reply_to_post(
post: post,
persona_id: persona_id,
@@ -10,6 +17,11 @@ module DiscourseAi
silent_mode: silent_mode,
feature_name: "automation - #{automation&.name}",
attributed_user: Discourse.system_user,
+ feature_context: {
+ automation_id: automation&.id,
+ automation_name: automation&.name,
+ action: action,
+ },
)
rescue => e
Discourse.warn_exception(
diff --git a/plugins/discourse-ai/lib/automation/llm_triage.rb b/plugins/discourse-ai/lib/automation/llm_triage.rb
index 05a1b1ddfac..19e2c1362af 100644
--- a/plugins/discourse-ai/lib/automation/llm_triage.rb
+++ b/plugins/discourse-ai/lib/automation/llm_triage.rb
@@ -14,6 +14,28 @@ module DiscourseAi
.exists?
end
+ def self.flagged_by_tool?(raw_context)
+ return false if raw_context.blank?
+
+ raw_context.any? do |entry|
+ next false if !entry.is_a?(Array)
+ next false if entry[2] != "tool" || entry[3] != "flag_post"
+
+ payload = entry[0]
+ status =
+ case payload
+ when String
+ JSON.parse(payload).with_indifferent_access[:status]
+ when Hash
+ payload.with_indifferent_access[:status]
+ end
+
+ status == "flagged"
+ rescue JSON::ParserError, TypeError
+ false
+ end
+ end
+
def self.handle(
post:,
triage_persona_id:,
@@ -75,8 +97,18 @@ module DiscourseAi
bot_ctx =
DiscourseAi::Personas::BotContext.new(
user: Discourse.system_user,
+ post: post,
skip_show_thinking: true,
feature_name: "llm_triage",
+ feature_context: {
+ automation_id: automation&.id,
+ automation_name: automation&.name,
+ base_path: Discourse.base_path,
+ action: action,
+ notify_author_pm: notify_author_pm,
+ notify_author_pm_user: notify_author_pm_user,
+ notify_author_pm_message: notify_author_pm_message,
+ },
messages: [{ type: :user, content: input }],
)
@@ -92,11 +124,17 @@ module DiscourseAi
}
result = +""
- bot.reply(bot_ctx, llm_args: llm_args) do |partial, _, type|
- result << partial if type.blank?
- end
+ raw_context =
+ bot.reply(bot_ctx, llm_args: llm_args) do |partial, _, type|
+ result << partial if type.blank?
+ end
+
+ flagged_by_tool = flagged_by_tool?(raw_context)
+
+ matched = result.present? && result.downcase.include?(search_for_text.downcase)
+ matched ||= flagged_by_tool
- if result.present? && result.downcase.include?(search_for_text.downcase)
+ if matched
user = User.find_by_username(canned_reply_user) if canned_reply_user.present?
original_user = user
user = user || Discourse.system_user
@@ -158,99 +196,101 @@ module DiscourseAi
automation_name: automation&.name.to_s,
)
- if flag_type == :spam || flag_type == :spam_silence
- result =
- PostActionCreator.new(
- Discourse.system_user,
- post,
- PostActionType.types[:spam],
- message: score_reason,
- queue_for_review: true,
- ).perform
-
- if flag_type == :spam_silence
- if result.success?
- SpamRule::AutoSilence.new(post.user, post).silence_user
- else
- Rails.logger.warn(
- "llm_triage: unable to flag post as spam, post action failed for #{post.id} with error: '#{result.errors.full_messages.join(",").truncate(3000)}'",
- )
+ if !flagged_by_tool
+ if flag_type == :spam || flag_type == :spam_silence
+ result =
+ PostActionCreator.new(
+ Discourse.system_user,
+ post,
+ PostActionType.types[:spam],
+ message: score_reason,
+ queue_for_review: true,
+ ).perform
+
+ if flag_type == :spam_silence
+ if result.success?
+ SpamRule::AutoSilence.new(post.user, post).silence_user
+ else
+ Rails.logger.warn(
+ "llm_triage: unable to flag post as spam, post action failed for #{post.id} with error: '#{result.errors.full_messages.join(",").truncate(3000)}'",
+ )
+ end
end
- end
- else
- reviewable =
- ReviewablePost.needs_review!(
- target: post,
- created_by: Discourse.system_user,
- reviewable_by_moderator: true,
+ else
+ reviewable =
+ ReviewablePost.needs_review!(
+ target: post,
+ created_by: Discourse.system_user,
+ reviewable_by_moderator: true,
+ )
+
+ reviewable.add_score(
+ Discourse.system_user,
+ ReviewableScore.types[:needs_approval],
+ reason: score_reason,
+ force_review: true,
)
- reviewable.add_score(
- Discourse.system_user,
- ReviewableScore.types[:needs_approval],
- reason: score_reason,
- force_review: true,
- )
+ # We cannot do this through the PostActionCreator because hiding a post is reserved for auto action flags.
+ # Those flags are off_topic, inappropriate, and spam. We want a more generic type for triage, so none of those
+ # fit here.
+ if flag_type == :review_hide
+ post.hide!(PostActionType.types[:notify_moderators])
+ elsif flag_type == :review_delete || flag_type == :review_delete_silence
+ # Soft-delete the post so it is hidden from users until a moderator handles it in review.
+ PostDestroyer.new(Discourse.system_user, post, context: "llm_triage").destroy
- # We cannot do this through the PostActionCreator because hiding a post is reserved for auto action flags.
- # Those flags are off_topic, inappropriate, and spam. We want a more generic type for triage, so none of those
- # fit here.
- if flag_type == :review_hide
- post.hide!(PostActionType.types[:notify_moderators])
- elsif flag_type == :review_delete || flag_type == :review_delete_silence
- # Soft-delete the post so it is hidden from users until a moderator handles it in review.
- PostDestroyer.new(Discourse.system_user, post, context: "llm_triage").destroy
-
- if flag_type == :review_delete_silence
- UserSilencer.silence(
- post.user,
- Discourse.system_user,
- message: :silenced_by_staff,
- post_id: @post&.id,
- )
+ if flag_type == :review_delete_silence
+ UserSilencer.silence(
+ post.user,
+ Discourse.system_user,
+ message: :silenced_by_staff,
+ post_id: @post&.id,
+ )
+ end
end
end
+ end
+ end
- if notify_author_pm && action != :edit && !already_flagged
- begin
- pm_sender =
- if notify_author_pm_user.present?
- User.find_by_username(notify_author_pm_user)
- else
- nil
- end
- pm_sender ||= Discourse.system_user
-
- subject =
- I18n.t("discourse_automation.scriptables.llm_triage.notify_author_pm.subject")
-
- default_body =
- I18n.t(
- "discourse_automation.scriptables.llm_triage.notify_author_pm.body",
- username: post.user.username,
- topic_title: post.topic.title,
- post_url: post.url,
- )
+ if notify_author_pm && action != :edit && !already_flagged
+ begin
+ pm_sender =
+ if notify_author_pm_user.present?
+ User.find_by_username(notify_author_pm_user)
+ else
+ nil
+ end
+ pm_sender ||= Discourse.system_user
- body = notify_author_pm_message.presence || default_body
+ subject =
+ I18n.t("discourse_automation.scriptables.llm_triage.notify_author_pm.subject")
- PostCreator.create!(
- pm_sender,
- title: subject,
- raw: body,
- archetype: Archetype.private_message,
- target_usernames: post.user.username,
- skip_validations: true,
- )
- rescue StandardError => e
- Discourse.warn_exception(
- e,
- message:
- "Error sending PM notification for triage on: #{post&.url} in LlmTriage.handle",
- )
- raise e if Rails.env.test?
- end
- end
+ default_body =
+ I18n.t(
+ "discourse_automation.scriptables.llm_triage.notify_author_pm.body",
+ username: post.user.username,
+ topic_title: post.topic.title,
+ post_url: post.url,
+ )
+
+ body = notify_author_pm_message.presence || default_body
+
+ PostCreator.create!(
+ pm_sender,
+ title: subject,
+ raw: body,
+ archetype: Archetype.private_message,
+ target_usernames: post.user.username,
+ skip_validations: true,
+ )
+ rescue StandardError => e
+ Discourse.warn_exception(
+ e,
+ message:
+ "Error sending PM notification for triage on: #{post&.url} in LlmTriage.handle",
+ )
+ raise e if Rails.env.test?
end
end
end
diff --git a/plugins/discourse-ai/lib/personas/bot_context.rb b/plugins/discourse-ai/lib/personas/bot_context.rb
index bbae463772b..69d58ea5827 100644
--- a/plugins/discourse-ai/lib/personas/bot_context.rb
+++ b/plugins/discourse-ai/lib/personas/bot_context.rb
@@ -9,6 +9,7 @@ module DiscourseAi
:private_message,
:custom_instructions,
:user,
+ :feature_context,
:skip_show_thinking,
:participants,
:chosen_tools,
@@ -32,6 +33,7 @@ module DiscourseAi
skip_show_thinking: nil,
messages: [],
custom_instructions: nil,
+ feature_context: nil,
site_url: nil,
site_title: nil,
site_description: nil,
@@ -51,6 +53,7 @@ module DiscourseAi
@skip_show_thinking = skip_show_thinking
@messages = messages
@custom_instructions = custom_instructions
+ @feature_context = feature_context || {}
@format_dates = format_dates
@message_id = message_id
@@ -158,6 +161,7 @@ module DiscourseAi
site_description: @site_description,
skip_show_thinking: @skip_show_thinking,
feature_name: @feature_name,
+ feature_context: @feature_context,
resource_url: @resource_url,
inferred_concepts: @inferred_concepts,
user_language: @user_language,
diff --git a/plugins/discourse-ai/lib/personas/persona.rb b/plugins/discourse-ai/lib/personas/persona.rb
index 07106f276e0..ff0fa7565e7 100644
--- a/plugins/discourse-ai/lib/personas/persona.rb
+++ b/plugins/discourse-ai/lib/personas/persona.rb
@@ -113,6 +113,7 @@ module DiscourseAi
Tools::Time,
Tools::Search,
Tools::Read,
+ Tools::FlagPost,
Tools::DbSchema,
Tools::SearchSettings,
Tools::SettingContext,
diff --git a/plugins/discourse-ai/lib/personas/tools/flag_post.rb b/plugins/discourse-ai/lib/personas/tools/flag_post.rb
new file mode 100644
index 00000000000..0313828a6bf
--- /dev/null
+++ b/plugins/discourse-ai/lib/personas/tools/flag_post.rb
@@ -0,0 +1,192 @@
+# frozen_string_literal: true
+
+module DiscourseAi
+ module Personas
+ module Tools
+ class FlagPost < Tool
+ FLAG_TYPES = %w[
+ review
+ review_hide
+ review_delete
+ review_delete_silence
+ spam
+ spam_silence
+ ].freeze
+
+ def self.signature
+ {
+ name: name,
+ description: "Flags the current post for review when verdict is true.",
+ parameters: [
+ {
+ name: "verdict",
+ description: "Whether the post should be flagged",
+ type: "boolean",
+ required: true,
+ },
+ {
+ name: "reason",
+ description: "Short explanation of why the post should be flagged",
+ type: "string",
+ required: true,
+ },
+ ],
+ }
+ end
+
+ def self.accepted_options
+ [option(:flag_type, type: :enum, values: FLAG_TYPES, default: "review")]
+ end
+
+ def self.name
+ "flag_post"
+ end
+
+ def verdict
+ !!parameters[:verdict]
+ end
+
+ def reason
+ parameters[:reason].to_s.strip
+ end
+
+ def flag_type
+ persona_flag_type = persona_option(:flag_type)
+ (persona_flag_type.presence || feature_context[:flag_type].presence || "review").to_s
+ end
+
+ def invoke
+ return error_response(I18n.t("discourse_ai.ai_bot.flag_post.errors.no_context")) if !post
+ if reason.blank?
+ return error_response(I18n.t("discourse_ai.ai_bot.flag_post.errors.no_reason"))
+ end
+ if !FLAG_TYPES.include?(flag_type)
+ return error_response(I18n.t("discourse_ai.ai_bot.flag_post.errors.invalid_flag_type"))
+ end
+
+ if !verdict
+ return { status: "skipped", message: I18n.t("discourse_ai.ai_bot.flag_post.skipped") }
+ end
+
+ if already_flagged?
+ return(
+ {
+ status: "skipped",
+ message: I18n.t("discourse_ai.ai_bot.flag_post.already_flagged"),
+ }
+ )
+ end
+
+ flag_success = true
+ if %w[spam spam_silence].include?(flag_type)
+ result =
+ PostActionCreator.new(
+ Discourse.system_user,
+ post,
+ PostActionType.types[:spam],
+ message: flag_reason,
+ queue_for_review: true,
+ ).perform
+ flag_success = result.success?
+
+ if flag_type == "spam_silence"
+ if flag_success
+ SpamRule::AutoSilence.new(post.user, post).silence_user
+ else
+ Rails.logger.warn(
+ "flag_post: unable to flag post as spam, post action failed for #{post.id} with error: '#{result.errors.full_messages.join(",").truncate(3000)}'",
+ )
+ end
+ end
+ else
+ reviewable =
+ ReviewablePost.needs_review!(
+ target: post,
+ created_by: Discourse.system_user,
+ reviewable_by_moderator: true,
+ )
+ reviewable.add_score(
+ Discourse.system_user,
+ ReviewableScore.types[:needs_approval],
+ reason: flag_reason,
+ force_review: true,
+ )
+
+ if flag_type == "review_hide"
+ post.hide!(PostActionType.types[:notify_moderators])
+ elsif %w[review_delete review_delete_silence].include?(flag_type)
+ PostDestroyer.new(Discourse.system_user, post, context: "flag_post").destroy
+
+ if flag_type == "review_delete_silence"
+ UserSilencer.silence(
+ post.user,
+ Discourse.system_user,
+ message: :silenced_by_staff,
+ post_id: @post&.id,
+ )
+ end
+ end
+ end
+
+ { status: "flagged", message: I18n.t("discourse_ai.ai_bot.flag_post.flagged") }
+ end
+
+ def description_args
+ { post_id: post&.id, verdict: verdict, flag_type: flag_type }
+ end
+
+ private
+
+ def post
+ @post ||= Post.find_by(id: context.post_id)
+ end
+
+ def already_flagged?
+ ReviewableScore
+ .pending
+ .where(
+ user: Discourse.system_user,
+ reviewable_score_type: [
+ ReviewableScore.types[:spam],
+ ReviewableScore.types[:needs_approval],
+ ],
+ )
+ .joins(:reviewable)
+ .where(reviewables: { target: post })
+ .exists?
+ end
+
+ def flag_reason
+ if feature_context[:automation_id].present? && feature_context[:automation_name].present?
+ I18n.t(
+ "discourse_automation.scriptables.llm_triage.flagged_post",
+ base_path: feature_context[:base_path] || Discourse.base_path,
+ llm_response: feature_context[:llm_response].presence || reason,
+ automation_id: feature_context[:automation_id].to_s,
+ automation_name: feature_context[:automation_name].to_s,
+ )
+ else
+ I18n.t("discourse_ai.ai_bot.flag_post.reason", reason: reason)
+ end
+ end
+
+ def error_response(message)
+ { status: "error", error: message }
+ end
+
+ def feature_context
+ return {} if !context.respond_to?(:feature_context)
+
+ context.feature_context || {}
+ end
+
+ def persona_option(name)
+ return nil if !persona_options.is_a?(Hash)
+ return nil if !persona_options.key?(name)
+
+ persona_options[name]
+ end
+ end
+ end
+ end
+end
diff --git a/plugins/discourse-ai/lib/personas/tools/tool.rb b/plugins/discourse-ai/lib/personas/tools/tool.rb
index 9299eafc400..3897207fa6d 100644
--- a/plugins/discourse-ai/lib/personas/tools/tool.rb
+++ b/plugins/discourse-ai/lib/personas/tools/tool.rb
@@ -69,7 +69,8 @@ module DiscourseAi
)
@parameters = parameters
@tool_call_id = tool_call_id
- @persona_options = persona_options
+ @persona_options =
+ persona_options.is_a?(Hash) ? persona_options.with_indifferent_access : persona_options
@bot_user = bot_user
@llm = llm
@context = context.nil? ? DiscourseAi::Personas::BotContext.new(messages: []) : context
diff --git a/plugins/discourse-ai/spec/lib/modules/automation/llm_triage_spec.rb b/plugins/discourse-ai/spec/lib/modules/automation/llm_triage_spec.rb
index af9248fe58d..68919422d6d 100644
--- a/plugins/discourse-ai/spec/lib/modules/automation/llm_triage_spec.rb
+++ b/plugins/discourse-ai/spec/lib/modules/automation/llm_triage_spec.rb
@@ -96,6 +96,35 @@ describe DiscourseAi::Automation::LlmTriage do
expect(reviewable.reviewable_scores.first.reason).to include("bad")
end
+ it "flags via tool call when the persona invokes flag_post" do
+ ai_persona.update!(tools: ["FlagPost"])
+ tool_call =
+ DiscourseAi::Completions::ToolCall.new(
+ name: "flag_post",
+ parameters: {
+ verdict: true,
+ reason: "Looks unsafe",
+ },
+ id: "tool_call_1",
+ )
+
+ DiscourseAi::Completions::Llm.with_prepared_responses([tool_call, "all good"]) do
+ triage(
+ post: post,
+ triage_persona_id: ai_persona.id,
+ search_for_text: "bad",
+ flag_post: true,
+ automation: nil,
+ )
+ end
+
+ reviewable = ReviewablePost.last
+
+ expect(reviewable.target_id).to eq(post.id)
+ expect(reviewable.target_type).to eq("Post")
+ expect(reviewable.reviewable_scores.first.reason).to include("Looks unsafe")
+ end
+
it "can handle spam flags" do
DiscourseAi::Completions::Llm.with_prepared_responses(["bad"]) do
triage(
diff --git a/plugins/discourse-ai/spec/lib/personas/tools/flag_post_spec.rb b/plugins/discourse-ai/spec/lib/personas/tools/flag_post_spec.rb
new file mode 100644
index 00000000000..48ccc9e986d
--- /dev/null
+++ b/plugins/discourse-ai/spec/lib/personas/tools/flag_post_spec.rb
@@ -0,0 +1,91 @@
+# frozen_string_literal: true
+
+RSpec.describe DiscourseAi::Personas::Tools::FlagPost 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)
+
+ before do
+ enable_current_plugin
+ SiteSetting.ai_bot_enabled = true
+ end
+
+ def tool(params = nil, persona_options: {}, **kwargs)
+ params ||= kwargs
+ described_class.new(
+ params,
+ bot_user: bot_user,
+ llm: llm,
+ context: context,
+ persona_options: persona_options,
+ )
+ end
+
+ let(:context) { DiscourseAi::Personas::BotContext.new(post: post) }
+
+ it "flags the post when verdict is true" do
+ result = nil
+
+ expect { result = tool(verdict: true, reason: "Clear spam").invoke }.to change {
+ ReviewablePost.count
+ }.by(1)
+
+ expect(result[:status]).to eq("flagged")
+ reviewable = ReviewablePost.find_by(target: post)
+ score =
+ ReviewableScore.find_by(
+ reviewable: reviewable,
+ user: Discourse.system_user,
+ reviewable_score_type: ReviewableScore.types[:needs_approval],
+ )
+ expect(score.reason).to include("Clear spam")
+ end
+
+ it "skips when verdict is false" do
+ result = nil
+
+ expect { result = tool(verdict: false, reason: "Does not matter").invoke }.not_to change {
+ ReviewablePost.count
+ }
+
+ expect(result[:status]).to eq("skipped")
+ end
+
+ it "skips when the post is already flagged" do
+ reviewable = ReviewablePost.needs_review!(target: post, created_by: Discourse.system_user)
+ reviewable.add_score(
+ Discourse.system_user,
+ ReviewableScore.types[:needs_approval],
+ reason: "Existing flag",
+ force_review: true,
+ )
+
+ result = nil
+
+ expect { result = tool(verdict: true, reason: "Duplicate flag").invoke }.not_to change {
+ ReviewableScore.count
+ }
+
+ expect(result[:status]).to eq("skipped")
+ end
+
+ it "returns an error when reason is blank" do
+ result = tool(verdict: true, reason: " ").invoke
+
+ expect(result[:status]).to eq("error")
+ end
+
+ it "applies the configured flag_type option" do
+ result =
+ tool(
+ { verdict: true, reason: "Needs review" },
+ persona_options: {
+ flag_type: "review_hide",
+ },
+ ).invoke
+
+ expect(result[:status]).to eq("flagged")
+ expect(post.reload).to be_hidden
+ end
+end