Skip to content

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

FEATURE: Add chat bot discovery controls (#45538)

Sambcd75aac9a44
diff --git a/app/controllers/admin/users_controller.rb b/app/controllers/admin/users_controller.rb
index 26d0ff9bb08..289522ef541 100644
--- a/app/controllers/admin/users_controller.rb
+++ b/app/controllers/admin/users_controller.rb
@@ -75,13 +75,17 @@ class Admin::UsersController < Admin::StaffController
end
def create_bot
- bot = params.expect(bot: %i[name username trust_level])
+ plugin_param_names = DiscoursePluginRegistry.bot_creation_params.keys
+ bot = params.expect(bot: %i[name username trust_level] + plugin_param_names)
+ plugin_params = bot.extract!(*plugin_param_names).to_h
# Request uses `key`, as `api_key` would be read as an authentication credential.
key = params[:key]
raise Discourse::InvalidParameters.new(:key) if key && !key.is_a?(ActionController::Parameters)
- User::CreateBot.call(service_params.merge(params: bot.to_h.merge(api_key: key&.to_unsafe_h))) do
+ User::CreateBot.call(
+ service_params.merge(params: bot.to_h.merge(api_key: key&.to_unsafe_h, plugin_params:)),
+ ) do
on_success do |user:, api_key: nil|
render json: {
user: AdminUserSerializer.new(user, scope: guardian, root: false).as_json,
diff --git a/app/services/user/create_bot.rb b/app/services/user/create_bot.rb
index 3357165cb90..fa9877b17fe 100644
--- a/app/services/user/create_bot.rb
+++ b/app/services/user/create_bot.rb
@@ -10,6 +10,7 @@ class User::CreateBot
attribute :name, :string
attribute :username, :string
attribute :trust_level, :integer, default: -> { SiteSetting.default_trust_level }
+ attribute :plugin_params, default: -> { {} }
attribute :api_key, :hash do
attribute :description, :string
attribute :scope_mode, :string
@@ -32,6 +33,7 @@ class User::CreateBot
transaction do
model :user, :create_bot
step :log_creation
+ step :apply_plugin_params
only_if(:api_key_requested) do
model :api_key, :create_api_key
step :log_api_key_creation
@@ -75,6 +77,14 @@ class User::CreateBot
StaffActionLogger.new(guardian.user).log_bot_creation(user)
end
+ def apply_plugin_params(params:, user:)
+ params.plugin_params.each do |name, value|
+ registration = DiscoursePluginRegistry.bot_creation_params[name.to_sym]
+ next unless registration && registration[:plugin].enabled?
+ registration[:callback].call(user, value)
+ end
+ end
+
def api_key_requested(params:)
params.api_key.present?
end
diff --git a/db/structure.sql b/db/structure.sql
index 07bbacae356..a452346540d 100644
--- a/db/structure.sql
+++ b/db/structure.sql
@@ -3465,6 +3465,37 @@ CREATE SEQUENCE public.chat_channels_id_seq
ALTER SEQUENCE public.chat_channels_id_seq OWNED BY public.chat_channels.id;
+--
+-- Name: chat_discoverable_bots; Type: TABLE; Schema: public; Owner: -
+--
+
+CREATE TABLE public.chat_discoverable_bots (
+ id bigint NOT NULL,
+ user_id integer NOT NULL,
+ created_at timestamp(6) without time zone NOT NULL,
+ updated_at timestamp(6) without time zone NOT NULL
+);
+
+
+--
+-- Name: chat_discoverable_bots_id_seq; Type: SEQUENCE; Schema: public; Owner: -
+--
+
+CREATE SEQUENCE public.chat_discoverable_bots_id_seq
+ START WITH 1
+ INCREMENT BY 1
+ NO MINVALUE
+ NO MAXVALUE
+ CACHE 1;
+
+
+--
+-- Name: chat_discoverable_bots_id_seq; Type: SEQUENCE OWNED BY; Schema: public; Owner: -
+--
+
+ALTER SEQUENCE public.chat_discoverable_bots_id_seq OWNED BY public.chat_discoverable_bots.id;
+
+
--
-- Name: chat_drafts; Type: TABLE; Schema: public; Owner: -
--
@@ -14872,6 +14903,13 @@ ALTER TABLE ONLY public.chat_channel_custom_fields ALTER COLUMN id SET DEFAULT n
ALTER TABLE ONLY public.chat_channels ALTER COLUMN id SET DEFAULT nextval('public.chat_channels_id_seq'::regclass);
+--
+-- Name: chat_discoverable_bots id; Type: DEFAULT; Schema: public; Owner: -
+--
+
+ALTER TABLE ONLY public.chat_discoverable_bots ALTER COLUMN id SET DEFAULT nextval('public.chat_discoverable_bots_id_seq'::regclass);
+
+
--
-- Name: chat_drafts id; Type: DEFAULT; Schema: public; Owner: -
--
@@ -17549,6 +17587,14 @@ ALTER TABLE ONLY public.chat_channels
ADD CONSTRAINT chat_channels_pkey PRIMARY KEY (id);
+--
+-- Name: chat_discoverable_bots chat_discoverable_bots_pkey; Type: CONSTRAINT; Schema: public; Owner: -
+--
+
+ALTER TABLE ONLY public.chat_discoverable_bots
+ ADD CONSTRAINT chat_discoverable_bots_pkey PRIMARY KEY (id);
+
+
--
-- Name: chat_drafts chat_drafts_pkey; Type: CONSTRAINT; Schema: public; Owner: -
--
@@ -22084,6 +22130,13 @@ CREATE UNIQUE INDEX index_chat_channels_on_slug ON public.chat_channels USING bt
CREATE INDEX index_chat_channels_on_status ON public.chat_channels USING btree (status);
+--
+-- Name: index_chat_discoverable_bots_on_user_id; Type: INDEX; Schema: public; Owner: -
+--
+
+CREATE UNIQUE INDEX index_chat_discoverable_bots_on_user_id ON public.chat_discoverable_bots USING btree (user_id);
+
+
--
-- Name: index_chat_mention_notifications_on_chat_mention_id; Type: INDEX; Schema: public; Owner: -
--
@@ -26582,6 +26635,7 @@ ALTER TABLE ONLY public.ad_plugin_house_ads_groups
SET search_path TO "$user", public;
INSERT INTO "schema_migrations" (version) VALUES
+('20261104011110'),
('20261102174233'),
('20261030215104'),
('20261030183551'),
diff --git a/frontend/discourse/admin/components/admin-bot-form.gjs b/frontend/discourse/admin/components/admin-bot-form.gjs
index 478a878b3c9..5f9eb0119cd 100644
--- a/frontend/discourse/admin/components/admin-bot-form.gjs
+++ b/frontend/discourse/admin/components/admin-bot-form.gjs
@@ -11,10 +11,13 @@ import {
validateGranularScopes,
} from "discourse/admin/lib/api-key-scopes";
import Form from "discourse/components/form";
+import PluginOutlet from "discourse/components/plugin-outlet";
+import lazyHash from "discourse/helpers/lazy-hash";
import { ajax } from "discourse/lib/ajax";
import { extractError } from "discourse/lib/ajax-error";
import discourseDebounce from "discourse/lib/debounce";
import { withoutPrefix } from "discourse/lib/get-url";
+import { applyValueTransformer } from "discourse/lib/transformer";
import DiscourseURL, { applyQueryParams } from "discourse/lib/url";
import DButton from "discourse/ui-kit/d-button";
import { i18n } from "discourse-i18n";
@@ -80,11 +83,15 @@ export default class AdminBotForm extends Component {
@action
async createBot(data) {
const payload = {
- bot: {
- name: data.name,
- username: data.username,
- trust_level: Number(data.trust_level),
- },
+ bot: applyValueTransformer(
+ "admin-new-bot-params",
+ {
+ name: data.name,
+ username: data.username,
+ trust_level: Number(data.trust_level),
+ },
+ { data }
+ ),
};
if (data.generate_api_key) {
@@ -244,6 +251,11 @@ export default class AdminBotForm extends Component {
</field.Control>
</form.Field>
+ <PluginOutlet
+ @name="admin-bot-form-fields"
+ @outletArgs={{lazyHash form=form transientData=transientData}}
+ />
+
<form.Field
@description={{i18n "admin.users.bots.generate_api_key_description"}}
@format="large"
diff --git a/frontend/discourse/app/lib/registry/transformers.ts b/frontend/discourse/app/lib/registry/transformers.ts
index 49415a89ddc..326a42fe0bc 100644
--- a/frontend/discourse/app/lib/registry/transformers.ts
+++ b/frontend/discourse/app/lib/registry/transformers.ts
@@ -43,6 +43,7 @@ export const BEHAVIOR_TRANSFORMERS = Object.freeze([
export const VALUE_TRANSFORMERS = Object.freeze([
"admin-dashboard-report-renderer",
"admin-new-bot-options",
+ "admin-new-bot-params",
"admin-onboarding-banner-location",
"admin-onboarding-start-posting-options",
"admin-onboarding-steps",
diff --git a/frontend/discourse/tests/acceptance/admin-bots-new-test.js b/frontend/discourse/tests/acceptance/admin-bots-new-test.js
index 9b7d002bf81..55f7ffb2b30 100644
--- a/frontend/discourse/tests/acceptance/admin-bots-new-test.js
+++ b/frontend/discourse/tests/acceptance/admin-bots-new-test.js
@@ -287,6 +287,21 @@ acceptance("Admin - New bot", function (needs) {
);
});
+ test("plugins can add values to the bot payload", async function (assert) {
+ withPluginApi((api) => {
+ api.registerValueTransformer(
+ "admin-new-bot-params",
+ ({ value, context }) => ({ ...value, extra: context.data.username })
+ );
+ });
+
+ await visit("/admin/users/bots/new");
+ await formKit(FORM).field("username").fillIn("plugin_bot");
+ await formKit(FORM).submit();
+
+ assert.strictEqual(payloads[0].bot.extra, "plugin_bot");
+ });
+
test("suggests a username from the name until one is typed", async function (assert) {
await visit("/admin/users/bots/new");
const form = formKit(FORM);
diff --git a/lib/discourse_plugin_registry.rb b/lib/discourse_plugin_registry.rb
index aa7a3db0ee5..15875b3fda9 100644
--- a/lib/discourse_plugin_registry.rb
+++ b/lib/discourse_plugin_registry.rb
@@ -80,6 +80,7 @@ class DiscoursePluginRegistry
define_register :admin_config_login_routes, Set
define_register :discourse_dev_populate_reviewable_types, Set
define_register :category_update_param_with_callback, Hash
+ define_register :bot_creation_params, Hash
define_filtered_register :staff_user_custom_fields
define_filtered_register :public_user_custom_fields
diff --git a/lib/plugin/instance.rb b/lib/plugin/instance.rb
index ddd6dd889af..92db8ff5a02 100644
--- a/lib/plugin/instance.rb
+++ b/lib/plugin/instance.rb
@@ -448,6 +448,14 @@ class Plugin::Instance
end
end
+ # Accept a scalar bot[<param_name>] when admins create a bot. The callback receives the bot
+ # and the value inside the creation transaction; raising rolls the creation back.
+ def register_bot_creation_param(param_name, &callback)
+ reloadable_patch do |plugin|
+ DiscoursePluginRegistry.bot_creation_params[param_name] = { plugin:, callback: }
+ end
+ end
+
def register_upload_unused(&block)
Upload.add_unused_callback(&block)
end
diff --git a/plugins/chat/admin/assets/javascripts/discourse/connectors/admin-bot-form-fields/chat-discoverable-field.gjs b/plugins/chat/admin/assets/javascripts/discourse/connectors/admin-bot-form-fields/chat-discoverable-field.gjs
new file mode 100644
index 00000000000..070cfc9b4e2
--- /dev/null
+++ b/plugins/chat/admin/assets/javascripts/discourse/connectors/admin-bot-form-fields/chat-discoverable-field.gjs
@@ -0,0 +1,20 @@
+import Component from "@glimmer/component";
+import { i18n } from "discourse-i18n";
+
+export default class ChatDiscoverableField extends Component {
+ static shouldRender(args, { siteSettings }) {
+ return siteSettings.chat_enabled;
+ }
+
+ <template>
+ <@outletArgs.form.Field
+ @format="large"
+ @name="chat_discoverable"
+ @title={{i18n "chat.admin.bot_discoverability.description"}}
+ @type="checkbox"
+ as |field|
+ >
+ <field.Control />
+ </@outletArgs.form.Field>
+ </template>
+}
diff --git a/plugins/chat/admin/assets/javascripts/discourse/connectors/admin-user-details/chat-bot-discoverability.gjs b/plugins/chat/admin/assets/javascripts/discourse/connectors/admin-user-details/chat-bot-discoverability.gjs
new file mode 100644
index 00000000000..056285d8816
--- /dev/null
+++ b/plugins/chat/admin/assets/javascripts/discourse/connectors/admin-user-details/chat-bot-discoverability.gjs
@@ -0,0 +1,56 @@
+import Component from "@glimmer/component";
+import { tracked } from "@glimmer/tracking";
+import { on } from "@ember/modifier";
+import { action } from "@ember/object";
+import { ajax } from "discourse/lib/ajax";
+import { popupAjaxError } from "discourse/lib/ajax-error";
+import DToggleSwitch from "discourse/ui-kit/d-toggle-switch";
+import { i18n } from "discourse-i18n";
+
+export default class ChatBotDiscoverability extends Component {
+ // The server only sends this to admins, for eligible bots, while chat is enabled.
+ static shouldRender(args) {
+ return args.model.chat_discoverable !== undefined;
+ }
+
+ @tracked saving = false;
+
+ @action
+ async toggleDiscoverability() {
+ const model = this.args.outletArgs.model;
+ const discoverable = !model.chat_discoverable;
+ model.set("chat_discoverable", discoverable);
+ this.saving = true;
+ try {
+ await ajax(`/chat/admin/bots/${model.id}/discoverability.json`, {
+ type: "PUT",
+ data: { discoverable },
+ });
+ } catch (error) {
+ model.set("chat_discoverable", !discoverable);
+ popupAjaxError(error);
+ } finally {
+ this.saving = false;
+ }
+ }
+
+ <template>
+ <section class="details chat-bot-discoverability">
+ <h1>{{i18n "chat.admin.title"}}</h1>
+ <div class="display-row">
+ <div class="field">{{i18n "chat.admin.bot_discoverability.label"}}</div>
+ <div class="value">
+ <DToggleSwitch
+ aria-label={{i18n "chat.admin.bot_discoverability.label"}}
+ disabled={{this.saving}}
+ @state={{@outletArgs.model.chat_discoverable}}
+ {{on "click" this.toggleDiscoverability}}
+ />
+ </div>
+ <div class="controls">{{i18n
+ "chat.admin.bot_discoverability.description"
+ }}</div>
+ </div>
+ </section>
+ </template>
+}
diff --git a/plugins/chat/admin/assets/javascripts/discourse/initializers/chat-admin-new-bot-params.js b/plugins/chat/admin/assets/javascripts/discourse/initializers/chat-admin-new-bot-params.js
new file mode 100644
index 00000000000..d27b84869ca
--- /dev/null
+++ b/plugins/chat/admin/assets/javascripts/discourse/initializers/chat-admin-new-bot-params.js
@@ -0,0 +1,15 @@
+import { apiInitializer } from "discourse/lib/api";
+
+export default apiInitializer((api) => {
+ if (!api.container.lookup("service:site-settings").chat_enabled) {
+ return;
+ }
+
+ api.registerValueTransformer(
+ "admin-new-bot-params",
+ ({ value, context }) => ({
+ ...value,
+ chat_discoverable: Boolean(context.data.chat_discoverable),
+ })
+ );
+});
diff --git a/plugins/chat/app/controllers/chat/admin/bot_discoverability_controller.rb b/plugins/chat/app/controllers/chat/admin/bot_discoverability_controller.rb
new file mode 100644
index 00000000000..c2cd3b086bc
--- /dev/null
+++ b/plugins/chat/app/controllers/chat/admin/bot_discoverability_controller.rb
@@ -0,0 +1,14 @@
+# frozen_string_literal: true
+
+class Chat::Admin::BotDiscoverabilityController < ::Admin::AdminController
+ requires_plugin Chat::PLUGIN_NAME
+
+ def update
+ Chat::UpdateBotDiscoverability.call(service_params) do
+ on_success { head :no_content }
+ on_failed_policy(:can_manage_bots) { raise Discourse::InvalidAccess }
+ on_model_not_found(:bot) { raise Discourse::NotFound }
+ on_failed_contract { |contract| render_json_error(contract.errors.full_messages) }
+ end
+ end
+end
diff --git a/plugins/chat/app/models/chat/discoverable_bot.rb b/plugins/chat/app/models/chat/discoverable_bot.rb
new file mode 100644
index 00000000000..32cf2fbee71
--- /dev/null
+++ b/plugins/chat/app/models/chat/discoverable_bot.rb
@@ -0,0 +1,21 @@
+# frozen_string_literal: true
+
+class Chat::DiscoverableBot < ActiveRecord::Base
+ self.table_name = "chat_discoverable_bots"
+
+ belongs_to :user
+end
+
+# == Schema Information
+#
+# Table name: chat_discoverable_bots
+#
+# id :bigint not null, primary key
+# created_at :datetime not null
+# updated_at :datetime not null
+# user_id :integer not null
+#
+# Indexes
+#
+# index_chat_discoverable_bots_on_user_id (user_id) UNIQUE
+#
diff --git a/plugins/chat/app/services/chat/search_chatable.rb b/plugins/chat/app/services/chat/search_chatable.rb
index 8fa1e332a5d..07175097c1c 100644
--- a/plugins/chat/app/services/chat/search_chatable.rb
+++ b/plugins/chat/app/services/chat/search_chatable.rb
@@ -81,6 +81,8 @@ module Chat
allowed_bot_user_ids =
DiscoursePluginRegistry.apply_modifier(:chat_allowed_bot_user_ids, [], guardian)
+ # Replacing modifiers must not drop bots explicitly listed by admins.
+ allowed_bot_user_ids |= Chat::DiscoverableBot.pluck(:user_id)
user_search = user_search.real(allowed_bot_user_ids:)
user_search = user_search.includes(:user_option)
diff --git a/plugins/chat/app/services/chat/update_bot_discoverability.rb b/plugins/chat/app/services/chat/update_bot_discoverability.rb
new file mode 100644
index 00000000000..d42ba8ab001
--- /dev/null
+++ b/plugins/chat/app/services/chat/update_bot_discoverability.rb
@@ -0,0 +1,64 @@
+# frozen_string_literal: true
+
+class Chat::UpdateBotDiscoverability
+ include Service::Base
+
+ policy :can_manage_bots
+
+ params do
+ attribute :user_id, :integer
+ attribute :discoverable, :boolean
+
+ validates :user_id, presence: true
+ validates :discoverable, inclusion: { in: [true, false] }
+ end
+
+ model :bot
+
+ transaction do
+ only_if(:discoverability_changes) do
+ only_if(:becomes_discoverable) { step :list_bot }
+ only_if(:stops_being_discoverable) { step :unlist_bot }
+ step :log_discoverability_change
+ end
+ end
+
+ private
+
+ def can_manage_bots(guardian:)
+ guardian.is_admin?
+ end
+
+ def fetch_bot(params:)
+ User.bot_users.where.not(id: Discourse::SYSTEM_USER_ID).find_by(id: params.user_id)
+ end
+
+ def discoverability_changes(bot:, params:)
+ bot.chat_discoverable_bot.present? != params.discoverable
+ end
+
+ def becomes_discoverable(params:)
+ params.discoverable
+ end
+
+ def stops_being_discoverable(params:)
+ !params.discoverable
+ end
+
+ def list_bot(bot:)
+ Chat::DiscoverableBot.create_or_find_by!(user: bot)
+ end
+
+ def unlist_bot(bot:)
+ bot.chat_discoverable_bot.destroy!
+ end
+
+ def log_discoverability_change(bot:, params:, guardian:)
+ StaffActionLogger.new(guardian.user).log_custom(
+ "chat_bot_discoverability_change",
+ subject: bot.username,
+ previous_value: (!params.discoverable).to_s,
+ new_value: params.discoverable.to_s,
+ )
+ end
+end
diff --git a/plugins/chat/assets/javascripts/discourse/model-types.ts b/plugins/chat/assets/javascripts/discourse/model-types.ts
new file mode 100644
index 00000000000..3785ed87551
--- /dev/null
+++ b/plugins/chat/assets/javascripts/discourse/model-types.ts
@@ -0,0 +1,8 @@
+declare module "discourse/admin/models/admin-user" {
+ interface AdminUserFields {
+ /** Only sent for eligible bots viewed by admins while chat is enabled. */
+ chat_discoverable?: boolean;
+ }
+}
+
+export {};
diff --git a/plugins/chat/config/locales/client.en.yml b/plugins/chat/config/locales/client.en.yml
index eb7188d90eb..628cb252cc8 100644
--- a/plugins/chat/config/locales/client.en.yml
+++ b/plugins/chat/config/locales/client.en.yml
@@ -14,6 +14,7 @@ en:
logs:
staff_actions:
actions:
+ chat_bot_discoverability_change: "Chat bot discoverability changed"
chat_channel_status_change: "Chat channel status changed"
chat_channel_delete: "Chat channel deleted"
chat_auto_remove_membership: "Memberships automatically removed from channels"
@@ -625,6 +626,9 @@ en:
members_label: "Members"
admin:
+ bot_discoverability:
+ label: "Show in chat"
+ description: "Let people find this bot when starting a chat direct message"
title: "Chat"
export_messages:
title: "Export chat messages"
diff --git a/plugins/chat/config/routes.rb b/plugins/chat/config/routes.rb
index d00262c73fa..3bfc0107457 100644
--- a/plugins/chat/config/routes.rb
+++ b/plugins/chat/config/routes.rb
@@ -69,6 +69,8 @@ Chat::Engine.routes.draw do
namespace :admin, defaults: { format: :json, constraints: StaffConstraint.new } do
post "export/messages" => "export#export_messages"
+ put "bots/:user_id/discoverability" => "bot_discoverability#update",
+ :constraints => AdminConstraint.new
end
# direct_messages_controller routes
diff --git a/plugins/chat/db/migrate/20261104011110_create_chat_discoverable_bots.rb b/plugins/chat/db/migrate/20261104011110_create_chat_discoverable_bots.rb
new file mode 100644
index 00000000000..cf1516c5ce0
--- /dev/null
+++ b/plugins/chat/db/migrate/20261104011110_create_chat_discoverable_bots.rb
@@ -0,0 +1,11 @@
+# frozen_string_literal: true
+
+class CreateChatDiscoverableBots < ActiveRecord::Migration[8.1]
+ def change
+ create_table :chat_discoverable_bots do |t|
+ t.integer :user_id, null: false
+ t.timestamps
+ end
+ add_index :chat_discoverable_bots, :user_id, unique: true
+ end
+end
diff --git a/plugins/chat/lib/chat/user_extension.rb b/plugins/chat/lib/chat/user_extension.rb
index 80734442878..7098d4df364 100644
--- a/plugins/chat/lib/chat/user_extension.rb
+++ b/plugins/chat/lib/chat/user_extension.rb
@@ -5,6 +5,7 @@ module Chat
extend ActiveSupport::Concern
prepended do
+ has_one :chat_discoverable_bot, class_name: "Chat::DiscoverableBot", dependent: :destroy
has_many :user_chat_channel_memberships,
class_name: "Chat::UserChatChannelMembership",
dependent: :destroy
diff --git a/plugins/chat/plugin.rb b/plugins/chat/plugin.rb
index cf58b7c1ea3..8d8ab52960e 100644
--- a/plugins/chat/plugin.rb
+++ b/plugins/chat/plugin.rb
@@ -47,6 +47,16 @@ end
require_relative "lib/chat/engine"
after_initialize do
+ register_bot_creation_param(:chat_discoverable) do |bot, value|
+ Chat::DiscoverableBot.create!(user: bot) if ActiveModel::Type::Boolean.new.cast(value)
+ end
+
+ add_to_serializer(
+ :admin_detailed_user,
+ :chat_discoverable,
+ include_condition: -> { scope.is_admin? && object.bot? && !object.is_system_user? },
+ ) { object.chat_discoverable_bot.present? }
+
original_message_bus_group_ids_lookup = MessageBus.group_ids_lookup
MessageBus.group_ids_lookup do |env|
host = RailsMultisite::ConnectionManagement.host(env)
diff --git a/plugins/chat/spec/models/user_spec.rb b/plugins/chat/spec/models/user_spec.rb
index efd67f89124..698c6c059a7 100644
--- a/plugins/chat/spec/models/user_spec.rb
+++ b/plugins/chat/spec/models/user_spec.rb
@@ -4,4 +4,5 @@ RSpec.describe User do
it { is_expected.to have_many(:user_chat_channel_memberships).dependent(:destroy) }
it { is_expected.to have_many(:chat_message_reactions).dependent(:destroy) }
it { is_expected.to have_many(:chat_mentions) }
+ it { is_expected.to have_one(:chat_discoverable_bot).dependent(:destroy) }
end
diff --git a/plugins/chat/spec/requests/chat/admin/bot_discoverability_controller_spec.rb b/plugins/chat/spec/requests/chat/admin/bot_discoverability_controller_spec.rb
new file mode 100644
index 00000000000..fdcd8671973
--- /dev/null
+++ b/plugins/chat/spec/requests/chat/admin/bot_discoverability_controller_spec.rb
@@ -0,0 +1,24 @@
+# frozen_string_literal: true
+
+RSpec.describe Chat::Admin::BotDiscoverabilityController do
+ fab!(:admin)
+ fab!(:bot)
+
+ describe "#update" do
+ it "saves an admin's change without a response body" do
+ sign_in(admin)
+ put "/chat/admin/bots/#{bot.id}/discoverability.json", params: { discoverable: true }
+ expect(response.status).to eq(204)
+ expect(Chat::DiscoverableBot.exists?(user_id: bot.id)).to eq(true)
+ end
+
+ it "rejects anonymous visitors, members and moderators" do
+ [nil, Fabricate(:user), Fabricate(:moderator)].each do |actor|
+ sign_in(actor) if actor
+ put "/chat/admin/bots/#{bot.id}/discoverability.json", params: { discoverable: true }
+ expect(response.status).to be_in([403, 404])
+ end
+ expect(Chat::DiscoverableBot.exists?(user_id: bot.id)).to eq(false)
+ end
+ end
+end
diff --git a/plugins/chat/spec/requests/core_ext/admin_users_bots_spec.rb b/plugins/chat/spec/requests/core_ext/admin_users_bots_spec.rb
new file mode 100644
index 00000000000..ba64f2e2762
--- /dev/null
+++ b/plugins/chat/spec/requests/core_ext/admin_users_bots_spec.rb
@@ -0,0 +1,49 @@
+# frozen_string_literal: true
+
+RSpec.describe Admin::UsersController do
+ fab!(:admin)
+
+ before { sign_in(admin) }
+
+ describe "#create_bot" do
+ it "shows the bot in chat DM search when requested" do
+ post "/admin/users/bots.json",
+ params: {
+ bot: {
+ username: "listed_bot",
+ chat_discoverable: true,
+ },
+ }
+ expect(response.status).to eq(201)
+ expect(Chat::DiscoverableBot.exists?(user_id: response.parsed_body.dig("user", "id"))).to eq(
+ true,
+ )
+ end
+
+ it "creates unlisted bots by default or when explicitly unchecked" do
+ [nil, false].each_with_index do |flag, index|
+ bot_params = { username: "unlisted_bot_#{index}" }
+ bot_params[:chat_discoverable] = flag unless flag.nil?
+ expect { post "/admin/users/bots.json", params: { bot: bot_params } }.not_to change(
+ Chat::DiscoverableBot,
+ :count,
+ )
+ expect(response.status).to eq(201)
+ end
+ end
+
+ it "ignores the setting while chat is disabled" do
+ SiteSetting.chat_enabled = false
+ expect do
+ post "/admin/users/bots.json",
+ params: {
+ bot: {
+ username: "disabled_bot",
+ chat_discoverable: true,
+ },
+ }
+ end.not_to change(Chat::DiscoverableBot, :count)
+ expect(response.status).to eq(201)
+ end
+ end
+end
diff --git a/plugins/chat/spec/serializer/admin_detailed_user_serializer_spec.rb b/plugins/chat/spec/serializer/admin_detailed_user_serializer_spec.rb
new file mode 100644
index 00000000000..2b4d8c8d5cb
--- /dev/null
+++ b/plugins/chat/spec/serializer/admin_detailed_user_serializer_spec.rb
@@ -0,0 +1,18 @@
+# frozen_string_literal: true
+
+RSpec.describe AdminDetailedUserSerializer do
+ fab!(:admin)
+ fab!(:bot)
+
+ def serialize(user, viewer)
+ described_class.new(user, scope: viewer.guardian, root: false).as_json
+ end
+
+ it "includes chat discovery only for bots other than the system user, viewed by admins" do
+ Chat::DiscoverableBot.create!(user: bot)
+ expect(serialize(bot, admin)[:chat_discoverable]).to eq(true)
+ expect(serialize(bot, Fabricate(:moderator))).not_to have_key(:chat_discoverable)
+ expect(serialize(admin, admin)).not_to have_key(:chat_discoverable)
+ expect(serialize(Discourse.system_user, admin)).not_to have_key(:chat_discoverable)
+ end
+end
diff --git a/plugins/chat/spec/services/chat/search_chatable_spec.rb b/plugins/chat/spec/services/chat/search_chatable_spec.rb
index 4a0e4b6cac4..fb3d32e7c40 100644
--- a/plugins/chat/spec/services/chat/search_chatable_spec.rb
+++ b/plugins/chat/spec/services/chat/search_chatable_spec.rb
@@ -69,6 +69,28 @@ RSpec.describe Chat::SearchChatable do
expect(result.users).to include(current_user, sam, charlie, alain)
end
+ it "includes listed bots but not unlisted bots" do
+ bot = Fabricate(:bot)
+ unlisted_bot = Fabricate(:bot)
+ Chat::DiscoverableBot.create!(user: bot)
+ params[:term] = bot.username
+ expect(result.users).to contain_exactly(bot)
+ params[:term] = unlisted_bot.username
+ expect(described_class.call(params: params, **dependencies).users).to be_empty
+ end
+
+ it "preserves listed bots when a modifier replaces the allowlist" do
+ bot = Fabricate(:bot)
+ Chat::DiscoverableBot.create!(user: bot)
+ params[:term] = bot.username
+ modifier = proc { [] }
+ plugin = Plugin::Instance.new
+ plugin.register_modifier(:chat_allowed_bot_user_ids, &modifier)
+ expect(result.users).to contain_exactly(bot)
+ ensure
+ DiscoursePluginRegistry.unregister_modifier(plugin, :chat_allowed_bot_user_ids, &modifier)
+ end
+
it "can filter usernames" do
params[:term] = "sam"
diff --git a/plugins/chat/spec/services/chat/update_bot_discoverability_spec.rb b/plugins/chat/spec/services/chat/update_bot_discoverability_spec.rb
new file mode 100644
index 00000000000..3149fcb101d
--- /dev/null
+++ b/plugins/chat/spec/services/chat/update_bot_discoverability_spec.rb
@@ -0,0 +1,82 @@
+# frozen_string_literal: true
+
+RSpec.describe Chat::UpdateBotDiscoverability do
+ describe described_class::Contract, type: :model do
+ it { is_expected.to validate_presence_of(:user_id) }
+ it { is_expected.to allow_values(true, false).for(:discoverable) }
+ it { is_expected.not_to allow_value(nil).for(:discoverable) }
+ end
+
+ describe ".call" do
+ subject(:result) { described_class.call(params: params, guardian: actor.guardian) }
+
+ fab!(:actor, :admin)
+ fab!(:bot)
+
+ let(:params) { { user_id: bot.id, discoverable: true } }
+
+ context "when the actor is a moderator" do
+ fab!(:actor, :moderator)
+ it { is_expected.to fail_a_policy(:can_manage_bots) }
+ end
+
+ context "when params are invalid" do
+ let(:params) { { user_id: bot.id } }
+
+ it { is_expected.to fail_a_contract }
+ end
+
+ context "when the target is a human" do
+ let(:params) { { user_id: actor.id, discoverable: true } }
+
+ it { is_expected.to fail_to_find_a_model(:bot) }
+ end
+
+ context "when the target is the system user" do
+ let(:params) { { user_id: Discourse::SYSTEM_USER_ID, discoverable: true } }
+
+ it { is_expected.to fail_to_find_a_model(:bot) }
+ end
+
+ context "when enabling discovery" do
+ it "lists the bot and logs the change" do
+ expect { result }.to change(Chat::DiscoverableBot, :count).by(1).and change(
+ UserHistory,
+ :count,
+ ).by(1)
+ expect(result).to run_successfully
+ expect(UserHistory.last).to have_attributes(
+ custom_type: "chat_bot_discoverability_change",
+ subject: bot.username,
+ previous_value: "false",
+ new_value: "true",
+ acting_user_id: actor.id,
+ )
+ end
+ end
+
+ context "when discovery is already enabled" do
+ before { Chat::DiscoverableBot.create!(user: bot) }
+
+ it "does not write or log a change" do
+ expect { result }.not_to change { [Chat::DiscoverableBot.count, UserHistory.count] }
+ expect(result).to run_successfully
+ end
+ end
+
+ context "when disabling discovery" do
+ let(:params) { { user_id: bot.id, discoverable: false } }
+
+ before { Chat::DiscoverableBot.create!(user: bot) }
+
+ it "unlists the bot and logs the change" do
+ expect { result }.to change(Chat::DiscoverableBot, :count).by(-1).and change(
+ UserHistory,
+ :count,
+ ).by(1)
+ expect(result).to run_successfully
+ expect(UserHistory.last).to have_attributes(previous_value: "true", new_value: "false")
+ end
+ end
+ end
+end
diff --git a/plugins/chat/spec/system/admin/bot_discoverability_spec.rb b/plugins/chat/spec/system/admin/bot_discoverability_spec.rb
new file mode 100644
index 00000000000..0625be8833a
--- /dev/null
+++ b/plugins/chat/spec/system/admin/bot_discoverability_spec.rb
@@ -0,0 +1,53 @@
+# frozen_string_literal: true
+
+RSpec.describe "Manage bot chat discovery" do
+ fab!(:admin)
+ fab!(:member, :user)
+
+ let(:form) { PageObjects::Components::FormKit.new(".admin-bot-form") }
+ let(:admin_user) { PageObjects::Pages::AdminUser.new }
+ let(:toggle) do
+ PageObjects::Components::DToggleSwitch.new(
+ ".chat-bot-discoverability .d-toggle-switch__checkbox",
+ )
+ end
+ let(:chat) { PageObjects::Pages::Chat.new }
+ let(:toasts) { PageObjects::Components::Toasts.new }
+
+ before do
+ chat_system_bootstrap(admin)
+ SiteSetting.direct_message_enabled_groups = Group::AUTO_GROUPS[:everyone]
+ SiteSetting.enable_names = false
+ end
+
+ it "lets admins choose whether members can find a bot when starting a chat" do
+ sign_in(admin)
+ visit "/admin/users/bots/new"
+ form.field("username").fill_in("discoverable_bot")
+ expect(form.field("chat_discoverable")).to be_unchecked
+ form.field("chat_discoverable").check
+ form.submit
+ expect(toasts).to have_success(
+ I18n.t("admin_js.admin.users.bots.created", username: "discoverable_bot"),
+ )
+ bot = User.find_by!(username: "discoverable_bot")
+
+ sign_in(member)
+ visit "/"
+ chat.open_new_message
+ chat.message_creator.filter(bot.username)
+ expect(chat.message_creator).to be_listing(bot)
+
+ sign_in(admin)
+ admin_user.visit(bot)
+ expect(toggle).to be_checked
+ toggle.toggle
+ try_until_success { expect(Chat::DiscoverableBot.exists?(user_id: bot.id)).to eq(false) }
+
+ sign_in(member)
+ visit "/"
+ chat.open_new_message
+ chat.message_creator.filter(bot.username)
+ expect(chat.message_creator).to be_not_listing(bot)
+ end
+end
diff --git a/plugins/chat/test/javascripts/acceptance/admin-new-bot-chat-discoverable-test.js b/plugins/chat/test/javascripts/acceptance/admin-new-bot-chat-discoverable-test.js
new file mode 100644
index 00000000000..aa4d4a4b0db
--- /dev/null
+++ b/plugins/chat/test/javascripts/acceptance/admin-new-bot-chat-discoverable-test.js
@@ -0,0 +1,45 @@
+import { visit } from "@ember/test-helpers";
+import { test } from "qunit";
+import formKit from "discourse/tests/helpers/form-kit-helper";
+import { acceptance } from "discourse/tests/helpers/qunit-helpers";
+
+[true, false].forEach((chatEnabled) => {
+ acceptance(
+ `Admin - New bot chat discovery - chat ${chatEnabled ? "enabled" : "disabled"}`,
+ function (needs) {
+ needs.user({ admin: true });
+ needs.settings({ chat_enabled: chatEnabled });
+
+ let payload;
+ needs.pretender((server, helper) => {
+ server.get("/admin/users/bots/new.json", () =>
+ helper.response({ default_trust_level: 1, name_required: false })
+ );
+ server.get("/admin/api/keys/scopes.json", () =>
+ helper.response({ scopes: {} })
+ );
+ server.get("/admin/users/list/bots.json", () => helper.response([]));
+ server.post("/admin/users/bots.json", (request) => {
+ payload = JSON.parse(request.requestBody);
+ return helper.response(201, { user: { id: -200, ...payload.bot } });
+ });
+ });
+
+ test("discovery is opt-in and only offered while chat is enabled", async function (assert) {
+ await visit("/admin/users/bots/new");
+ assert
+ .dom('[data-name="chat_discoverable"] input')
+ .exists({ count: chatEnabled ? 1 : 0 });
+
+ const form = formKit(".admin-bot-form");
+ await form.field("username").fillIn("test_bot");
+ await form.submit();
+
+ assert.strictEqual(
+ payload.bot.chat_discoverable,
+ chatEnabled ? false : undefined
+ );
+ });
+ }
+ );
+});
diff --git a/plugins/chat/test/javascripts/components/chat-bot-discoverability-test.gjs b/plugins/chat/test/javascripts/components/chat-bot-discoverability-test.gjs
new file mode 100644
index 00000000000..6320c4313ab
--- /dev/null
+++ b/plugins/chat/test/javascripts/components/chat-bot-discoverability-test.gjs
@@ -0,0 +1,37 @@
+import { click, render } from "@ember/test-helpers";
+import { module, test } from "qunit";
+import sinon from "sinon";
+import AdminUser from "discourse/admin/models/admin-user";
+import lazyHash from "discourse/helpers/lazy-hash";
+import { setupRenderingTest } from "discourse/tests/helpers/component-test";
+import pretender from "discourse/tests/helpers/create-pretender";
+import ChatBotDiscoverability from "discourse/plugins/chat/discourse/connectors/admin-user-details/chat-bot-discoverability";
+
+module("Component | ChatBotDiscoverability", function (hooks) {
+ setupRenderingTest(hooks);
+
+ test("reverts a failed save", async function (assert) {
+ const bot = AdminUser.create({
+ id: -200,
+ username: "test_bot",
+ chat_discoverable: false,
+ });
+ sinon.stub(this.owner.lookup("service:dialog"), "alert");
+ pretender.put("/chat/admin/bots/-200/discoverability.json", () => [
+ 500,
+ { "Content-Type": "application/json" },
+ JSON.stringify({ errors: ["Save failed"] }),
+ ]);
+
+ await render(
+ <template>
+ <ChatBotDiscoverability @outletArgs={{lazyHash model=bot}} />
+ </template>
+ );
+ await click('[role="switch"]');
+
+ assert.dom('[role="switch"]').hasAttribute("aria-checked", "false");
+ assert.false(bot.chat_discoverable);
+ assert.dom('[role="switch"]').isNotDisabled();
+ });
+});
diff --git a/spec/requests/admin/bots_controller_spec.rb b/spec/requests/admin/bots_controller_spec.rb
index 9cad46f65d1..f50a2407cbe 100644
--- a/spec/requests/admin/bots_controller_spec.rb
+++ b/spec/requests/admin/bots_controller_spec.rb
@@ -98,6 +98,48 @@ RSpec.describe Admin::UsersController do
end
describe "#create_bot" do
+ context "with a plugin bot creation parameter" do
+ let(:plugin) { Plugin::Instance.new }
+ let(:received) { [] }
+
+ before do
+ sign_in(admin)
+ @original_bot_creation_params = DiscoursePluginRegistry.bot_creation_params.dup
+ plugin.register_bot_creation_param(:test_bot_option) do |bot, value|
+ received << [bot.id, value]
+ end
+ end
+
+ after { DiscoursePluginRegistry.bot_creation_params.replace(@original_bot_creation_params) }
+
+ it "accepts scalar parameters inside the bot envelope" do
+ post "/admin/users/bots.json",
+ params: {
+ bot: {
+ username: "plugin_bot",
+ test_bot_option: true,
+ },
+ }
+ expect(response.status).to eq(201)
+ expect(received).to eq([[response.parsed_body.dig("user", "id"), "true"]])
+ end
+
+ it "ignores parameters outside the envelope and non-scalar values" do
+ post "/admin/users/bots.json",
+ params: {
+ bot: {
+ username: "nested_bot",
+ test_bot_option: {
+ admin: true,
+ },
+ },
+ test_bot_option: true,
+ }
+ expect(response.status).to eq(201)
+ expect(received).to be_empty
+ end
+ end
+
let(:bot_params) { { name: "Release helper", username: "release_helper", trust_level: 0 } }
it "rejects anonymous requests without creating a user" do
diff --git a/spec/services/user/create_bot_spec.rb b/spec/services/user/create_bot_spec.rb
index 91954fd41a1..1bfa1d6eb9c 100644
--- a/spec/services/user/create_bot_spec.rb
+++ b/spec/services/user/create_bot_spec.rb
@@ -77,6 +77,43 @@ RSpec.describe User::CreateBot do
let(:params) { { name: "Release helper", username: "release_helper", trust_level: 2 } }
let(:dependencies) { { guardian: actor.guardian } }
+ context "with plugin parameters" do
+ let(:plugin) { Plugin::Instance.new }
+ let(:received) { [] }
+ let(:callback) { proc { |bot, value| received << [bot, value] } }
+
+ before do
+ @original_bot_creation_params = DiscoursePluginRegistry.bot_creation_params.dup
+ plugin.register_bot_creation_param(:test_bot_option, &callback)
+ params[:plugin_params] = { test_bot_option: true }
+ end
+
+ after { DiscoursePluginRegistry.bot_creation_params.replace(@original_bot_creation_params) }
+
+ it "passes the new bot and the value to the plugin callback" do
+ expect(result).to run_successfully
+ expect(received).to eq([[result.user, true]])
+ end
+
+ it "ignores disabled plugins and unregistered parameters" do
+ plugin.stubs(:enabled?).returns(false)
+ params[:plugin_params][:unknown] = true
+ expect(result).to run_successfully
+ expect(received).to be_empty
+ end
+
+ context "when the callback raises" do
+ let(:callback) { proc { raise Discourse::InvalidParameters.new(:test_bot_option) } }
+
+ it "rolls back the bot and its audit log" do
+ params[:api_key] = { scope_mode: "global" }
+ expect do
+ expect { result }.to raise_error(Discourse::InvalidParameters)
+ end.not_to change { [User.count, UserHistory.count, ApiKey.count] }
+ end
+ end
+ end
+
context "when the contract is invalid" do
let(:params) { { username: "" } }