Skip to content

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

FEATURE: Add AI agent suspend/silence tools with inline approval review (#41497)

Gabriel Grubbacc14e6e402cf
diff --git a/plugins/discourse-ai/app/models/reviewable_ai_tool_action.rb b/plugins/discourse-ai/app/models/reviewable_ai_tool_action.rb
index a194a6e81b8..4305f07b3ca 100644
--- a/plugins/discourse-ai/app/models/reviewable_ai_tool_action.rb
+++ b/plugins/discourse-ai/app/models/reviewable_ai_tool_action.rb
@@ -19,6 +19,7 @@ class ReviewableAiToolAction < Reviewable
def build_actions(actions, guardian, args)
return actions if !pending?
+ return actions if !Reviewable.viewable_by(guardian.user).exists?(id: id)
approve =
actions.add_bundle(
@@ -40,6 +41,38 @@ class ReviewableAiToolAction < Reviewable
end
def perform_approve(performed_by, args)
+ ensure_inline_post_matches_target!(args)
+ ensure_performed_by_is_a_real_person!(performed_by)
+
+ tool, tool_class, context = build_tool!
+ context.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).
+ result =
+ if defined?(DiscourseAutomation)
+ DiscourseAutomation.suppress_triggers { tool.invoke }
+ else
+ tool.invoke
+ end
+
+ ensure_tool_succeeded!(result)
+
+ create_result(:success, :approved)
+ end
+
+ def perform_reject(performed_by, args)
+ ensure_inline_post_matches_target!(args)
+ ensure_performed_by_is_a_real_person!(performed_by)
+
+ create_result(:success, :rejected)
+ end
+
+ private
+
+ # Rebuilds the tool from the persisted action. Returns [tool, tool_class,
+ # context]; the caller sets context.user for audit attribution as needed.
+ def build_tool!
tool_action = target
if tool_action.blank?
raise Discourse::InvalidAccess.new(
@@ -66,30 +99,61 @@ class ReviewableAiToolAction < Reviewable
)
end
+ context = DiscourseAi::Agents::BotContext.new(messages: [])
+ context.reviewable_id = id
+
tool =
tool_class.new(
tool_action.tool_parameters.symbolize_keys,
bot_user: bot_user,
llm: nil,
- context: DiscourseAi::Agents::BotContext.new(messages: []),
+ context: context,
)
- # Suppress automation re-triggers caused by the tool's side effects
- # (e.g. edit_tags → topic_tags_changed → automation fires again → loop).
- if defined?(DiscourseAutomation)
- DiscourseAutomation.suppress_triggers { tool.invoke }
- else
- tool.invoke
- end
+ [tool, tool_class, context]
+ end
- create_result(:success, :approved)
+ def ensure_inline_post_matches_target!(args)
+ inline_post_id = args[:post_id] || args["post_id"]
+ return if inline_post_id.blank?
+
+ expected_post_id = target&.post_id
+ if expected_post_id.blank? || inline_post_id.to_i != expected_post_id
+ raise Discourse::InvalidAccess.new(
+ I18n.t("discourse_ai.reviewables.ai_tool_action.post_mismatch"),
+ )
+ end
end
- def perform_reject(performed_by, args)
- create_result(:success, :rejected)
+ def ensure_performed_by_is_a_real_person!(performed_by)
+ if performed_by.blank? || performed_by.bot?
+ raise Discourse::InvalidAccess.new(
+ I18n.t("discourse_ai.reviewables.ai_tool_action.performer_not_human"),
+ )
+ end
end
- private
+ # The replayed tool reports precondition/service failures as an error hash
+ # (e.g. the approver lost permission, or the target was already actioned
+ # between enqueue and approval). Surface the reason to the moderator and let
+ # the surrounding transaction roll back so the reviewable stays pending,
+ # instead of recording a phantom approval for an action that never ran.
+ def ensure_tool_succeeded!(result)
+ return unless result.is_a?(Hash) && result[:status].to_s == "error"
+
+ error =
+ result[:error].to_s.presence ||
+ I18n.t("discourse_ai.reviewables.ai_tool_action.execution_error_unknown")
+
+ raise Discourse::InvalidAccess.new(
+ "ai_tool_action_execution_error",
+ nil,
+ custom_message: "discourse_ai.reviewables.ai_tool_action.execution_error",
+ custom_message_params: {
+ error: error,
+ },
+ )
+ end
def build_action(actions, id, icon:, bundle: nil)
actions.add(id, bundle: bundle) do |action|
diff --git a/plugins/discourse-ai/assets/javascripts/discourse/components/ai-tool-approval.gjs b/plugins/discourse-ai/assets/javascripts/discourse/components/ai-tool-approval.gjs
new file mode 100644
index 00000000000..bc5ebaeea09
--- /dev/null
+++ b/plugins/discourse-ai/assets/javascripts/discourse/components/ai-tool-approval.gjs
@@ -0,0 +1,203 @@
+import Component from "@glimmer/component";
+import { tracked } from "@glimmer/tracking";
+import { fn } from "@ember/helper";
+import { action } from "@ember/object";
+import didInsert from "@ember/render-modifiers/modifiers/did-insert";
+import { service } from "@ember/service";
+import { ajax } from "discourse/lib/ajax";
+import { popupAjaxError } from "discourse/lib/ajax-error";
+import DButton from "discourse/ui-kit/d-button";
+import { i18n } from "discourse-i18n";
+
+const STATUSES = { pending: 0, approved: 1, rejected: 2 };
+
+export default class AiToolApproval extends Component {
+ @service currentUser;
+
+ @tracked reviewable;
+ @tracked loading = true;
+ @tracked performing = false;
+ @tracked loadError = false;
+ @tracked notAuthorized = false;
+ @tracked expanded = false;
+
+ get isStaff() {
+ return this.currentUser?.staff;
+ }
+
+ get isPending() {
+ return this.reviewable?.status === STATUSES.pending;
+ }
+
+ get isResolved() {
+ return this.reviewable && !this.isPending;
+ }
+
+ // the summary is always visible while pending; once resolved it collapses
+ // behind the status header and reveals on expand
+ get showDetails() {
+ return this.isPending || this.expanded;
+ }
+
+ get statusLabel() {
+ if (this.reviewable?.status === STATUSES.approved) {
+ return i18n("discourse_ai.ai_tool_approval.approved");
+ }
+ if (this.reviewable?.status === STATUSES.rejected) {
+ return i18n("discourse_ai.ai_tool_approval.rejected");
+ }
+ }
+
+ get toolParameters() {
+ const params = this.reviewable?.tool_parameters;
+ if (!params || typeof params !== "object") {
+ return [];
+ }
+ return Object.entries(params)
+ .filter(([key]) => key !== "username")
+ .map(([key, value]) => ({
+ key,
+ value:
+ typeof value === "object" ? JSON.stringify(value) : String(value),
+ }));
+ }
+
+ get targetUsername() {
+ return this.reviewable?.tool_parameters?.username;
+ }
+
+ @action
+ toggleExpanded() {
+ this.expanded = !this.expanded;
+ }
+
+ @action
+ async loadReviewable() {
+ try {
+ const response = await ajax(`/review/${this.args.reviewableId}`);
+ this.reviewable = response.reviewable;
+ } catch (error) {
+ const status = error?.jqXHR?.status;
+ if (status === 403 || status === 404) {
+ // regular users can't see the review queue — show the same
+ // "awaiting approval" state they'd get if the fetch had succeeded
+ this.notAuthorized = true;
+ } else {
+ this.loadError = true;
+ }
+ } finally {
+ this.loading = false;
+ }
+ }
+
+ @action
+ async performAction(actionId) {
+ if (this.performing || !this.reviewable || !this.args.postId) {
+ return;
+ }
+
+ this.performing = true;
+
+ try {
+ await ajax(`/review/${this.args.reviewableId}/perform/${actionId}`, {
+ type: "PUT",
+ data: {
+ post_id: this.args.postId,
+ version: this.reviewable.version,
+ },
+ });
+ this.reviewable = {
+ ...this.reviewable,
+ status: actionId === "approve" ? STATUSES.approved : STATUSES.rejected,
+ };
+ } catch (error) {
+ popupAjaxError(error);
+ } finally {
+ this.performing = false;
+ }
+ }
+
+ <template>
+ <div {{didInsert this.loadReviewable}} class="ai-tool-approval">
+ {{#if this.loading}}
+ <span class="ai-tool-approval__status">{{i18n
+ "discourse_ai.ai_tool_approval.loading"
+ }}</span>
+ {{else if this.notAuthorized}}
+ <span class="ai-tool-approval__status">{{i18n
+ "discourse_ai.ai_tool_approval.awaiting_staff"
+ }}</span>
+ {{else if this.loadError}}
+ <span class="ai-tool-approval__status">{{i18n
+ "discourse_ai.ai_tool_approval.load_error"
+ }}</span>
+ {{else}}
+ {{#if this.isResolved}}
+ <DButton
+ class="btn-flat ai-tool-approval__toggle"
+ @icon={{if this.expanded "chevron-down" "chevron-right"}}
+ @translatedLabel={{this.statusLabel}}
+ @action={{this.toggleExpanded}}
+ />
+ {{/if}}
+
+ {{#if this.showDetails}}
+ <div class="ai-tool-approval__summary">
+ <span class="ai-tool-approval__label">{{i18n
+ "discourse_ai.ai_tool_approval.agent"
+ }}</span>
+ <span
+ class="ai-tool-approval__value"
+ >{{this.reviewable.payload.agent_name}}</span>
+
+ <span class="ai-tool-approval__label">{{i18n
+ "discourse_ai.ai_tool_approval.tool"
+ }}</span>
+ <span
+ class="ai-tool-approval__value"
+ >{{this.reviewable.tool_name}}</span>
+
+ {{#if this.targetUsername}}
+ <span class="ai-tool-approval__label">{{i18n
+ "discourse_ai.ai_tool_approval.user"
+ }}</span>
+ <span
+ class="ai-tool-approval__value"
+ >@{{this.targetUsername}}</span>
+ {{/if}}
+
+ {{#each this.toolParameters as |param|}}
+ <span class="ai-tool-approval__label">{{param.key}}</span>
+ <span class="ai-tool-approval__value">{{param.value}}</span>
+ {{/each}}
+ </div>
+ {{/if}}
+
+ {{#if this.isPending}}
+ {{#if this.isStaff}}
+ <div class="ai-tool-approval__actions">
+ <DButton
+ class="btn-danger"
+ @icon="xmark"
+ @label="discourse_ai.ai_tool_approval.reject"
+ @isLoading={{this.performing}}
+ @action={{fn this.performAction "reject"}}
+ />
+ <DButton
+ class="btn-primary"
+ @icon="check"
+ @label="discourse_ai.ai_tool_approval.approve"
+ @isLoading={{this.performing}}
+ @action={{fn this.performAction "approve"}}
+ />
+ </div>
+ {{else}}
+ <span class="ai-tool-approval__status">{{i18n
+ "discourse_ai.ai_tool_approval.awaiting_staff"
+ }}</span>
+ {{/if}}
+ {{/if}}
+ {{/if}}
+ </div>
+ </template>
+}
diff --git a/plugins/discourse-ai/assets/javascripts/discourse/initializers/ai-tool-approval.gjs b/plugins/discourse-ai/assets/javascripts/discourse/initializers/ai-tool-approval.gjs
new file mode 100644
index 00000000000..22b0295b81e
--- /dev/null
+++ b/plugins/discourse-ai/assets/javascripts/discourse/initializers/ai-tool-approval.gjs
@@ -0,0 +1,46 @@
+import { apiInitializer } from "discourse/lib/api";
+import AiToolApproval from "../components/ai-tool-approval";
+
+function initializeAiToolApproval(api) {
+ api.decorateCookedElement(
+ (element, helper) => {
+ if (!helper.renderGlimmer) {
+ return;
+ }
+
+ // The card markup is globally allow-listed, so a regular user could
+ // embed it in their own post. Only mount the actionable card inside
+ // bot-authored posts (bot/system users have a non-positive id); anyone
+ // else's `div.ai-tool-approval` stays inert. Server-side authz on the
+ // /review load and perform endpoints remains the real gate.
+ const post = helper.getModel?.();
+ if (!post?.id || post.user_id > 0) {
+ return;
+ }
+
+ [
+ ...element.querySelectorAll("div[data-ai-tool-approval-reviewable-id]"),
+ ].forEach((cardElement) => {
+ const reviewableId = cardElement.getAttribute(
+ "data-ai-tool-approval-reviewable-id"
+ );
+
+ helper.renderGlimmer(
+ cardElement,
+ <template>
+ <AiToolApproval
+ @postId={{post.id}}
+ @reviewableId={{reviewableId}}
+ />
+ </template>
+ );
+ });
+ },
+ {
+ id: "ai-tool-approval",
+ onlyStream: true,
+ }
+ );
+}
+
+export default apiInitializer(initializeAiToolApproval);
diff --git a/plugins/discourse-ai/assets/javascripts/lib/discourse-markdown/ai-tool-approval.js b/plugins/discourse-ai/assets/javascripts/lib/discourse-markdown/ai-tool-approval.js
new file mode 100644
index 00000000000..e0c1718fd72
--- /dev/null
+++ b/plugins/discourse-ai/assets/javascripts/lib/discourse-markdown/ai-tool-approval.js
@@ -0,0 +1,6 @@
+export function setup(helper) {
+ // The mount point is an empty <div> keyed only by the reviewable id; the
+ // AiToolApproval card component (which owns the `.ai-tool-approval` class) is
+ // rendered into it client-side, so only the data attribute needs allow-listing.
+ helper.allowList(["div[data-ai-tool-approval-reviewable-id]"]);
+}
diff --git a/plugins/discourse-ai/assets/stylesheets/modules/ai-bot/common/ai-tool-approval.scss b/plugins/discourse-ai/assets/stylesheets/modules/ai-bot/common/ai-tool-approval.scss
new file mode 100644
index 00000000000..60d9778dd6d
--- /dev/null
+++ b/plugins/discourse-ai/assets/stylesheets/modules/ai-bot/common/ai-tool-approval.scss
@@ -0,0 +1,43 @@
+.ai-tool-approval {
+ border: 1px solid var(--primary-low);
+ border-radius: var(--d-border-radius);
+ padding: var(--space-3) var(--space-4);
+ margin: var(--space-2) 0;
+ background: var(--primary-very-low);
+
+ &__summary {
+ display: grid;
+ grid-template-columns: max-content 1fr;
+ gap: var(--space-1) var(--space-3);
+ margin-bottom: var(--space-3);
+ }
+
+ &__label {
+ color: var(--primary-medium);
+ font-size: var(--font-down-1);
+ }
+
+ &__value {
+ word-break: break-word;
+ }
+
+ &__actions {
+ display: flex;
+ justify-content: flex-end;
+ gap: var(--space-2);
+ }
+
+ &__status {
+ color: var(--primary-medium);
+ font-style: italic;
+ }
+
+ &__toggle.btn-flat {
+ padding-inline: 0;
+
+ .d-button-label {
+ font-style: italic;
+ color: var(--primary-medium);
+ }
+ }
+}
diff --git a/plugins/discourse-ai/config/locales/client.en.yml b/plugins/discourse-ai/config/locales/client.en.yml
index 38d99d64d1c..49fa8c148a9 100644
--- a/plugins/discourse-ai/config/locales/client.en.yml
+++ b/plugins/discourse-ai/config/locales/client.en.yml
@@ -250,6 +250,18 @@ en:
bot_chats:
tab_label: "Bot chats"
+ ai_tool_approval:
+ loading: "Loading..."
+ load_error: "Couldn't load this pending action."
+ agent: "Agent"
+ tool: "Action"
+ user: "User"
+ approve: "Approve"
+ reject: "Reject"
+ approved: "Approved"
+ rejected: "Rejected"
+ awaiting_staff: "Awaiting staff approval"
+
default_llm:
title: "Default LLM model"
description: "The default LLM model to use for all AI features. This will be used if no LLM is specified in the feature configuration or agent. If no default LLM is specified, the last created LLM will be used."
diff --git a/plugins/discourse-ai/config/locales/server.en.yml b/plugins/discourse-ai/config/locales/server.en.yml
index 8c9dc05bf39..736805d8159 100644
--- a/plugins/discourse-ai/config/locales/server.en.yml
+++ b/plugins/discourse-ai/config/locales/server.en.yml
@@ -604,6 +604,8 @@ en:
categories: "List categories"
flag_post: "Flag post"
close_topic: "Close topic"
+ suspend_user: "Suspend user"
+ silence_user: "Silence user"
unlist_topic: "Unlist topic"
lock_post: "Lock post"
delete_topic: "Delete topic"
@@ -650,6 +652,8 @@ en:
categories: "List all publicly visible categories on the forum"
flag_post: "Flag the current post for staff review"
close_topic: "Close or open a topic"
+ suspend_user: "Suspend (ban) a user, blocking them from logging in or posting"
+ silence_user: "Silence a user, blocking them from posting while they can still read"
unlist_topic: "List or unlist a topic"
lock_post: "Lock or unlock a post"
delete_topic: "Delete a topic"
@@ -696,6 +700,8 @@ en:
random_picker: "Picking from %{options}, picked: %{result}"
flag_post: "Flagging post %{post_id} (flag_post: %{flag_post})"
close_topic: "Closing topic %{topic_id} (closed: %{closed})"
+ suspend_user: "Suspending %{username} for %{duration_days} day(s)"
+ silence_user: "Silencing %{username} for %{duration_days} day(s)"
unlist_topic: "Unlisting topic %{topic_id} (unlisted: %{unlisted})"
lock_post: "Locking post %{post_id} (locked: %{locked})"
delete_topic: "Deleting topic %{topic_id} (deleted: %{deleted})"
@@ -767,6 +773,24 @@ en:
no_reason: "A reason is required to close or open a topic."
success: "Topic updated successfully."
+ suspend_user:
+ errors:
+ not_found: "User not found."
+ not_allowed: "You are not allowed to suspend this user."
+ no_reason: "A reason is required to suspend a user."
+ invalid_duration: "Duration must be a positive whole number of days, up to %{max}."
+ failed: "Failed to suspend user."
+ success: "User %{username} has been suspended."
+
+ silence_user:
+ errors:
+ not_found: "User not found."
+ not_allowed: "You are not allowed to silence this user."
+ no_reason: "A reason is required to silence a user."
+ invalid_duration: "Duration must be a positive whole number of days, up to %{max}."
+ failed: "Failed to silence user."
+ success: "User %{username} has been silenced."
+
unlist_topic:
errors:
not_found: "Topic not found."
@@ -904,7 +928,10 @@ en:
target_missing: "The tool action target no longer exists."
tool_not_found: "Tool '%{tool_name}' is no longer available."
bot_user_missing: "The bot user no longer exists."
+ performer_not_human: "This action must be approved or rejected by a real person, not a bot."
+ post_mismatch: "This approval card does not belong to this post."
execution_error: "Tool execution failed: %{error}"
+ execution_error_unknown: "an unexpected error occurred"
summarization:
configuration_hint:
diff --git a/plugins/discourse-ai/lib/agents/agent.rb b/plugins/discourse-ai/lib/agents/agent.rb
index d33ac00c761..91e1b8d763e 100644
--- a/plugins/discourse-ai/lib/agents/agent.rb
+++ b/plugins/discourse-ai/lib/agents/agent.rb
@@ -98,6 +98,8 @@ module DiscourseAi
Tools::Read,
Tools::FlagPost,
Tools::CloseTopic,
+ Tools::SuspendUser,
+ Tools::SilenceUser,
Tools::UnlistTopic,
Tools::LockPost,
Tools::DeleteTopic,
diff --git a/plugins/discourse-ai/lib/agents/bot.rb b/plugins/discourse-ai/lib/agents/bot.rb
index 7155e5f6dfe..b05962a5c88 100644
--- a/plugins/discourse-ai/lib/agents/bot.rb
+++ b/plugins/discourse-ai/lib/agents/bot.rb
@@ -370,9 +370,21 @@ module DiscourseAi
force_review: true,
)
- placeholder =
- build_placeholder(tool.summary, I18n.t("discourse_ai.ai_bot.tool_pending_approval"))
- update_blk.call(placeholder, nil, :thinking)
+ # :custom_raw lands in the persisted reply as visible content —
+ # a :thinking emission would be dropped (or collapsed into the
+ # thinking details block) depending on the agent's show_thinking.
+ # This is an empty mount point (keyed by the reviewable id); the client
+ # decorator renders the AiToolApproval card component into it, so the
+ # `.ai-tool-approval` element exists only once, on the component itself.
+ approval_card = "<div data-ai-tool-approval-reviewable-id='#{reviewable.id}'></div>"
+
+ approval_content =
+ build_placeholder(
+ tool.summary,
+ I18n.t("discourse_ai.ai_bot.tool_pending_approval"),
+ custom_raw: approval_card,
+ )
+ update_blk.call(approval_content, nil, :custom_raw)
{ status: "pending_approval", message: I18n.t("discourse_ai.ai_bot.tool_pending_approval") }
end
@@ -439,6 +451,9 @@ module DiscourseAi
def invoke_tool(tool, context, &update_blk)
if tool_requires_approval?(tool)
+ if (error = tool.validation_error)
+ return error
+ end
return enqueue_tool_for_approval(tool, context, &update_blk)
end
diff --git a/plugins/discourse-ai/lib/agents/bot_context.rb b/plugins/discourse-ai/lib/agents/bot_context.rb
index 8f9a29ec6bc..8561fe26a21 100644
--- a/plugins/discourse-ai/lib/agents/bot_context.rb
+++ b/plugins/discourse-ai/lib/agents/bot_context.rb
@@ -25,7 +25,8 @@ module DiscourseAi
:user_language,
:bypass_response_format,
:mcp_state,
- :guardian
+ :guardian,
+ :reviewable_id
def initialize(
post: nil,
diff --git a/plugins/discourse-ai/lib/agents/tools/silence_user.rb b/plugins/discourse-ai/lib/agents/tools/silence_user.rb
new file mode 100644
index 00000000000..2133cf27c78
--- /dev/null
+++ b/plugins/discourse-ai/lib/agents/tools/silence_user.rb
@@ -0,0 +1,152 @@
+# frozen_string_literal: true
+
+module DiscourseAi
+ module Agents
+ module Tools
+ class SilenceUser < Tool
+ # ~100 years — an effectively permanent silence, while keeping
+ # `duration_days.days.from_now` inside a representable time range.
+ MAX_DURATION_DAYS = 36_500
+
+ def self.signature
+ {
+ name: name,
+ description:
+ "Silences a user, blocking them from creating new posts/replies while they can still read the forum.",
+ parameters: [
+ {
+ name: "username",
+ description: "The username of the user to silence",
+ type: "string",
+ required: true,
+ },
+ {
+ name: "duration_days",
+ description:
+ "How many days to silence the user for. Use a very large number (e.g. 36500) for an effectively permanent silence.",
+ type: "integer",
+ required: true,
+ },
+ {
+ name: "reason",
+ description: "Short explanation of why the user is being silenced",
+ type: "string",
+ required: true,
+ },
+ {
+ name: "message",
+ description: "Optional message sent to the user explaining the silence",
+ type: "string",
+ },
+ ],
+ }
+ end
+
+ def self.name
+ "silence_user"
+ end
+
+ def self.requires_approval?
+ true
+ end
+
+ def self.attribute_to_approver?
+ true
+ end
+
+ def invoke
+ if (error = validation_error)
+ return error
+ end
+ perform_silence
+ end
+
+ # Returns an error response when the request cannot proceed, or nil
+ # when it is valid. Checked before the action is queued for approval
+ # (and again at approval-replay time), so a bad username, missing
+ # reason, or out-of-range duration never creates a review item that
+ # could only fail. The approver's permission is intentionally not
+ # checked here — it is enforced against the approving moderator in
+ # #invoke.
+ def validation_error
+ if User.find_by_username(parameters[:username]).blank?
+ return error_response(I18n.t("discourse_ai.ai_bot.silence_user.errors.not_found"))
+ end
+
+ if reason.blank?
+ return error_response(I18n.t("discourse_ai.ai_bot.silence_user.errors.no_reason"))
+ end
+
+ if invalid_duration?
+ return(
+ error_response(
+ I18n.t(
+ "discourse_ai.ai_bot.silence_user.errors.invalid_duration",
+ max: MAX_DURATION_DAYS,
+ ),
+ )
+ )
+ end
+
+ nil
+ end
+
+ def description_args
+ { username: parameters[:username], duration_days: parameters[:duration_days] }
+ end
+
+ private
+
+ def perform_silence
+ user = User.find_by_username(parameters[:username])
+
+ if !guardian.can_silence_user?(user)
+ return error_response(I18n.t("discourse_ai.ai_bot.silence_user.errors.not_allowed"))
+ end
+
+ result =
+ User::Silence.call(
+ guardian: guardian,
+ params: {
+ user_id: user.id,
+ reason: reason,
+ silenced_till: duration_days.days.from_now,
+ message: parameters[:message],
+ reviewable_id: context.reviewable_id,
+ },
+ )
+
+ return error_response(silence_error_message(result)) if result.failure?
+
+ {
+ status: "success",
+ message: I18n.t("discourse_ai.ai_bot.silence_user.success", username: user.username),
+ }
+ end
+
+ def duration_days
+ Integer(parameters[:duration_days], exception: false)
+ end
+
+ def invalid_duration?
+ days = duration_days
+ days.nil? || days <= 0 || days > MAX_DURATION_DAYS
+ end
+
+ def silence_error_message(result)
+ contract_result = result["result.contract.default"]
+ return contract_result.errors.full_messages.to_sentence if contract_result&.failure?
+
+ %i[not_silenced_already can_silence_all_users].each do |policy_name|
+ policy_result = result["result.policy.#{policy_name}"]
+ next if !policy_result&.failure?
+ return policy_result.reason if policy_result.reason.present?
+ return I18n.t("discourse_ai.ai_bot.silence_user.errors.failed")
+ end
+
+ I18n.t("discourse_ai.ai_bot.silence_user.errors.failed")
+ end
+ end
+ end
+ end
+end
diff --git a/plugins/discourse-ai/lib/agents/tools/suspend_user.rb b/plugins/discourse-ai/lib/agents/tools/suspend_user.rb
new file mode 100644
index 00000000000..0c599aa884c
--- /dev/null
+++ b/plugins/discourse-ai/lib/agents/tools/suspend_user.rb
@@ -0,0 +1,152 @@
+# frozen_string_literal: true
+
+module DiscourseAi
+ module Agents
+ module Tools
+ class SuspendUser < Tool
+ # ~100 years — an effectively permanent ban, while keeping
+ # `duration_days.days.from_now` inside a representable time range.
+ MAX_DURATION_DAYS = 36_500
+
+ def self.signature
+ {
+ name: name,
+ description:
+ "Suspends (bans) a user, fully blocking them from logging in or posting until the suspension ends.",
+ parameters: [
+ {
+ name: "username",
+ description: "The username of the user to suspend/ban",
+ type: "string",
+ required: true,
+ },
+ {
+ name: "duration_days",
+ description:
+ "How many days to suspend the user for. Use a very large number (e.g. 36500) for a permanent ban.",
+ type: "integer",
+ required: true,
+ },
+ {
+ name: "reason",
+ description: "Short explanation of why the user is being suspended/banned",
+ type: "string",
+ required: true,
+ },
+ {
+ name: "message",
+ description: "Optional message sent to the user explaining the suspension",
+ type: "string",
+ },
+ ],
+ }
+ end
+
+ def self.name
+ "suspend_user"
+ end
+
+ def self.requires_approval?
+ true
+ end
+
+ def self.attribute_to_approver?
+ true
+ end
+
+ def invoke
+ if (error = validation_error)
+ return error
+ end
+ perform_suspend
+ end
+
+ # Returns an error response when the request cannot proceed, or nil
+ # when it is valid. Checked before the action is queued for approval
+ # (and again at approval-replay time), so a bad username, missing
+ # reason, or out-of-range duration never creates a review item that
+ # could only fail. The approver's permission is intentionally not
+ # checked here — it is enforced against the approving moderator in
+ # #invoke.
+ def validation_error
+ if User.find_by_username(parameters[:username]).blank?
+ return error_response(I18n.t("discourse_ai.ai_bot.suspend_user.errors.not_found"))
+ end
+
+ if reason.blank?
+ return error_response(I18n.t("discourse_ai.ai_bot.suspend_user.errors.no_reason"))
+ end
+
+ if invalid_duration?
+ return(
+ error_response(
+ I18n.t(
+ "discourse_ai.ai_bot.suspend_user.errors.invalid_duration",
+ max: MAX_DURATION_DAYS,
+ ),
+ )
+ )
+ end
+
+ nil
+ end
+
+ def description_args
+ { username: parameters[:username], duration_days: parameters[:duration_days] }
+ end
+
+ private
+
+ def perform_suspend
+ user = User.find_by_username(parameters[:username])
+
+ if !guardian.can_suspend?(user)
+ return error_response(I18n.t("discourse_ai.ai_bot.suspend_user.errors.not_allowed"))
+ end
+
+ result =
+ User::Suspend.call(
+ guardian: guardian,
+ params: {
+ user_id: user.id,
+ reason: reason,
+ suspend_until: duration_days.days.from_now,
+ message: parameters[:message],
+ reviewable_id: context.reviewable_id,
+ },
+ )
+
+ return error_response(suspend_error_message(result)) if result.failure?
+
+ {
+ status: "success",
+ message: I18n.t("discourse_ai.ai_bot.suspend_user.success", username: user.username),
+ }
+ end
+
+ def duration_days
+ Integer(parameters[:duration_days], exception: false)
+ end
+
+ def invalid_duration?
+ days = duration_days
+ days.nil? || days <= 0 || days > MAX_DURATION_DAYS
+ end
+
+ def suspend_error_message(result)
+ contract_result = result["result.contract.default"]
+ return contract_result.errors.full_messages.to_sentence if contract_result&.failure?
+
+ %i[not_suspended_already can_suspend_all_users].each do |policy_name|
+ policy_result = result["result.policy.#{policy_name}"]
+ next if !policy_result&.failure?
+ return policy_result.reason if policy_result.reason.present?
+ return I18n.t("discourse_ai.ai_bot.suspend_user.errors.failed")
+ end
+
+ I18n.t("discourse_ai.ai_bot.suspend_user.errors.failed")
+ end
+ end
+ end
+ end
+end
diff --git a/plugins/discourse-ai/lib/agents/tools/tool.rb b/plugins/discourse-ai/lib/agents/tools/tool.rb
index 46ac396c380..72381fcb006 100644
--- a/plugins/discourse-ai/lib/agents/tools/tool.rb
+++ b/plugins/discourse-ai/lib/agents/tools/tool.rb
@@ -47,6 +47,14 @@ module DiscourseAi
false
end
+ # When true, the replayed tool (after approval) is given the
+ # approving moderator as context.user, so guardian checks and
+ # downstream audit logs (StaffActionLogger, UserHistory) credit
+ # the real approver instead of the bot account.
+ def attribute_to_approver?
+ false
+ end
+
def inject_prompt(prompt:, context:, agent:)
end
@@ -128,6 +136,15 @@ module DiscourseAi
true
end
+ # Validation run before a tool that requires approval is queued (and
+ # again at approval-replay time). Return an error response (see
+ # #error_response) when the request is invalid, so a malformed or
+ # infeasible action (e.g. an unknown username) never creates a review
+ # item that could only fail on approval. Return nil when it is valid.
+ def validation_error
+ nil
+ end
+
protected
def fetch_default_branch(repo)
diff --git a/plugins/discourse-ai/plugin.rb b/plugins/discourse-ai/plugin.rb
index 729e6971850..6ddf4a1c9f1 100644
--- a/plugins/discourse-ai/plugin.rb
+++ b/plugins/discourse-ai/plugin.rb
@@ -58,6 +58,7 @@ register_asset "stylesheets/modules/llms/common/ai-credit-bar.scss"
register_asset "stylesheets/modules/ai-bot/common/ai-tools.scss"
register_asset "stylesheets/modules/ai-bot/common/ai-artifact.scss"
+register_asset "stylesheets/modules/ai-bot/common/ai-tool-approval.scss"
module ::DiscourseAi
PLUGIN_NAME = "discourse-ai"
@@ -131,6 +132,7 @@ after_initialize do
register_reviewable_type ReviewableAiChatMessage
register_reviewable_type ReviewableAiPost
register_reviewable_type ReviewableAiToolAction
+ add_permitted_reviewable_param :reviewable_ai_tool_action, :post_id
on(:reviewable_transitioned_to) do |new_status, reviewable|
ModelAccuracy.adjust_model_accuracy(new_status, reviewable)
diff --git a/plugins/discourse-ai/spec/lib/agents/bot_spec.rb b/plugins/discourse-ai/spec/lib/agents/bot_spec.rb
index 74309804b7b..b20e46ff96d 100644
--- a/plugins/discourse-ai/spec/lib/agents/bot_spec.rb
+++ b/plugins/discourse-ai/spec/lib/agents/bot_spec.rb
@@ -777,5 +777,45 @@ RSpec.describe DiscourseAi::Agents::Bot do
expect(topic.reload.closed).to eq(true)
expect(ReviewableAiToolAction.count).to eq(0)
end
+
+ it "does not create a reviewable when the tool's args are invalid" do
+ toggle_enabled_bots(bots: [fake])
+ Group.refresh_automatic_groups!
+
+ failing_precheck_tool_class =
+ Class.new(DiscourseAi::Agents::Tools::CloseTopic) do
+ def validation_error
+ error_response("nope")
+ end
+ end
+
+ AiAgent.create!(
+ name: "PrecheckAgent",
+ system_prompt: "test",
+ description: "test",
+ allowed_group_ids: [Group::AUTO_GROUPS[:trust_level_0]],
+ require_approval: true,
+ )
+
+ agent_class = DiscourseAi::Agents::Agent.find_by(user: admin, name: "PrecheckAgent")
+ test_bot_user = DiscourseAi::AiBot::EntryPoint.find_user_from_model(fake.name)
+ bot = described_class.as(test_bot_user, agent: agent_class.new)
+
+ tool =
+ failing_precheck_tool_class.new(
+ { topic_id: topic.id, closed: true, reason: "Off-topic" },
+ bot_user: test_bot_user,
+ llm: bot.llm,
+ )
+
+ context = DiscourseAi::Agents::BotContext.new(messages: [])
+
+ result = bot.send(:invoke_tool, tool, context) { |*args| }
+
+ expect(result[:status]).to eq("error")
+ expect(topic.reload.closed).to eq(false)
+ expect(AiToolAction.count).to eq(0)
+ expect(ReviewableAiToolAction.count).to eq(0)
+ end
end
end
diff --git a/plugins/discourse-ai/spec/lib/agents/tools/silence_user_spec.rb b/plugins/discourse-ai/spec/lib/agents/tools/silence_user_spec.rb
new file mode 100644
index 00000000000..0263302e5be
--- /dev/null
+++ b/plugins/discourse-ai/spec/lib/agents/tools/silence_user_spec.rb
@@ -0,0 +1,142 @@
+# frozen_string_literal: true
+
+RSpec.describe DiscourseAi::Agents::Tools::SilenceUser 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!(:user)
+
+ 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 "silences the user" do
+ result =
+ tool(username: user.username, duration_days: 7, reason: "Repeated off-topic posts").invoke
+
+ expect(result[:status]).to eq("success")
+ expect(user.reload.silenced?).to eq(true)
+ end
+
+ it "returns an error when user is not found" do
+ result = tool(username: "nonexistent", duration_days: 7, reason: "Test").invoke
+
+ expect(result[:status]).to eq("error")
+ end
+
+ it "returns an error when reason is blank" do
+ result = tool(username: user.username, duration_days: 7, reason: " ").invoke
+
+ expect(result[:status]).to eq("error")
+ expect(user.reload.silenced?).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(
+ { username: user.username, duration_days: 7, 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(user.reload.silenced?).to eq(false)
+ end
+
+ it "returns an error when the user is already silenced" do
+ UserSilencer.new(user, Discourse.system_user, reason: "Prior offense").silence
+
+ result = tool(username: user.username, duration_days: 7, reason: "Test").invoke
+
+ expect(result[:status]).to eq("error")
+ expect(result[:error]).to include("already silenced")
+ end
+
+ it "returns an error and does not silence when duration_days is zero" do
+ result = tool(username: user.username, duration_days: 0, reason: "Test").invoke
+
+ expect(result[:status]).to eq("error")
+ expect(user.reload.silenced?).to eq(false)
+ end
+
+ it "returns an error and does not silence when duration_days is negative" do
+ result = tool(username: user.username, duration_days: -5, reason: "Test").invoke
+
+ expect(result[:status]).to eq("error")
+ expect(user.reload.silenced?).to eq(false)
+ end
+
+ it "returns an error and does not silence when duration_days is not numeric" do
+ result = tool(username: user.username, duration_days: "soon", reason: "Test").invoke
+
+ expect(result[:status]).to eq("error")
+ expect(user.reload.silenced?).to eq(false)
+ end
+
+ it "returns an error and does not silence when duration_days exceeds the maximum" do
+ result =
+ tool(
+ username: user.username,
+ duration_days: described_class::MAX_DURATION_DAYS + 1,
+ reason: "Test",
+ ).invoke
+
+ expect(result[:status]).to eq("error")
+ expect(user.reload.silenced?).to eq(false)
+ end
+
+ it "silences at the maximum allowed duration" do
+ result =
+ tool(
+ username: user.username,
+ duration_days: described_class::MAX_DURATION_DAYS,
+ reason: "Permanent silence",
+ ).invoke
+
+ expect(result[:status]).to eq("success")
+ expect(user.reload.silenced?).to eq(true)
+ end
+
+ describe "#validation_error" do
+ it "returns an error for an unknown username, without performing the action" do
+ result = tool(username: "nonexistent", duration_days: 7, reason: "Test").validation_error
+
+ expect(result[:status]).to eq("error")
+ end
+
+ it "returns an error for a blank reason and for an out-of-range duration" do
+ expect(
+ tool(username: user.username, duration_days: 7, reason: " ").validation_error[:status],
+ ).to eq("error")
+ expect(
+ tool(
+ username: user.username,
+ duration_days: described_class::MAX_DURATION_DAYS + 1,
+ reason: "Test",
+ ).validation_error[
+ :status
+ ],
+ ).to eq("error")
+ end
+
+ it "returns nil for a valid request and does not silence" do
+ result = tool(username: user.username, duration_days: 7, reason: "Test").validation_error
+
+ expect(result).to be_nil
+ expect(user.reload.silenced?).to eq(false)
+ end
+ end
+end
diff --git a/plugins/discourse-ai/spec/lib/agents/tools/suspend_user_spec.rb b/plugins/discourse-ai/spec/lib/agents/tools/suspend_user_spec.rb
new file mode 100644
index 00000000000..8c24463f782
--- /dev/null
+++ b/plugins/discourse-ai/spec/lib/agents/tools/suspend_user_spec.rb
@@ -0,0 +1,146 @@
+# frozen_string_literal: true
+
+RSpec.describe DiscourseAi::Agents::Tools::SuspendUser 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!(:user)
+
+ 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 "suspends the user" do
+ result = tool(username: user.username, duration_days: 7, reason: "Repeated spam links").invoke
+
+ expect(result[:status]).to eq("success")
+ expect(user.reload.suspended?).to eq(true)
+ end
+
+ it "returns an error when user is not found" do
+ result = tool(username: "nonexistent", duration_days: 7, reason: "Test").invoke
+
+ expect(result[:status]).to eq("error")
+ end
+
+ it "returns an error when reason is blank" do
+ result = tool(username: user.username, duration_days: 7, reason: " ").invoke
+
+ expect(result[:status]).to eq("error")
+ expect(user.reload.suspended?).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(
+ { username: user.username, duration_days: 7, 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(user.reload.suspended?).to eq(false)
+ end
+
+ it "returns an error when the user is already suspended" do
+ UserSuspender.new(
+ user,
+ suspended_till: 1.week.from_now,
+ reason: "Prior offense",
+ by_user: Discourse.system_user,
+ ).suspend
+
+ result = tool(username: user.username, duration_days: 7, reason: "Test").invoke
+
+ expect(result[:status]).to eq("error")
+ expect(result[:error]).to include("already suspended")
+ end
+
+ it "returns an error and does not suspend when duration_days is zero" do
+ result = tool(username: user.username, duration_days: 0, reason: "Test").invoke
+
+ expect(result[:status]).to eq("error")
+ expect(user.reload.suspended?).to eq(false)
+ end
+
+ it "returns an error and does not suspend when duration_days is negative" do
+ result = tool(username: user.username, duration_days: -5, reason: "Test").invoke
+
+ expect(result[:status]).to eq("error")
+ expect(user.reload.suspended?).to eq(false)
+ end
+
+ it "returns an error and does not suspend when duration_days is not numeric" do
+ result = tool(username: user.username, duration_days: "soon", reason: "Test").invoke
+
+ expect(result[:status]).to eq("error")
+ expect(user.reload.suspended?).to eq(false)
+ end
+
+ it "returns an error and does not suspend when duration_days exceeds the maximum" do
+ result =
+ tool(
+ username: user.username,
+ duration_days: described_class::MAX_DURATION_DAYS + 1,
+ reason: "Test",
+ ).invoke
+
+ expect(result[:status]).to eq("error")
+ expect(user.reload.suspended?).to eq(false)
+ end
+
+ it "suspends at the maximum allowed duration" do
+ result =
+ tool(
+ username: user.username,
+ duration_days: described_class::MAX_DURATION_DAYS,
+ reason: "Permanent ban",
+ ).invoke
+
+ expect(result[:status]).to eq("success")
+ expect(user.reload.suspended?).to eq(true)
+ end
+
+ describe "#validation_error" do
+ it "returns an error for an unknown username, without performing the action" do
+ result = tool(username: "nonexistent", duration_days: 7, reason: "Test").validation_error
+
+ expect(result[:status]).to eq("error")
+ end
+
+ it "returns an error for a blank reason and for an out-of-range duration" do
+ expect(
+ tool(username: user.username, duration_days: 7, reason: " ").validation_error[:status],
+ ).to eq("error")
+ expect(
+ tool(
+ username: user.username,
+ duration_days: described_class::MAX_DURATION_DAYS + 1,
+ reason: "Test",
+ ).validation_error[
+ :status
+ ],
+ ).to eq("error")
+ end
+
+ it "returns nil for a valid request and does not suspend" do
+ result = tool(username: user.username, duration_days: 7, reason: "Test").validation_error
+
+ expect(result).to be_nil
+ expect(user.reload.suspended?).to eq(false)
+ end
+ end
+end
diff --git a/plugins/discourse-ai/spec/models/reviewable_ai_tool_action_spec.rb b/plugins/discourse-ai/spec/models/reviewable_ai_tool_action_spec.rb
index 5d78d4ebcca..adbba593093 100644
--- a/plugins/discourse-ai/spec/models/reviewable_ai_tool_action_spec.rb
+++ b/plugins/discourse-ai/spec/models/reviewable_ai_tool_action_spec.rb
@@ -88,6 +88,36 @@ RSpec.describe ReviewableAiToolAction do
expect(actions.has?(:approve)).to eq(false)
expect(actions.has?(:reject)).to eq(false)
end
+
+ it "returns no actions for a user who cannot see the review queue" do
+ tool_action = create_tool_action
+ reviewable = create_reviewable(tool_action)
+ regular_user = Fabricate(:user)
+
+ actions = Reviewable::Actions.new(reviewable, Guardian.new(regular_user), {})
+ reviewable.build_actions(actions, Guardian.new(regular_user), {})
+
+ expect(actions.has?(:approve)).to eq(false)
+ expect(actions.has?(:reject)).to eq(false)
+ end
+
+ it "returns actions for a category group moderator scoped to the reviewable's category" do
+ category = Fabricate(:category)
+ post = Fabricate(:post, topic: Fabricate(:topic, category: category))
+ tool_action = create_tool_action(post_id: post.id)
+ reviewable = create_reviewable(tool_action)
+
+ SiteSetting.enable_category_group_moderation = true
+ group = Fabricate(:group)
+ Fabricate(:category_moderation_group, category:, group:)
+ group_moderator = Fabricate(:user, groups: [group])
+
+ actions = Reviewable::Actions.new(reviewable, Guardian.new(group_moderator), {})
+ reviewable.build_actions(actions, Guardian.new(group_moderator), {})
+
+ expect(actions.has?(:approve)).to eq(true)
+ expect(actions.has?(:reject)).to eq(true)
+ end
end
describe "#perform_approve" do
@@ -102,6 +132,20 @@ RSpec.describe ReviewableAiToolAction do
expect(topic.reload.closed).to eq(true)
end
+ it "rejects inline approval from a different post", :aggregate_failures do
+ post = Fabricate(:post, topic: topic)
+ other_post = Fabricate(:post)
+ tool_action = create_tool_action(post_id: post.id)
+ reviewable = create_reviewable(tool_action)
+
+ expect { reviewable.perform(admin, :approve, post_id: other_post.id) }.to raise_error(
+ Discourse::InvalidAccess,
+ )
+
+ expect(reviewable.reload).to be_pending
+ expect(topic.reload.closed).to eq(false)
+ end
+
it "raises error when target is missing" do
tool_action = create_tool_action
reviewable = create_reviewable(tool_action)
@@ -118,14 +162,90 @@ RSpec.describe ReviewableAiToolAction do
expect { reviewable.perform(admin, :approve) }.to raise_error(Discourse::InvalidAccess)
end
- it "approves even when tool returns an error result (e.g. stale target)" do
+ it "raises and stays pending when the tool returns an error result (e.g. stale target)" do
tool_action = create_tool_action(params: { topic_id: -999, closed: true, reason: "test" })
reviewable = create_reviewable(tool_action)
+ expect { reviewable.perform(admin, :approve) }.to raise_error(Discourse::InvalidAccess)
+ expect(reviewable.reload).to be_pending
+ end
+
+ it "raises and stays pending when the approver lacks permission at replay time" do
+ target_user = Fabricate(:user)
+ tool_action =
+ create_tool_action(
+ tool_name: "suspend_user",
+ params: {
+ username: target_user.username,
+ duration_days: 7,
+ reason: "Spam",
+ },
+ )
+ reviewable = create_reviewable(tool_action)
+ moderator = Fabricate(:moderator)
+
+ # A plain moderator cannot suspend an admin, so the replayed tool fails.
+ target_user.update!(admin: true)
+
+ expect { reviewable.perform(moderator, :approve) }.to raise_error(Discourse::InvalidAccess)
+ expect(reviewable.reload).to be_pending
+ expect(target_user.reload.suspended?).to eq(false)
+ end
+
+ it "raises error when performed_by is a bot account" do
+ tool_action = create_tool_action
+ reviewable = create_reviewable(tool_action)
+
+ expect { reviewable.perform(bot_user, :approve) }.to raise_error(Discourse::InvalidAccess)
+ expect(topic.reload.closed).to eq(false)
+ end
+
+ it "attributes the action to the approving moderator for tools that opt into attribute_to_approver?" do
+ target_user = Fabricate(:user)
+ tool_action =
+ create_tool_action(
+ tool_name: "suspend_user",
+ params: {
+ username: target_user.username,
+ duration_days: 7,
+ reason: "Spam",
+ },
+ )
+ reviewable = create_reviewable(tool_action)
+
result = reviewable.perform(admin, :approve)
expect(result.success?).to eq(true)
- expect(result.transition_to).to eq(:approved)
+ expect(target_user.reload.suspended?).to eq(true)
+
+ suspend_history = UserHistory.where(action: UserHistory.actions[:suspend_user]).last
+ expect(suspend_history.acting_user_id).to eq(admin.id)
+ expect(suspend_history.target_user_id).to eq(target_user.id)
+ expect(suspend_history.reviewable_id).to eq(reviewable.id)
+ end
+
+ it "attributes a silence_user approval to the approving moderator" do
+ target_user = Fabricate(:user)
+ tool_action =
+ create_tool_action(
+ tool_name: "silence_user",
+ params: {
+ username: target_user.username,
+ duration_days: 7,
+ reason: "Spam",
+ },
+ )
+ reviewable = create_reviewable(tool_action)
+
+ result = reviewable.perform(admin, :approve)
+
+ expect(result.success?).to eq(true)
+ expect(target_user.reload.silenced?).to eq(true)
+
+ silence_history = UserHistory.where(action: UserHistory.actions[:silence_user]).last
+ expect(silence_history.acting_user_id).to eq(admin.id)
+ expect(silence_history.target_user_id).to eq(target_user.id)
+ expect(silence_history.reviewable_id).to eq(reviewable.id)
end
end
@@ -140,5 +260,25 @@ RSpec.describe ReviewableAiToolAction do
expect(result.transition_to).to eq(:rejected)
expect(topic.reload.closed).to eq(false)
end
+
+ it "rejects inline rejection from a different post" do
+ post = Fabricate(:post, topic: topic)
+ other_post = Fabricate(:post)
+ tool_action = create_tool_action(post_id: post.id)
+ reviewable = create_reviewable(tool_action)
+
+ expect { reviewable.perform(admin, :reject, post_id: other_post.id) }.to raise_error(
+ Discourse::InvalidAccess,
+ )
+
+ expect(reviewable.reload).to be_pending
+ end
+
+ it "raises error when performed_by is a bot account" do
+ tool_action = create_tool_action
+ reviewable = create_reviewable(tool_action)
+
+ expect { reviewable.perform(bot_user, :reject) }.to raise_error(Discourse::InvalidAccess)
+ end
end
end
diff --git a/plugins/discourse-ai/test/javascripts/integration/components/ai-tool-approval-test.gjs b/plugins/discourse-ai/test/javascripts/integration/components/ai-tool-approval-test.gjs
new file mode 100644
index 00000000000..17f09c3a52c
--- /dev/null
+++ b/plugins/discourse-ai/test/javascripts/integration/components/ai-tool-approval-test.gjs
@@ -0,0 +1,125 @@
+import { getOwner } from "@ember/owner";
+import { click, render } from "@ember/test-helpers";
+import { module, test } from "qunit";
+import { setupRenderingTest } from "discourse/tests/helpers/component-test";
+import pretender, { response } from "discourse/tests/helpers/create-pretender";
+import {
+ logIn,
+ updateCurrentUser,
+} from "discourse/tests/helpers/qunit-helpers";
+import { i18n } from "discourse-i18n";
+import AiToolApproval from "discourse/plugins/discourse-ai/discourse/components/ai-tool-approval";
+
+module("Integration | Component | AiToolApproval", function (hooks) {
+ setupRenderingTest(hooks);
+
+ hooks.beforeEach(function () {
+ logIn(getOwner(this));
+ });
+
+ const reviewable = {
+ id: 42,
+ version: 0,
+ status: 0,
+ tool_name: "suspend_user",
+ tool_parameters: { username: "baduser", duration_days: 7, reason: "Spam" },
+ payload: { agent_name: "Snorlax" },
+ };
+
+ test("staff can review and approve a pending action", async function (assert) {
+ updateCurrentUser({ moderator: true, admin: false });
+
+ pretender.get("/review/42", () => response({ reviewable }));
+ pretender.put("/review/42/perform/approve", (request) => {
+ assert.strictEqual(
+ request.requestBody,
+ "post_id=123&version=0",
+ "sends the rendered post id with the inline action"
+ );
+
+ return response({ reviewable_perform_result: { success: true } });
+ });
+
+ await render(
+ <template><AiToolApproval @postId="123" @reviewableId="42" /></template>
+ );
+
+ assert.dom(".ai-tool-approval__value").exists("shows the tool's details");
+ assert
+ .dom(".ai-tool-approval__actions .btn-primary")
+ .exists("shows the approve button to staff");
+
+ await click(".ai-tool-approval__actions .btn-primary");
+
+ assert
+ .dom(".ai-tool-approval__toggle")
+ .hasText("Approved", "collapses to a status toggle after approving");
+ assert
+ .dom(".ai-tool-approval__summary")
+ .doesNotExist("hides the details once resolved");
+
+ await click(".ai-tool-approval__toggle");
+
+ assert
+ .dom(".ai-tool-approval__summary")
+ .includesText("Spam", "expands to reveal the approved action's reason");
+ });
+
+ test("an approved action collapses to an expandable status with no revert action", async function (assert) {
+ updateCurrentUser({ moderator: true, admin: false });
+
+ const approved = { ...reviewable, status: 1 };
+ pretender.get("/review/42", () => response({ reviewable: approved }));
+
+ await render(
+ <template><AiToolApproval @postId="123" @reviewableId="42" /></template>
+ );
+
+ assert
+ .dom(".ai-tool-approval__toggle")
+ .hasText("Approved", "shows the collapsed approved state");
+
+ await click(".ai-tool-approval__toggle");
+
+ assert
+ .dom(".ai-tool-approval__summary")
+ .includesText("Spam", "expands to reveal what was approved");
+ assert
+ .dom(".ai-tool-approval__actions")
+ .doesNotExist("offers no revert action");
+ });
+
+ test("non-staff sees a pending message without action buttons", async function (assert) {
+ updateCurrentUser({ moderator: false, admin: false });
+
+ pretender.get("/review/42", () => response({ reviewable }));
+
+ await render(
+ <template><AiToolApproval @postId="123" @reviewableId="42" /></template>
+ );
+
+ assert
+ .dom(".ai-tool-approval__actions")
+ .doesNotExist("hides the action buttons");
+ assert
+ .dom(".ai-tool-approval__status")
+ .exists("shows an awaiting-approval message");
+ });
+
+ test("a 403 from the review endpoint shows the awaiting-approval message, not an error", async function (assert) {
+ updateCurrentUser({ moderator: false, admin: false });
+
+ pretender.get("/review/42", () => response(403, {}));
+
+ await render(
+ <template><AiToolApproval @postId="123" @reviewableId="42" /></template>
+ );
+
+ assert
+ .dom(".ai-tool-approval__status")
+ .hasText(
+ i18n("discourse_ai.ai_tool_approval.awaiting_staff"),
+ "shows awaiting approval instead of a load error"
+ );
+ });
+});