A platform for community discussion. Free, open, simple.
FEATURE: Approve AI moderation actions inline in bot chat DMs (#41565)
Gabriel Grubba9c09e988b398
diff --git a/plugins/chat/assets/javascripts/discourse/lib/chat-channel-subscription-manager.js b/plugins/chat/assets/javascripts/discourse/lib/chat-channel-subscription-manager.jsindex 8ca82466702..15afe1074db 100644--- a/plugins/chat/assets/javascripts/discourse/lib/chat-channel-subscription-manager.js+++ b/plugins/chat/assets/javascripts/discourse/lib/chat-channel-subscription-manager.js@@ -157,6 +157,7 @@ export default class ChatChannelSubscriptionManager {message.uploads = cloneJSON(data.chat_message.uploads || []);message.edited = data.chat_message.edited;message.streaming = data.chat_message.streaming;+ message.blocks = data.chat_message.blocks;}}diff --git a/plugins/chat/assets/javascripts/discourse/lib/chat-channel-thread-subscription-manager.js b/plugins/chat/assets/javascripts/discourse/lib/chat-channel-thread-subscription-manager.jsindex 68d73efdb06..e3b6016281e 100644--- a/plugins/chat/assets/javascripts/discourse/lib/chat-channel-thread-subscription-manager.js+++ b/plugins/chat/assets/javascripts/discourse/lib/chat-channel-thread-subscription-manager.js@@ -141,6 +141,7 @@ export default class ChatChannelThreadSubscriptionManager {message.uploads = cloneJSON(data.chat_message.uploads || []);message.edited = data.chat_message.edited;message.streaming = data.chat_message.streaming;+ message.blocks = data.chat_message.blocks;}}diff --git a/plugins/chat/assets/javascripts/discourse/models/chat-message.js b/plugins/chat/assets/javascripts/discourse/models/chat-message.jsindex 16f5ca3a5ac..3ecd479b60f 100644--- a/plugins/chat/assets/javascripts/discourse/models/chat-message.js+++ b/plugins/chat/assets/javascripts/discourse/models/chat-message.js@@ -54,6 +54,7 @@ export default class ChatMessage {@tracked deletedById;@tracked streaming;@tracked pinned;+ @tracked blocks;@autoTrackedArray reactions;@tracked _deletedAt;diff --git a/plugins/discourse-ai/config/locales/server.en.yml b/plugins/discourse-ai/config/locales/server.en.ymlindex 736805d8159..f2de228d123 100644--- a/plugins/discourse-ai/config/locales/server.en.yml+++ b/plugins/discourse-ai/config/locales/server.en.yml@@ -405,6 +405,11 @@ en:default_pm_prefix: "[Untitled AI bot PM]"thinking: "Thinking"tool_pending_approval: "This action requires moderator approval before it can be executed."+ chat_tool_approval:+ approved: "Approved by @%{username}."+ rejected: "Rejected by @%{username}."+ failed: "Could not complete the action: %{error}"+ unexpected_error: "an unexpected error occurred"agents:default_llm_required: "Default LLM model is required prior to enabling Chat"cannot_delete_system_agent: "System agents cannot be deleted, please disable it instead"diff --git a/plugins/discourse-ai/lib/agents/bot.rb b/plugins/discourse-ai/lib/agents/bot.rbindex b05962a5c88..724049df701 100644--- a/plugins/discourse-ai/lib/agents/bot.rb+++ b/plugins/discourse-ai/lib/agents/bot.rb@@ -370,21 +370,31 @@ module DiscourseAiforce_review: true,)- # :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,+ if context.channel_id.present?+ # In chat the reply is rendered as interactive "blocks"; the chat+ # reply handler turns this into an Approve/Reject block message.+ update_blk.call(+ { reviewable_id: reviewable.id, summary: tool.summary, details: tool.details },+ nil,+ :chat_approval,)- update_blk.call(approval_content, nil, :custom_raw)+ else+ # :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)+ end{ status: "pending_approval", message: I18n.t("discourse_ai.ai_bot.tool_pending_approval") }enddiff --git a/plugins/discourse-ai/lib/ai_bot/chat_tool_approval.rb b/plugins/discourse-ai/lib/ai_bot/chat_tool_approval.rbnew file mode 100644index 00000000000..f932404c315--- /dev/null+++ b/plugins/discourse-ai/lib/ai_bot/chat_tool_approval.rb@@ -0,0 +1,136 @@+# frozen_string_literal: true++module DiscourseAi+ module AiBot+ # Bridges the ReviewableAiToolAction approval queue to the Chat plugin's+ # interactive "blocks", so a moderator can approve/reject a bot-requested+ # action inline in a chat conversation — mirroring the inline card used in+ # the bot's PM/topic replies. Scoped to bot direct-message channels.+ module ChatToolApproval+ ACTION_PREFIX = "ai_tool_approval"++ def self.build_action_id(action, reviewable_id)+ "#{ACTION_PREFIX}::#{action}::#{reviewable_id}"+ end++ def self.parse_action_id(raw)+ prefix, action, reviewable_id = raw.to_s.split("::")+ return if prefix != ACTION_PREFIX+ return if !%w[approve reject].include?(action)+ return if reviewable_id.to_i <= 0++ { action: action, reviewable_id: reviewable_id.to_i }+ end++ def self.pending_blocks(reviewable_id)+ [+ {+ type: "actions",+ schema_version: 1,+ elements: [+ {+ type: "button",+ schema_version: 1,+ action_id: build_action_id("approve", reviewable_id),+ style: "primary",+ text: {+ type: "plain_text",+ text: I18n.t("discourse_ai.reviewables.ai_tool_action.approve.title"),+ },+ },+ {+ type: "button",+ schema_version: 1,+ action_id: build_action_id("reject", reviewable_id),+ style: "danger",+ text: {+ type: "plain_text",+ text: I18n.t("discourse_ai.reviewables.ai_tool_action.reject.title"),+ },+ },+ ],+ },+ ]+ end++ # Handles a :chat_message_interaction event: performs the approval/+ # rejection and rewrites the message to its resolved state. Done inline+ # (not in a background job) so the buttons are cleared before the request+ # returns — the button is disabled while in flight, so this closes the+ # window for a double-click hitting an already-resolved message.+ def self.handle_interaction(interaction)+ return if interaction.blank?++ parsed = parse_action_id(interaction.action&.dig("action_id"))+ return if parsed.blank?++ reviewable = ReviewableAiToolAction.find_by(id: parsed[:reviewable_id])+ return if reviewable.blank? || !reviewable.pending?++ user = interaction.user+ return if user.blank?++ # Same authorization as the review queue: only users who can see this+ # reviewable may act on it. Everyone else is silently ignored.+ return if !Reviewable.viewable_by(user).exists?(id: reviewable.id)++ message = interaction.message++ begin+ reviewable.perform(user, parsed[:action].to_sym)+ status_key = parsed[:action] == "approve" ? "approved" : "rejected"+ resolve_message!(+ message,+ I18n.t("discourse_ai.ai_bot.chat_tool_approval.#{status_key}", username: user.username),+ )+ rescue => e+ # The reviewable stays pending; keep the buttons for a retry and+ # surface the reason. Never let the event handler raise — that would+ # 500 the interaction request.+ append_error!(+ message,+ I18n.t("discourse_ai.ai_bot.chat_tool_approval.failed", error: failure_reason(e)),+ )+ end+ end++ # Surfaces a user-facing reason for a failed action. Only the localized+ # messages our own flow raises (Discourse::InvalidAccess) are shown; any+ # other/unexpected exception falls back to a generic message so internal+ # error text is never leaked into the chat.+ def self.failure_reason(error)+ if error.is_a?(Discourse::InvalidAccess)+ if error.custom_message.present?+ return I18n.t(error.custom_message, error.custom_message_params || {})+ end+ return error.message if error.message.present?+ end++ I18n.t("discourse_ai.ai_bot.chat_tool_approval.unexpected_error")+ end++ # Appends the resolved status to the approval message and removes the+ # buttons so it can no longer be actioned.+ def self.resolve_message!(message, status_text)+ return if message.blank?++ message.message = "#{message.message}\n\n#{status_text}"+ message.blocks = nil+ message.cook+ message.save!+ ::Chat::Publisher.publish_edit!(message.chat_channel, message.reload)+ end++ # Keeps the buttons in place (so a permitted moderator can retry) but+ # surfaces why the action could not be completed.+ def self.append_error!(message, status_text)+ return if message.blank?++ message.message = "#{message.message}\n\n#{status_text}"+ message.cook+ message.save!+ ::Chat::Publisher.publish_edit!(message.chat_channel, message.reload)+ end+ end+ end+enddiff --git a/plugins/discourse-ai/lib/ai_bot/entry_point.rb b/plugins/discourse-ai/lib/ai_bot/entry_point.rbindex d934d971d7b..254186af319 100644--- a/plugins/discourse-ai/lib/ai_bot/entry_point.rb+++ b/plugins/discourse-ai/lib/ai_bot/entry_point.rb@@ -278,6 +278,10 @@ module DiscourseAiDiscourseAi::AiBot::Playground.schedule_chat_reply(chat_message, channel, user, context)end+ plugin.on(:chat_message_interaction) do |interaction|+ DiscourseAi::AiBot::ChatToolApproval.handle_interaction(interaction)+ end+plugin.register_editable_topic_custom_field(:ai_agent_id)plugin.add_api_key_scope(diff --git a/plugins/discourse-ai/lib/ai_bot/playground.rb b/plugins/discourse-ai/lib/ai_bot/playground.rbindex 9ab65f77b9d..2077715b8f0 100644--- a/plugins/discourse-ai/lib/ai_bot/playground.rb+++ b/plugins/discourse-ai/lib/ai_bot/playground.rb@@ -356,10 +356,15 @@ module DiscourseAicancel_manager: context.cancel_manager,)+ pending_approvals = []new_prompts =bot.reply(context) do |partial, placeholder, type|# no support for thinking by designnext if type == :thinking || type == :partial_tool+ if type == :chat_approval+ pending_approvals << partial+ next+ endstreamer << partialend@@ -373,6 +378,16 @@ module DiscourseAistreamer = nilend+ pending_approvals.each do |pending_approval|+ post_chat_tool_approval(+ pending_approval,+ channel: channel,+ guardian: guardian,+ thread_id: reply&.thread_id || message.reload.thread_id,+ fallback_in_reply_to_id: message.id,+ )+ end+replyrescue LlmCreditAllocation::CreditLimitExceeded => eif streamer && streamer.instance_variable_get(:@client_id)@@ -408,6 +423,30 @@ module DiscourseAistreamer.done if streamerend+ # Posts the queued tool action as its own chat message carrying the+ # Approve/Reject blocks, in the same thread as the bot's reply so it sits+ # with the conversation. It must be a fresh message (not an edit of the+ # reply): the chat client only renders blocks present at message creation.+ # Scoped to bot direct-message channels; elsewhere the reviewable is still+ # created and remains actionable from /review.+ def post_chat_tool_approval(info, channel:, guardian:, thread_id:, fallback_in_reply_to_id:)+ return if !channel.direct_message_channel?++ raw = +"**#{info[:summary]}**\n#{info[:details]}".strip+ raw << "\n\n_#{I18n.t("discourse_ai.ai_bot.tool_pending_approval")}_"++ ChatSDK::Message.create(+ raw: raw,+ channel_id: channel.id,+ guardian: guardian,+ thread_id: thread_id,+ in_reply_to_id: thread_id ? nil : fallback_in_reply_to_id,+ force_thread: thread_id.blank?,+ enforce_membership: !channel.direct_message_channel?,+ blocks: DiscourseAi::AiBot::ChatToolApproval.pending_blocks(info[:reviewable_id]),+ )+ end+def reply_to(post,custom_instructions: nil,diff --git a/plugins/discourse-ai/spec/lib/ai_bot/chat_tool_approval_spec.rb b/plugins/discourse-ai/spec/lib/ai_bot/chat_tool_approval_spec.rbnew file mode 100644index 00000000000..625e52e9ce9--- /dev/null+++ b/plugins/discourse-ai/spec/lib/ai_bot/chat_tool_approval_spec.rb@@ -0,0 +1,207 @@+# frozen_string_literal: true++RSpec.describe DiscourseAi::AiBot::ChatToolApproval do+ fab!(:admin)+ fab!(:ai_agent)+ fab!(:target_user, :user)+ fab!(:non_staff) { Fabricate(:user, trust_level: TrustLevel[1]) }++ let(:bot_user) { Discourse.system_user }++ before do+ enable_current_plugin+ SiteSetting.ai_bot_enabled = true+ SiteSetting.chat_enabled = true+ end++ fab!(:dm_channel) { Fabricate(:direct_message_channel, users: [admin, target_user]) }++ def create_reviewable(username: target_user.username)+ action =+ AiToolAction.create!(+ tool_name: "suspend_user",+ tool_parameters: {+ username: username,+ duration_days: 3,+ reason: "spam",+ },+ ai_agent: ai_agent,+ bot_user_id: bot_user.id,+ )+ reviewable =+ ReviewableAiToolAction.needs_review!(+ target: action,+ created_by: bot_user,+ reviewable_by_moderator: true,+ payload: {+ agent_name: "Test",+ reason: "spam",+ },+ )+ reviewable.add_score(+ Discourse.system_user,+ ReviewableScore.types[:needs_approval],+ force_review: true,+ )+ reviewable+ end++ def message_for(reviewable)+ message = Fabricate(:chat_message, chat_channel: dm_channel, user: bot_user)+ message.update!(blocks: DiscourseAi::AiBot::ChatToolApproval.pending_blocks(reviewable.id))+ message+ end++ def interaction_for(reviewable, user:, action: "approve", message: nil)+ Chat::MessageInteraction.new(+ user: user,+ message: message || message_for(reviewable),+ action: {+ "action_id" => DiscourseAi::AiBot::ChatToolApproval.build_action_id(action, reviewable.id),+ },+ )+ end++ describe ".build_action_id / .parse_action_id" do+ it "round-trips a valid action id" do+ id = described_class.build_action_id("approve", 42)+ expect(described_class.parse_action_id(id)).to eq(action: "approve", reviewable_id: 42)+ end++ it "rejects foreign, unknown, and malformed ids" do+ expect(described_class.parse_action_id("other::approve::1")).to be_nil+ expect(described_class.parse_action_id("ai_tool_approval::destroy::1")).to be_nil+ expect(described_class.parse_action_id("ai_tool_approval::approve::0")).to be_nil+ expect(described_class.parse_action_id(nil)).to be_nil+ end+ end++ describe ".pending_blocks" do+ it "builds an actions block with approve/reject buttons carrying the reviewable id" do+ blocks = described_class.pending_blocks(7)++ expect(blocks.first[:type]).to eq("actions")+ expect(blocks.first[:elements].map { |e| e[:action_id] }).to contain_exactly(+ "ai_tool_approval::approve::7",+ "ai_tool_approval::reject::7",+ )+ end+ end++ describe ".handle_interaction" do+ it "approves: suspends the user (credited to the approver) and resolves the message" do+ reviewable = create_reviewable+ message = message_for(reviewable)++ described_class.handle_interaction(+ interaction_for(reviewable, user: admin, action: "approve", message: message),+ )++ expect(target_user.reload.suspended?).to eq(true)++ message.reload+ expect(message.blocks).to be_blank+ expect(message.message).to include(admin.username)++ history = UserHistory.where(action: UserHistory.actions[:suspend_user]).last+ expect(history.acting_user_id).to eq(admin.id)+ expect(history.target_user_id).to eq(target_user.id)+ end++ it "rejects: resolves the message without suspending" do+ reviewable = create_reviewable+ message = message_for(reviewable)++ described_class.handle_interaction(+ interaction_for(reviewable, user: admin, action: "reject", message: message),+ )++ expect(target_user.reload.suspended?).to eq(false)+ reviewable.reload+ expect(reviewable).not_to be_pending+ expect(reviewable.status.to_s).to eq("rejected")+ expect(message.reload.blocks).to be_blank+ end++ it "does nothing for a user who cannot see the review queue" do+ reviewable = create_reviewable+ message = message_for(reviewable)++ described_class.handle_interaction(+ interaction_for(reviewable, user: non_staff, message: message),+ )++ expect(target_user.reload.suspended?).to eq(false)+ expect(reviewable.reload).to be_pending+ expect(message.reload.blocks).to be_present+ end++ it "ignores foreign action ids" do+ reviewable = create_reviewable+ message = message_for(reviewable)+ interaction =+ Chat::MessageInteraction.new(+ user: admin,+ message: message,+ action: {+ "action_id" => "some_other_plugin::approve::#{reviewable.id}",+ },+ )++ described_class.handle_interaction(interaction)++ expect(reviewable.reload).to be_pending+ expect(target_user.reload.suspended?).to eq(false)+ end++ it "does nothing for a reviewable that is no longer pending" do+ reviewable = create_reviewable+ reviewable.perform(admin, :reject)++ expect {+ described_class.handle_interaction(interaction_for(reviewable, user: admin))+ }.not_to change { target_user.reload.suspended? }+ end++ it "keeps the buttons and surfaces the real reason when the action fails" do+ reviewable = create_reviewable(username: "does_not_exist")+ message = message_for(reviewable)++ described_class.handle_interaction(+ interaction_for(reviewable, user: admin, action: "approve", message: message),+ )++ expect(reviewable.reload).to be_pending+ message.reload+ expect(message.blocks).to be_present+ # the localized tool error, not the raw "ai_tool_action_execution_error" type+ expect(message.message).to include(+ I18n.t("discourse_ai.ai_bot.suspend_user.errors.not_found"),+ )+ expect(message.message).not_to include("ai_tool_action_execution_error")+ end+ end++ describe "end-to-end via Chat::CreateMessageInteraction" do+ it "approves through the real interaction service (transaction + event)" do+ reviewable = create_reviewable+ message = message_for(reviewable)++ result =+ Chat::CreateMessageInteraction.call(+ params: {+ message_id: message.id,+ channel_id: dm_channel.id,+ action_id:+ DiscourseAi::AiBot::ChatToolApproval.build_action_id("approve", reviewable.id),+ },+ guardian: Guardian.new(admin),+ )++ expect(result.success?).to eq(true)+ expect(target_user.reload.suspended?).to eq(true)+ expect(reviewable.reload).not_to be_pending+ expect(message.reload.blocks).to be_blank+ end+ end+enddiff --git a/plugins/discourse-ai/spec/lib/modules/ai_bot/playground_spec.rb b/plugins/discourse-ai/spec/lib/modules/ai_bot/playground_spec.rbindex 226e271480f..1525253267c 100644--- a/plugins/discourse-ai/spec/lib/modules/ai_bot/playground_spec.rb+++ b/plugins/discourse-ai/spec/lib/modules/ai_bot/playground_spec.rb@@ -678,6 +678,60 @@ RSpec.describe DiscourseAi::AiBot::Playground do# thinking about thisend+ it "posts an approval message for every tool awaiting approval" do+ first_target = Fabricate(:user)+ second_target = Fabricate(:user)+ agent.update!(tools: ["SuspendUser"], require_approval: true)++ first_tool_call =+ DiscourseAi::Completions::ToolCall.new(+ name: "suspend_user",+ id: "suspend-first",+ parameters: {+ username: first_target.username,+ duration_days: 3,+ reason: "spam",+ },+ )+ second_tool_call =+ DiscourseAi::Completions::ToolCall.new(+ name: "suspend_user",+ id: "suspend-second",+ parameters: {+ username: second_target.username,+ duration_days: 3,+ reason: "spam",+ },+ )++ message =+ DiscourseAi::Completions::Llm.with_prepared_responses(+ [[first_tool_call, second_tool_call], "Both actions are awaiting approval."],+ ) { ChatSDK::Message.create(channel_id: dm_channel.id, raw: "Suspend both", guardian:) }++ message.reload+ approval_messages =+ Chat::Message.where(chat_channel: dm_channel).where.not(blocks: nil).order(:id)+ reviewable_ids = ReviewableAiToolAction.order(:id).last(2).map(&:id)++ expect(+ approval_messages.map do |approval_message|+ approval_message.blocks.first["elements"].map { |element| element["action_id"] }+ end,+ ).to eq(+ reviewable_ids.map do |reviewable_id|+ %W[+ ai_tool_approval::approve::#{reviewable_id}+ ai_tool_approval::reject::#{reviewable_id}+ ]+ end,+ )+ expect(approval_messages.map(&:thread_id)).to contain_exactly(+ message.thread_id,+ message.thread_id,+ )+ end+it "can reply to a chat message" domessage =DiscourseAi::Completions::Llm.with_prepared_responses(["World"]) do