A platform for community discussion. Free, open, simple.
FIX: Gate AI bot user provisioning on feature settings (#44803)
Sam5e11656cae4a
diff --git a/plugins/discourse-ai/app/models/ai_agent.rb b/plugins/discourse-ai/app/models/ai_agent.rbindex 2f745665e7e..92c777f7c85 100644--- a/plugins/discourse-ai/app/models/ai_agent.rb+++ b/plugins/discourse-ai/app/models/ai_agent.rb@@ -453,7 +453,13 @@ class AiAgent < ActiveRecord::Baseendend+ def self.automatic_user_provisioning_enabled?+ SiteSetting.discourse_ai_enabled && SiteSetting.ai_bot_enabled+ end+def self.ensure_users!+ return if !automatic_user_provisioning_enabled?+where(enabled: true).find_each { |agent| agent.ensure_user! if agent.needs_user? }end@@ -475,7 +481,7 @@ class AiAgent < ActiveRecord::Baseenddef needs_user?- enabled? && supports_bot_user? &&+ self.class.automatic_user_provisioning_enabled? && enabled? && supports_bot_user? &&(force_default_llm? || allow_topic_mentions? || allow_personal_messages? ||allow_chat_direct_messages? || allow_chat_channel_mentions?diff --git a/plugins/discourse-ai/lib/ai_bot/entry_point.rb b/plugins/discourse-ai/lib/ai_bot/entry_point.rbindex 6e4d062f641..e5c8304ae91 100644--- a/plugins/discourse-ai/lib/ai_bot/entry_point.rb+++ b/plugins/discourse-ai/lib/ai_bot/entry_point.rb@@ -462,7 +462,11 @@ module DiscourseAi{ stream_completion: { actions: %w[discourse_ai/admin/ai_agents#stream_reply] } },)+ plugin.on_enabled_change { |_old_value, new_value| AiAgent.ensure_users! if new_value }+plugin.on(:site_setting_changed) do |name, old_value, new_value|+ AiAgent.ensure_users! if name == :ai_bot_enabled && new_value+if name == :ai_embeddings_selected_model && DiscourseAi::Embeddings.enabled? &&new_value != old_valueRagDocumentFragment.delete_alldiff --git a/plugins/discourse-ai/spec/db/fixtures/ai_agents_spec.rb b/plugins/discourse-ai/spec/db/fixtures/ai_agents_spec.rbnew file mode 100644index 00000000000..e24c1b9a9b7--- /dev/null+++ b/plugins/discourse-ai/spec/db/fixtures/ai_agents_spec.rb@@ -0,0 +1,32 @@+# frozen_string_literal: true++RSpec.describe AiAgent do+ subject(:seed_agents) do+ load Rails.root.join("plugins/discourse-ai/db/fixtures/agents/603_ai_agents.rb") # rubocop:disable Discourse/Plugins/UseRequireRelative+ end++ [false, true].product([false, true])+ .each do |ai_enabled, bot_enabled|+ it "seeds definitions with provisioning gated by both settings (AI: #{ai_enabled}, bot: #{bot_enabled})" do+ AiAgent.delete_all+ SiteSetting.discourse_ai_enabled = ai_enabled+ SiteSetting.ai_bot_enabled = bot_enabled++ if ai_enabled && bot_enabled+ expect { seed_agents }.to change(User, :count)++ conversational_agents = AiAgent.all.select(&:needs_user?)+ expect(conversational_agents).to be_present+ expect(conversational_agents).to all(have_attributes(user: be_present))+ expect(AiAgent.where.not(id: conversational_agents.map(&:id)).pluck(:user_id)).to all(+ be_nil,+ )+ else+ expect { seed_agents }.not_to change(User, :count)+ expect(AiAgent.pluck(:user_id)).to all(be_nil)+ end++ expect(AiAgent.pluck(:id)).to match_array(DiscourseAi::Agents::Agent.system_agents.values)+ end+ end+enddiff --git a/plugins/discourse-ai/spec/lib/ai_bot/user_flair_spec.rb b/plugins/discourse-ai/spec/lib/ai_bot/user_flair_spec.rbindex 9866ba0a353..436255800eb 100644--- a/plugins/discourse-ai/spec/lib/ai_bot/user_flair_spec.rb+++ b/plugins/discourse-ai/spec/lib/ai_bot/user_flair_spec.rb@@ -28,7 +28,8 @@ RSpec.describe DiscourseAi::AiBot::UserFlair doendit "preserves pre-upgrade historical members during a full sync" do- group = Group.find_by(name: described_class::GROUP_NAME)+ group =+ Group.find_or_create_by!(name: described_class::GROUP_NAME) { |group| group.automatic = true }group.add(bot_user, automatic: true)bot_user.update!(flair_group_id: group.id)diff --git a/plugins/discourse-ai/spec/lib/modules/ai_bot/entry_point_spec.rb b/plugins/discourse-ai/spec/lib/modules/ai_bot/entry_point_spec.rbindex 1e99b88e8ae..7a34e034d3d 100644--- a/plugins/discourse-ai/spec/lib/modules/ai_bot/entry_point_spec.rb+++ b/plugins/discourse-ai/spec/lib/modules/ai_bot/entry_point_spec.rb@@ -2,6 +2,62 @@describe DiscourseAi::AiBot::EntryPoint dodescribe "#inject_into" do+ describe "automatic agent user provisioning" do+ before do+ SiteSetting.discourse_ai_enabled = false+ SiteSetting.ai_bot_enabled = false+ end++ %i[discourse_ai_enabled ai_bot_enabled].each do |first_setting|+ it "provisions users only after enabling both settings, starting with #{first_setting}" do+ agent = Fabricate(:ai_agent)+ second_setting =+ first_setting == :discourse_ai_enabled ? :ai_bot_enabled : :discourse_ai_enabled++ expect { SiteSetting.public_send("#{first_setting}=", true) }.not_to change(User, :count)+ expect(agent.reload.user_id).to be_nil++ SiteSetting.public_send("#{second_setting}=", true)++ user = agent.reload.user+ expect(user).to be_present+ expect(user).to be_bot++ expect do+ SiteSetting.public_send("#{first_setting}=", false)+ SiteSetting.public_send("#{first_setting}=", true)+ end.not_to change(User, :count)+ expect(agent.reload.user).to eq(user)+ end+ end++ it "leaves users unprovisioned on unrelated changes and disablement" do+ SiteSetting.discourse_ai_enabled = true+ SiteSetting.ai_bot_enabled = true+ agent = Fabricate(:ai_agent)++ expect do+ SiteSetting.ai_bot_allowed_groups = Group::AUTO_GROUPS[:admins].to_s+ SiteSetting.ai_bot_enabled = false+ SiteSetting.discourse_ai_enabled = false+ end.not_to change(User, :count)+ expect(agent.reload.user_id).to be_nil+ end++ it "does not provision when settings are refreshed from the provider" do+ agent = Fabricate(:ai_agent)+ SiteSetting.provider.save(:discourse_ai_enabled, "t", SiteSetting.types[:bool])+ SiteSetting.provider.save(:ai_bot_enabled, "t", SiteSetting.types[:bool])++ expect { SiteSetting.refresh! }.not_to change(User, :count)+ expect(agent.reload.user_id).to be_nil++ AiAgent.ensure_users!++ expect(agent.reload.user).to be_present+ end+ end+describe "registers conversations as a homepage option" dofab!(:user)fab!(:bot_allowed_group, :group)diff --git a/plugins/discourse-ai/spec/models/ai_agent_multisite_spec.rb b/plugins/discourse-ai/spec/models/ai_agent_multisite_spec.rbindex 2e26a8c6994..b7e9f64b2b2 100644--- a/plugins/discourse-ai/spec/models/ai_agent_multisite_spec.rb+++ b/plugins/discourse-ai/spec/models/ai_agent_multisite_spec.rb@@ -3,6 +3,28 @@RSpec.describe AiAgent, type: :multisite dobefore { enable_current_plugin }+ it "provisions users using the current site's settings and connection" do+ SiteSetting.ai_bot_enabled = true+ default_agent = Fabricate(:ai_agent)++ test_multisite_connection("second") do+ SiteSetting.discourse_ai_enabled = true+ SiteSetting.ai_bot_enabled = false+ second_agent = Fabricate(:ai_agent)++ expect { AiAgent.ensure_users! }.not_to change(User, :count)+ expect(second_agent.reload.user_id).to be_nil++ SiteSetting.ai_bot_enabled = true++ expect(second_agent.reload.user).to be_present+ end++ expect(default_agent.reload.user_id).to be_nil+ AiAgent.ensure_users!+ expect(default_agent.reload.user).to be_present+ end+it "is able to amend settings on system agents on multisite" doagent = AiAgent.find_by(name: "Designer")expect(agent.allow_personal_messages).to eq(true)diff --git a/plugins/discourse-ai/spec/models/ai_agent_spec.rb b/plugins/discourse-ai/spec/models/ai_agent_spec.rbindex 2c55815beea..033d4cf56ce 100644--- a/plugins/discourse-ai/spec/models/ai_agent_spec.rb+++ b/plugins/discourse-ai/spec/models/ai_agent_spec.rb@@ -362,7 +362,79 @@ RSpec.describe AiAgent doendend- it "provisions a conversational agent idempotently" do+ describe ".ensure_users!" do+ [false, true].product([false, true])+ .each do |ai_enabled, bot_enabled|+ it "only provisions automatically with both settings enabled (AI: #{ai_enabled}, bot: #{bot_enabled})" do+ SiteSetting.discourse_ai_enabled = ai_enabled+ SiteSetting.ai_bot_enabled = bot_enabled+ agent = Fabricate(:ai_agent)+ provisioning_enabled = ai_enabled && bot_enabled++ expect(agent.needs_user?).to eq(provisioning_enabled)+ expect { 2.times { AiAgent.ensure_users! } }.to change(User, :count).by(+ provisioning_enabled ? 1 : 0,+ )+ expect(agent.reload.user.present?).to eq(provisioning_enabled)+ end+ end++ it "preserves existing users when automatic provisioning is disabled" do+ agent = Fabricate(:ai_agent)+ user = agent.create_user!+ SiteSetting.ai_bot_enabled = false++ expect { AiAgent.ensure_users! }.not_to change(User, :count)+ expect(agent.reload.user).to eq(user)+ expect(user.reload).to be_active+ end++ it "skips disabled, nonconversational, and unsupported system agents" do+ SiteSetting.ai_bot_enabled = true+ disabled_agent = Fabricate(:ai_agent, enabled: false)+ nonconversational_agent = Fabricate(:ai_agent, allow_personal_messages: false)+ unsupported_agent =+ AiAgent.find(DiscourseAi::Agents::Agent.system_agents[DiscourseAi::Agents::LocaleDetector])+ unsupported_agent.update!(enabled: true, allow_personal_messages: true)+ expect(unsupported_agent.needs_user?).to eq(false)++ expect { AiAgent.ensure_users! }.not_to change(User, :count)+ expect(+ [disabled_agent, nonconversational_agent, unsupported_agent].map do |agent|+ agent.reload.user_id+ end,+ ).to eq([nil, nil, nil])+ end+ end++ describe "#needs_user?" do+ it "requires a conversational entry point or a forced default model" do+ SiteSetting.ai_bot_enabled = true+ basic_agent.allow_personal_messages = false++ expect(basic_agent.needs_user?).to eq(false)++ %i[+ force_default_llm+ allow_topic_mentions+ allow_personal_messages+ allow_chat_direct_messages+ allow_chat_channel_mentions+ ].each do |field|+ basic_agent.public_send("#{field}=", true)+ expect(basic_agent.needs_user?).to eq(true), "expected #{field} to require a user"+ basic_agent.public_send("#{field}=", false)+ end++ basic_agent.allow_personal_messages = true+ basic_agent.enabled = false+ expect(basic_agent.needs_user?).to eq(false)+ end+ end++ it "provisions a conversational agent idempotently even when both features are disabled" do+ SiteSetting.discourse_ai_enabled = false+ SiteSetting.ai_bot_enabled = falseagent = Fabricate(:ai_agent, allow_personal_messages: true, default_llm: llm_model)expect { 2.times { agent.ensure_user! } }.to change { User.count }.by(1)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.rbindex ce51ab8f70e..d596b2bccd5 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@@ -10,6 +10,7 @@ RSpec.describe ReviewableAiToolAction dobefore doenable_current_pluginSiteSetting.ai_bot_enabled = true+ ai_agent.reloadenddef create_tool_action(tool_name: "close_topic", params: nil, post_id: nil)@@ -174,7 +175,7 @@ RSpec.describe ReviewableAiToolAction doendit "creates a category from an approval card authored by the agent's user" do- agent_user = ai_agent.create_user!+ agent_user = ai_agent.usersource_post = Fabricate(:post, topic: topic)tool_action =create_tool_action(@@ -201,7 +202,6 @@ RSpec.describe ReviewableAiToolAction doendit "rejects an approval card copied by an unrelated agent" do- ai_agent.create_user!other_agent_user = Fabricate(:ai_agent).create_user!source_post = Fabricate(:post, topic: topic)reviewable = create_reviewable(create_tool_action(post_id: source_post.id))@@ -221,7 +221,7 @@ RSpec.describe ReviewableAiToolAction doendit "rejects an agent's approval card copied to another topic" do- agent_user = ai_agent.create_user!+ agent_user = ai_agent.usersource_post = Fabricate(:post, topic: topic)reviewable = create_reviewable(create_tool_action(post_id: source_post.id))copied_post =@@ -470,7 +470,7 @@ RSpec.describe ReviewableAiToolAction doendit "accepts inline rejection from the agent's user" do- agent_user = ai_agent.create_user!+ agent_user = ai_agent.usersource_post = Fabricate(:post, topic: topic)reviewable = create_reviewable(create_tool_action(post_id: source_post.id))approval_post =diff --git a/plugins/discourse-ai/spec/requests/admin/ai_agents_controller_spec.rb b/plugins/discourse-ai/spec/requests/admin/ai_agents_controller_spec.rbindex eab09c43b29..d84186bcf66 100644--- a/plugins/discourse-ai/spec/requests/admin/ai_agents_controller_spec.rb+++ b/plugins/discourse-ai/spec/requests/admin/ai_agents_controller_spec.rb@@ -340,6 +340,8 @@ RSpec.describe DiscourseAi::Admin::AiAgentsController doendit "creates a new AiAgent" do+ SiteSetting.ai_bot_enabled = true+expect {post "/admin/plugins/discourse-ai/ai-agents.json",params: { ai_agent: valid_attributes }.to_json,@@ -380,6 +382,38 @@ RSpec.describe DiscourseAi::Admin::AiAgentsController do}.to change(AiAgent, :count).by(1)end+ it "creates a conversational agent without a user while the bot is disabled" do+ SiteSetting.ai_bot_enabled = false++ expect do+ post "/admin/plugins/discourse-ai/ai-agents.json",+ params: {+ ai_agent: valid_attributes,+ },+ as: :json+ end.not_to change(User, :count)++ expect(response).to have_http_status(:created)+ agent = AiAgent.find(response.parsed_body.dig("ai_agent", "id"))+ expect(agent.allow_personal_messages).to eq(true)+ expect(agent.user_id).to be_nil+ expect(response.parsed_body.dig("ai_agent", "user_id")).to be_nil+ end++ it "blocks creation while AI is disabled" do+ SiteSetting.discourse_ai_enabled = false++ expect do+ post "/admin/plugins/discourse-ai/ai-agents.json",+ params: {+ ai_agent: valid_attributes,+ },+ as: :json+ end.not_to change(AiAgent, :count)++ expect(response).to have_http_status(:not_found)+ end+it "creates with ai_agent payload on ai-agents endpoint" doexpect {post "/admin/plugins/discourse-ai/ai-agents.json",@@ -424,14 +458,29 @@ RSpec.describe DiscourseAi::Admin::AiAgentsController doenddescribe "POST #create_user" do- it "creates a user for the agent" do- post "/admin/plugins/discourse-ai/ai-agents/#{ai_agent.id}/create-user.json"+ it "explicitly creates a user for the agent while the bot is disabled" do+ SiteSetting.ai_bot_enabled = false++ expect do+ post "/admin/plugins/discourse-ai/ai-agents/#{ai_agent.id}/create-user.json"+ end.to change(User, :count).by(1)ai_agent.reloadexpect(response).to be_successfulexpect(response.parsed_body["user"]["id"]).to eq(ai_agent.user_id)end+ it "blocks explicit creation while AI is disabled" do+ SiteSetting.discourse_ai_enabled = false++ expect do+ post "/admin/plugins/discourse-ai/ai-agents/#{ai_agent.id}/create-user.json"+ end.not_to change(User, :count)++ expect(response).to have_http_status(:not_found)+ expect(ai_agent.reload.user_id).to be_nil+ end+it "refuses for system agents that are never talked to" dolocale_detector =AiAgent.find(DiscourseAi::Agents::Agent.system_agents[DiscourseAi::Agents::LocaleDetector])@@ -535,7 +584,31 @@ RSpec.describe DiscourseAi::Admin::AiAgentsController doexpect(response).to have_http_status(:ok)end+ it "updates conversational entry points without creating a user while the bot is disabled" do+ SiteSetting.ai_bot_enabled = false++ expect do+ put "/admin/plugins/discourse-ai/ai-agents/#{ai_agent.id}.json",+ params: {+ ai_agent: {+ allow_personal_messages: true,+ allow_topic_mentions: true,+ allow_chat_direct_messages: true,+ allow_chat_channel_mentions: true,+ default_llm_id: llm_model.id,+ force_default_llm: true,+ },+ }+ end.not_to change(User, :count)++ expect(response).to have_http_status(:ok)+ expect(ai_agent.reload.force_default_llm).to eq(true)+ expect(ai_agent.user_id).to be_nil+ expect(response.parsed_body.dig("ai_agent", "user_id")).to be_nil+ end+it "creates a missing bot user when forcing the default LLM" do+ SiteSetting.ai_bot_enabled = trueagent = Fabricate(:ai_agent, name: "test_bot2", user_id: nil, default_llm_id: llm_model.id)put "/admin/plugins/discourse-ai/ai-agents/#{agent.id}.json",@@ -552,6 +625,7 @@ RSpec.describe DiscourseAi::Admin::AiAgentsController doendit "creates a missing bot user when enabling mention/chat entry points" do+ SiteSetting.ai_bot_enabled = true%i[allow_topic_mentionsallow_chat_direct_messages@@ -575,6 +649,7 @@ RSpec.describe DiscourseAi::Admin::AiAgentsController doendit "creates a missing bot user for a personal-message agent" do+ SiteSetting.ai_bot_enabled = trueagent =Fabricate(:ai_agent,@@ -1120,6 +1195,23 @@ RSpec.describe DiscourseAi::Admin::AiAgentsController do}end+ [false, true].each do |bot_enabled|+ it "imports a conversational agent with automatic provisioning #{bot_enabled ? "enabled" : "disabled"}" do+ SiteSetting.ai_bot_enabled = bot_enabled++ expect do+ post "/admin/plugins/discourse-ai/ai-agents/import.json",+ params: valid_import_data,+ as: :json+ end.to change(User, :count).by(bot_enabled ? 1 : 0)++ expect(response).to have_http_status(:created)+ agent = AiAgent.find(response.parsed_body.dig("ai_agent", "id"))+ expect(agent.allow_personal_messages).to eq(true)+ expect(agent.user.present?).to eq(bot_enabled)+ end+ end+it "imports a new agent successfully" doexpect {post "/admin/plugins/discourse-ai/ai-agents/import.json",diff --git a/plugins/discourse-ai/spec/requests/topics_controller_spec.rb b/plugins/discourse-ai/spec/requests/topics_controller_spec.rbindex d410f2ca134..c0ab10d99ff 100644--- a/plugins/discourse-ai/spec/requests/topics_controller_spec.rb+++ b/plugins/discourse-ai/spec/requests/topics_controller_spec.rb@@ -13,9 +13,6 @@ RSpec.describe TopicsController dobefore { sign_in(user) }it "preloads agents without N+1 queries for an HTML request when the bot is disabled" do- get post.topic.relative_url- expect(response.status).to eq(200)-agents = []query_counts =[1, 2].map do |agent_count|@@ -28,6 +25,8 @@ RSpec.describe TopicsController dotools: [],)end+ get post.topic.relative_url+ expect(response.status).to eq(200)AiAgent.agent_cache.flush!queries = track_sql_queries { get post.topic.relative_url }