A platform for community discussion. Free, open, simple.
FIX: Never reuse a deleted AI agent bot user id (#42853)
Régis Hanold55f1dcce56f
diff --git a/db/structure.sql b/db/structure.sqlindex 5fa8b9bf490..02acbf00d25 100644--- a/db/structure.sql+++ b/db/structure.sql@@ -23357,6 +23357,7 @@ ALTER TABLE ONLY public.ad_plugin_house_ads_groupsSET search_path TO "$user", public;INSERT INTO "schema_migrations" (version) VALUES+('20260824091843'),('20260824072257'),('20260824051214'),('20260820171539'),diff --git a/plugins/discourse-ai/admin/assets/javascripts/discourse/components/ai-agent-editor.gjs b/plugins/discourse-ai/admin/assets/javascripts/discourse/components/ai-agent-editor.gjsindex 2b09ab6e1ec..13197d19b7f 100644--- a/plugins/discourse-ai/admin/assets/javascripts/discourse/components/ai-agent-editor.gjs+++ b/plugins/discourse-ai/admin/assets/javascripts/discourse/components/ai-agent-editor.gjs@@ -236,6 +236,10 @@ export default class AgentEditor extends Component {}}+ get supportsAddressing() {+ return this.args.model.isNew || this.args.model.can_have_bot_user;+ }+get adminUser() {// Work around user not being extensible.const userClone = Object.assign({}, this.args.model?.user);@@ -1363,68 +1367,42 @@ export default class AgentEditor extends Component {<field.Control /></form.Field>- {{#unless @model.isNew}}- <form.Container- @title={{i18n "discourse_ai.ai_agent.user"}}- @tooltip={{unless- data.user- (i18n "discourse_ai.ai_agent.create_user_help")- }}- class="ai-agent-editor__ai_bot_user"- >- {{#if data.user}}- <a- class="avatar"- href={{data.user.path}}- data-user-card={{data.user.username}}- >- {{dBoundAvatarTemplate data.user.avatar_template "small"}}- </a>- <LinkTo @route="adminUser" @model={{this.adminUser}}>- {{data.user.username}}- </LinkTo>- {{else}}- <form.Button- @action={{fn this.createUser form}}- @label="discourse_ai.ai_agent.create_user"- class="btn-default ai-agent-editor__create-user"- />- {{/if}}- </form.Container>- {{/unless}}-- <form.Field- @name="allow_personal_messages"- @title={{i18n "discourse_ai.ai_agent.allow_personal_messages"}}- @tooltip={{i18n- "discourse_ai.ai_agent.allow_personal_messages_help"- }}- @showTitle={{false}}- @format="large"- @type="checkbox"- as |field|- >- <field.Control />- </form.Field>-- <form.Field- @name="allow_topic_mentions"- @title={{i18n "discourse_ai.ai_agent.allow_topic_mentions"}}- @tooltip={{i18n "discourse_ai.ai_agent.allow_topic_mentions_help"}}- @showTitle={{false}}- @format="large"- @type="checkbox"- as |field|- >- <field.Control />- </form.Field>+ {{#if this.supportsAddressing}}+ {{#unless @model.isNew}}+ <form.Container+ @title={{i18n "discourse_ai.ai_agent.user"}}+ @tooltip={{unless+ data.user+ (i18n "discourse_ai.ai_agent.create_user_help")+ }}+ class="ai-agent-editor__ai_bot_user"+ >+ {{#if data.user}}+ <a+ class="avatar"+ href={{data.user.path}}+ data-user-card={{data.user.username}}+ >+ {{dBoundAvatarTemplate data.user.avatar_template "small"}}+ </a>+ <LinkTo @route="adminUser" @model={{this.adminUser}}>+ {{data.user.username}}+ </LinkTo>+ {{else}}+ <form.Button+ @action={{fn this.createUser form}}+ @label="discourse_ai.ai_agent.create_user"+ class="btn-default ai-agent-editor__create-user"+ />+ {{/if}}+ </form.Container>+ {{/unless}}- {{#if this.chatPluginEnabled}}<form.Field- @name="allow_chat_direct_messages"- @title={{i18n "discourse_ai.ai_agent.allow_chat_direct_messages"}}+ @name="allow_personal_messages"+ @title={{i18n "discourse_ai.ai_agent.allow_personal_messages"}}@tooltip={{i18n- "discourse_ai.ai_agent.allow_chat_direct_messages_help"+ "discourse_ai.ai_agent.allow_personal_messages_help"}}@showTitle={{false}}@format="large"@@ -1435,12 +1413,10 @@ export default class AgentEditor extends Component {</form.Field><form.Field- @name="allow_chat_channel_mentions"- @title={{i18n- "discourse_ai.ai_agent.allow_chat_channel_mentions"- }}+ @name="allow_topic_mentions"+ @title={{i18n "discourse_ai.ai_agent.allow_topic_mentions"}}@tooltip={{i18n- "discourse_ai.ai_agent.allow_chat_channel_mentions_help"+ "discourse_ai.ai_agent.allow_topic_mentions_help"}}@showTitle={{false}}@format="large"@@ -1449,6 +1425,40 @@ export default class AgentEditor extends Component {><field.Control /></form.Field>++ {{#if this.chatPluginEnabled}}+ <form.Field+ @name="allow_chat_direct_messages"+ @title={{i18n+ "discourse_ai.ai_agent.allow_chat_direct_messages"+ }}+ @tooltip={{i18n+ "discourse_ai.ai_agent.allow_chat_direct_messages_help"+ }}+ @showTitle={{false}}+ @format="large"+ @type="checkbox"+ as |field|+ >+ <field.Control />+ </form.Field>++ <form.Field+ @name="allow_chat_channel_mentions"+ @title={{i18n+ "discourse_ai.ai_agent.allow_chat_channel_mentions"+ }}+ @tooltip={{i18n+ "discourse_ai.ai_agent.allow_chat_channel_mentions_help"+ }}+ @showTitle={{false}}+ @format="large"+ @type="checkbox"+ as |field|+ >+ <field.Control />+ </form.Field>+ {{/if}}{{/if}}</form.Section>diff --git a/plugins/discourse-ai/app/controllers/discourse_ai/admin/ai_agents_controller.rb b/plugins/discourse-ai/app/controllers/discourse_ai/admin/ai_agents_controller.rbindex 2fc85fe4d68..aa7b00c767b 100644--- a/plugins/discourse-ai/app/controllers/discourse_ai/admin/ai_agents_controller.rb+++ b/plugins/discourse-ai/app/controllers/discourse_ai/admin/ai_agents_controller.rb@@ -99,6 +99,8 @@ module DiscourseAienddef create_user+ raise Discourse::InvalidAccess if !@ai_agent.supports_bot_user?+user = @ai_agent.create_user!render json: BasicUserSerializer.new(user, root: "user")enddiff --git a/plugins/discourse-ai/app/models/ai_agent.rb b/plugins/discourse-ai/app/models/ai_agent.rbindex 4168fb119f0..454da7472fa 100644--- a/plugins/discourse-ai/app/models/ai_agent.rb+++ b/plugins/discourse-ai/app/models/ai_agent.rb@@ -60,6 +60,7 @@ class AiAgent < ActiveRecord::Basevalidate :subagent_ids_are_validvalidate :subagents_can_not_use_spawn_agentvalidate :rag_document_sources_count_within_limit+ validate :bot_user_supported, if: :user_id_changed?has_many :rag_document_fragments, dependent: :destroy, as: :targethas_many :rag_document_sources, dependent: :destroy, as: :target@@ -418,27 +419,25 @@ class AiAgent < ActiveRecord::Baseendend- FIRST_AGENT_USER_ID = -1200+ def self.detach_user!(user_id)+ return if where(user_id: user_id).update_all(user_id: nil) == 0- def create_user!- raise "User already exists" if user_id && User.exists?(user_id)+ agent_cache.flush!+ DiscourseAi::AiHelper::Assistant.clear_prompt_cache!+ end++ def supports_bot_user?+ return true if !system- # find the first id smaller than FIRST_USER_ID that is not taken- id = nil+ !!DiscourseAi::Agents::Agent.system_agents_by_id[id]&.supports_bot_user?+ end- id = DB.query_single(<<~SQL, FIRST_AGENT_USER_ID, FIRST_AGENT_USER_ID - 200).first- WITH seq AS (- SELECT generate_series(?, ?, -1) AS id- )- SELECT seq.id FROM seq- LEFT JOIN users ON users.id = seq.id- WHERE users.id IS NULL- ORDER BY seq.id DESC- SQL+ def can_have_bot_user?+ user.present? || supports_bot_user?+ end- id = DB.query_single(<<~SQL).first if id.nil?- SELECT min(id) - 1 FROM users- SQL+ def create_user!+ raise "User already exists" if user_id && User.exists?(user_id)# note .invalid is a reserved TLD which will route nowhereuser =@@ -449,7 +448,7 @@ class AiAgent < ActiveRecord::Baseactive: true,approved: true,trust_level: TrustLevel[4],- id: id,+ id: DiscourseAi::BotUser.next_id,)user.save!(validate: false)@@ -571,6 +570,12 @@ class AiAgent < ActiveRecord::Base)end+ def bot_user_supported+ return if user_id.blank? || supports_bot_user?++ errors.add(:base, I18n.t("discourse_ai.ai_bot.agents.bot_user_unsupported"))+ end+def chat_preconditionsif (allow_chat_channel_mentions || allow_chat_direct_messages || allow_topic_mentions ||diff --git a/plugins/discourse-ai/app/models/llm_model.rb b/plugins/discourse-ai/app/models/llm_model.rbindex 0cd1bf610bc..23ca1ff2330 100644--- a/plugins/discourse-ai/app/models/llm_model.rb+++ b/plugins/discourse-ai/app/models/llm_model.rb@@ -5,7 +5,6 @@ class LlmModel < ActiveRecord::Base# has been promoted to pre-deployself.ignored_columns = %w[enabled_chat_bot]- FIRST_BOT_USER_ID = -1200BEDROCK_PROVIDER_NAME = "aws_bedrock"BEDROCK_CONVERSE_PROVIDER_NAME = "aws_bedrock_converse"GOOGLE_VERTEX_AI_PROVIDER_NAME = "google_vertex_ai"@@ -520,13 +519,9 @@ class LlmModel < ActiveRecord::Baseif enable_checkif !user- next_id = DB.query_single(<<~SQL).first- SELECT min(id) - 1 FROM users- SQL-new_user =User.new(- id: [FIRST_BOT_USER_ID, next_id].min,+ id: DiscourseAi::BotUser.next_id,email: "no_email_#{SecureRandom.hex}",name: name.titleize,username: UserNameSuggester.suggest(name),diff --git a/plugins/discourse-ai/app/serializers/localized_ai_agent_serializer.rb b/plugins/discourse-ai/app/serializers/localized_ai_agent_serializer.rbindex 1e7209f07ae..40b0cb4a480 100644--- a/plugins/discourse-ai/app/serializers/localized_ai_agent_serializer.rb+++ b/plugins/discourse-ai/app/serializers/localized_ai_agent_serializer.rb@@ -17,6 +17,7 @@ class LocalizedAiAgentSerializer < ApplicationSerializer:top_p,:default_llm_id,:user_id,+ :can_have_bot_user?,:vision_enabled,:vision_max_pixels,:rag_chunk_tokens,diff --git a/plugins/discourse-ai/config/locales/server.en.yml b/plugins/discourse-ai/config/locales/server.en.ymlindex b186ae78b01..2459327a785 100644--- a/plugins/discourse-ai/config/locales/server.en.yml+++ b/plugins/discourse-ai/config/locales/server.en.yml@@ -472,6 +472,7 @@ en:unexpected_error: "an unexpected error occurred"agents:default_llm_required: "Default LLM model is required prior to enabling Chat"+ bot_user_unsupported: "This agent is used internally by a feature and cannot have a bot user"cannot_delete_system_agent: "System agents cannot be deleted, please disable it instead"cannot_edit_system_agent: "System agents can only be renamed, you may not edit tools or system prompt, instead disable and make a copy"cannot_have_duplicate_tools: "Can not have duplicate tools"diff --git a/plugins/discourse-ai/db/post_migrate/20260824091843_nullify_dangling_agent_user_ids.rb b/plugins/discourse-ai/db/post_migrate/20260824091843_nullify_dangling_agent_user_ids.rbnew file mode 100644index 00000000000..43b6695b4c6--- /dev/null+++ b/plugins/discourse-ai/db/post_migrate/20260824091843_nullify_dangling_agent_user_ids.rb@@ -0,0 +1,28 @@+# frozen_string_literal: true++class NullifyDanglingAgentUserIds < ActiveRecord::Migration[8.0]+ def up+ execute <<~SQL if Migration::Helpers.existing_site?+ INSERT INTO plugin_store_rows (plugin_name, key, type_name, value)+ SELECT 'discourse-ai', 'bot_user_id_floor', 'Integer',+ LEAST(+ (SELECT min(id) FROM users),+ (SELECT min(user_id) FROM ai_agents),+ (SELECT min(user_id) FROM llm_models),+ -1200+ )::text+ ON CONFLICT (plugin_name, key) DO NOTHING+ SQL++ execute <<~SQL+ UPDATE ai_agents+ SET user_id = NULL+ WHERE user_id IS NOT NULL+ AND NOT EXISTS (SELECT 1 FROM users WHERE users.id = ai_agents.user_id)+ SQL+ end++ def down+ raise ActiveRecord::IrreversibleMigration+ end+enddiff --git a/plugins/discourse-ai/lib/agents/agent.rb b/plugins/discourse-ai/lib/agents/agent.rbindex 3d935eb5787..019af8570eb 100644--- a/plugins/discourse-ai/lib/agents/agent.rb+++ b/plugins/discourse-ai/lib/agents/agent.rb@@ -42,6 +42,10 @@ module DiscourseAifalseend+ def supports_bot_user?+ agents_supporting_bot_user.any? { |klass| self <= klass }+ end+def allow_chat_channel_mentionsfalseend@@ -215,6 +219,24 @@ module DiscourseAiendend+ def agents_supporting_bot_user+ @agents_supporting_bot_user ||= [+ General,+ SqlHelper,+ Artist,+ SettingsExplorer,+ Researcher,+ Creative,+ DiscourseHelper,+ GithubHelper,+ WebArtifactCreator,+ Designer,+ ForumResearcher,+ Discover,+ DiscourseAdminAssistant,+ ].freeze+ end+def builtin_system_agents@builtin_system_agents ||= {General => -1,diff --git a/plugins/discourse-ai/lib/bot_user.rb b/plugins/discourse-ai/lib/bot_user.rbnew file mode 100644index 00000000000..18aa7a801fd--- /dev/null+++ b/plugins/discourse-ai/lib/bot_user.rb@@ -0,0 +1,32 @@+# frozen_string_literal: true++module DiscourseAi+ module BotUser+ FIRST_ID = -1200+ FLOOR_KEY = "bot_user_id_floor"++ def self.next_id+ DistributedMutex.synchronize("#{DiscourseAi::PLUGIN_NAME}_#{FLOOR_KEY}") do+ id = [claimed_id, floor].compact.min - 1+ PluginStore.set(DiscourseAi::PLUGIN_NAME, FLOOR_KEY, id)+ id+ end+ end++ def self.floor+ PluginStore.get(DiscourseAi::PLUGIN_NAME, FLOOR_KEY)+ end++ def self.claimed_id+ DB.query_single(<<~SQL, FIRST_ID).first+ SELECT LEAST(+ (SELECT min(id) FROM users),+ (SELECT min(user_id) FROM ai_agents),+ (SELECT min(user_id) FROM llm_models),+ ?+ )+ SQL+ end+ private_class_method :claimed_id+ end+enddiff --git a/plugins/discourse-ai/plugin.rb b/plugins/discourse-ai/plugin.rbindex 260f27d50b6..d2cf1698f7d 100644--- a/plugins/discourse-ai/plugin.rb+++ b/plugins/discourse-ai/plugin.rb@@ -133,8 +133,6 @@ after_initialize doregister_problem_check ProblemCheck::AiLlmStatusregister_problem_check ProblemCheck::AiLlmVisionDelegationregister_problem_check ProblemCheck::AiImageCaptionAgent- #register_problem_check ProblemCheck::AiCreditSoftLimit- #register_problem_check ProblemCheck::AiCreditHardLimitregister_reviewable_type ReviewableAiChatMessageregister_reviewable_type ReviewableAiPost@@ -148,18 +146,15 @@ after_initialize doendend- # when an account is removed, clear the user's own logs and the logs tied to- # the content being deleted with the account. the content callback runs before- # discourse reassigns/soft-deletes the user's posts, so ownership is still intact.- on(:user_destroyed) { |user| DiscourseAi::AiApiAuditLogCleaner.delete_for_user(user.id) }+ on(:user_destroyed) do |user|+ DiscourseAi::AiApiAuditLogCleaner.delete_for_user(user.id)+ AiAgent.detach_user!(user.id)+ endregister_user_destroyer_on_content_deletion_callback(Proc.new { |user| DiscourseAi::AiApiAuditLogCleaner.delete_for_user_content(user) },)- # outside account deletion, only purge logs once the content is permanently- # gone; a soft-deleted (trashed) post or topic is still recoverable, so its- # audit log must remainon(:post_destroyed) do |post|if !Post.with_deleted.exists?(post.id)DiscourseAi::AiApiAuditLogCleaner.delete_for_post(post.id)diff --git a/plugins/discourse-ai/spec/lib/agents/agent_spec.rb b/plugins/discourse-ai/spec/lib/agents/agent_spec.rbindex 7b2c2b5c6d7..380cb99734b 100644--- a/plugins/discourse-ai/spec/lib/agents/agent_spec.rb+++ b/plugins/discourse-ai/spec/lib/agents/agent_spec.rb@@ -30,6 +30,12 @@ class FakeExternalAgent < DiscourseAi::Agents::Agentendend+class FakeExternalBotAgent < FakeExternalAgent+ def self.supports_bot_user?+ true+ end+end+class TestAgent < DiscourseAi::Agents::Agentdef tools[@@ -376,18 +382,21 @@ RSpec.describe DiscourseAi::Agents::Agent dopluginend- def register_fake_feature(module_name: :test_module, feature: :test_feature)+ def register_fake_feature(+ module_name: :test_module,+ feature: :test_feature,+ agent_klass: FakeExternalAgent+ )DiscoursePluginRegistry.register_external_ai_feature(- {- module_name: module_name,- feature: feature,- agent_klass: FakeExternalAgent,- enabled_by_setting: nil,- },+ { module_name:, feature:, agent_klass:, enabled_by_setting: nil },fake_plugin,)end+ def external_agent_row(agent_klass)+ AiAgent.new(system: true, id: described_class.external_agent_id(agent_klass))+ end+def reset_external_registry!described_class.instance_variable_set(:@external_registry_signature, nil)described_class.instance_variable_set(:@system_agents, nil)@@ -452,6 +461,17 @@ RSpec.describe DiscourseAi::Agents::Agent doexpect(tool_names).to include("fake_external_tool")end+ it "lets an external agent opt into a bot user" do+ register_fake_feature(feature: :bot_feature, agent_klass: FakeExternalBotAgent)+ register_fake_feature++ opted_in = external_agent_row(FakeExternalBotAgent)+ default = external_agent_row(FakeExternalAgent)++ expect(opted_in.can_have_bot_user?).to eq(true)+ expect(default.can_have_bot_user?).to eq(false)+ end+it "produces one agent entry when two features share the same agent_klass" doregister_fake_feature(feature: :feature_one)register_fake_feature(feature: :feature_two)diff --git a/plugins/discourse-ai/spec/models/ai_agent_spec.rb b/plugins/discourse-ai/spec/models/ai_agent_spec.rbindex a956406ece2..7dc8031eb1b 100644--- a/plugins/discourse-ai/spec/models/ai_agent_spec.rb+++ b/plugins/discourse-ai/spec/models/ai_agent_spec.rb@@ -267,7 +267,89 @@ RSpec.describe AiAgent doexpect(user.username).to eq("test_bot")expect(user.name).to eq("Test")expect(user.bot?).to be(true)- expect(user.id).to be <= AiAgent::FIRST_AGENT_USER_ID+ expect(user.id).to be < DiscourseAi::BotUser::FIRST_ID+ end++ it "does not recycle an id another agent still points at" do+ other = Fabricate(:ai_agent, name: "other")+ stale_user = other.create_user!+ stale_user.destroy!+ other.update_columns(user_id: stale_user.id)+ PluginStore.remove(DiscourseAi::PLUGIN_NAME, DiscourseAi::BotUser::FLOOR_KEY)++ user = basic_agent.create_user!++ expect(user.id).to be < stale_user.id+ end++ it "does not recycle an id an llm model still points at" do+ llm_model.update!(user_id: -5000)+ PluginStore.remove(DiscourseAi::PLUGIN_NAME, DiscourseAi::BotUser::FLOOR_KEY)++ user = basic_agent.create_user!++ expect(user.id).to eq(-5001)+ end++ it "does not recycle the id of a bot user that was deleted" do+ agent = Fabricate(:ai_agent, name: "deleted")+ deleted_id = agent.create_user!.id+ UserDestroyer.new(Discourse.system_user).destroy(agent.reload.user)++ user = basic_agent.create_user!++ expect(user.id).to be < deleted_id+ end++ it "clears the reference when the bot user is destroyed" do+ agent = Fabricate(:ai_agent, name: "destroyed")+ user = agent.create_user!++ UserDestroyer.new(Discourse.system_user).destroy(user)++ expect(agent.reload.user_id).to eq(nil)+ end++ describe "#can_have_bot_user?" do+ def system_agent(klass)+ AiAgent.find(DiscourseAi::Agents::Agent.system_agents[klass])+ end++ it "is true for custom agents" do+ expect(Fabricate(:ai_agent).can_have_bot_user?).to eq(true)+ end++ it "is true for an internal agent that already owns one" do+ agent = system_agent(DiscourseAi::Agents::LocaleDetector)+ agent.update_columns(user_id: Fabricate(:user).id)++ expect(agent.can_have_bot_user?).to eq(true)+ expect(agent.supports_bot_user?).to eq(false)+ end++ it "is false when the reference dangles, so the UI matches the endpoint" do+ agent = system_agent(DiscourseAi::Agents::LocaleDetector)+ agent.update_columns(user_id: -123_456)++ expect(agent.can_have_bot_user?).to eq(false)+ end++ it "refuses to assign a bot user to an agent that has no use for one" do+ agent = system_agent(DiscourseAi::Agents::LocaleDetector)+ agent.user_id = Fabricate(:user).id++ expect(agent).not_to be_valid+ end++ it "is true for agents users talk to" do+ expect(system_agent(DiscourseAi::Agents::General).can_have_bot_user?).to eq(true)+ expect(system_agent(DiscourseAi::Agents::Discover).can_have_bot_user?).to eq(true)+ end++ it "is false for agents a feature invokes internally" do+ expect(system_agent(DiscourseAi::Agents::LocaleDetector).can_have_bot_user?).to eq(false)+ expect(system_agent(DiscourseAi::Agents::Summarizer).can_have_bot_user?).to eq(false)+ endendit "removes all rag embeddings when rag params change" dodiff --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 1a23cb0ef5f..c79676be18d 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@@ -135,6 +135,7 @@ RSpec.describe DiscourseAi::Admin::AiAgentsController doexpect(serializer_agent2["default_llm_id"]).to eq(llm_model.id)expect(serializer_agent2).not_to have_key("question_consolidator_llm_id")expect(serializer_agent2["user_id"]).to eq(agent2.user_id)+ expect(serializer_agent2["can_have_bot_user"]).to eq(true)expect(serializer_agent2["user"]["id"]).to eq(agent2.user_id)expect(serializer_agent2["forced_tool_count"]).to eq(2)@@ -422,6 +423,16 @@ RSpec.describe DiscourseAi::Admin::AiAgentsController doexpect(response).to be_successfulexpect(response.parsed_body["user"]["id"]).to eq(ai_agent.user_id)end++ it "refuses for system agents that are never talked to" do+ locale_detector =+ AiAgent.find(DiscourseAi::Agents::Agent.system_agents[DiscourseAi::Agents::LocaleDetector])++ post "/admin/plugins/discourse-ai/ai-agents/#{locale_detector.id}/create-user.json"++ expect(response.status).to eq(403)+ expect(locale_detector.reload.user_id).to eq(nil)+ endenddescribe "PUT #update" do