Skip to content

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

FIX: Allow AI bot conversations when PM creation is restricted (#41232)

Mark VanLandingham4dc694aa2cfc
diff --git a/lib/guardian.rb b/lib/guardian.rb
index 120767860a3..0a131d5cc40 100644
--- a/lib/guardian.rb
+++ b/lib/guardian.rb
@@ -469,7 +469,7 @@ class Guardian
##
# This should be used as a final check for when a user is sending a message
# to a target user or group.
- def can_send_private_message?(target, notify_moderators: false)
+ def can_send_private_message?(target, notify_moderators: false, private_message_context: nil)
target_is_user = target.is_a?(User)
target_is_group = target.is_a?(Group)
from_system = @user.is_system_user?
@@ -489,8 +489,22 @@ class Guardian
# even if they are not in personal_message_enabled_groups
group_is_messageable = target_is_group && Group.messageable(@user).where(id: target.id).exists?
+ plugin_can_send_private_message_to_target =
+ authenticated? &&
+ DiscoursePluginRegistry.apply_modifier(
+ :guardian_can_send_private_message_to_target,
+ false,
+ guardian: self,
+ target: target,
+ private_message_context: private_message_context,
+ notify_moderators: notify_moderators,
+ )
+
# User is authenticated and can send PMs, this can be covered by trust levels as well via AUTO_GROUPS
- (can_send_private_messages?(notify_moderators: notify_moderators) || group_is_messageable) &&
+ (
+ can_send_private_messages?(notify_moderators: notify_moderators) || group_is_messageable ||
+ plugin_can_send_private_message_to_target
+ ) &&
# User disabled private message
(is_staff? || target_is_group || target.user_option.allow_private_messages) &&
# Can't send PMs to suspended users
diff --git a/lib/post_creator.rb b/lib/post_creator.rb
index 0c70517f403..3008ec3a8e9 100644
--- a/lib/post_creator.rb
+++ b/lib/post_creator.rb
@@ -52,6 +52,7 @@ class PostCreator
# target_user_ids - array of user IDs for membership (private message, alternative to target_usernames)
# target_group_names - comma delimited list of groups for membership (private message)
# target_emails - comma delimited list of emails for membership (private message)
+ # private_message_context - optional context for plugin PM permission modifiers
# created_at - Topic creation time (optional)
# pinned_at - Topic pinned time (optional)
# pinned_globally - Is the topic pinned globally (optional)
diff --git a/lib/topic_creator.rb b/lib/topic_creator.rb
index 853a9010af5..e8179172bec 100644
--- a/lib/topic_creator.rb
+++ b/lib/topic_creator.rb
@@ -356,6 +356,7 @@ class TopicCreator
@guardian.can_send_private_message?(
obj,
notify_moderators: topic&.subtype == TopicSubtype.notify_moderators,
+ private_message_context: @opts[:private_message_context],
)
rollback_with!(topic, :cant_send_pm)
end
diff --git a/plugins/discourse-ai/app/controllers/discourse_ai/ai_bot/conversations_controller.rb b/plugins/discourse-ai/app/controllers/discourse_ai/ai_bot/conversations_controller.rb
index 47cfba9ce79..c77a62913e3 100644
--- a/plugins/discourse-ai/app/controllers/discourse_ai/ai_bot/conversations_controller.rb
+++ b/plugins/discourse-ai/app/controllers/discourse_ai/ai_bot/conversations_controller.rb
@@ -29,6 +29,16 @@ module DiscourseAi
end
end
+ def create
+ result = NewPostManager.new(current_user, create_params).perform
+ json = serialize_data(result, NewPostResultSerializer, root: false).symbolize_keys
+ status = json[:success] ? :ok : :unprocessable_entity
+ json = json[:post] if json[:success] && json[:errors].blank? &&
+ json[:action].to_s != "enqueued"
+
+ render json: json, status: status
+ end
+
def update_starred
UpdateConversationStar.call(star_service_params) do
on_success { |params:| render json: success_json.merge(starred: params.starred) }
@@ -48,6 +58,54 @@ module DiscourseAi
private
+ def create_params
+ bot_user = find_bot_user!
+ topic_custom_fields = create_topic_custom_fields
+
+ create_params = {
+ raw: params.require(:raw),
+ title: I18n.t("discourse_ai.ai_bot.default_pm_prefix"),
+ archetype: Archetype.private_message,
+ target_usernames: bot_user.username,
+ private_message_context: DiscourseAi::AiBot::PERSONAL_MESSAGE_CONTEXT,
+ guardian: guardian,
+ first_post_checks: true,
+ advance_draft: true,
+ ip_address: request.remote_ip,
+ user_agent: request.user_agent,
+ referrer: request.env["HTTP_REFERER"],
+ writing_device: BrowserDetection.device(request.user_agent),
+ }
+
+ if topic_custom_fields.present?
+ create_params[:topic_opts] = { custom_fields: topic_custom_fields }
+ end
+
+ create_params
+ end
+
+ def find_bot_user!
+ username = params.require(:target_username).to_s.downcase
+ bot_user = User.find_by(username_lower: username)
+ raise Discourse::InvalidParameters.new(:target_username) if bot_user.blank?
+
+ guardian.ensure_can_send_pm_to_ai_bot!(bot_user)
+
+ bot_user
+ end
+
+ def create_topic_custom_fields
+ return {} if params[:ai_agent_id].blank?
+
+ agent_id = params[:ai_agent_id].to_i
+ agent = DiscourseAi::Agents::Agent.find_by(user: current_user, id: agent_id)
+ if agent.blank? || !agent.allow_personal_messages
+ raise Discourse::InvalidParameters.new(:ai_agent_id)
+ end
+
+ { "ai_agent_id" => agent.id }
+ end
+
def star_service_params
service_params.deep_merge(params: { topic_id: params[:topic_id] })
end
diff --git a/plugins/discourse-ai/assets/javascripts/discourse/services/ai-bot-conversations-hidden-submit.js b/plugins/discourse-ai/assets/javascripts/discourse/services/ai-bot-conversations-hidden-submit.js
index af188909892..727798fa97f 100644
--- a/plugins/discourse-ai/assets/javascripts/discourse/services/ai-bot-conversations-hidden-submit.js
+++ b/plugins/discourse-ai/assets/javascripts/discourse/services/ai-bot-conversations-hidden-submit.js
@@ -69,16 +69,12 @@ export default class AiBotConversationsHiddenSubmit extends Service {
}
try {
- const response = await ajax("/posts.json", {
+ const response = await ajax("/discourse-ai/ai-bot/conversations.json", {
method: "POST",
data: {
raw: rawContent,
- title,
- archetype: "private_message",
- target_recipients: this.targetUsername,
- meta_data: {
- ai_agent_id: this.agentId,
- },
+ target_username: this.targetUsername,
+ ai_agent_id: this.agentId,
},
});
diff --git a/plugins/discourse-ai/config/routes.rb b/plugins/discourse-ai/config/routes.rb
index afe7f28dc7e..5ca6a62563f 100644
--- a/plugins/discourse-ai/config/routes.rb
+++ b/plugins/discourse-ai/config/routes.rb
@@ -46,6 +46,7 @@ DiscourseAi::Engine.routes.draw do
scope module: :ai_bot, path: "/ai-bot/conversations" do
get "/" => "conversations#index"
+ post "/" => "conversations#create"
put "/:topic_id/starred" => "conversations#update_starred"
end
diff --git a/plugins/discourse-ai/lib/ai_bot.rb b/plugins/discourse-ai/lib/ai_bot.rb
index d4940732653..ad88c3e4247 100644
--- a/plugins/discourse-ai/lib/ai_bot.rb
+++ b/plugins/discourse-ai/lib/ai_bot.rb
@@ -7,5 +7,6 @@ module DiscourseAi
POST_AI_LLM_NAME_FIELD = "ai_llm_name"
POST_AI_LLM_MODEL_ID_FIELD = "ai_llm_model_id"
POST_AI_AGENT_ID_FIELD = "ai_agent_id"
+ PERSONAL_MESSAGE_CONTEXT = "discourse_ai.ai_bot_personal_message"
end
end
diff --git a/plugins/discourse-ai/lib/ai_bot/entry_point.rb b/plugins/discourse-ai/lib/ai_bot/entry_point.rb
index c68d1c220cf..d934d971d7b 100644
--- a/plugins/discourse-ai/lib/ai_bot/entry_point.rb
+++ b/plugins/discourse-ai/lib/ai_bot/entry_point.rb
@@ -42,6 +42,29 @@ module DiscourseAi
SQL
end
+ def self.personal_message_bot_user_ids(user)
+ return [] if user.blank? || !SiteSetting.ai_bot_enabled
+
+ bot_user_ids = []
+
+ if user.in_any_groups?(SiteSetting.ai_bot_allowed_groups_map)
+ bot_user_ids.concat(
+ LlmModel
+ .where(id: LlmModel.enabled_chat_bot_ids)
+ .where.not(user_id: nil)
+ .pluck(:user_id),
+ )
+ end
+
+ bot_user_ids.concat(
+ AiAgent
+ .allowed_modalities(user: user, allow_personal_messages: true)
+ .map { |agent| agent[:user_id] },
+ )
+
+ bot_user_ids.compact
+ end
+
# Most errors are simply "not_allowed"
# we do not want to reveal information about this system
# the 2 exceptions are "other_people_in_pm" and "other_content_in_pm"
@@ -87,6 +110,14 @@ module DiscourseAi
SQL
end
+ plugin.register_modifier(:guardian_can_send_private_message_to_target) do |allowed, params|
+ allowed ||
+ (
+ params[:private_message_context] == PERSONAL_MESSAGE_CONTEXT &&
+ params[:guardian].can_send_pm_to_ai_bot?(params[:target])
+ )
+ end
+
plugin.on(:topic_created) do |topic|
next if !topic.private_message?
creator = topic.user
diff --git a/plugins/discourse-ai/lib/guardian_extensions.rb b/plugins/discourse-ai/lib/guardian_extensions.rb
index 2b857b96858..992f8480aa0 100644
--- a/plugins/discourse-ai/lib/guardian_extensions.rb
+++ b/plugins/discourse-ai/lib/guardian_extensions.rb
@@ -73,6 +73,14 @@ module DiscourseAi
user.in_any_groups?(SiteSetting.ai_bot_debugging_allowed_groups_map)
end
+ def can_send_pm_to_ai_bot?(target)
+ return false if anonymous?
+ return false if !SiteSetting.discourse_ai_enabled || !SiteSetting.ai_bot_enabled
+ return false if !target.is_a?(::User)
+
+ DiscourseAi::AiBot::EntryPoint.personal_message_bot_user_ids(user).include?(target.id)
+ end
+
def can_share_ai_bot_conversation?(target)
return false if anonymous?
diff --git a/plugins/discourse-ai/spec/requests/ai_bot/conversation_creation_spec.rb b/plugins/discourse-ai/spec/requests/ai_bot/conversation_creation_spec.rb
new file mode 100644
index 00000000000..40b208d554b
--- /dev/null
+++ b/plugins/discourse-ai/spec/requests/ai_bot/conversation_creation_spec.rb
@@ -0,0 +1,153 @@
+# frozen_string_literal: true
+
+RSpec.describe "AI bot conversation creation" do
+ fab!(:current_user) { Fabricate(:user, refresh_auto_groups: true) }
+ fab!(:other_user, :user)
+ fab!(:llm_model) { Fabricate(:llm_model, name: "gpt-4") }
+
+ before do
+ enable_current_plugin
+ toggle_enabled_bots(bots: [llm_model])
+ SiteSetting.ai_bot_allowed_groups = Group::AUTO_GROUPS[:trust_level_0]
+ SiteSetting.personal_message_enabled_groups = Group::AUTO_GROUPS[:staff]
+ sign_in(current_user)
+ end
+
+ it "denies regular PM creation" do
+ expect do
+ post "/posts.json",
+ params: {
+ raw: "This normal personal message should not be created.",
+ title: "Normal personal message",
+ archetype: Archetype.private_message,
+ target_recipients: other_user.username,
+ }
+ end.not_to change { Topic.private_messages_for_user(current_user).count }
+
+ expect(response.status).to eq(422)
+ expect(response.parsed_body["errors"]).to include(
+ I18n.t("activerecord.errors.models.topic.attributes.base.cant_send_pm"),
+ )
+
+ expect do
+ post "/discourse-ai/ai-bot/conversations.json",
+ params: {
+ raw: "This bot conversation route must not create a regular PM.",
+ target_username: other_user.username,
+ }
+ end.not_to change { Topic.private_messages_for_user(current_user).count }
+
+ expect(response.status).to eq(403)
+ end
+
+ it "keeps regular AI bot PM creation denied through the posts endpoint" do
+ bot_user = llm_model.reload.user
+
+ expect do
+ post "/posts.json",
+ params: {
+ raw: "This AI bot personal message should not be created through posts.",
+ title: "AI bot personal message",
+ archetype: Archetype.private_message,
+ target_recipients: bot_user.username,
+ }
+ end.not_to change { Topic.private_messages_for_user(current_user).count }
+
+ expect(response.status).to eq(422)
+ expect(response.parsed_body["errors"]).to include(
+ I18n.t("activerecord.errors.models.topic.attributes.base.cant_send_pm"),
+ )
+ end
+
+ it "allows creating and using an AI bot conversation" do
+ bot_user = llm_model.reload.user
+
+ expect do
+ post "/discourse-ai/ai-bot/conversations.json",
+ params: {
+ raw: "Please help me with this AI bot conversation.",
+ target_username: bot_user.username,
+ }
+ end.to change { Topic.private_messages_for_user(current_user).count }.by(1)
+
+ expect(response.status).to eq(200)
+ topic = Topic.find(response.parsed_body["topic_id"])
+ expect(topic.allowed_users).to contain_exactly(current_user, bot_user)
+ expect(topic.custom_fields[DiscourseAi::AiBot::TOPIC_AI_BOT_PM_FIELD]).to eq("t")
+
+ get "/discourse-ai/ai-bot/conversations.json"
+
+ expect(response.status).to eq(200)
+ expect(
+ response.parsed_body["conversations"].map { |conversation| conversation["id"] },
+ ).to include(topic.id)
+
+ post "/posts.json",
+ params: {
+ raw: "Here is a follow-up message for the AI bot.",
+ topic_id: topic.id,
+ }
+
+ expect(response.status).to eq(200)
+ expect(response.parsed_body["topic_id"]).to eq(topic.id)
+ end
+
+ it "allows a PM-enabled agent without a bot user" do
+ bot_user = llm_model.reload.user
+ agent =
+ Fabricate(
+ :ai_agent,
+ allowed_group_ids: [Group::AUTO_GROUPS[:trust_level_0]],
+ allow_personal_messages: true,
+ )
+
+ expect do
+ post "/discourse-ai/ai-bot/conversations.json",
+ params: {
+ raw: "Please run this PM-enabled agent in a bot conversation.",
+ target_username: bot_user.username,
+ ai_agent_id: agent.id,
+ }
+ end.to change { Topic.private_messages_for_user(current_user).count }.by(1)
+
+ expect(response.status).to eq(200)
+ topic = Topic.find(response.parsed_body["topic_id"])
+ expect(topic.custom_fields["ai_agent_id"]).to eq(agent.id.to_s)
+ end
+
+ it "rejects a forged visible agent that is not allowed in personal messages" do
+ bot_user = llm_model.reload.user
+ forged_agent =
+ Fabricate(
+ :ai_agent,
+ allowed_group_ids: [Group::AUTO_GROUPS[:trust_level_0]],
+ allow_personal_messages: false,
+ )
+
+ expect do
+ post "/discourse-ai/ai-bot/conversations.json",
+ params: {
+ raw: "Please run this forged agent in a bot conversation.",
+ target_username: bot_user.username,
+ ai_agent_id: forged_agent.id,
+ }
+ end.not_to change { Topic.private_messages_for_user(current_user).count }
+
+ expect(response.status).to eq(400)
+ end
+
+ it "uses AI bot access settings for bot conversations" do
+ SiteSetting.ai_bot_allowed_groups = Group::AUTO_GROUPS[:staff]
+ bot_user = llm_model.reload.user
+
+ expect do
+ post "/discourse-ai/ai-bot/conversations.json",
+ params: {
+ raw: "Please help me with this AI bot conversation.",
+ target_username: bot_user.username,
+ }
+ end.not_to change { Topic.private_messages_for_user(current_user).count }
+
+ expect(response.status).to eq(403)
+ end
+end
diff --git a/plugins/discourse-ai/test/javascripts/acceptance/ai-bot-conversations-test.js b/plugins/discourse-ai/test/javascripts/acceptance/ai-bot-conversations-test.js
index 6afac86c5ce..4199942a462 100644
--- a/plugins/discourse-ai/test/javascripts/acceptance/ai-bot-conversations-test.js
+++ b/plugins/discourse-ai/test/javascripts/acceptance/ai-bot-conversations-test.js
@@ -5,7 +5,7 @@ import { acceptance } from "discourse/tests/helpers/qunit-helpers";
const INPUT = "#ai-bot-conversations-input";
acceptance("AI Bot - Conversations IME handling", function (needs) {
- let postRequests = 0;
+ let conversationRequests = 0;
needs.user({
ai_enabled_agents: [],
@@ -33,8 +33,8 @@ acceptance("AI Bot - Conversations IME handling", function (needs) {
})
);
- server.post("/posts.json", () => {
- postRequests += 1;
+ server.post("/discourse-ai/ai-bot/conversations.json", () => {
+ conversationRequests += 1;
return helper.response({
id: 1,
topic_id: 1,
@@ -46,7 +46,7 @@ acceptance("AI Bot - Conversations IME handling", function (needs) {
server.get("/t/:slug/:id.json", () => helper.response({}));
});
- needs.hooks.beforeEach(() => (postRequests = 0));
+ needs.hooks.beforeEach(() => (conversationRequests = 0));
async function prepareDraft() {
await visit("/discourse-ai/ai-bot/conversations");
@@ -59,7 +59,7 @@ acceptance("AI Bot - Conversations IME handling", function (needs) {
await triggerEvent(INPUT, "keydown", { key: "Enter" });
await triggerEvent(INPUT, "beforeinput", { inputType: "insertLineBreak" });
- assert.strictEqual(postRequests, 1, "submitted once");
+ assert.strictEqual(conversationRequests, 1, "submitted once");
});
test("Shift+Enter does not submit", async function (assert) {
@@ -68,7 +68,7 @@ acceptance("AI Bot - Conversations IME handling", function (needs) {
await triggerEvent(INPUT, "keydown", { key: "Enter", shiftKey: true });
await triggerEvent(INPUT, "beforeinput", { inputType: "insertLineBreak" });
- assert.strictEqual(postRequests, 0, "did not submit");
+ assert.strictEqual(conversationRequests, 0, "did not submit");
});
test("IME-confirming Enter does not submit", async function (assert) {
@@ -79,6 +79,6 @@ acceptance("AI Bot - Conversations IME handling", function (needs) {
inputType: "insertCompositionText",
});
- assert.strictEqual(postRequests, 0, "did not submit");
+ assert.strictEqual(conversationRequests, 0, "did not submit");
});
});
diff --git a/spec/lib/guardian_spec.rb b/spec/lib/guardian_spec.rb
index f8a4f7e7d00..48004f03515 100644
--- a/spec/lib/guardian_spec.rb
+++ b/spec/lib/guardian_spec.rb
@@ -200,6 +200,47 @@ RSpec.describe Guardian do
DiscoursePluginRegistry.unregister_modifier(plugin, modifier, &allow_block)
end
+ it "allows plugins to control a target-specific PM context" do
+ SiteSetting.personal_message_enabled_groups = Group::AUTO_GROUPS[:staff]
+ target_context_modifier = :guardian_can_send_private_message_to_target
+ target_context_block =
+ Proc.new do |allowed, params|
+ allowed ||
+ (
+ params[:guardian].user == user && params[:target] == another_user &&
+ params[:private_message_context] == :plugin_context
+ )
+ end
+
+ DiscoursePluginRegistry.register_modifier(
+ plugin,
+ target_context_modifier,
+ &target_context_block
+ )
+
+ expect(Guardian.new(user).can_send_private_message?(another_user)).to eq(false)
+ expect(
+ Guardian.new(user).can_send_private_message?(
+ another_user,
+ private_message_context: :plugin_context,
+ ),
+ ).to eq(true)
+
+ another_user.user_option.update!(allow_private_messages: false)
+ expect(
+ Guardian.new(user).can_send_private_message?(
+ another_user,
+ private_message_context: :plugin_context,
+ ),
+ ).to eq(false)
+ ensure
+ DiscoursePluginRegistry.unregister_modifier(
+ plugin,
+ target_context_modifier,
+ &target_context_block
+ )
+ end
+
context "when personal_message_enabled_groups does not contain the user" do
let(:group) { Fabricate(:group) }
before { SiteSetting.personal_message_enabled_groups = group.id }