Skip to content

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

FEATURE: Manage bot accounts in admin (#45212)

Sam612ca6d1d7ee
diff --git a/app/assets/stylesheets/admin/admin_base.scss b/app/assets/stylesheets/admin/admin_base.scss
index 64396d60739..05939c12ed7 100644
--- a/app/assets/stylesheets/admin/admin_base.scss
+++ b/app/assets/stylesheets/admin/admin_base.scss
@@ -1142,8 +1142,9 @@ section.details {
.directory-table__cell {
&,
a,
- a:visited {
- color: #bbb;
+ a:visited,
+ .directory-table__value {
+ color: var(--primary-low-mid);
}
}
}
diff --git a/app/assets/stylesheets/admin/api.scss b/app/assets/stylesheets/admin/api.scss
index 128b1be249e..0c8b63ba512 100644
--- a/app/assets/stylesheets/admin/api.scss
+++ b/app/assets/stylesheets/admin/api.scss
@@ -28,14 +28,6 @@
display: none;
}
- .scopes-table__object {
- display: contents;
- }
-
- .form-kit__collection {
- display: contents;
- }
-
.api-key-show {
.form-element,
.form-element-desc {
@@ -64,73 +56,6 @@
}
}
- .generated-api-key-container {
- display: flex;
- flex-direction: column;
- gap: var(--space-4);
- }
-
- .generated-api-key-container .alert {
- margin-bottom: 0;
- }
-
- .generated-api-key {
- flex: 1;
- padding: var(--space-2) var(--space-3);
- font-family: var(--d-font-family--monospace);
- font-size: var(--font-down-1);
- background: var(--primary-very-low);
- border: 1px solid var(--primary-low);
- border-radius: var(--d-border-radius);
- user-select: all;
- word-break: break-all;
-
- &__details {
- display: flex;
- flex-direction: column;
- gap: var(--space-2);
- padding: var(--space-3) var(--space-4);
- background: var(--primary-very-low);
- border-radius: var(--d-border-radius);
- }
-
- &__detail-row {
- display: flex;
- gap: var(--space-2);
- }
-
- &__label {
- font-weight: bold;
- min-width: 8em;
- }
-
- &__scope-badges {
- display: flex;
- flex-wrap: wrap;
- gap: var(--space-1);
- }
-
- &__scope-badge {
- display: inline-block;
- padding: 0.15em 0.5em;
- font-family: var(--d-font-family--monospace);
- font-size: var(--font-down-1);
- background: var(--primary-very-low);
- border: 1px solid var(--primary-low);
- border-radius: var(--d-border-radius);
- }
-
- &__scope-param {
- color: var(--primary-medium);
- }
-
- &__key-row {
- display: flex;
- align-items: center;
- gap: var(--space-2);
- }
- }
-
.api-key {
padding: 10px;
margin-bottom: 10px;
@@ -159,46 +84,115 @@
text-align: left;
width: 50%;
}
+ }
+}
- .scopes-title {
- margin-top: 20px;
- }
+// Shared by every API key form
+.generated-api-key-container {
+ display: flex;
+ flex-direction: column;
+ gap: var(--space-4);
+}
+
+.generated-api-key-container .alert {
+ margin-bottom: 0;
+}
+
+.generated-api-key {
+ flex: 1;
+ padding: var(--space-2) var(--space-3);
+ font-family: var(--d-font-family--monospace);
+ font-size: var(--font-down-1);
+ background: var(--primary-very-low);
+ border: 1px solid var(--primary-low);
+ border-radius: var(--d-border-radius);
+ user-select: all;
+ word-break: break-all;
+
+ &__details {
+ display: flex;
+ flex-direction: column;
+ gap: var(--space-2);
+ padding: var(--space-3) var(--space-4);
+ background: var(--primary-very-low);
+ border-radius: var(--d-border-radius);
}
- .scopes-table.grid {
- margin: 20px 0;
+ &__detail-row {
+ display: flex;
+ gap: var(--space-2);
+ }
- tr {
- grid-template-columns: repeat(4, 1fr);
+ &__label {
+ font-weight: bold;
+ min-width: 8em;
+ }
- input {
- margin-bottom: 2px;
- }
+ &__scope-badges {
+ display: flex;
+ flex-wrap: wrap;
+ gap: var(--space-1);
+ }
- @include viewport.until(sm) {
- grid-template-columns: repeat(2, 1fr);
- row-gap: 0.5em;
+ &__scope-badge {
+ display: inline-block;
+ padding: 0.15em 0.5em;
+ font-family: var(--d-font-family--monospace);
+ font-size: var(--font-down-1);
+ background: var(--primary-very-low);
+ border: 1px solid var(--primary-low);
+ border-radius: var(--d-border-radius);
+ }
- &.scope-resource-name {
- row-gap: 0;
- }
- }
- }
+ &__scope-param {
+ color: var(--primary-medium);
+ }
- .scope-resource-name {
- font-size: var(--font-up-1);
- }
+ &__key-row {
+ display: flex;
+ align-items: center;
+ gap: var(--space-2);
+ }
+}
+
+.scopes-table.grid {
+ margin: 0;
- .scope-tooltip {
- font-size: var(--font-down-1);
+ .scopes-table__object,
+ .form-kit__collection {
+ display: contents;
+ }
+
+ tr {
+ grid-template-columns: repeat(4, 1fr);
+
+ input {
+ margin-bottom: 2px;
}
- .scope-name {
- font-weight: bold;
- font-size: var(--font-0);
- display: inline;
+ @include viewport.until(sm) {
+ grid-template-columns: repeat(2, 1fr);
+ row-gap: 0.5em;
+
+ &.scope-resource-name {
+ row-gap: 0;
+ }
}
}
+
+ .scope-resource-name {
+ font-size: var(--font-up-1);
+ }
+
+ .scope-tooltip {
+ font-size: var(--font-down-1);
+ }
+
+ .scope-name {
+ font-weight: bold;
+ font-size: var(--font-0);
+ display: inline;
+ }
}
// Webhook
diff --git a/app/assets/stylesheets/admin/users.scss b/app/assets/stylesheets/admin/users.scss
index babffc058bf..5966e894255 100644
--- a/app/assets/stylesheets/admin/users.scss
+++ b/app/assets/stylesheets/admin/users.scss
@@ -125,12 +125,75 @@
}
.admin-users-list {
+ &__source,
+ &__source-header {
+ justify-content: start;
+ text-align: start;
+ }
+
+ // Matches the cell padding so the heading lines up with the sources below.
+ &__source-header.directory-table__column-header {
+ padding-inline: 0.25em;
+ }
+
+ // Long usernames truncate instead of widening the column past its header.
+ &__username {
+ @include ellipsis;
+ flex: 1 1 auto;
+ min-width: 0;
+ contain: inline-size;
+ }
+
+ &__source-values {
+ min-width: 0;
+ max-width: 28ch;
+ }
+
+ &__source-item {
+ display: flex;
+ align-items: center;
+ gap: var(--space-2);
+ min-width: 0;
+ }
+
+ &__source-label {
+ @include ellipsis;
+ min-width: 0;
+ }
+
+ &__source-user {
+ display: flex;
+ align-items: center;
+ gap: var(--space-2);
+
+ // Outranks the list's general avatar margin; the gap spaces it instead.
+ img.avatar {
+ margin: 0;
+ }
+ }
+
+ // Same breakpoint as the directory table's stacked layout.
+ @container (max-width: 47em) {
+ &__source .directory-table__label {
+ flex-basis: 30%;
+ }
+
+ &__source-values {
+ max-width: 70%;
+ }
+ }
+
.directory-table__cell {
padding: 0.5em 0.25em;
&.username {
align-items: center;
justify-content: start;
+ min-width: 0;
+
+ .avatar {
+ flex-shrink: 0;
+ }
}
&.email {
@@ -173,6 +236,12 @@
&__column-header-wrapper {
display: flex;
+ border-bottom: 1px solid var(--table-border-color);
+
+ // The wrapper's border runs under the bulk-select buttons too.
+ .directory-table__column-header {
+ border-bottom: none;
+ }
}
&__cell-bulk-select {
@@ -254,3 +323,43 @@
width: 100%;
gap: var(--space-2);
}
+
+.admin-bot-form {
+ .form-kit__field-toggle {
+ display: grid;
+ grid-template-areas:
+ "title content"
+ "description description";
+ grid-template-columns: 1fr auto;
+ align-items: center;
+ gap: 0.5em;
+ width: 100%;
+
+ @include viewport.from(sm) {
+ width: var(--form-kit-large-input);
+ }
+
+ .form-kit__container-title,
+ .form-kit__container-description,
+ .form-kit__container-content {
+ width: auto;
+ }
+
+ .form-kit__container-title {
+ grid-area: title;
+ }
+
+ .form-kit__container-description {
+ grid-area: description;
+ }
+
+ .form-kit__container-content {
+ grid-area: content;
+ }
+ }
+}
+
+.select-kit.admin-users__subheader-new-bot .select-kit-body {
+ min-width: auto;
+ max-width: 22em;
+}
diff --git a/app/assets/stylesheets/common/components/_index.scss b/app/assets/stylesheets/common/components/_index.scss
index 24f70b4294c..f68eb04df27 100644
--- a/app/assets/stylesheets/common/components/_index.scss
+++ b/app/assets/stylesheets/common/components/_index.scss
@@ -26,6 +26,7 @@
@import "docked-composer";
@import "d-toggle-switch";
@import "d-virtual-list";
+@import "d-user-avatar-flair";
@import "date-input";
@import "date-picker";
@import "date-range-picker";
diff --git a/app/assets/stylesheets/common/components/d-user-avatar-flair.scss b/app/assets/stylesheets/common/components/d-user-avatar-flair.scss
new file mode 100644
index 00000000000..4914933b4d2
--- /dev/null
+++ b/app/assets/stylesheets/common/components/d-user-avatar-flair.scss
@@ -0,0 +1,13 @@
+.avatar-flair.--bot {
+ background-color: var(--primary);
+ color: var(--secondary);
+ border-radius: var(--d-border-radius);
+
+ .d-icon {
+ box-sizing: border-box;
+ width: 100%;
+ height: 100%;
+ padding: 15%;
+ fill: var(--secondary);
+ }
+}
diff --git a/app/assets/stylesheets/common/select-kit/select-kit.scss b/app/assets/stylesheets/common/select-kit/select-kit.scss
index 33daa0ca965..d712fcf9a89 100644
--- a/app/assets/stylesheets/common/select-kit/select-kit.scss
+++ b/app/assets/stylesheets/common/select-kit/select-kit.scss
@@ -113,6 +113,10 @@
padding-right: 0.5em;
}
+ &.btn-small {
+ font-size: var(--font-down-1);
+ }
+
/* hide native indicator */
&::-webkit-details-marker {
display: none;
@@ -187,6 +191,14 @@
color: var(--primary-medium);
}
+ &.btn-primary .angle-icon {
+ color: var(--d-button-primary-icon-color);
+ }
+
+ &.btn-danger .angle-icon {
+ color: var(--d-button-danger-icon-color);
+ }
+
.d-button-label {
display: flex;
align-items: center;
diff --git a/app/controllers/admin/api_controller.rb b/app/controllers/admin/api_controller.rb
index 6aa0f752f0e..151ff1cb9ea 100644
--- a/app/controllers/admin/api_controller.rb
+++ b/app/controllers/admin/api_controller.rb
@@ -78,7 +78,10 @@ class Admin::ApiController < Admin::AdminController
api_key = ApiKey.new(api_key_params)
ApiKey.transaction do
api_key.created_by = current_user
- api_key.api_key_scopes = build_scopes
+ api_key.api_key_scopes =
+ ApiKeyScope.build_from_params(
+ params.require(:key)[:scopes].to_a.map { it.try(:to_unsafe_h) || it },
+ )
api_key.scope_mode = params.dig(:key, :scope_mode)
if username = params.require(:key).permit(:username)[:username].presence
api_key.user = User.find_by_username(username)
@@ -120,34 +123,6 @@ class Admin::ApiController < Admin::AdminController
raise Discourse::InvalidParameters if params.dig(:key, :scopes).blank?
end
- def build_scopes
- params.require(:key)[:scopes].to_a.map do |scope_params|
- resource, action = scope_params[:scope_id].split(":")
-
- mapping = ApiKeyScope.scope_mappings.dig(resource.to_sym, action.to_sym)
- raise Discourse::InvalidParameters if mapping.nil? # invalid mapping
-
- ApiKeyScope.new(
- resource: resource,
- action: action,
- allowed_parameters:
- build_params(scope_params, ApiKeyScope.restrictable_parameters(mapping)),
- )
- end
- end
-
- def build_params(scope_params, params)
- return if params.nil?
-
- scope_params
- .slice(*params)
- .tap do |allowed_params|
- allowed_params.each do |k, v|
- v.blank? ? allowed_params.delete(k) : allowed_params[k] = v.split(",")
- end
- end
- end
-
def update_params
editable_fields = [:description]
permitted_params = params.permit(key: [*editable_fields])[:key]
diff --git a/app/controllers/admin/users_controller.rb b/app/controllers/admin/users_controller.rb
index 3aa714a1096..26d0ff9bb08 100644
--- a/app/controllers/admin/users_controller.rb
+++ b/app/controllers/admin/users_controller.rb
@@ -1,6 +1,11 @@
# frozen_string_literal: true
class Admin::UsersController < Admin::StaffController
+ skip_before_action :check_xhr, only: :new_bot
+
+ before_action :ensure_admin, only: %i[new_bot create_bot bot_username_suggestion]
+ before_action :rate_limit_bot_creation, only: :create_bot
+
before_action :fetch_user,
only: %i[
suspend
@@ -41,6 +46,11 @@ class Admin::UsersController < Admin::StaffController
silence_reasons: query.penalty_reasons(users.select(&:silenced?), :silence_user),
suspend_reasons: query.penalty_reasons(users.select(&:suspended?), :suspend_user),
}
+ if params[:query] == "bots"
+ opts[:user_ids] = users.map(&:id)
+ opts[:bot_creators] = query.bot_creators(opts[:user_ids]) if guardian.is_admin?
+ end
+
if params[:show_emails] == "true"
StaffActionLogger.new(current_user).log_show_emails(users, context: request.path)
opts[:emails_desired] = true
@@ -49,6 +59,55 @@ class Admin::UsersController < Admin::StaffController
render_serialized(users, AdminUserListSerializer, opts)
end
+ def new_bot
+ if request.format.json?
+ render json: {
+ default_trust_level: SiteSetting.default_trust_level,
+ name_required: SiteSetting.full_name_requirement == "required_at_signup",
+ }
+ else
+ render "default/empty"
+ end
+ end
+
+ def bot_username_suggestion
+ render json: { username: UserNameSuggester.suggest(params.require(:name)) }
+ end
+
+ def create_bot
+ bot = params.expect(bot: %i[name username trust_level])
+
+ # 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
+ on_success do |user:, api_key: nil|
+ render json: {
+ user: AdminUserSerializer.new(user, scope: guardian, root: false).as_json,
+ key:
+ api_key && ApiKeySerializer.new(api_key, scope: guardian, root: false).as_json,
+ }.compact,
+ status: :created,
+ location: admin_user_show_path(id: user.id, username: user.username)
+ end
+ on_failed_policy(:can_create_bot) { raise Discourse::InvalidAccess }
+ on_failed_policy(:site_not_archived) { raise Discourse::SiteArchived }
+ on_failed_contract { |contract| render_json_error(contract.errors.full_messages) }
+ on_model_not_found(:bot_id) { |result| raise result.exception }
+ on_model_errors(:user) { |user| render_json_error(user) }
+ on_model_not_found(:user) do |result|
+ raise result.exception if result.exception
+ raise Discourse::NotFound
+ end
+ on_model_errors(:api_key) { |invalid_key| render_json_error(invalid_key) }
+ on_model_not_found(:api_key) do |result|
+ raise result.exception if result.exception
+ raise Discourse::NotFound
+ end
+ end
+ end
+
def show
@user = User.find_by(id: params[:id])
raise Discourse::NotFound unless @user
@@ -600,6 +659,10 @@ class Admin::UsersController < Admin::StaffController
private
+ def rate_limit_bot_creation
+ RateLimiter.new(current_user, "create-bot", 10, 1.minute, apply_limit_to_staff: true).performed!
+ end
+
def fetch_user
@user = User.find_by(id: params[:user_id])
raise Discourse::NotFound unless @user
diff --git a/app/models/api_key_scope.rb b/app/models/api_key_scope.rb
index 46fa6875fcd..1d9dacd4f12 100644
--- a/app/models/api_key_scope.rb
+++ b/app/models/api_key_scope.rb
@@ -299,6 +299,24 @@ class ApiKeyScope < ActiveRecord::Base
).presence
end
+ def build_from_params(scopes_params)
+ Array(scopes_params).map do |scope_params|
+ raise Discourse::InvalidParameters.new(:scopes) if !scope_params.is_a?(Hash)
+
+ scope_params = scope_params.with_indifferent_access
+ resource, action = scope_params[:scope_id].to_s.split(":")
+ mapping = scope_mappings.dig(resource&.to_sym, action&.to_sym)
+ raise Discourse::InvalidParameters.new(:scopes) if mapping.nil?
+
+ new(
+ resource:,
+ action:,
+ allowed_parameters:
+ allowed_parameters_from(scope_params, restrictable_parameters(mapping)),
+ )
+ end
+ end
+
def scope_mappings
plugin_mappings = DiscoursePluginRegistry.api_key_scope_mappings
return default_mappings if plugin_mappings.empty?
@@ -361,6 +379,17 @@ class ApiKeyScope < ActiveRecord::Base
urls.to_a
end
+
+ private
+
+ def allowed_parameters_from(scope_params, restrictable)
+ return if restrictable.nil?
+
+ scope_params
+ .slice(*restrictable)
+ .compact_blank
+ .transform_values { |value| value.to_s.split(",") }
+ end
end
def permits?(env)
diff --git a/app/models/user_history.rb b/app/models/user_history.rb
index 070932ce88d..2bcd44ee579 100644
--- a/app/models/user_history.rb
+++ b/app/models/user_history.rb
@@ -188,6 +188,7 @@ class UserHistory < ActiveRecord::Base
add_access_control_list_owner: 133,
remove_access_control_list_owner: 134,
assume_access_control_ownership: 135,
+ create_bot: 136,
)
end
@@ -195,6 +196,7 @@ class UserHistory < ActiveRecord::Base
def self.staff_actions
@staff_actions ||= %i[
delete_user
+ create_bot
change_trust_level
change_site_setting
change_theme
diff --git a/app/serializers/admin_user_list_serializer.rb b/app/serializers/admin_user_list_serializer.rb
index ca4c0b7dc5c..62e619bfa4f 100644
--- a/app/serializers/admin_user_list_serializer.rb
+++ b/app/serializers/admin_user_list_serializer.rb
@@ -27,7 +27,8 @@ class AdminUserListSerializer < BasicUserSerializer
:can_be_deleted,
:can_be_suspended,
:silence_reason,
- :suspend_reason
+ :suspend_reason,
+ :bot_creator
%i[days_visited posts_read_count topics_entered post_count].each do |sym|
attributes sym
@@ -142,4 +143,18 @@ class AdminUserListSerializer < BasicUserSerializer
def include_suspend_reason?
@options[:include_suspend_reason]
end
+
+ def bot_creator
+ creator = @options[:bot_creators][object.id]
+ {
+ username: creator[:username],
+ avatar_template: User.avatar_template(creator[:username], creator[:uploaded_avatar_id]),
+ url:
+ "#{Discourse.base_path}/admin/users/#{creator[:id]}/#{UrlHelper.encode_component(creator[:username].downcase)}",
+ }
+ end
+
+ def include_bot_creator?
+ scope.is_admin? && object.bot? && @options[:bot_creators]&.key?(object.id)
+ end
end
diff --git a/app/services/staff_action_logger.rb b/app/services/staff_action_logger.rb
index c3c7be38b30..dd10ee773e8 100644
--- a/app/services/staff_action_logger.rb
+++ b/app/services/staff_action_logger.rb
@@ -39,6 +39,17 @@ class StaffActionLogger
)
end
+ def log_bot_creation(user)
+ UserHistory.create!(
+ params.merge(
+ action: UserHistory.actions[:create_bot],
+ target_user_id: user.id,
+ subject: user.username,
+ details: "trust_level: #{user.trust_level}",
+ ),
+ )
+ end
+
def log_custom(custom_type, details = nil)
raise Discourse::InvalidParameters.new(:custom_type) unless custom_type
diff --git a/app/services/user/create_bot.rb b/app/services/user/create_bot.rb
new file mode 100644
index 00000000000..3357165cb90
--- /dev/null
+++ b/app/services/user/create_bot.rb
@@ -0,0 +1,99 @@
+# frozen_string_literal: true
+
+class User::CreateBot
+ include Service::Base
+
+ policy :can_create_bot
+ policy :site_not_archived
+
+ params do
+ attribute :name, :string
+ attribute :username, :string
+ attribute :trust_level, :integer, default: -> { SiteSetting.default_trust_level }
+ attribute :api_key, :hash do
+ attribute :description, :string
+ attribute :scope_mode, :string
+ attribute :scopes, :array
+
+ validates :description, length: { maximum: 255 }
+ validates :scope_mode, inclusion: { in: ApiKey.scope_modes.keys }
+ end
+
+ validates :name,
+ presence: true,
+ if: -> { SiteSetting.full_name_requirement == "required_at_signup" }
+ validates :username, presence: true
+ validates :trust_level, inclusion: { in: TrustLevel.valid_range }
+ end
+
+ # Commit the reservation before the creation transaction can hide it from other requests.
+ model :bot_id, :reserve_bot_id
+
+ transaction do
+ model :user, :create_bot
+ step :log_creation
+ only_if(:api_key_requested) do
+ model :api_key, :create_api_key
+ step :log_api_key_creation
+ end
+ end
+
+ private
+
+ def can_create_bot(guardian:)
+ guardian.is_admin?
+ end
+
+ def site_not_archived
+ !SiteSetting.site_archived
+ end
+
+ def reserve_bot_id
+ BotUser.new("core").next_id
+ end
+
+ def create_bot(params:, guardian:, bot_id:)
+ User.create(
+ id: bot_id,
+ name: params.name,
+ username: params.username,
+ trust_level: params.trust_level,
+ email: "#{SecureRandom.hex}@does-not-exist.invalid",
+ active: true,
+ approved: true,
+ approved_by_id: guardian.user.id,
+ approved_at: Time.current,
+ admin: false,
+ moderator: false,
+ enforce_username_restrictions: true,
+ # Internal addresses are not subject to signup email-domain restrictions.
+ skip_email_validation: true,
+ )
+ end
+
+ def log_creation(user:, guardian:)
+ StaffActionLogger.new(guardian.user).log_bot_creation(user)
+ end
+
+ def api_key_requested(params:)
+ params.api_key.present?
+ end
+
+ def create_api_key(params:, user:, guardian:)
+ ApiKey.create(
+ user:,
+ created_by: guardian.user,
+ description: params.api_key.description.presence || user.username,
+ scope_mode: params.api_key.scope_mode,
+ api_key_scopes: ApiKeyScope.build_from_params(params.api_key.scopes),
+ )
+ end
+
+ def log_api_key_creation(api_key:, guardian:)
+ StaffActionLogger.new(guardian.user).log_api_key(
+ api_key,
+ UserHistory.actions[:api_key_create],
+ changes: api_key.saved_changes,
+ )
+ end
+end
diff --git a/config/locales/client.en.yml b/config/locales/client.en.yml
index 5cfecdd966d..7b3eb31d034 100644
--- a/config/locales/client.en.yml
+++ b/config/locales/client.en.yml
@@ -1808,6 +1808,7 @@ en:
user:
said: "%{username}:"
+ bot_account: "Automated account"
profile: "Profile"
profile_possessive: "%{username}'s profile"
mute: "Mute"
@@ -9609,6 +9610,7 @@ en:
permanently_delete_post_revisions: "permanently delete post revisions"
mcp_client_updated: "update MCP OAuth client"
delete_user: "delete user"
+ create_bot: "Create bot"
change_trust_level: "change trust level"
change_username: "change username"
change_site_setting: "change site setting"
@@ -10005,6 +10007,7 @@ en:
suspended: "Suspended"
silenced: "Silenced"
staged: "Staged"
+ bots: "Bots"
activation_filter:
label: "Activation status"
all: "All users"
@@ -10015,6 +10018,24 @@ en:
bot: "Bot accounts"
all: "All accounts"
approved: "Approved?"
+ source: "Source"
+ bots:
+ new: "New bot"
+ new_options:
+ bot:
+ label: "General-purpose bot"
+ description: "An account for integrations, webhooks, or automated posting through the API."
+ back: "Back to bots"
+ help: "Bots are user accounts that can't log in, for integrations and automated posting."
+ generate_api_key: "Generate API key"
+ generate_api_key_description: "Only needed for external services that act as this bot. Discourse plugins don't need one."
+ scope_mode_description: "The key only has this bot's permissions."
+ name: "Name"
+ username: "Username"
+ trust_level: "Trust level"
+ create: "Create bot"
+ created: "Bot @%{username} created."
+ created_by: "Created by @%{username}"
titles:
active: "Active users"
new: "New users"
@@ -10030,6 +10051,7 @@ en:
silenced: "Silenced users"
suspended: "Suspended users"
staged: "Staged users"
+ bots: "Bots"
not_verified: "Not verified"
check_email:
title: "Reveal this user's email address"
@@ -10042,6 +10064,8 @@ en:
text: "Delete associated accounts"
user:
+ account_type: "Account type"
+ bot: "Bot"
suspend_failed: "Something went wrong suspending this user %{error}"
unsuspend_failed: "Something went wrong unsuspending this user %{error}"
suspend_duration: "Suspend user until:"
@@ -10152,10 +10176,10 @@ en:
like_count: Likes Given / Received
last_100_days: "in the last 100 days"
private_topics_count: Personal Messages
- posts_read_count: Posts Read
- post_count: Posts Created
+ posts_read_count: Posts read
+ post_count: Posts created
second_factor_enabled: Two-Factor Authentication Enabled
- topics_entered: Topics Viewed
+ topics_entered: Topics viewed
flags_given_count: Flags Given
flags_received_count: Flags Received
warnings_received_count: Warnings Received
diff --git a/config/routes.rb b/config/routes.rb
index c83ef7df697..4a238001734 100644
--- a/config/routes.rb
+++ b/config/routes.rb
@@ -171,6 +171,11 @@ Discourse::Application.routes.draw do
end
resources :groups, only: [:destroy], constraints: AdminConstraint.new
+ get "users/bots/new" => "users#new_bot"
+ get "users/bots/username_suggestion" => "users#bot_username_suggestion",
+ :constraints => AdminConstraint.new
+ post "users/bots" => "users#create_bot", :constraints => AdminConstraint.new
+
resources :users, id: RouteFormat.username, only: %i[index destroy] do
collection do
get "list" => "users#index"
diff --git a/frontend/discourse/admin/components/admin-bot-form.gjs b/frontend/discourse/admin/components/admin-bot-form.gjs
new file mode 100644
index 00000000000..478a878b3c9
--- /dev/null
+++ b/frontend/discourse/admin/components/admin-bot-form.gjs
@@ -0,0 +1,280 @@
+import Component from "@glimmer/component";
+import { cached, tracked } from "@glimmer/tracking";
+import { action } from "@ember/object";
+import { service } from "@ember/service";
+import ApiKeyScopeFields from "discourse/admin/components/api-key-scope-fields";
+import GeneratedApiKey from "discourse/admin/components/generated-api-key";
+import {
+ buildScopesFormData,
+ scopesPayload,
+ selectedScopes,
+ validateGranularScopes,
+} from "discourse/admin/lib/api-key-scopes";
+import Form from "discourse/components/form";
+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 DiscourseURL, { applyQueryParams } from "discourse/lib/url";
+import DButton from "discourse/ui-kit/d-button";
+import { i18n } from "discourse-i18n";
+
+export default class AdminBotForm extends Component {
+ @service router;
+ @service site;
+ @service siteSettings;
+ @service toasts;
+
+ @tracked generatedApiKey;
+ @tracked createdKeyData;
+
+ #formApi;
+ // Suggestions only replace a username the admin hasn't typed themselves.
+ #suggestedUsername = "";
+
+ @cached
+ get formData() {
+ return {
+ name: "",
+ username: "",
+ trust_level: this.args.defaultTrustLevel,
+ generate_api_key: false,
+ scope_mode: "global",
+ scopes: buildScopesFormData(this.args.apiKeyScopes.scopes),
+ };
+ }
+
+ get usernameValidation() {
+ return `required|length:${this.siteSettings.min_username_length},${this.siteSettings.max_username_length}`;
+ }
+
+ get #usernameIsSuggested() {
+ return (this.#formApi.get("username") ?? "") === this.#suggestedUsername;
+ }
+
+ @action
+ registerFormApi(api) {
+ this.#formApi = api;
+ }
+
+ @action
+ async updateName(name, { set }) {
+ await set("name", name);
+
+ if (this.#usernameIsSuggested) {
+ discourseDebounce(this, this.#suggestUsername, name, 300);
+ }
+ }
+
+ @action
+ validate(data, helpers) {
+ helpers.removeError("base");
+
+ if (data.generate_api_key) {
+ validateGranularScopes(data, helpers);
+ } else {
+ helpers.removeError("scopes");
+ }
+ }
+
+ @action
+ async createBot(data) {
+ const payload = {
+ bot: {
+ name: data.name,
+ username: data.username,
+ trust_level: Number(data.trust_level),
+ },
+ };
+
+ if (data.generate_api_key) {
+ payload.key = { scope_mode: data.scope_mode };
+
+ const scopes = scopesPayload(
+ data.scope_mode,
+ data.scopes,
+ this.args.apiKeyScopes.globalScopes
+ );
+ if (scopes) {
+ payload.key.scopes = scopes;
+ }
+ }
+
+ let result;
+ try {
+ result = await ajax("/admin/users/bots.json", {
+ type: "POST",
+ contentType: "application/json",
+ data: JSON.stringify(payload),
+ });
+ } catch (error) {
+ this.#formApi.addError("base", {
+ title: i18n("admin.users.bots.create"),
+ message: extractError(error),
+ });
+ return;
+ }
+
+ this.toasts.success({
+ duration: "short",
+ data: {
+ message: i18n("admin.users.bots.created", {
+ username: result.user.username,
+ }),
+ },
+ });
+
+ if (result.key) {
+ this.generatedApiKey = result.key.key;
+ this.createdKeyData = {
+ description: result.key.description,
+ scopeMode: data.scope_mode,
+ scopes:
+ data.scope_mode === "granular" ? selectedScopes(data.scopes) : null,
+ };
+ } else {
+ await this.showBots();
+ }
+ }
+
+ @action
+ async showBots() {
+ const botsUrl = applyQueryParams(
+ this.router.urlFor("adminUsersList.show", "bots"),
+ {
+ filter: null,
+ username: null,
+ order: "created",
+ asc: null,
+ account_type: null,
+ activation: null,
+ }
+ );
+ await this.router.transitionTo(withoutPrefix(botsUrl));
+ // The list manages sorting outside Ember's query-param registry.
+ DiscourseURL.replaceState(botsUrl);
+ }
+
+ async #suggestUsername(name) {
+ let username = "";
+ if (name?.trim()) {
+ try {
+ ({ username } = await ajax(
+ "/admin/users/bots/username_suggestion.json",
+ {
+ data: { name },
+ }
+ ));
+ } catch {
+ return;
+ }
+ }
+
+ if (
+ this.isDestroying ||
+ this.#formApi.get("name") !== name ||
+ !this.#usernameIsSuggested
+ ) {
+ return;
+ }
+
+ this.#suggestedUsername = username ?? "";
+ await this.#formApi.set("username", this.#suggestedUsername);
+ }
+
+ <template>
+ {{#if this.generatedApiKey}}
+ <GeneratedApiKey
+ @apiKey={{this.generatedApiKey}}
+ @details={{this.createdKeyData}}
+ >
+ <DButton
+ class="btn-default admin-bot-form__back"
+ @action={{this.showBots}}
+ @label="admin.users.bots.back"
+ />
+ </GeneratedApiKey>
+ {{else}}
+ <Form
+ class="admin-bot-form"
+ ...attributes
+ @data={{this.formData}}
+ @onRegisterApi={{this.registerFormApi}}
+ @onSubmit={{this.createBot}}
+ @validate={{this.validate}}
+ as |form transientData|
+ >
+ <form.Field
+ @format="large"
+ @name="name"
+ @onSet={{this.updateName}}
+ @title={{i18n "admin.users.bots.name"}}
+ @type="input"
+ @validation={{if @nameRequired "required"}}
+ as |field|
+ >
+ <field.Control />
+ </form.Field>
+
+ <form.Field
+ @format="large"
+ @name="username"
+ @title={{i18n "admin.users.bots.username"}}
+ @type="input"
+ @validation={{this.usernameValidation}}
+ as |field|
+ >
+ <field.Control />
+ </form.Field>
+
+ <form.Field
+ @format="large"
+ @name="trust_level"
+ @title={{i18n "admin.users.bots.trust_level"}}
+ @type="select"
+ @validation="required"
+ as |field|
+ >
+ <field.Control as |control|>
+ {{#each this.site.trustLevels as |trustLevel|}}
+ <control.Option @value={{trustLevel.id}}>
+ {{trustLevel.detailedName}}
+ </control.Option>
+ {{/each}}
+ </field.Control>
+ </form.Field>
+
+ <form.Field
+ @description={{i18n "admin.users.bots.generate_api_key_description"}}
+ @format="large"
+ @name="generate_api_key"
+ @title={{i18n "admin.users.bots.generate_api_key"}}
+ @type="toggle"
+ as |field|
+ >
+ <field.Control />
+ </form.Field>
+
+ {{#if transientData.generate_api_key}}
+ <ApiKeyScopeFields
+ @form={{form}}
+ @scopeModeDescription={{i18n
+ "admin.users.bots.scope_mode_description"
+ }}
+ @transientData={{transientData}}
+ />
+ {{/if}}
+
+ <form.Actions>
+ <form.Submit @label="admin.users.bots.create" />
+ <form.Button
+ class="btn-default admin-bot-form__cancel"
+ @label="cancel"
+ @route="adminUsersList.show"
+ @routeModels="bots"
+ />
+ </form.Actions>
+ </Form>
+ {{/if}}
+ </template>
+}
diff --git a/frontend/discourse/admin/components/admin-config-areas/api-keys-new.gjs b/frontend/discourse/admin/components/admin-config-areas/api-keys-new.gjs
index 72828104c91..5e371b8956c 100644
--- a/frontend/discourse/admin/components/admin-config-areas/api-keys-new.gjs
+++ b/frontend/discourse/admin/components/admin-config-areas/api-keys-new.gjs
@@ -1,39 +1,26 @@
import Component from "@glimmer/component";
import { cached, tracked } from "@glimmer/tracking";
-import { concat, fn, get, hash } from "@ember/helper";
+import { fn, hash } from "@ember/helper";
import { action } from "@ember/object";
import { service } from "@ember/service";
-import ApiKeyUrlsModal from "discourse/admin/components/modal/api-key-urls";
-import { API_KEY_SCOPE_MODES } from "discourse/admin/lib/constants";
+import ApiKeyScopeFields from "discourse/admin/components/api-key-scope-fields";
+import GeneratedApiKey from "discourse/admin/components/generated-api-key";
+import {
+ buildScopesFormData,
+ loadApiKeyScopes,
+ scopesPayload,
+ selectedScopes,
+ validateGranularScopes,
+} from "discourse/admin/lib/api-key-scopes";
import BackButton from "discourse/components/back-button";
import Form from "discourse/components/form";
-import { ajax } from "discourse/lib/ajax";
import { popupAjaxError } from "discourse/lib/ajax-error";
-import { bind } from "discourse/lib/decorators";
-import { clipboardCopy } from "discourse/lib/utilities";
import EmailGroupUserChooser from "discourse/select-kit/components/email-group-user-chooser";
import DButton from "discourse/ui-kit/d-button";
import DConditionalLoadingSection from "discourse/ui-kit/d-conditional-loading-section";
-import dIcon from "discourse/ui-kit/helpers/d-icon";
import { i18n } from "discourse-i18n";
-/**
- * @typedef {{
- * scope_id: string,
- * key: string,
- * name: string,
- * params: string[] | null,
- * urls: string[]
- * }} ApiKeyScopeDefinition
- */
-/**
- * @typedef {{
- * scope_id: string,
- * key: string,
- * name: string,
- * params: string[]
- * } & Record<string, string | string[] | undefined>} SelectedApiKeyScope
- */
+/** @import { ApiKeyScopeDefinition, SelectedApiKeyScope } from "discourse/admin/lib/api-key-scopes" */
/**
* @typedef {{
* description: string,
@@ -42,9 +29,7 @@ import { i18n } from "discourse-i18n";
* }} CreatedApiKeyData
*/
export default class AdminConfigAreasApiKeysNew extends Component {
- @service modal;
@service store;
- @service toasts;
@tracked username;
@tracked loadingScopes = false;
@@ -63,9 +48,7 @@ export default class AdminConfigAreasApiKeysNew extends Component {
{ id: "single", name: i18n("admin.api.single_user") },
];
- scopeModes = API_KEY_SCOPE_MODES.map((scopeMode) => {
- return { id: scopeMode, name: i18n(`admin.api.scopes.${scopeMode}`) };
- });
+ validateGranularScopes = validateGranularScopes;
/** @type {ApiKeyScopeDefinition[] | null} */
globalScopes = null;
@@ -77,36 +60,13 @@ export default class AdminConfigAreasApiKeysNew extends Component {
@cached
get formData() {
- let scopes = Object.keys(this.scopes).reduce((result, resource) => {
- result[resource] = this.scopes[resource].map((scope) => {
- const params = scope.params
- ? scope.params.reduce((acc, param) => {
- acc[param] = undefined;
- return acc;
- }, {})
- : {};
-
- return {
- key: scope.key,
- enabled: undefined,
- urls: scope.urls,
- ...(params && { params }),
- };
- });
- return result;
- }, {});
-
return {
user_mode: "all",
scope_mode: "global",
- scopes,
+ scopes: buildScopesFormData(this.scopes),
};
}
- get scopeModeLabel() {
- return i18n(`admin.api.scopes.${this.createdKeyData.scopeMode}`);
- }
-
@action
updateUsername(field, selected) {
this.username = selected[0];
@@ -120,16 +80,17 @@ export default class AdminConfigAreasApiKeysNew extends Component {
scope_mode: data.scope_mode,
};
- if (data.user_mode === "single") {
- payload.username = data.user;
+ const scopes = scopesPayload(
+ data.scope_mode,
+ data.scopes,
+ this.globalScopes
+ );
+ if (scopes) {
+ payload.scopes = scopes;
}
- if (data.scope_mode === "granular") {
- payload.scopes = this.#selectedScopes(data.scopes);
- } else if (data.scope_mode === "read_only") {
- payload.scopes = this.globalScopes.filter(
- (scope) => scope.key === "read"
- );
+ if (data.user_mode === "single") {
+ payload.username = data.user;
}
try {
@@ -139,87 +100,19 @@ export default class AdminConfigAreasApiKeysNew extends Component {
description: data.description,
scopeMode: data.scope_mode,
scopes:
- data.scope_mode === "granular"
- ? this.#selectedScopes(data.scopes)
- : null,
+ data.scope_mode === "granular" ? selectedScopes(data.scopes) : null,
};
} catch (error) {
popupAjaxError(error);
}
}
- @action
- async copyApiKey() {
- await clipboardCopy(this.generatedApiKey);
- this.toasts.success({
- data: { message: i18n("admin.api_keys.key_copied_to_clipboard") },
- duration: "short",
- });
- }
-
- @bind
- atLeastOneGranularScope(data, { addError, removeError }) {
- removeError("scopes");
-
- if (
- data.scope_mode === "granular" &&
- this.#selectedScopes(data.scopes).length === 0
- ) {
- addError("scopes", {
- title: i18n("admin.api.scopes.title"),
- message: i18n("admin.api.scopes.one_or_more"),
- });
- }
- }
-
- @action
- async showURLs(urls) {
- await this.modal.show(ApiKeyUrlsModal, {
- model: { urls },
- });
- }
-
- @action
- paramsObjectKeys(paramsObjectData) {
- return Object.keys(paramsObjectData);
- }
-
- @action
- scopesDataKeys(scopesData) {
- return Object.keys(scopesData).sort();
- }
-
- #selectedScopes(scopes) {
- const enabledScopes = [];
-
- for (const [resource, resourceScopes] of Object.entries(scopes)) {
- enabledScopes.push(
- resourceScopes
- .filter((s) => s.enabled)
- .map((s) => {
- return {
- scope_id: `${resource}:${s.key}`,
- key: s.key,
- name: s.key,
- params: Object.keys(s.params),
- ...s.params,
- };
- })
- );
- }
-
- return enabledScopes.flat();
- }
-
async #loadScopes() {
try {
this.loadingScopes = true;
- const data = await ajax("/admin/api/keys/scopes.json");
-
- this.globalScopes = data.scopes.global;
- delete data.scopes.global;
-
- this.scopes = data.scopes;
+ const { globalScopes, scopes } = await loadApiKeyScopes();
+ this.globalScopes = globalScopes;
+ this.scopes = scopes;
} catch (error) {
popupAjaxError(error);
} finally {
@@ -234,74 +127,22 @@ export default class AdminConfigAreasApiKeysNew extends Component {
<div class="admin-config-area__primary-content">
<div class="admin-config-area-card">
{{#if this.generatedApiKey}}
- <div class="generated-api-key-container">
- <div class="alert alert-warning">
- {{dIcon "triangle-exclamation"}}
- <span>{{i18n "admin.api.not_shown_again"}}</span>
- </div>
-
- {{#if this.createdKeyData}}
- <div class="generated-api-key__details">
- {{#if this.createdKeyData.description}}
- <div class="generated-api-key__detail-row">
- <span class="generated-api-key__label">{{i18n
- "admin.api.description"
- }}</span>
- <span>{{this.createdKeyData.description}}</span>
- </div>
- {{/if}}
- <div class="generated-api-key__detail-row">
- <span class="generated-api-key__label">{{i18n
- "admin.api.scope_mode"
- }}</span>
- <span>{{this.scopeModeLabel}}</span>
- </div>
- {{#if this.createdKeyData.scopes}}
- <div class="generated-api-key__detail-row">
- <span class="generated-api-key__label">{{i18n
- "admin.api.scopes.title"
- }}</span>
- <span class="generated-api-key__scope-badges">
- {{#each this.createdKeyData.scopes as |scope|}}
- <span class="generated-api-key__scope-badge">
- {{scope.scope_id}}
- {{#each scope.params as |paramName|}}
- {{#if (get scope paramName)}}
- <span
- class="generated-api-key__scope-param"
- >({{paramName}}: {{get scope paramName}})</span>
- {{/if}}
- {{/each}}
- </span>
- {{/each}}
- </span>
- </div>
- {{/if}}
- </div>
- {{/if}}
-
- <div class="generated-api-key__key-row">
- <code class="generated-api-key">{{this.generatedApiKey}}</code>
- <DButton
- class="btn-default generated-api-key__copy-btn"
- @action={{this.copyApiKey}}
- @icon="copy"
- @label="admin.api_keys.copy_key"
- />
- </div>
-
+ <GeneratedApiKey
+ @apiKey={{this.generatedApiKey}}
+ @details={{this.createdKeyData}}
+ >
<DButton
class="continue btn-default"
@label="admin.api_keys.continue"
@route="adminApiKeys.index"
/>
- </div>
+ </GeneratedApiKey>
{{else}}
<DConditionalLoadingSection @isLoading={{this.loadingScopes}}>
<Form
@data={{this.formData}}
@onSubmit={{this.save}}
- @validate={{this.atLeastOneGranularScope}}
+ @validate={{this.validateGranularScopes}}
as |form transientData|
>
<form.Field
@@ -354,114 +195,10 @@ export default class AdminConfigAreasApiKeysNew extends Component {
</form.Field>
{{/if}}
- <form.Field
- @format="large"
- @name="scope_mode"
- @title={{i18n "admin.api.scope_mode"}}
- @type="select"
- @validation="required"
- as |field|
- >
- <field.Control as |select|>
- {{#each this.scopeModes as |scopeMode|}}
- <select.Option
- @value={{scopeMode.id}}
- >{{scopeMode.name}}</select.Option>
- {{/each}}
- </field.Control>
- </form.Field>
-
- {{#if (eq transientData.scope_mode "granular")}}
- <h2 class="scopes-title">{{i18n
- "admin.api.scopes.title"
- }}</h2>
- <p>{{i18n "admin.api.scopes.description"}}</p>
- <table class="scopes-table grid">
- <thead>
- <tr>
- <td></td>
- <td>{{i18n "admin.api.scopes.allowed_urls"}}</td>
- <td>{{i18n
- "admin.api.scopes.optional_allowed_parameters"
- }}</td>
- </tr>
- </thead>
- <tbody>
- <form.Object
- class="scopes-table__object"
- @name="scopes"
- as |scopesObject scopesData|
- >
- {{#each (this.scopesDataKeys scopesData) as |scopeKey|}}
- <tr class="scope-resource-name">
- <td><b>{{scopeKey}}</b></td>
- <td></td>
- <td></td>
- <td></td>
- </tr>
-
- <scopesObject.Collection
- @name={{scopeKey}}
- @tagName="div"
- as |topicsCollection index collectionData|
- >
- <tr>
- <td>
- <topicsCollection.Field
- @name="enabled"
- @title={{collectionData.key}}
- @tooltip={{i18n
- (concat
- "admin.api.scopes.descriptions."
- scopeKey
- "."
- collectionData.key
- )
- }}
- @type="checkbox"
- as |field|
- >
- <field.Control />
- </topicsCollection.Field>
- </td>
- <td>
- <DButton
- class="btn-info"
- @action={{fn
- this.showURLs
- collectionData.urls
- }}
- @icon="link"
- />
- </td>
- <td>
- <topicsCollection.Object
- @name="params"
- as |paramsObject paramsObjectData|
- >
- {{#each
- (this.paramsObjectKeys paramsObjectData)
- as |name|
- }}
- <paramsObject.Field
- @name={{name}}
- @showTitle={{false}}
- @title={{name}}
- @type="input"
- as |field|
- >
- <field.Control placeholder={{name}} />
- </paramsObject.Field>
- {{/each}}
- </topicsCollection.Object>
- </td>
- </tr>
- </scopesObject.Collection>
- {{/each}}
- </form.Object>
- </tbody>
- </table>
- {{/if}}
+ <ApiKeyScopeFields
+ @form={{form}}
+ @transientData={{transientData}}
+ />
<form.Actions>
<form.Submit class="save" @label="admin.api_keys.save" />
diff --git a/frontend/discourse/admin/components/admin-new-bot-button.gjs b/frontend/discourse/admin/components/admin-new-bot-button.gjs
new file mode 100644
index 00000000000..46caa0e69b2
--- /dev/null
+++ b/frontend/discourse/admin/components/admin-new-bot-button.gjs
@@ -0,0 +1,72 @@
+import Component from "@glimmer/component";
+import { hash } from "@ember/helper";
+import { action } from "@ember/object";
+import { service } from "@ember/service";
+import { applyValueTransformer } from "discourse/lib/transformer";
+import DropdownSelectBox from "discourse/select-kit/components/dropdown-select-box";
+import { i18n } from "discourse-i18n";
+
+const BOT_OPTION = {
+ id: "bot",
+ icon: "robot",
+ label: "admin.users.bots.new_options.bot.label",
+ description: "admin.users.bots.new_options.bot.description",
+ route: "adminBotsNew",
+};
+
+/**
+ * The "New bot" action for the bots list. Becomes a dropdown explaining each
+ * path when other bot-creating flows are registered via `admin-new-bot-options`.
+ */
+export default class AdminNewBotButton extends Component {
+ @service router;
+
+ get options() {
+ return applyValueTransformer("admin-new-bot-options", [BOT_OPTION]);
+ }
+
+ get hasChoices() {
+ return this.options.length > 1;
+ }
+
+ get content() {
+ return this.options.map((option) => ({
+ id: option.id,
+ name: i18n(option.label),
+ description: i18n(option.description),
+ icon: option.icon,
+ }));
+ }
+
+ @action
+ select(id) {
+ const option = this.options.find((o) => o.id === id);
+ this.router.transitionTo(option.route, ...(option.routeModels ?? []), {
+ queryParams: option.queryParams ?? {},
+ });
+ }
+
+ <template>
+ {{#if this.hasChoices}}
+ <@actions.Wrapped>
+ <DropdownSelectBox
+ class="admin-users__subheader-new-bot"
+ @content={{this.content}}
+ @onChange={{this.select}}
+ @options={{hash
+ showCaret=true
+ translatedNone=(i18n "admin.users.bots.new")
+ customStyle=true
+ btnCustomClasses="btn-primary btn-small"
+ }}
+ />
+ </@actions.Wrapped>
+ {{else}}
+ <@actions.Primary
+ class="admin-users__subheader-new-bot"
+ @label="admin.users.bots.new"
+ @route="adminBotsNew"
+ />
+ {{/if}}
+ </template>
+}
diff --git a/frontend/discourse/admin/components/api-key-scope-fields.gjs b/frontend/discourse/admin/components/api-key-scope-fields.gjs
new file mode 100644
index 00000000000..404a5ff3dba
--- /dev/null
+++ b/frontend/discourse/admin/components/api-key-scope-fields.gjs
@@ -0,0 +1,147 @@
+import Component from "@glimmer/component";
+import { concat, fn } from "@ember/helper";
+import { action } from "@ember/object";
+import { service } from "@ember/service";
+import ApiKeyUrlsModal from "discourse/admin/components/modal/api-key-urls";
+import { API_KEY_SCOPE_MODES } from "discourse/admin/lib/constants";
+import DButton from "discourse/ui-kit/d-button";
+import { i18n } from "discourse-i18n";
+
+/**
+ * Scope mode select and granular scopes table for an API key FormKit form.
+ * The form data needs `scope_mode`, plus `scopes` built with
+ * `buildScopesFormData`.
+ */
+export default class ApiKeyScopeFields extends Component {
+ @service modal;
+
+ scopeModes = API_KEY_SCOPE_MODES.map((scopeMode) => {
+ return { id: scopeMode, name: i18n(`admin.api.scopes.${scopeMode}`) };
+ });
+
+ @action
+ async showURLs(urls) {
+ await this.modal.show(ApiKeyUrlsModal, {
+ model: { urls },
+ });
+ }
+
+ @action
+ paramsObjectKeys(paramsObjectData) {
+ return Object.keys(paramsObjectData);
+ }
+
+ @action
+ scopesDataKeys(scopesData) {
+ return Object.keys(scopesData).sort();
+ }
+
+ <template>
+ <@form.Field
+ @description={{@scopeModeDescription}}
+ @format="large"
+ @name="scope_mode"
+ @title={{i18n "admin.api.scope_mode"}}
+ @type="select"
+ @validation="required"
+ as |field|
+ >
+ <field.Control as |select|>
+ {{#each this.scopeModes as |scopeMode|}}
+ <select.Option
+ @value={{scopeMode.id}}
+ >{{scopeMode.name}}</select.Option>
+ {{/each}}
+ </field.Control>
+ </@form.Field>
+
+ {{#if (eq @transientData.scope_mode "granular")}}
+ <@form.Section
+ class="api-key-scopes"
+ @subtitle={{i18n "admin.api.scopes.description"}}
+ @title={{i18n "admin.api.scopes.title"}}
+ >
+ <table class="scopes-table grid">
+ <thead>
+ <tr>
+ <td></td>
+ <td>{{i18n "admin.api.scopes.allowed_urls"}}</td>
+ <td>{{i18n "admin.api.scopes.optional_allowed_parameters"}}</td>
+ </tr>
+ </thead>
+ <tbody>
+ <@form.Object
+ class="scopes-table__object"
+ @name="scopes"
+ as |scopesObject scopesData|
+ >
+ {{#each (this.scopesDataKeys scopesData) as |scopeKey|}}
+ <tr class="scope-resource-name">
+ <td><b>{{scopeKey}}</b></td>
+ <td></td>
+ <td></td>
+ <td></td>
+ </tr>
+
+ <scopesObject.Collection
+ @name={{scopeKey}}
+ @tagName="div"
+ as |topicsCollection index collectionData|
+ >
+ <tr>
+ <td>
+ <topicsCollection.Field
+ @name="enabled"
+ @title={{collectionData.key}}
+ @tooltip={{i18n
+ (concat
+ "admin.api.scopes.descriptions."
+ scopeKey
+ "."
+ collectionData.key
+ )
+ }}
+ @type="checkbox"
+ as |field|
+ >
+ <field.Control />
+ </topicsCollection.Field>
+ </td>
+ <td>
+ <DButton
+ class="btn-info"
+ @action={{fn this.showURLs collectionData.urls}}
+ @icon="link"
+ />
+ </td>
+ <td>
+ <topicsCollection.Object
+ @name="params"
+ as |paramsObject paramsObjectData|
+ >
+ {{#each
+ (this.paramsObjectKeys paramsObjectData)
+ as |name|
+ }}
+ <paramsObject.Field
+ @name={{name}}
+ @showTitle={{false}}
+ @title={{name}}
+ @type="input"
+ as |field|
+ >
+ <field.Control placeholder={{name}} />
+ </paramsObject.Field>
+ {{/each}}
+ </topicsCollection.Object>
+ </td>
+ </tr>
+ </scopesObject.Collection>
+ {{/each}}
+ </@form.Object>
+ </tbody>
+ </table>
+ </@form.Section>
+ {{/if}}
+ </template>
+}
diff --git a/frontend/discourse/admin/components/generated-api-key.gjs b/frontend/discourse/admin/components/generated-api-key.gjs
new file mode 100644
index 00000000000..0802b62c536
--- /dev/null
+++ b/frontend/discourse/admin/components/generated-api-key.gjs
@@ -0,0 +1,91 @@
+import Component from "@glimmer/component";
+import { get } from "@ember/helper";
+import { action } from "@ember/object";
+import { service } from "@ember/service";
+import { clipboardCopy } from "discourse/lib/utilities";
+import DButton from "discourse/ui-kit/d-button";
+import dIcon from "discourse/ui-kit/helpers/d-icon";
+import { i18n } from "discourse-i18n";
+
+/**
+ * Shows a newly created API key once, with a summary of what it can do.
+ * Yields so the caller can provide the way out of this screen.
+ */
+export default class GeneratedApiKey extends Component {
+ @service toasts;
+
+ get scopeModeLabel() {
+ return i18n(`admin.api.scopes.${this.args.details.scopeMode}`);
+ }
+
+ @action
+ async copyApiKey() {
+ await clipboardCopy(this.args.apiKey);
+ this.toasts.success({
+ data: { message: i18n("admin.api_keys.key_copied_to_clipboard") },
+ duration: "short",
+ });
+ }
+
+ <template>
+ <div class="generated-api-key-container">
+ <div class="alert alert-warning">
+ {{dIcon "triangle-exclamation"}}
+ <span>{{i18n "admin.api.not_shown_again"}}</span>
+ </div>
+
+ {{#if @details}}
+ <div class="generated-api-key__details">
+ {{#if @details.description}}
+ <div class="generated-api-key__detail-row">
+ <span class="generated-api-key__label">{{i18n
+ "admin.api.description"
+ }}</span>
+ <span>{{@details.description}}</span>
+ </div>
+ {{/if}}
+ <div class="generated-api-key__detail-row">
+ <span class="generated-api-key__label">{{i18n
+ "admin.api.scope_mode"
+ }}</span>
+ <span>{{this.scopeModeLabel}}</span>
+ </div>
+ {{#if @details.scopes}}
+ <div class="generated-api-key__detail-row">
+ <span class="generated-api-key__label">{{i18n
+ "admin.api.scopes.title"
+ }}</span>
+ <span class="generated-api-key__scope-badges">
+ {{#each @details.scopes as |scope|}}
+ <span class="generated-api-key__scope-badge">
+ {{scope.scope_id}}
+ {{#each scope.params as |paramName|}}
+ {{#if (get scope paramName)}}
+ <span
+ class="generated-api-key__scope-param"
+ >({{paramName}}:
+ {{get scope paramName}})</span>
+ {{/if}}
+ {{/each}}
+ </span>
+ {{/each}}
+ </span>
+ </div>
+ {{/if}}
+ </div>
+ {{/if}}
+
+ <div class="generated-api-key__key-row">
+ <code class="generated-api-key">{{@apiKey}}</code>
+ <DButton
+ class="btn-default generated-api-key__copy-btn"
+ @action={{this.copyApiKey}}
+ @icon="copy"
+ @label="admin.api_keys.copy_key"
+ />
+ </div>
+
+ {{yield}}
+ </div>
+ </template>
+}
diff --git a/frontend/discourse/admin/controllers/admin-user/index.js b/frontend/discourse/admin/controllers/admin-user/index.js
index c6b38d83598..d52009e0796 100644
--- a/frontend/discourse/admin/controllers/admin-user/index.js
+++ b/frontend/discourse/admin/controllers/admin-user/index.js
@@ -42,6 +42,11 @@ export default class AdminUserIndexController extends Controller {
ssoLastPayload = null;
isLoading = false;
+ @computed("model.id")
+ get isBot() {
+ return Number.isInteger(this.model?.id) && this.model.id <= 0;
+ }
+
@computed("siteSettings.enable_badges")
get showBadges() {
return this.siteSettings.enable_badges;
diff --git a/frontend/discourse/admin/controllers/admin-users-list/show.js b/frontend/discourse/admin/controllers/admin-users-list/show.js
index 475c213deb6..4f4d15288d0 100644
--- a/frontend/discourse/admin/controllers/admin-users-list/show.js
+++ b/frontend/discourse/admin/controllers/admin-users-list/show.js
@@ -46,14 +46,15 @@ export default class AdminUsersListShowController extends Controller {
/** @type {boolean | string | null | undefined} */
@tracked asc = null;
- @tracked showEmails = false;
/** @type {HTMLInputElement | null} */
lastSelected = null;
#page = 1;
+
#results = trackedArray();
#canLoadMore = true;
+ @tracked _showEmails = false;
get users() {
return this.#results.flat();
@@ -66,6 +67,22 @@ export default class AdminUsersListShowController extends Controller {
get columnCount() {
let colCount = 7; // note that the first column is hardcoded in the template
+ if (this.showSource) {
+ colCount += 1;
+ }
+
+ if (this.showPostCount) {
+ colCount += 1;
+ }
+
+ if (!this.showLastEmailed) {
+ colCount -= 1;
+ }
+
+ if (!this.showReadTime) {
+ colCount -= 1;
+ }
+
if (this.showEmails) {
colCount += 1;
}
@@ -78,6 +95,10 @@ export default class AdminUsersListShowController extends Controller {
}
get canCheckEmails() {
+ if (this.query === "bots") {
+ return false;
+ }
+
return new CanCheckEmailsHelper(
this.model?.id,
this.siteSettings.moderators_view_emails,
@@ -85,10 +106,30 @@ export default class AdminUsersListShowController extends Controller {
).canCheckEmails;
}
+ get showEmails() {
+ return this.canCheckEmails && this._showEmails;
+ }
+
+ get showLastEmailed() {
+ return this.query !== "bots";
+ }
+
+ get showPostCount() {
+ return this.query === "bots";
+ }
+
+ get showReadTime() {
+ return this.query !== "bots";
+ }
+
get showSilenceReason() {
return this.query === "silenced";
}
+ get showSource() {
+ return this.query === "bots" && this.currentUser.admin;
+ }
+
get showSuspendReason() {
return this.query === "suspended";
}
@@ -164,7 +205,7 @@ export default class AdminUsersListShowController extends Controller {
@action
toggleEmailVisibility() {
- this.showEmails = !this.showEmails;
+ this._showEmails = !this._showEmails;
this.resetFilters();
}
diff --git a/frontend/discourse/admin/lib/api-key-scopes.js b/frontend/discourse/admin/lib/api-key-scopes.js
new file mode 100644
index 00000000000..b281b000e98
--- /dev/null
+++ b/frontend/discourse/admin/lib/api-key-scopes.js
@@ -0,0 +1,110 @@
+import { ajax } from "discourse/lib/ajax";
+import { i18n } from "discourse-i18n";
+
+/**
+ * @typedef {{
+ * scope_id: string,
+ * key: string,
+ * name: string,
+ * params: string[] | null,
+ * urls: string[]
+ * }} ApiKeyScopeDefinition
+ */
+/**
+ * @typedef {{
+ * scope_id: string,
+ * key: string,
+ * name: string,
+ * params: string[]
+ * } & Record<string, string | string[] | undefined>} SelectedApiKeyScope
+ */
+
+/**
+ * Fetches the available scopes, with the global ones split out since they
+ * back the read-only scope mode rather than the granular table.
+ *
+ * @returns {Promise<{
+ * globalScopes: ApiKeyScopeDefinition[],
+ * scopes: Record<string, ApiKeyScopeDefinition[]>
+ * }>}
+ */
+export async function loadApiKeyScopes() {
+ const { scopes } = await ajax("/admin/api/keys/scopes.json");
+ const { global: globalScopes, ...resourceScopes } = scopes;
+ return { globalScopes, scopes: resourceScopes };
+}
+
+/**
+ * Builds the initial FormKit data for the granular scopes table.
+ *
+ * @param {Record<string, ApiKeyScopeDefinition[]>} scopes
+ */
+export function buildScopesFormData(scopes) {
+ return Object.fromEntries(
+ Object.entries(scopes).map(([resource, resourceScopes]) => [
+ resource,
+ resourceScopes.map((scope) => ({
+ key: scope.key,
+ enabled: undefined,
+ urls: scope.urls,
+ params: Object.fromEntries(
+ (scope.params ?? []).map((param) => [param, undefined])
+ ),
+ })),
+ ])
+ );
+}
+
+/**
+ * @param {Record<string, any[]>} scopesData granular scopes form data
+ * @returns {SelectedApiKeyScope[]}
+ */
+export function selectedScopes(scopesData) {
+ return Object.entries(scopesData).flatMap(([resource, resourceScopes]) =>
+ resourceScopes
+ .filter((scope) => scope.enabled)
+ .map((scope) => ({
+ scope_id: `${resource}:${scope.key}`,
+ key: scope.key,
+ name: scope.key,
+ params: Object.keys(scope.params),
+ ...scope.params,
+ }))
+ );
+}
+
+/**
+ * The scopes to send for a scope mode; global keys send none.
+ *
+ * @param {string} scopeMode
+ * @param {Record<string, any[]>} scopesData granular scopes form data
+ * @param {ApiKeyScopeDefinition[]} globalScopes
+ * @returns {Array<SelectedApiKeyScope | ApiKeyScopeDefinition> | undefined}
+ */
+export function scopesPayload(scopeMode, scopesData, globalScopes) {
+ if (scopeMode === "granular") {
+ return selectedScopes(scopesData);
+ } else if (scopeMode === "read_only") {
+ return globalScopes.filter((scope) => scope.key === "read");
+ }
+}
+
+/**
+ * FormKit validator requiring a granular key to have at least one scope.
+ *
+ * @param {{ scope_mode: string, scopes: Record<string, any[]> }} data
+ * @param {{ addError: Function, removeError: Function }} helpers
+ */
+export function validateGranularScopes(data, { addError, removeError }) {
+ removeError("scopes");
+
+ if (
+ data.scope_mode === "granular" &&
+ selectedScopes(data.scopes).length === 0
+ ) {
+ addError("scopes", {
+ title: i18n("admin.api.scopes.title"),
+ message: i18n("admin.api.scopes.one_or_more"),
+ });
+ }
+}
diff --git a/frontend/discourse/admin/routes/admin-bots-new.js b/frontend/discourse/admin/routes/admin-bots-new.js
new file mode 100644
index 00000000000..fe7d4429e1f
--- /dev/null
+++ b/frontend/discourse/admin/routes/admin-bots-new.js
@@ -0,0 +1,16 @@
+import { loadApiKeyScopes } from "discourse/admin/lib/api-key-scopes";
+import { ajax } from "discourse/lib/ajax";
+import DiscourseRoute from "discourse/routes/discourse";
+import { i18n } from "discourse-i18n";
+
+export default class AdminBotsNewRoute extends DiscourseRoute {
+ async model() {
+ const defaults = await ajax("/admin/users/bots/new.json");
+ const apiKeyScopes = await loadApiKeyScopes();
+ return { ...defaults, apiKeyScopes };
+ }
+
+ titleToken() {
+ return i18n("admin.users.bots.new");
+ }
+}
diff --git a/frontend/discourse/admin/routes/admin-route-map.js b/frontend/discourse/admin/routes/admin-route-map.js
index a9bf8495d3c..163c2eb46be 100644
--- a/frontend/discourse/admin/routes/admin-route-map.js
+++ b/frontend/discourse/admin/routes/admin-route-map.js
@@ -197,6 +197,11 @@ export default function () {
}
);
+ this.route("adminBotsNew", {
+ path: "/users/bots/new",
+ resetNamespace: true,
+ });
+
this.route(
"adminUsers",
{ path: "/users", resetNamespace: true },
diff --git a/frontend/discourse/admin/templates/admin-bots-new.gjs b/frontend/discourse/admin/templates/admin-bots-new.gjs
new file mode 100644
index 00000000000..661812cbe43
--- /dev/null
+++ b/frontend/discourse/admin/templates/admin-bots-new.gjs
@@ -0,0 +1,27 @@
+import AdminBotForm from "discourse/admin/components/admin-bot-form";
+import AdminConfigAreaCard from "discourse/admin/components/admin-config-area-card";
+import BackButton from "discourse/components/back-button";
+
+export default <template>
+ <BackButton
+ @label="admin.users.bots.back"
+ @model="bots"
+ @route="adminUsersList.show"
+ />
+ <div class="admin-config-area">
+ <div class="admin-config-area__primary-content">
+ <AdminConfigAreaCard
+ @description="admin.users.bots.help"
+ @heading="admin.users.bots.new"
+ >
+ <:content>
+ <AdminBotForm
+ @apiKeyScopes={{@model.apiKeyScopes}}
+ @defaultTrustLevel={{@model.default_trust_level}}
+ @nameRequired={{@model.name_required}}
+ />
+ </:content>
+ </AdminConfigAreaCard>
+ </div>
+ </div>
+</template>
diff --git a/frontend/discourse/admin/templates/admin-user/index.gjs b/frontend/discourse/admin/templates/admin-user/index.gjs
index 2c9eea4c9be..14ca16304ea 100644
--- a/frontend/discourse/admin/templates/admin-user/index.gjs
+++ b/frontend/discourse/admin/templates/admin-user/index.gjs
@@ -68,6 +68,13 @@ export default <template>
/>
</div>
+ {{#if @controller.isBot}}
+ <div class="display-row admin-user__bot-indicator">
+ <div class="field">{{i18n "admin.user.account_type"}}</div>
+ <div class="value">{{dIcon "robot"}} {{i18n "admin.user.bot"}}</div>
+ </div>
+ {{/if}}
+
<div class="display-row name">
<AdminEditableField
@action={{@controller.saveName}}
diff --git a/frontend/discourse/admin/templates/admin-users-list/show.gjs b/frontend/discourse/admin/templates/admin-users-list/show.gjs
index 916d23907cb..d6a269c3e18 100644
--- a/frontend/discourse/admin/templates/admin-users-list/show.gjs
+++ b/frontend/discourse/admin/templates/admin-users-list/show.gjs
@@ -2,6 +2,7 @@ import { concat, fn, get } from "@ember/helper";
import { on } from "@ember/modifier";
import { LinkTo } from "@ember/routing";
import { trustHTML } from "@ember/template";
+import AdminNewBotButton from "discourse/admin/components/admin-new-bot-button";
import { USER_ACCOUNT_TYPES } from "discourse/admin/lib/user-account-types";
import PluginOutlet from "discourse/components/plugin-outlet";
import DMenu from "discourse/float-kit/components/d-menu";
@@ -54,6 +55,9 @@ const ACCOUNT_TYPE_FILTER_OPTIONS = [
export default <template>
<DPageSubheader @titleLabel={{@controller.title}}>
<:actions as |actions|>
+ {{#if (and (eq @controller.query "bots") @controller.currentUser.admin)}}
+ <AdminNewBotButton @actions={{actions}} />
+ {{/if}}
{{#if @controller.canCheckEmails}}
{{#if @controller.showEmails}}
<actions.Default
@@ -208,6 +212,13 @@ export default <template>
@order={{@controller.order}}
/>
</div>
+ {{#if @controller.showSource}}
+ <div
+ class="directory-table__column-header admin-users-list__source-header"
+ >
+ {{i18n "admin.users.source"}}
+ </div>
+ {{/if}}
<DTableHeaderToggle
class={{if
@controller.showEmails
@@ -221,14 +232,16 @@ export default <template>
@onToggle={{@controller.updateOrder}}
@order={{@controller.order}}
/>
- <DTableHeaderToggle
- @asc={{@controller.asc}}
- @automatic={{true}}
- @field="last_emailed"
- @labelKey="admin.users.last_emailed"
- @onToggle={{@controller.updateOrder}}
- @order={{@controller.order}}
- />
+ {{#if @controller.showLastEmailed}}
+ <DTableHeaderToggle
+ @asc={{@controller.asc}}
+ @automatic={{true}}
+ @field="last_emailed"
+ @labelKey="admin.users.last_emailed"
+ @onToggle={{@controller.updateOrder}}
+ @order={{@controller.order}}
+ />
+ {{/if}}
<DTableHeaderToggle
@asc={{@controller.asc}}
@automatic={{true}}
@@ -257,14 +270,26 @@ export default <template>
@onToggle={{@controller.updateOrder}}
@order={{@controller.order}}
/>
- <DTableHeaderToggle
- @asc={{@controller.asc}}
- @automatic={{true}}
- @field="read_time"
- @labelKey="admin.user.time_read"
- @onToggle={{@controller.updateOrder}}
- @order={{@controller.order}}
- />
+ {{#if @controller.showPostCount}}
+ <DTableHeaderToggle
+ @asc={{@controller.asc}}
+ @automatic={{true}}
+ @field="posts"
+ @labelKey="admin.user.post_count"
+ @onToggle={{@controller.updateOrder}}
+ @order={{@controller.order}}
+ />
+ {{/if}}
+ {{#if @controller.showReadTime}}
+ <DTableHeaderToggle
+ @asc={{@controller.asc}}
+ @automatic={{true}}
+ @field="read_time"
+ @labelKey="admin.user.time_read"
+ @onToggle={{@controller.updateOrder}}
+ @order={{@controller.order}}
+ />
+ {{/if}}
<DTableHeaderToggle
@asc={{@controller.asc}}
@automatic={{true}}
@@ -318,6 +343,7 @@ export default <template>
class="user
{{user.selected}}
{{unless user.active 'not-activated'}}
+ {{if user.bot_inactive 'not-activated'}}
directory-table__row"
data-user-id={{user.id}}
>
@@ -361,13 +387,75 @@ export default <template>
>
{{dAvatar user imageSize="small"}}
</a>
- <LinkTo @model={{user}} @route="adminUser">
+ <LinkTo
+ class="admin-users-list__username"
+ title={{user.username}}
+ @model={{user}}
+ @route="adminUser"
+ >
{{user.username}}
</LinkTo>
{{#if user.staged}}
{{dIcon "far-envelope" title="user.staged"}}
{{/if}}
</div>
+ {{#if @controller.showSource}}
+ <div class="directory-table__cell admin-users-list__source">
+ <span class="directory-table__label">
+ <span>{{i18n "admin.users.source"}}</span>
+ </span>
+ <div
+ class="directory-table__value admin-users-list__source-values"
+ >
+ {{#each user.sources as |source|}}
+ <div class="admin-users-list__source-item">
+ {{#if source.note}}
+ <DTooltip
+ class="admin-users-list__source-label"
+ @content={{source.note}}
+ @label={{source.label}}
+ />
+ {{else if source.url}}
+ <a
+ class="admin-users-list__source-label"
+ href={{source.url}}
+ title={{source.label}}
+ >{{source.label}}</a>
+ {{else}}
+ <span
+ class="admin-users-list__source-label"
+ title={{source.label}}
+ >{{source.label}}</span>
+ {{/if}}
+ </div>
+ {{else}}
+ {{#if user.bot_creator}}
+ <div
+ class="admin-users-list__source-item"
+ title={{i18n
+ "admin.users.bots.created_by"
+ username=user.bot_creator.username
+ }}
+ >
+ <a
+ aria-label={{i18n
+ "admin.users.bots.created_by"
+ username=user.bot_creator.username
+ }}
+ class="admin-users-list__source-label admin-users-list__source-user"
+ href={{user.bot_creator.url}}
+ >
+ {{dAvatar user.bot_creator imageSize="tiny"}}
+ {{user.bot_creator.username}}
+ </a>
+ </div>
+ {{else}}
+ &mdash;
+ {{/if}}
+ {{/each}}
+ </div>
+ </div>
+ {{/if}}
<div
class="directory-table__cell email
{{if @controller.showEmails '' 'hidden'}}"
@@ -377,27 +465,29 @@ export default <template>
</span>
</div>
- {{#if user.last_emailed_at}}
- <div
- class="directory-table__cell last-emailed"
- title={{rawDate user.last_emailed_at}}
- >
- <span class="directory-table__label">
- <span>{{i18n "admin.users.last_emailed"}}</span>
- </span>
- <span class="directory-table__value">
- {{dFormatDuration user.last_emailed_age}}
- </span>
- </div>
- {{else}}
- <div class="directory-table__cell last-emailed">
- <span class="directory-table__label">
- <span>{{i18n "admin.users.last_emailed"}}</span>
- </span>
- <span class="directory-table__value">
- {{dFormatDuration user.last_emailed_age}}
- </span>
- </div>
+ {{#if @controller.showLastEmailed}}
+ {{#if user.last_emailed_at}}
+ <div
+ class="directory-table__cell last-emailed"
+ title={{rawDate user.last_emailed_at}}
+ >
+ <span class="directory-table__label">
+ <span>{{i18n "admin.users.last_emailed"}}</span>
+ </span>
+ <span class="directory-table__value">
+ {{dFormatDuration user.last_emailed_age}}
+ </span>
+ </div>
+ {{else}}
+ <div class="directory-table__cell last-emailed">
+ <span class="directory-table__label">
+ <span>{{i18n "admin.users.last_emailed"}}</span>
+ </span>
+ <span class="directory-table__value">
+ {{dFormatDuration user.last_emailed_age}}
+ </span>
+ </div>
+ {{/if}}
{{/if}}
<div
@@ -434,14 +524,28 @@ export default <template>
{{dNumber user.posts_read_count}}
</span>
</div>
- <div class="directory-table__cell time-read">
- <span class="directory-table__label">
- <span>{{i18n "admin.user.time_read"}}</span>
- </span>
- <span class="directory-table__value">
- {{dFormatDuration user.time_read}}
- </span>
- </div>
+ {{#if @controller.showPostCount}}
+ <div
+ class="directory-table__cell admin-users-list__posts-created"
+ >
+ <span class="directory-table__label">
+ <span>{{i18n "admin.user.post_count"}}</span>
+ </span>
+ <span class="directory-table__value">
+ {{dNumber user.post_count}}
+ </span>
+ </div>
+ {{/if}}
+ {{#if @controller.showReadTime}}
+ <div class="directory-table__cell time-read">
+ <span class="directory-table__label">
+ <span>{{i18n "admin.user.time_read"}}</span>
+ </span>
+ <span class="directory-table__value">
+ {{dFormatDuration user.time_read}}
+ </span>
+ </div>
+ {{/if}}
<div
class="directory-table__cell created"
title={{rawDate user.created_at}}
diff --git a/frontend/discourse/admin/templates/admin-users.gjs b/frontend/discourse/admin/templates/admin-users.gjs
index 1f984fb6f54..ff43e8ab781 100644
--- a/frontend/discourse/admin/templates/admin-users.gjs
+++ b/frontend/discourse/admin/templates/admin-users.gjs
@@ -80,9 +80,10 @@ export default <template>
@routeParam="staged"
/>
<DNavItem
- class="admin-users-tabs__groups"
- @label="groups.index.title"
- @route="adminGroups.index"
+ class="admin-users-tabs__bots"
+ @label="admin.users.nav.bots"
+ @route="adminUsersList.show"
+ @routeParam="bots"
/>
</:tabs>
</DPageHeader>
diff --git a/frontend/discourse/app/components/user-card-contents.gjs b/frontend/discourse/app/components/user-card-contents.gjs
index 2aff7ee83f0..be47052114c 100644
--- a/frontend/discourse/app/components/user-card-contents.gjs
+++ b/frontend/discourse/app/components/user-card-contents.gjs
@@ -479,14 +479,15 @@ export default class UserCardContents extends CardContentsBase {
}}
>
<div class="user-card-avatar-wrapper">
- <div aria-hidden="true" class="user-card-avatar">
+ <div class="user-card-avatar">
{{#if this.contentHidden}}
- <span class="card-huge-avatar">{{dBoundAvatar
- this.user
- "huge"
- }}</span>
+ <span
+ aria-hidden="true"
+ class="card-huge-avatar"
+ >{{dBoundAvatar this.user "huge"}}</span>
{{else}}
<a
+ aria-hidden="true"
class="card-huge-avatar"
href={{this.avatarUrl}}
tabindex="-1"
diff --git a/frontend/discourse/app/lib/registry/transformers.ts b/frontend/discourse/app/lib/registry/transformers.ts
index 76c9324aeb5..49415a89ddc 100644
--- a/frontend/discourse/app/lib/registry/transformers.ts
+++ b/frontend/discourse/app/lib/registry/transformers.ts
@@ -42,6 +42,7 @@ export const BEHAVIOR_TRANSFORMERS = Object.freeze([
// eslint-discourse keep-array-sorted
export const VALUE_TRANSFORMERS = Object.freeze([
"admin-dashboard-report-renderer",
+ "admin-new-bot-options",
"admin-onboarding-banner-location",
"admin-onboarding-start-posting-options",
"admin-onboarding-steps",
diff --git a/frontend/discourse/app/ui-kit/d-avatar-flair.gjs b/frontend/discourse/app/ui-kit/d-avatar-flair.gjs
index 14727376011..ee5d0367a15 100644
--- a/frontend/discourse/app/ui-kit/d-avatar-flair.gjs
+++ b/frontend/discourse/app/ui-kit/d-avatar-flair.gjs
@@ -51,6 +51,7 @@ export default class DAvatarFlair extends Component {
}}
style={{this.style}}
title={{this.title}}
+ ...attributes
>
{{#if this.isIcon}}
{{dIcon this.icon}}
diff --git a/frontend/discourse/app/ui-kit/d-user-avatar-flair.gjs b/frontend/discourse/app/ui-kit/d-user-avatar-flair.gjs
index b4a1a2c6c86..5a751d8eccc 100644
--- a/frontend/discourse/app/ui-kit/d-user-avatar-flair.gjs
+++ b/frontend/discourse/app/ui-kit/d-user-avatar-flair.gjs
@@ -2,6 +2,7 @@ import Component from "@glimmer/component";
import { service } from "@ember/service";
import autoGroupFlairForUser from "discourse/lib/avatar-flair";
import DAvatarFlair from "discourse/ui-kit/d-avatar-flair";
+import { i18n } from "discourse-i18n";
export default class DUserAvatarFlair extends Component {
@service site;
@@ -33,6 +34,11 @@ export default class DUserAvatarFlair extends Component {
}
}
+ get isBot() {
+ const id = this.args.user?.id;
+ return Number.isInteger(id) && id <= 0;
+ }
+
<template>
{{#if this.flair}}
<DAvatarFlair
@@ -41,6 +47,15 @@ export default class DUserAvatarFlair extends Component {
@flairName={{this.flair.flairName}}
@flairUrl={{this.flair.flairUrl}}
/>
+ {{else if this.isBot}}
+ <DAvatarFlair
+ aria-label={{i18n "user.bot_account"}}
+ class="--bot"
+ role="img"
+ title={{i18n "user.bot_account"}}
+ @flairName="bot"
+ @flairUrl="robot"
+ />
{{/if}}
</template>
}
diff --git a/frontend/discourse/tests/acceptance/admin-bots-new-test.js b/frontend/discourse/tests/acceptance/admin-bots-new-test.js
new file mode 100644
index 00000000000..9b7d002bf81
--- /dev/null
+++ b/frontend/discourse/tests/acceptance/admin-bots-new-test.js
@@ -0,0 +1,706 @@
+import {
+ click,
+ currentURL,
+ resetOnerror,
+ settled,
+ setupOnerror,
+ triggerEvent,
+ visit,
+ waitFor,
+ waitUntil,
+} from "@ember/test-helpers";
+import { test } from "qunit";
+import sinon from "sinon";
+import { setPrefix } from "discourse/lib/get-url";
+import { withPluginApi } from "discourse/lib/plugin-api";
+import pretender from "discourse/tests/helpers/create-pretender";
+import formKit from "discourse/tests/helpers/form-kit-helper";
+import { acceptance, currentUser } from "discourse/tests/helpers/qunit-helpers";
+import selectKit from "discourse/tests/helpers/select-kit-helper";
+import { i18n } from "discourse-i18n";
+
+const NEW_BOT_BUTTON = ".admin-users__subheader-new-bot";
+const FORM = ".admin-bot-form";
+
+acceptance("Admin - New bot", function (needs) {
+ needs.user({ admin: true });
+
+ let defaultTrustLevel;
+ let nameRequired;
+ let payloads;
+ let listQueries;
+ let createdUser;
+ let failCreation;
+
+ needs.pretender((server, helper) => {
+ defaultTrustLevel = 2;
+ nameRequired = false;
+ payloads = [];
+ listQueries = [];
+ createdUser = null;
+ failCreation = false;
+
+ ["", "/forum"].forEach((prefix) => {
+ server.get(`${prefix}/session/csrf`, () =>
+ helper.response({ csrf: "test-csrf-token" })
+ );
+
+ server.get(`${prefix}/admin/users/bots/new.json`, () =>
+ helper.response({
+ default_trust_level: defaultTrustLevel,
+ name_required: nameRequired,
+ })
+ );
+
+ server.get(
+ `${prefix}/admin/users/bots/username_suggestion.json`,
+ (request) =>
+ helper.response({
+ username: request.queryParams.name
+ .toLowerCase()
+ .replace(/\s+/g, "_"),
+ })
+ );
+
+ server.get(`${prefix}/admin/api/keys/scopes.json`, () =>
+ helper.response({
+ scopes: {
+ global: [
+ {
+ scope_id: "global:read",
+ key: "read",
+ name: "read",
+ params: null,
+ urls: [],
+ },
+ ],
+ topics: [
+ {
+ scope_id: "topics:write",
+ key: "write",
+ name: "write",
+ params: ["topic_id"],
+ urls: [],
+ },
+ ],
+ },
+ })
+ );
+
+ server.get(`${prefix}/admin/users/list/bots.json`, (request) => {
+ listQueries.push(request.queryParams);
+ return helper.response(
+ createdUser && !request.queryParams.filter
+ ? [
+ {
+ ...createdUser,
+ bot_creator: {
+ username: currentUser().username,
+ url: `/admin/users/${currentUser().id}/${currentUser().username}`,
+ },
+ },
+ ]
+ : []
+ );
+ });
+
+ server.post(`${prefix}/admin/users/bots.json`, (request) => {
+ const payload = JSON.parse(request.requestBody);
+ payloads.push(payload);
+
+ if (failCreation) {
+ return helper.response(422, {
+ errors: ["Username has already been taken"],
+ });
+ }
+
+ createdUser = { id: -200, ...payload.bot };
+ return helper.response(201, {
+ user: createdUser,
+ ...(payload.key && {
+ key: {
+ key: "generated-secret-key",
+ description: payload.bot.username,
+ },
+ }),
+ });
+ });
+ });
+ });
+
+ test("offers a menu explaining each path when other bot flows are registered", async function (assert) {
+ withPluginApi((api) => {
+ api.registerValueTransformer("admin-new-bot-options", ({ value }) => [
+ ...value,
+ {
+ id: "other",
+ icon: "key",
+ label: "admin.api.new_key",
+ description: "admin.users.bots.help",
+ route: "adminApiKeys.new",
+ },
+ ]);
+ });
+
+ const dropdown = selectKit(NEW_BOT_BUTTON);
+
+ await visit("/admin/users/list/bots");
+ await dropdown.expand();
+
+ assert.strictEqual(
+ dropdown.rows().length,
+ 2,
+ "lists the generic bot and the registered flow"
+ );
+ assert.strictEqual(
+ dropdown.rowByValue("bot").label(),
+ i18n("admin.users.bots.new_options.bot.label")
+ );
+ assert.strictEqual(
+ dropdown.rowByValue("bot").description(),
+ i18n("admin.users.bots.new_options.bot.description"),
+ "explains when to choose each path"
+ );
+
+ await dropdown.selectRowByValue("other");
+ assert.strictEqual(
+ currentURL(),
+ "/admin/api/keys/new",
+ "opens the registered flow"
+ );
+
+ await visit("/admin/users/list/bots");
+ await dropdown.expand();
+ await dropdown.selectRowByValue("bot");
+ assert.strictEqual(
+ currentURL(),
+ "/admin/users/bots/new",
+ "opens the generic bot form"
+ );
+ });
+
+ test("only the Bots subheader has the primary creation action", async function (assert) {
+ await visit("/admin/users/list/bots");
+
+ assert
+ .dom(NEW_BOT_BUTTON)
+ .hasText(i18n("admin.users.bots.new"), "admins see the creation action");
+ assert
+ .dom(NEW_BOT_BUTTON)
+ .hasClass("btn-primary", "creation is the primary action");
+
+ await click(NEW_BOT_BUTTON);
+ assert.strictEqual(
+ currentURL(),
+ "/admin/users/bots/new",
+ "the action opens the dedicated page"
+ );
+
+ await click(".back-button");
+ await click(".admin-users-tabs__active a");
+ assert
+ .dom(NEW_BOT_BUTTON)
+ .doesNotExist("other user lists have no creation action");
+ });
+
+ test("the form loads directly without the Users page shell", async function (assert) {
+ await visit("/admin/users/bots/new");
+
+ assert.dom(FORM).exists("the form is directly loadable");
+ assert
+ .dom(".admin-users")
+ .doesNotExist("the Users header and tabs are not inherited");
+ assert
+ .dom(".admin-config-area-card__title")
+ .hasText(
+ i18n("admin.users.bots.new"),
+ "the card has a localized heading"
+ );
+ assert
+ .dom(".admin-config-area-card__description")
+ .hasText(
+ i18n("admin.users.bots.help"),
+ "the account-only boundary is explained"
+ );
+ assert
+ .dom(".back-button")
+ .hasAttribute("href", "/admin/users/list/bots", "back returns to Bots");
+ assert.deepEqual(
+ formKit(FORM).field("trust_level").options(),
+ ["0", "1", "2", "3", "4"],
+ "all five trust levels are available"
+ );
+ assert
+ .form(FORM)
+ .field("trust_level")
+ .hasValue("2", "the site default trust level is selected");
+ assert
+ .dom(`${FORM} [data-name]`)
+ .exists(
+ { count: 4 },
+ "only name, username, trust level and the API key toggle are editable"
+ );
+ });
+
+ test("creates a bot with the site's default trust level and shows a success toast", async function (assert) {
+ await visit("/admin/users/bots/new");
+ const toasts = this.owner.lookup("service:toasts");
+ const successToast = sinon.spy(toasts.success);
+ sinon.replaceGetter(toasts, "success", () => successToast);
+ const form = formKit(FORM);
+ await form.field("name").fillIn("Release helper");
+ await form.field("username").fillIn("release_helper");
+ await form.submit();
+
+ assert.deepEqual(
+ payloads,
+ [
+ {
+ bot: {
+ name: "Release helper",
+ username: "release_helper",
+ trust_level: 2,
+ },
+ },
+ ],
+ "one narrow bot payload is submitted"
+ );
+ assert.strictEqual(
+ currentURL(),
+ "/admin/users/list/bots?order=created",
+ "success returns to newest-first Bots"
+ );
+ assert
+ .dom(".directory-table__cell.username")
+ .includesText("release_helper", "the new bot is visible in the list");
+ assert.true(successToast.calledOnce, "creation shows one success toast");
+ assert.strictEqual(
+ successToast.firstCall.args[0].data.message,
+ i18n("admin.users.bots.created", { username: "release_helper" }),
+ "the success toast identifies the created bot"
+ );
+ assert
+ .dom(".admin-users-list__source-values")
+ .hasText(
+ currentUser().username,
+ "a manual bot identifies its creator in Source"
+ );
+ });
+
+ test("suggests a username from the name until one is typed", async function (assert) {
+ await visit("/admin/users/bots/new");
+ const form = formKit(FORM);
+
+ await form.field("name").fillIn("Release helper");
+ await settled();
+ assert
+ .form(FORM)
+ .field("username")
+ .hasValue("release_helper", "the username follows the name");
+
+ await form.field("name").fillIn("Deploy helper");
+ await settled();
+ assert
+ .form(FORM)
+ .field("username")
+ .hasValue("deploy_helper", "the suggestion updates with the name");
+
+ await form.field("username").fillIn("custom_bot");
+ await form.field("name").fillIn("Another helper");
+ await settled();
+ assert
+ .form(FORM)
+ .field("username")
+ .hasValue("custom_bot", "a typed username is kept");
+ });
+
+ test("clearing the name clears a suggested username only", async function (assert) {
+ await visit("/admin/users/bots/new");
+ const form = formKit(FORM);
+
+ await form.field("name").fillIn("Release helper");
+ await settled();
+ await form.field("name").fillIn("");
+ await settled();
+ assert
+ .form(FORM)
+ .field("username")
+ .hasValue("", "the suggested username is cleared");
+
+ await form.field("username").fillIn("custom_bot");
+ await form.field("name").fillIn("Release helper");
+ await form.field("name").fillIn("");
+ await settled();
+ assert
+ .form(FORM)
+ .field("username")
+ .hasValue("custom_bot", "a typed username is kept");
+ });
+
+ test("can generate an API key that is shown once", async function (assert) {
+ await visit("/admin/users/bots/new");
+ const form = formKit(FORM);
+ await form.field("username").fillIn("release_helper");
+
+ assert
+ .form(FORM)
+ .field("scope_mode")
+ .doesNotExist("key fields stay hidden until requested");
+
+ await form.field("generate_api_key").toggle();
+ await form.field("scope_mode").select("read_only");
+ await form.submit();
+
+ assert.deepEqual(
+ payloads[0].key,
+ {
+ scope_mode: "read_only",
+ scopes: [
+ {
+ scope_id: "global:read",
+ key: "read",
+ name: "read",
+ params: null,
+ urls: [],
+ },
+ ],
+ },
+ "the key request is sent alongside the bot"
+ );
+ assert
+ .dom(".generated-api-key")
+ .hasText("generated-secret-key", "the new key is shown");
+ assert.strictEqual(
+ currentURL(),
+ "/admin/users/bots/new",
+ "the key stays on screen until dismissed"
+ );
+
+ await click(".admin-bot-form__back");
+
+ assert.strictEqual(
+ currentURL(),
+ "/admin/users/list/bots?order=created",
+ "back returns to newest-first Bots"
+ );
+ });
+
+ test("a granular key requires at least one scope", async function (assert) {
+ await visit("/admin/users/bots/new");
+ const form = formKit(FORM);
+ await form.field("username").fillIn("release_helper");
+ await form.field("generate_api_key").toggle();
+ await form.field("scope_mode").select("granular");
+ await form.submit();
+
+ assert.deepEqual(payloads, [], "nothing is submitted");
+ assert
+ .form(FORM)
+ .hasErrors(
+ { scopes: i18n("admin.api.scopes.one_or_more") },
+ "the missing scope is reported"
+ );
+ });
+
+ test("submits the selected trust level including level zero", async function (assert) {
+ await visit("/admin/users/bots/new");
+ const form = formKit(FORM);
+ await form.field("username").fillIn("custom_bot");
+ await form.field("trust_level").select("0");
+ await form.submit();
+
+ assert.deepEqual(
+ payloads,
+ [{ bot: { name: "", username: "custom_bot", trust_level: 0 } }],
+ "the explicit trust level is sent without extra fields"
+ );
+ });
+
+ test("the admin metadata can default to trust level zero", async function (assert) {
+ defaultTrustLevel = 0;
+ await visit("/admin/users/bots/new");
+ const form = formKit(FORM);
+ assert
+ .form(FORM)
+ .field("trust_level")
+ .hasValue("0", "zero is selected rather than a placeholder");
+ await form.field("username").fillIn("default_zero_bot");
+ await form.submit();
+
+ assert.strictEqual(
+ payloads[0].bot.trust_level,
+ 0,
+ "the zero default is valid and submitted"
+ );
+ });
+
+ test("the admin metadata can require a name", async function (assert) {
+ nameRequired = true;
+ await visit("/admin/users/bots/new");
+ const form = formKit(FORM);
+ await form.field("username").fillIn("named_bot");
+ await form.submit();
+
+ assert
+ .form(FORM)
+ .hasErrors(
+ { name: i18n("form_kit.errors.required") },
+ "the site name policy is validated inline"
+ );
+ assert.strictEqual(
+ payloads.length,
+ 0,
+ "a required name is not submitted blank"
+ );
+ await form.field("name").fillIn("Named bot");
+ await form.submit();
+ assert.strictEqual(
+ payloads[0].bot.name,
+ "Named bot",
+ "adding a name allows submission"
+ );
+ });
+
+ test("requires a valid username before submitting", async function (assert) {
+ await visit("/admin/users/bots/new");
+ await formKit(FORM).submit();
+
+ assert
+ .form(FORM)
+ .hasErrors(
+ { username: i18n("form_kit.errors.required") },
+ "required username validation is inline"
+ );
+ assert.strictEqual(payloads.length, 0, "invalid data is not submitted");
+ });
+
+ test("server validation errors stay inline and allow correction and retry", async function (assert) {
+ failCreation = true;
+ await visit("/admin/users/bots/new");
+ const form = formKit(FORM);
+ await form.field("name").fillIn("Release helper");
+ await form.field("username").fillIn("taken_bot");
+ await form.submit();
+
+ assert.strictEqual(
+ currentURL(),
+ "/admin/users/bots/new",
+ "an error does not navigate away"
+ );
+ assert
+ .dom(`${FORM} .form-kit__errors-summary`)
+ .includesText(
+ "Username has already been taken",
+ "server errors are displayed in the form"
+ );
+ assert
+ .form(FORM)
+ .field("name")
+ .hasValue("Release helper", "the entered name is retained");
+ assert
+ .form(FORM)
+ .field("username")
+ .hasValue("taken_bot", "the entered username is retained");
+ assert
+ .dom(`${FORM} button[type=submit]`)
+ .isEnabled("submission is enabled after the request fails");
+
+ failCreation = false;
+ await form.field("username").fillIn("available_bot");
+ await form.submit();
+ assert.strictEqual(payloads.length, 2, "the corrected form can be retried");
+ assert.strictEqual(
+ currentURL(),
+ "/admin/users/list/bots?order=created",
+ "the retry succeeds"
+ );
+ });
+
+ test("back cancels without creating an account and re-entry starts fresh", async function (assert) {
+ await visit("/admin/users/bots/new");
+ await formKit(FORM).field("username").fillIn("unsaved_bot");
+ await click(".back-button");
+ await click(".dialog-footer .btn-primary");
+
+ assert.strictEqual(
+ currentURL(),
+ "/admin/users/list/bots",
+ "discarding the draft returns to Bots"
+ );
+ assert.strictEqual(payloads.length, 0, "back does not create an account");
+
+ await click(NEW_BOT_BUTTON);
+ assert
+ .form(FORM)
+ .field("username")
+ .hasNoValue("a new visit has no stale username");
+ assert
+ .form(FORM)
+ .field("trust_level")
+ .hasValue("2", "a new visit restores the site default");
+ });
+
+ test("cancel returns to Bots without creating an account", async function (assert) {
+ await visit("/admin/users/bots/new");
+ await formKit(FORM).field("username").fillIn("cancelled_bot");
+ await click(".admin-bot-form__cancel");
+ await click(".dialog-footer .btn-primary");
+
+ assert.strictEqual(
+ currentURL(),
+ "/admin/users/list/bots",
+ "cancel returns to Bots after discarding the draft"
+ );
+ assert.strictEqual(payloads.length, 0, "cancel does not create an account");
+ });
+
+ ["", "/forum"].forEach((prefix) => {
+ test(`creation clears stale search, sorting and account-type state (prefix: "${prefix}")`, async function (assert) {
+ setPrefix(prefix);
+ // The router service cannot configure the test location’s root URL.
+ // eslint-disable-next-line ember/no-private-routing-service
+ this.owner.lookup("router:main").rootURL = `${prefix}/`;
+ await visit(
+ "/admin/users/list/bots?filter=missing&username=old_bot&order=username&asc=true&account_type=human&activation=not_activated"
+ );
+ await click(NEW_BOT_BUTTON);
+ assert
+ .dom(".back-button")
+ .hasAttribute(
+ "href",
+ `${prefix}/admin/users/list/bots?username=old_bot`,
+ "router-generated links include the subfolder"
+ );
+ const form = formKit(FORM);
+ await form.field("username").fillIn("visible_bot");
+ await form.submit();
+
+ assert.strictEqual(
+ currentURL(),
+ "/admin/users/list/bots?order=created",
+ "stale query parameters are removed"
+ );
+ const query = listQueries.at(-1);
+ assert.strictEqual(
+ query.order,
+ "created",
+ "Bots is fetched newest first"
+ );
+ for (const key of [
+ "filter",
+ "username",
+ "asc",
+ "account_type",
+ "activation",
+ ]) {
+ assert.false(Boolean(query[key]), `${key} does not hide the new bot`);
+ }
+ assert.strictEqual(query.page, "1", "the first page is fetched");
+ assert
+ .dom(".directory-table__cell.username")
+ .includesText(
+ "visible_bot",
+ "the created bot is not hidden by stale filters"
+ );
+ assert
+ .dom(".d-filter-controls input")
+ .hasNoValue("the search control is reset");
+ });
+ });
+
+ test("awaits creation and prevents duplicate pending submissions", async function (assert) {
+ let pendingRequest;
+ pretender.post(
+ "/admin/users/bots.json",
+ (request) => {
+ pendingRequest = request;
+ payloads.push(request.requestBody);
+ return [
+ 201,
+ { "Content-Type": "application/json" },
+ JSON.stringify({ user: { id: -201, username: "pending_bot" } }),
+ ];
+ },
+ true
+ );
+
+ await visit("/admin/users/bots/new");
+ await formKit(FORM).field("username").fillIn("pending_bot");
+ const submission = formKit(FORM).submit();
+ await waitUntil(() => pendingRequest);
+ await waitFor(`${FORM} button[type=submit][disabled]`);
+
+ assert.strictEqual(
+ currentURL(),
+ "/admin/users/bots/new",
+ "navigation waits for creation"
+ );
+ assert
+ .dom(`${FORM} button[type=submit]`)
+ .isDisabled("the submit button is disabled while pending");
+ const duplicate = triggerEvent(FORM, "submit");
+ assert.strictEqual(payloads.length, 1, "only one request is pending");
+
+ pretender.resolve(pendingRequest);
+ await Promise.all([submission, duplicate]);
+ await settled();
+ assert.strictEqual(
+ payloads.length,
+ 1,
+ "a duplicate submit does not create another bot"
+ );
+ assert.strictEqual(
+ currentURL(),
+ "/admin/users/list/bots?order=created",
+ "creation completes normally"
+ );
+ });
+});
+
+acceptance("Admin - New bot - moderator", function (needs) {
+ needs.user({ admin: false, moderator: true });
+
+ let metadataRequests;
+ needs.pretender((server, helper) => {
+ metadataRequests = 0;
+ server.get("/admin/users/bots/new.json", () => {
+ metadataRequests++;
+ return helper.response(403, { errors: [i18n("errors.desc.forbidden")] });
+ });
+ server.get("/admin/users/list/bots.json", () => helper.response([]));
+ });
+
+ test("moderators can list bots but cannot see the creation action", async function (assert) {
+ await visit("/admin/users/list/bots");
+ assert
+ .dom(".admin-users-tabs__bots")
+ .exists("moderators can access the Bots list");
+ assert
+ .dom(NEW_BOT_BUTTON)
+ .doesNotExist("moderators have no creation action");
+ });
+
+ test("moderators cannot load the form by navigating directly", async function (assert) {
+ setupOnerror(() => {});
+ try {
+ await visit("/admin/users/bots/new");
+ } catch {}
+ await settled();
+ resetOnerror();
+ assert.dom(FORM).doesNotExist("the creation form is not rendered");
+ assert
+ .dom(".error-page .reason")
+ .hasText(i18n("errors.reasons.forbidden"), "direct access is forbidden");
+ assert
+ .dom(".error-page .desc")
+ .hasText(
+ i18n("errors.desc.forbidden"),
+ "the admin requirement is explained"
+ );
+ assert.strictEqual(
+ metadataRequests,
+ 1,
+ "the server rejects access to admin metadata"
+ );
+ });
+});
diff --git a/frontend/discourse/tests/acceptance/admin-user-index-test.js b/frontend/discourse/tests/acceptance/admin-user-index-test.js
index 665724e0d87..2696d3c7b59 100644
--- a/frontend/discourse/tests/acceptance/admin-user-index-test.js
+++ b/frontend/discourse/tests/acceptance/admin-user-index-test.js
@@ -30,6 +30,18 @@ acceptance("Admin - User Index", function (needs) {
return helper.response({ id: 2, username: "new-sam" });
});
+ server.get("/admin/users/-1234.json", () =>
+ helper.response({
+ id: -1234,
+ username: "helper_bot",
+ name: "Helper bot",
+ active: true,
+ admin: false,
+ moderator: false,
+ avatar_template: "/letter_avatar_proxy/v4/letter/h/f0a364/{size}.png",
+ })
+ );
+
server.get("/admin/users/3.json", () => {
return helper.response({
id: 3,
@@ -224,6 +236,21 @@ acceptance("Admin - User Index", function (needs) {
deleteData = null;
});
+ test("identifies bot accounts on the user details page", async function (assert) {
+ await visit("/admin/users/-1234/helper_bot");
+ assert
+ .dom(".admin-user__bot-indicator .value")
+ .hasText(i18n("admin.user.bot"), "the bot account is identified");
+ assert
+ .dom(".admin-user__bot-indicator .d-icon-robot")
+ .exists("the indicator includes the bot icon");
+
+ await visit("/admin/users/2/sam");
+ assert
+ .dom(".admin-user__bot-indicator")
+ .doesNotExist("human accounts have no bot indicator");
+ });
+
test("can edit username", async function (assert) {
await visit("/admin/users/2/sam");
diff --git a/frontend/discourse/tests/acceptance/admin-users-list-test.js b/frontend/discourse/tests/acceptance/admin-users-list-test.js
index dd7c1cd2dd5..271fc02b64b 100644
--- a/frontend/discourse/tests/acceptance/admin-users-list-test.js
+++ b/frontend/discourse/tests/acceptance/admin-users-list-test.js
@@ -1,4 +1,11 @@
-import { click, currentURL, fillIn, visit } from "@ember/test-helpers";
+import {
+ click,
+ currentURL,
+ fillIn,
+ settled,
+ triggerEvent,
+ visit,
+} from "@ember/test-helpers";
import { test } from "qunit";
import { acceptance } from "discourse/tests/helpers/qunit-helpers";
import stubIntersectionObserver from "discourse/tests/helpers/stub-intersection-observer";
@@ -12,8 +19,86 @@ acceptance("Admin - Users List", function (needs) {
needs.user();
let lastActivationFilter;
+ let lastBotShowEmails;
+ let lastBotQuery;
needs.pretender((server, helper) => {
+ server.get("/admin/users/list/bots.json", (request) => {
+ lastBotShowEmails = request.queryParams.show_emails;
+ lastBotQuery = request.queryParams;
+ return helper.response([
+ {
+ id: -100,
+ username: "helper_bot",
+ post_count: 12,
+ bot_creator: {
+ username: "sam",
+ avatar_template:
+ "/letter_avatar_proxy/v4/letter/s/3be4f8/{size}.png",
+ url: "/admin/users/2/sam",
+ },
+ sources: [
+ { label: "<strong>Helper</strong>", url: "/admin/bots/helper" },
+ { label: "Support", url: "/forum/admin/bots/support" },
+ ],
+ },
+ {
+ id: -101,
+ username: "historical_bot",
+ sources: [{ label: "<em>Historical integration</em>" }],
+ },
+ {
+ id: -106,
+ username: "paused_bot",
+ sources: [{ label: "Paused agent", note: "Integration disabled" }],
+ bot_inactive: true,
+ },
+ { id: -102, username: "unknown_bot" },
+ { id: -103, username: "unattributed_bot", sources: [] },
+ {
+ id: -105,
+ username: "manual_bot",
+ bot_creator: {
+ username: "sam",
+ avatar_template:
+ "/letter_avatar_proxy/v4/letter/s/3be4f8/{size}.png",
+ url: "/admin/users/2/sam",
+ },
+ },
+ {
+ id: -106,
+ username: "escaped_creator_bot",
+ sources: [],
+ bot_creator: {
+ username: "<em>sam</em>",
+ url: "/forum/admin/users/2/sam",
+ },
+ },
+ {
+ id: -104,
+ username: "long_name_bot",
+ sources: [
+ {
+ label: "An agent with a very very very long name dot com",
+ url: "/admin/bots/long-name",
+ },
+ ],
+ },
+ ]);
+ });
+
+ for (const tab of ["staff", "staged"]) {
+ server.get(`/admin/users/list/${tab}.json`, () =>
+ helper.response([
+ {
+ id: 5,
+ username: "sam",
+ sources: [{ label: "Integration", url: "/admin/bots/helper" }],
+ },
+ ])
+ );
+ }
+
server.get("/admin/users/list/silenced.json", () =>
helper.response([
{
@@ -54,6 +139,337 @@ acceptance("Admin - Users List", function (needs) {
});
});
+ test("shows Bots without Groups in the users tabs", async function (assert) {
+ await visit("/admin/users/list/active");
+
+ assert
+ .dom(".admin-users-tabs__groups")
+ .doesNotExist("omits the Groups tab");
+ assert
+ .dom(".admin-users-tabs__bots a")
+ .hasText(i18n("admin.users.nav.bots"), "labels the tab Bots");
+
+ await click(".admin-users-tabs__bots a");
+
+ assert.strictEqual(
+ currentURL(),
+ "/admin/users/list/bots",
+ "opens the bots list"
+ );
+ assert
+ .dom(".admin-users-tabs__bots a")
+ .hasClass("active", "selects the Bots tab");
+ assert
+ .dom(".users-list .user .username")
+ .includesText("helper_bot", "lists bot accounts");
+ assert
+ .dom(".d-filter-controls__dropdown")
+ .doesNotExist("does not offer a human account filter");
+ });
+
+ test("shows linked bot sources with escaped labels", async function (assert) {
+ await visit("/admin/users/list/bots");
+
+ assert
+ .dom(".admin-users-list__source-header")
+ .hasText(i18n("admin.users.source"), "labels the Source column");
+ assert
+ .dom(
+ '[data-user-id="-100"] .admin-users-list__source .directory-table__label'
+ )
+ .hasText(i18n("admin.users.source"), "labels the source on mobile");
+ assert
+ .dom('[data-user-id="-100"] .admin-users-list__source a')
+ .exists({ count: 2 }, "renders links for each source");
+ assert
+ .dom(
+ '[data-user-id="-100"] .admin-users-list__source a[href="/admin/bots/helper"]'
+ )
+ .hasText("<strong>Helper</strong>", "escapes the source label")
+ .hasAttribute(
+ "href",
+ "/admin/bots/helper",
+ "uses the internal source URL"
+ );
+ assert
+ .dom('[data-user-id="-100"] .admin-users-list__source strong')
+ .doesNotExist("does not trust source HTML");
+ assert
+ .dom(
+ '[data-user-id="-100"] .admin-users-list__source a[href="/forum/admin/bots/support"]'
+ )
+ .hasText("Support", "preserves a source URL that includes the base path");
+ });
+
+ test("shows creator attribution when a bot has no configured source", async function (assert) {
+ await visit("/admin/users/list/bots");
+
+ const label = i18n("admin.users.bots.created_by", { username: "sam" });
+ assert
+ .dom('[data-user-id="-105"] .admin-users-list__source a img.avatar')
+ .exists("shows the creator's avatar");
+ assert
+ .dom('[data-user-id="-105"] .admin-users-list__source a')
+ .hasText("sam", "identifies the creator by username")
+ .hasAttribute(
+ "aria-label",
+ label,
+ "explains the creator relationship accessibly"
+ )
+ .hasAttribute(
+ "href",
+ "/admin/users/2/sam",
+ "links to the creator's admin page"
+ );
+ assert
+ .dom('[data-user-id="-105"] .admin-users-list__source-item')
+ .hasAttribute("title", label, "preserves the full attribution on hover");
+ assert
+ .dom(
+ '[data-user-id="-100"] .admin-users-list__source a[href="/admin/users/2/sam"]'
+ )
+ .doesNotExist("a configured source takes precedence over the creator");
+ });
+
+ test("escapes creator names and preserves subfolder links", async function (assert) {
+ await visit("/admin/users/list/bots");
+
+ assert
+ .dom('[data-user-id="-106"] .admin-users-list__source a')
+ .hasText("<em>sam</em>", "escapes the creator name")
+ .hasAttribute(
+ "href",
+ "/forum/admin/users/2/sam",
+ "preserves the supplied base path"
+ );
+ assert
+ .dom('[data-user-id="-106"] .admin-users-list__source em')
+ .doesNotExist("does not interpret creator names as HTML");
+ });
+
+ test("preserves the full source name when visually truncated", async function (assert) {
+ await visit("/admin/users/list/bots");
+
+ const label = "An agent with a very very very long name dot com";
+ assert
+ .dom('[data-user-id="-104"] .admin-users-list__source-item a')
+ .hasAttribute("title", label, "reveals the full name on hover")
+ .hasText(label, "retains the full accessible link text")
+ .hasAttribute(
+ "href",
+ "/admin/bots/long-name",
+ "preserves the destination"
+ );
+ });
+
+ test("shows historical bot sources without links", async function (assert) {
+ await visit("/admin/users/list/bots");
+
+ assert
+ .dom(
+ '[data-user-id="-101"] .admin-users-list__source .directory-table__value'
+ )
+ .hasText(
+ "<em>Historical integration</em>",
+ "escapes a text-only source label"
+ );
+ assert
+ .dom(
+ '[data-user-id="-101"] .admin-users-list__source a, [data-user-id="-101"] .admin-users-list__source em'
+ )
+ .doesNotExist(
+ "does not add a link or trust HTML for a historical source"
+ );
+ });
+
+ test("shows a source note in a tooltip", async function (assert) {
+ await visit("/admin/users/list/bots");
+
+ assert
+ .dom('[data-user-id="-106"] .admin-users-list__source-label')
+ .hasText("Paused agent", "the label is shown as is");
+
+ await triggerEvent(
+ '[data-user-id="-106"] .admin-users-list__source-label',
+ "pointermove"
+ );
+ assert
+ .dom(".fk-d-tooltip__content")
+ .hasText("Integration disabled", "the note is shown in a tooltip");
+ assert
+ .dom('[data-user-id="-106"]')
+ .hasClass(
+ "not-activated",
+ "an inactive bot is dimmed like a disabled one"
+ );
+ });
+
+ test("shows a fallback for missing or empty bot sources", async function (assert) {
+ await visit("/admin/users/list/bots");
+
+ for (const id of [-102, -103]) {
+ assert
+ .dom(
+ `[data-user-id="${id}"] .admin-users-list__source .directory-table__value`
+ )
+ .hasText("—", "uses an em dash when no sources are available");
+ assert
+ .dom(`[data-user-id="${id}"] .admin-users-list__source a`)
+ .doesNotExist("does not link an unknown source");
+ }
+ });
+
+ test("only shows the Source column on the Bots tab", async function (assert) {
+ await visit("/admin/users/list/bots");
+
+ assert
+ .dom(".admin-users-list__source-header")
+ .exists("shows the header on the Bots tab");
+
+ for (const tab of [
+ "active",
+ "new",
+ "staff",
+ "suspended",
+ "silenced",
+ "staged",
+ ]) {
+ await visit(`/admin/users/list/${tab}`);
+
+ assert
+ .dom(".admin-users-list__source-header, .admin-users-list__source")
+ .doesNotExist(`omits the Source column on the ${tab} tab`);
+ }
+ });
+
+ test("shows posts created on Bots and sorts activity columns in both directions", async function (assert) {
+ await visit("/admin/users/list/bots");
+
+ assert
+ .dom(
+ '[data-user-id="-100"] .admin-users-list__posts-created .directory-table__value'
+ )
+ .hasText("12", "shows the bot's post count");
+ assert
+ .dom("#table-header-toggle-posts")
+ .hasText(i18n("admin.user.post_count"), "labels the count column");
+
+ for (const field of ["topics_viewed", "posts_read", "posts", "created"]) {
+ const header = `#table-header-toggle-${field}`;
+ await click(header);
+ assert.strictEqual(
+ lastBotQuery.order,
+ field,
+ `requests sorting by ${field}`
+ );
+ assert.false(
+ Boolean(lastBotQuery.asc),
+ `${field} initially sorts descending`
+ );
+ assert
+ .dom(header)
+ .hasAttribute("aria-pressed", "true", "announces descending order");
+
+ await click(header);
+ assert.strictEqual(
+ lastBotQuery.asc,
+ "true",
+ `${field} can sort ascending`
+ );
+ assert
+ .dom(header)
+ .hasAttribute("aria-pressed", "mixed", "announces ascending order");
+ }
+
+ await visit("/admin/users/list/active");
+ assert
+ .dom("#table-header-toggle-posts, .admin-users-list__posts-created")
+ .doesNotExist("the added column is specific to Bots");
+ });
+
+ test("hides human activity columns on Bots and keeps the grid aligned", async function (assert) {
+ this.siteSettings.must_approve_users = false;
+
+ await visit("/admin/users/list/active");
+ await click(".admin-users__subheader-show-emails");
+ await visit("/admin/users/list/bots");
+
+ assert
+ .dom(".admin-users-list__source-header")
+ .exists("admins retain the Source header");
+ assert
+ .dom(".admin-users-list__source")
+ .exists({ count: 8 }, "admins retain a Source cell for every bot");
+ assert
+ .dom(".users-list")
+ .hasAttribute(
+ "style",
+ /repeat\(7,/,
+ "accounts for Source and the two hidden columns"
+ );
+
+ assert
+ .dom("#table-header-toggle-last_emailed, .users-list .last-emailed")
+ .doesNotExist("omits the Last Emailed header and cells on Bots");
+
+ assert
+ .dom("#table-header-toggle-read_time, .users-list .time-read")
+ .doesNotExist("omits the Read Time header and cells on Bots");
+
+ assert
+ .dom(
+ ".admin-users__subheader-show-emails, .admin-users__subheader-hide-emails"
+ )
+ .doesNotExist(
+ "omits email actions on Bots even after revealing emails elsewhere"
+ );
+ assert
+ .dom("#table-header-toggle-email")
+ .isNotVisible("keeps the email header hidden on Bots");
+ assert
+ .dom(".users-list .email:not(.hidden)")
+ .doesNotExist("keeps all email cells hidden on Bots");
+ assert.strictEqual(
+ lastBotShowEmails,
+ "false",
+ "does not request bot email addresses"
+ );
+
+ this.siteSettings.must_approve_users = true;
+ await settled();
+
+ assert
+ .dom(".users-list")
+ .hasAttribute("style", /repeat\(8,/, "adds the approval grid column");
+
+ await visit("/admin/users/list/active");
+
+ assert
+ .dom(".admin-users__subheader-hide-emails")
+ .exists("preserves email visibility on human user lists");
+ assert
+ .dom("#table-header-toggle-last_emailed")
+ .exists("keeps the Last Emailed header on other tabs");
+ assert
+ .dom(".users-list .last-emailed")
+ .exists("keeps the Last Emailed cells on other tabs");
+
+ assert
+ .dom("#table-header-toggle-read_time")
+ .exists("keeps the Read Time header on other tabs");
+ assert
+ .dom(".users-list .time-read")
+ .exists("keeps the Read Time cells on other tabs");
+
+ assert
+ .dom(".users-list")
+ .hasAttribute(
+ "style",
+ /repeat\(9,/,
+ "restores the standard columns on other tabs"
+ );
+ });
+
test("lists users", async function (assert) {
await visit("/admin/users/list/active");
@@ -289,6 +705,50 @@ acceptance("Admin - Users List - pagination", function (needs) {
});
});
+acceptance("Admin - Users List - moderator bots", function (needs) {
+ needs.user({ admin: false, moderator: true });
+
+ needs.pretender((server, helper) => {
+ server.get("/admin/users/list/bots.json", () =>
+ helper.response([{ id: -100, username: "helper_bot" }])
+ );
+ });
+
+ test("omits the admin-only Source column and keeps the grid aligned", async function (assert) {
+ this.siteSettings.must_approve_users = false;
+
+ await visit("/admin/users/list/bots");
+
+ assert
+ .dom('.users-list [data-user-id="-100"] .username')
+ .includesText("helper_bot", "moderators can still list bot accounts");
+ assert
+ .dom(".admin-users-list__source-header, .admin-users-list__source")
+ .doesNotExist("moderators have no Source header or cells");
+ assert
+ .dom(".users-list")
+ .hasAttribute(
+ "style",
+ /repeat\(6,/,
+ "does not reserve a Source grid column"
+ );
+
+ this.siteSettings.must_approve_users = true;
+ await settled();
+
+ assert
+ .dom(".users-list")
+ .hasAttribute(
+ "style",
+ /repeat\(7,/,
+ "adds only the approval grid column"
+ );
+ assert
+ .dom(".admin-users-list__source-header, .admin-users-list__source")
+ .doesNotExist("approval does not expose the admin-only Source column");
+ });
+});
+
acceptance("Admin - Users List - staff account types", function (needs) {
needs.user();
diff --git a/frontend/discourse/tests/acceptance/user-card-test.js b/frontend/discourse/tests/acceptance/user-card-test.js
index 0c8616db4eb..33ecb568d68 100644
--- a/frontend/discourse/tests/acceptance/user-card-test.js
+++ b/frontend/discourse/tests/acceptance/user-card-test.js
@@ -26,6 +26,78 @@ acceptance("User Card", function (needs) {
});
});
+acceptance("User Card - bot flair", function (needs) {
+ needs.user();
+
+ let profileHidden;
+
+ needs.pretender((server, helper) => {
+ profileHidden = false;
+ server.get("/u/charlie/card.json", () => {
+ const card = cloneJSON(userFixtures["/u/charlie/card.json"]);
+ card.user.id = -1201;
+ card.user.profile_hidden = profileHidden;
+ return helper.response(card);
+ });
+ });
+
+ test("exposes the bot marker without announcing the redundant avatar", async function (assert) {
+ await visit("/t/internationalization-localization/280");
+ await click(".topic-map__users-trigger");
+ await click('a[data-user-card="charlie"]');
+
+ assert
+ .dom(".user-card .avatar-flair.--bot")
+ .hasAttribute("role", "img", "the card exposes the bot marker");
+ assert
+ .dom(".user-card .avatar-flair.--bot")
+ .hasAttribute(
+ "aria-label",
+ i18n("user.bot_account"),
+ "the card describes the automated account"
+ );
+ assert
+ .dom(".user-card .user-card-avatar")
+ .doesNotHaveAttribute(
+ "aria-hidden",
+ "the marker is not hidden from assistive technology"
+ );
+ assert
+ .dom(".user-card .card-huge-avatar")
+ .hasAttribute("aria-hidden", "true", "the redundant avatar stays hidden");
+ });
+ test("keeps a hidden profile's redundant avatar hidden without hiding its bot marker", async function (assert) {
+ profileHidden = true;
+ await visit("/t/internationalization-localization/280");
+ await click(".topic-map__users-trigger");
+ await click('a[data-user-card="charlie"]');
+
+ assert
+ .dom(".user-card .profile-hidden")
+ .exists("the hidden-profile branch is displayed");
+ assert
+ .dom(".user-card span.card-huge-avatar")
+ .hasAttribute(
+ "aria-hidden",
+ "true",
+ "the non-interactive avatar stays hidden"
+ );
+ assert
+ .dom(".user-card .user-card-avatar")
+ .doesNotHaveAttribute(
+ "aria-hidden",
+ "the marker's parent remains exposed"
+ );
+ assert
+ .dom(".user-card .avatar-flair.--bot")
+ .hasAttribute(
+ "aria-label",
+ i18n("user.bot_account"),
+ "the hidden profile still exposes its bot marker"
+ );
+ });
+});
+
acceptance("Category Card", function (needs) {
needs.user();
needs.settings({ enable_category_hashtag_cards: true });
diff --git a/frontend/discourse/tests/integration/ui-kit/d-avatar-flair-test.gjs b/frontend/discourse/tests/integration/ui-kit/d-avatar-flair-test.gjs
index bb8e00336d0..3cc25276d91 100644
--- a/frontend/discourse/tests/integration/ui-kit/d-avatar-flair-test.gjs
+++ b/frontend/discourse/tests/integration/ui-kit/d-avatar-flair-test.gjs
@@ -62,4 +62,46 @@ module("Integration | ui-kit | DAvatarFlair", function (hooks) {
);
assert.dom("svg").doesNotExist("does not have an svg icon");
});
+
+ test("forwards attributes while allowing the default tooltip to be overridden", async function (assert) {
+ await render(
+ <template>
+ <DAvatarFlair
+ aria-label="Custom description"
+ class="custom-flair"
+ role="img"
+ title="Custom tooltip"
+ @flairName="stable-name"
+ @flairUrl="robot"
+ />
+ </template>
+ );
+
+ assert
+ .dom(".avatar-flair")
+ .hasClass(
+ "avatar-flair-stable-name",
+ "the flair name remains the CSS hook"
+ );
+ assert
+ .dom(".avatar-flair")
+ .hasClass("custom-flair", "caller classes are merged");
+ assert
+ .dom(".avatar-flair")
+ .hasAttribute(
+ "title",
+ "Custom tooltip",
+ "the caller can override the default tooltip"
+ );
+ assert
+ .dom(".avatar-flair")
+ .hasAttribute("role", "img", "semantic attributes are forwarded");
+ assert
+ .dom(".avatar-flair")
+ .hasAttribute(
+ "aria-label",
+ "Custom description",
+ "accessible labels are forwarded"
+ );
+ });
});
diff --git a/frontend/discourse/tests/integration/ui-kit/d-user-avatar-flair-test.gjs b/frontend/discourse/tests/integration/ui-kit/d-user-avatar-flair-test.gjs
index 96f0c92536e..6b3d824d429 100644
--- a/frontend/discourse/tests/integration/ui-kit/d-user-avatar-flair-test.gjs
+++ b/frontend/discourse/tests/integration/ui-kit/d-user-avatar-flair-test.gjs
@@ -1,9 +1,11 @@
-import { render } from "@ember/test-helpers";
+import { tracked } from "@glimmer/tracking";
+import { render, settled } from "@ember/test-helpers";
import { module, test } from "qunit";
import { resetFlair } from "discourse/lib/avatar-flair";
import { AUTO_GROUPS } from "discourse/lib/constants";
import { setupRenderingTest } from "discourse/tests/helpers/component-test";
import DUserAvatarFlair from "discourse/ui-kit/d-user-avatar-flair";
+import I18n, { i18n } from "discourse-i18n";
function setupSiteGroups(that) {
that.site.groups = [
@@ -190,4 +192,202 @@ module("Integration | ui-kit | DUserAvatarFlair", function (hooks) {
assert.dom(".avatar-flair").doesNotExist("does not render a flair");
});
+
+ test("bot accounts default to accessible robot flair, including system and zero IDs", async function (assert) {
+ const user = tracked({ id: -1201 });
+ await render(
+ <template><DUserAvatarFlair @user={{user.value}} /></template>
+ );
+
+ for (const id of [-1201, -1, 0]) {
+ user.value = { id };
+ await settled();
+
+ assert
+ .dom(".avatar-flair.--bot")
+ .exists({ count: 1 }, `one fallback is rendered for user ${id}`);
+ assert
+ .dom(".avatar-flair .d-icon-robot")
+ .exists(`user ${id} has the robot icon`);
+ assert
+ .dom(".avatar-flair")
+ .hasAttribute("role", "img", "the marker has image semantics");
+ assert
+ .dom(".avatar-flair")
+ .hasAttribute(
+ "aria-label",
+ i18n("user.bot_account"),
+ "the marker has a translated accessible name"
+ );
+ assert
+ .dom(".avatar-flair")
+ .hasAttribute(
+ "title",
+ i18n("user.bot_account"),
+ "the tooltip is translated"
+ );
+ }
+ });
+
+ test("human accounts and missing or invalid IDs have no bot flair", async function (assert) {
+ const user = tracked(undefined);
+ await render(
+ <template><DUserAvatarFlair @user={{user.value}} /></template>
+ );
+
+ for (const value of [
+ undefined,
+ null,
+ {},
+ { id: null },
+ { id: false },
+ { id: "-1201" },
+ { id: -1.5 },
+ { id: 1, username: "release_bot" },
+ ]) {
+ user.value = value;
+ await settled();
+ assert
+ .dom(".avatar-flair")
+ .doesNotExist(`no bot flair for ${JSON.stringify(value)}`);
+ }
+ });
+
+ test("AI and configured group flair take precedence over the robot fallback", async function (assert) {
+ const user = tracked(undefined);
+ await render(
+ <template><DUserAvatarFlair @user={{user.value}} /></template>
+ );
+
+ for (const flair of [
+ { flair_url: "discourse-ai", flair_name: "AI" },
+ { flair_url: "shield-halved", flair_name: "Team" },
+ { flair_url: "/images/avatar.png", flair_name: "Image" },
+ { flair_bg_color: "123456", flair_name: "Background" },
+ ]) {
+ user.value = { id: -1201, flair_group_id: 42, ...flair };
+ await settled();
+
+ assert
+ .dom(".avatar-flair")
+ .exists({ count: 1 }, "only the configured flair is rendered");
+ assert
+ .dom(".avatar-flair")
+ .hasAttribute(
+ "title",
+ flair.flair_name,
+ "the configured tooltip is preserved"
+ );
+ assert
+ .dom(".avatar-flair.--bot")
+ .doesNotExist("configured flair wins over the fallback");
+ assert
+ .dom(".d-icon-robot")
+ .doesNotExist("the robot is not stacked with configured flair");
+ if (flair.flair_url === "discourse-ai") {
+ assert
+ .dom(".d-icon-discourse-ai")
+ .exists("the existing AI mark is retained");
+ }
+ }
+ });
+
+ test("resolved automatic group flair takes precedence for bot accounts", async function (assert) {
+ setupSiteGroups(this);
+ const user = { id: -1, admin: true, flair_group_id: AUTO_GROUPS.admins.id };
+ await render(<template><DUserAvatarFlair @user={{user}} /></template>);
+
+ assert
+ .dom(".d-icon-bars")
+ .exists("the existing automatic flair is retained");
+ assert
+ .dom(".avatar-flair.--bot")
+ .doesNotExist("automatic flair wins over the fallback");
+ });
+
+ test("bot accounts fall back when group flair is unset or cannot be resolved", async function (assert) {
+ setupSiteGroups(this);
+ const user = tracked({ id: -1201, trust_level: 2, flair_group_id: null });
+ await render(
+ <template><DUserAvatarFlair @user={{user.value}} /></template>
+ );
+
+ assert
+ .dom(".d-icon-robot")
+ .exists("an unset group does not prevent the bot fallback");
+ assert
+ .dom(".d-icon-dice-two")
+ .doesNotExist("unset automatic flair remains disabled");
+
+ user.value = { id: -1201, flair_group_id: 999 };
+ await settled();
+ assert
+ .dom(".d-icon-robot")
+ .exists("an unresolved group falls back to the bot icon");
+ });
+
+ test("the fallback updates when account identity or AI flair changes", async function (assert) {
+ const user = tracked({ id: 1 });
+ await render(
+ <template><DUserAvatarFlair @user={{user.value}} /></template>
+ );
+ assert.dom(".avatar-flair").doesNotExist("humans have no default flair");
+
+ user.value = { id: -1201 };
+ await settled();
+ assert
+ .dom(".d-icon-robot")
+ .exists("bot identity enables the default flair");
+
+ user.value = {
+ id: -1201,
+ flair_group_id: 42,
+ flair_url: "discourse-ai",
+ flair_name: "AI",
+ };
+ await settled();
+ assert.dom(".d-icon-discourse-ai").exists("AI flair replaces the fallback");
+ assert.dom(".d-icon-robot").doesNotExist("only one marker remains");
+
+ user.value = { id: 1 };
+ await settled();
+ assert
+ .dom(".avatar-flair")
+ .doesNotExist("the fallback is removed for humans");
+ });
+
+ test("translated bot labels do not become CSS classes", async function (assert) {
+ const translations = I18n.translations[I18n.locale].js.user;
+ const originalLabel = translations.bot_account;
+ const label = "حساب آلي";
+ translations.bot_account = label;
+
+ try {
+ const user = { id: -1201 };
+ await render(<template><DUserAvatarFlair @user={{user}} /></template>);
+
+ assert
+ .dom(".avatar-flair")
+ .hasAttribute(
+ "title",
+ label,
+ "the tooltip uses the current translation"
+ );
+ assert
+ .dom(".avatar-flair")
+ .hasAttribute(
+ "aria-label",
+ label,
+ "the accessible name uses the current translation"
+ );
+ assert
+ .dom(".avatar-flair")
+ .hasClass(
+ "avatar-flair-bot",
+ "the flair class stays locale-independent"
+ );
+ } finally {
+ translations.bot_account = originalLabel;
+ }
+ });
});
diff --git a/lib/admin_user_index_query.rb b/lib/admin_user_index_query.rb
index 1b487fd29a2..81d00441d97 100644
--- a/lib/admin_user_index_query.rb
+++ b/lib/admin_user_index_query.rb
@@ -120,6 +120,8 @@ class AdminUserIndexQuery
@query.not_suspended.where(approved: false, active: true)
when "staged"
@query.where(staged: true)
+ when "bots"
+ @query.bot_users
end
end
@@ -245,6 +247,33 @@ class AdminUserIndexQuery
.each_with_object({}) { |record, hash| hash[record.target_user_id] = record.details }
end
+ def bot_creators(user_ids)
+ return {} if user_ids.empty? || !guardian&.is_admin?
+
+ UserHistory
+ .where(action: UserHistory.actions[:create_bot], target_user_id: user_ids)
+ .joins("LEFT JOIN users AS creators ON creators.id = user_histories.acting_user_id")
+ .order(:target_user_id, :id)
+ .select(
+ "DISTINCT ON (user_histories.target_user_id) user_histories.target_user_id, " \
+ "creators.id AS creator_id, creators.username AS creator_username, " \
+ "creators.uploaded_avatar_id AS creator_uploaded_avatar_id",
+ )
+ .filter_map do |history|
+ next unless history.creator_id
+
+ [
+ history.target_user_id,
+ {
+ id: history.creator_id,
+ username: history.creator_username,
+ uploaded_avatar_id: history.creator_uploaded_avatar_id,
+ },
+ ]
+ end
+ .to_h
+ end
+
def normalized_order
params[:order]&.downcase&.sub(/ (asc|desc)\z/, "")
end
diff --git a/lib/bot_user.rb b/lib/bot_user.rb
new file mode 100644
index 00000000000..214ebf04d74
--- /dev/null
+++ b/lib/bot_user.rb
@@ -0,0 +1,33 @@
+# frozen_string_literal: true
+
+class BotUser
+ FIRST_ID = -1200
+ FLOOR_KEY = "bot_user_id_floor"
+
+ def initialize(namespace)
+ @store = PluginStore.new(namespace.to_s)
+ end
+
+ def next_id
+ DistributedMutex.synchronize(FLOOR_KEY) do
+ id = [claimed_id, floor].compact.min - 1
+ @store.set(FLOOR_KEY, id)
+ id
+ end
+ end
+
+ private
+
+ # Include every namespace so IDs reserved before user creation cannot collide.
+ def floor
+ PluginStoreRow
+ .where(key: FLOOR_KEY, type_name: %w[Integer Fixnum])
+ .pluck(:value)
+ .map(&:to_i)
+ .min
+ end
+
+ def claimed_id
+ [User.minimum(:id), FIRST_ID].compact.min
+ end
+end
diff --git a/plugins/chat/test/javascripts/components/chat-user-avatar-test.gjs b/plugins/chat/test/javascripts/components/chat-user-avatar-test.gjs
index cbdb56eaae7..5b03f331dc8 100644
--- a/plugins/chat/test/javascripts/components/chat-user-avatar-test.gjs
+++ b/plugins/chat/test/javascripts/components/chat-user-avatar-test.gjs
@@ -3,6 +3,7 @@ import { render } from "@ember/test-helpers";
import { module, test } from "qunit";
import CoreFabricators from "discourse/lib/fabricators";
import { setupRenderingTest } from "discourse/tests/helpers/component-test";
+import { i18n } from "discourse-i18n";
import ChatUserAvatar from "discourse/plugins/chat/discourse/components/chat-user-avatar";
function containerSelector(user, options = {}) {
@@ -90,4 +91,74 @@ module("Component | <ChatUserAvatar />", function (hooks) {
assert.dom(".clickable").doesNotExist();
});
+
+ test("bot avatar flair follows the palette even with chat icon styles", async function (assert) {
+ const user = new CoreFabricators(this.owner).user({ id: -1201 });
+
+ await render(
+ <template>
+ <div class="light-palette" style="--primary: #222; --secondary: #fff;">
+ <ChatUserAvatar @user={{user}} />
+ </div>
+ <div class="dark-palette" style="--primary: #eee; --secondary: #111;">
+ <ChatUserAvatar @interactive={{false}} @user={{user}} />
+ </div>
+ </template>
+ );
+
+ for (const selector of [".light-palette", ".dark-palette"]) {
+ assert
+ .dom(`${selector} .avatar-flair.--bot`)
+ .hasAttribute(
+ "aria-label",
+ i18n("user.bot_account"),
+ "chat exposes the translated marker"
+ );
+ assert
+ .dom(`${selector} .d-icon-robot`)
+ .exists("chat renders the default robot icon");
+ }
+ assert
+ .dom(".light-palette .avatar-flair")
+ .hasStyle(
+ { backgroundColor: "rgb(34, 34, 34)" },
+ "the light palette provides the badge surface"
+ );
+ assert
+ .dom(".light-palette .d-icon-robot")
+ .hasStyle(
+ { fill: "rgb(255, 255, 255)" },
+ "chat styles preserve icon contrast in the light palette"
+ );
+ assert
+ .dom(".dark-palette .avatar-flair")
+ .hasStyle(
+ { backgroundColor: "rgb(238, 238, 238)" },
+ "the dark palette provides the badge surface"
+ );
+ assert
+ .dom(".dark-palette .d-icon-robot")
+ .hasStyle(
+ { fill: "rgb(17, 17, 17)" },
+ "chat styles preserve icon contrast in the dark palette"
+ );
+ });
+
+ test("AI flair wins over the robot fallback in chat", async function (assert) {
+ const user = new CoreFabricators(this.owner).user({ id: -1201 });
+ user.setProperties({
+ flair_group_id: 42,
+ flair_name: "discourse_ai_users",
+ flair_url: "discourse-ai",
+ });
+
+ await render(<template><ChatUserAvatar @user={{user}} /></template>);
+
+ assert
+ .dom(".avatar-flair .d-icon-discourse-ai")
+ .exists("chat preserves the configured AI mark");
+ assert
+ .dom(".avatar-flair.--bot")
+ .doesNotExist("chat does not stack a default bot mark");
+ });
});
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.gjs
index 10c3057130e..94c98e5eca7 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
@@ -72,6 +72,10 @@ export default class AgentEditor extends Component {
return data;
}
+ get cameFromBots() {
+ return this.router.currentRoute?.queryParams?.source === "bots";
+ }
+
get chatPluginEnabled() {
return this.siteSettings.chat_enabled;
}
@@ -239,7 +243,8 @@ export default class AgentEditor extends Component {
addUniqueValueToArray(this.args.agents.content, agentToSave);
await this.router.replaceWith(
"adminPlugins.show.discourse-ai-agents.edit",
- agentToSave
+ agentToSave,
+ { queryParams: { source: this.cameFromBots ? "bots" : null } }
);
}
this.toasts.success({
@@ -700,10 +705,18 @@ export default class AgentEditor extends Component {
}
<template>
- <BackButton
- @label="discourse_ai.ai_agent.back"
- @route="adminPlugins.show.discourse-ai-agents"
- />
+ {{#if this.cameFromBots}}
+ <BackButton
+ @label="admin.users.bots.back"
+ @model="bots"
+ @route="adminUsersList.show"
+ />
+ {{else}}
+ <BackButton
+ @label="discourse_ai.ai_agent.back"
+ @route="adminPlugins.show.discourse-ai-agents"
+ />
+ {{/if}}
<div
class="ai-agent-editor"
{{didInsert this.updateAllGroups @model.id}}
diff --git a/plugins/discourse-ai/admin/assets/javascripts/discourse/initializers/admin-new-bot-options.js b/plugins/discourse-ai/admin/assets/javascripts/discourse/initializers/admin-new-bot-options.js
new file mode 100644
index 00000000000..fb3cace0d29
--- /dev/null
+++ b/plugins/discourse-ai/admin/assets/javascripts/discourse/initializers/admin-new-bot-options.js
@@ -0,0 +1,20 @@
+import { apiInitializer } from "discourse/lib/api";
+
+export default apiInitializer((api) => {
+ if (!api.getCurrentUser()?.admin) {
+ return;
+ }
+
+ api.registerValueTransformer("admin-new-bot-options", ({ value }) => [
+ ...value,
+ {
+ id: "ai-agent",
+ icon: "discourse-sparkles",
+ label: "discourse_ai.ai_agent.new_bot_option.label",
+ description: "discourse_ai.ai_agent.new_bot_option.description",
+ route: "adminPlugins.show.discourse-ai-agents.new",
+ routeModels: ["discourse-ai"],
+ queryParams: { source: "bots" },
+ },
+ ]);
+});
diff --git a/plugins/discourse-ai/admin/assets/javascripts/discourse/routes/admin-plugins/show/discourse-ai-agents/edit.js b/plugins/discourse-ai/admin/assets/javascripts/discourse/routes/admin-plugins/show/discourse-ai-agents/edit.js
index a47cc306ca7..ac6d625c4b1 100644
--- a/plugins/discourse-ai/admin/assets/javascripts/discourse/routes/admin-plugins/show/discourse-ai-agents/edit.js
+++ b/plugins/discourse-ai/admin/assets/javascripts/discourse/routes/admin-plugins/show/discourse-ai-agents/edit.js
@@ -1,6 +1,10 @@
import DiscourseRoute from "discourse/routes/discourse";
export default class AdminPluginsShowDiscourseAiAgentsEdit extends DiscourseRoute {
+ queryParams = {
+ source: {},
+ };
+
async model(params) {
const allAgents = this.modelFor("adminPlugins.show.discourse-ai-agents");
const id = parseInt(params.id, 10);
diff --git a/plugins/discourse-ai/admin/assets/javascripts/discourse/routes/admin-plugins/show/discourse-ai-agents/new.js b/plugins/discourse-ai/admin/assets/javascripts/discourse/routes/admin-plugins/show/discourse-ai-agents/new.js
index ee8dc605235..a537a0405ed 100644
--- a/plugins/discourse-ai/admin/assets/javascripts/discourse/routes/admin-plugins/show/discourse-ai-agents/new.js
+++ b/plugins/discourse-ai/admin/assets/javascripts/discourse/routes/admin-plugins/show/discourse-ai-agents/new.js
@@ -5,6 +5,7 @@ import { i18n } from "discourse-i18n";
export default class AdminPluginsShowDiscourseAiAgentsNew extends DiscourseRoute {
queryParams = {
copyFrom: { refreshModel: true },
+ source: {},
};
async model({ copyFrom }) {
diff --git a/plugins/discourse-ai/app/models/ai_agent.rb b/plugins/discourse-ai/app/models/ai_agent.rb
index 73c9c608869..20191ec308c 100644
--- a/plugins/discourse-ai/app/models/ai_agent.rb
+++ b/plugins/discourse-ai/app/models/ai_agent.rb
@@ -85,6 +85,9 @@ class AiAgent < ActiveRecord::Base
after_update :sync_spam_detection_model, if: :saved_change_to_default_llm_id?
before_destroy :ensure_not_system
after_destroy :remove_destroyed_agent_from_subagents
+ after_destroy :sync_bot_user_activation
+ after_save :sync_bot_user_activation,
+ if: -> { saved_change_to_enabled? || saved_change_to_user_id? }
def self.agent_cache
@agent_cache ||= DiscourseAi::MultisiteHash.new("agent_cache")
@@ -533,6 +536,23 @@ class AiAgent < ActiveRecord::Base
private
+ def sync_bot_user_activation
+ user_ids = [user_id]
+ user_ids.concat(saved_change_to_user_id) if !destroyed? && saved_change_to_user_id?
+
+ User
+ .bot_users
+ .where(id: user_ids.compact.uniq)
+ .order(:id)
+ .lock
+ .each do |bot_user|
+ next if bot_user.is_system_user? || bot_user.staff?
+
+ active = self.class.where(user_id: bot_user.id, enabled: true).exists?
+ bot_user.update!(active:) if bot_user.active? != active
+ end
+ end
+
# Spam scans use an explicit model setting, so agent edits must update it too.
# Clearing the agent default preserves the model selected for spam detection.
def sync_spam_detection_model
@@ -550,10 +570,10 @@ class AiAgent < ActiveRecord::Base
email: "#{SecureRandom.hex}@does-not-exist.invalid",
name: name.titleize,
username: UserNameSuggester.suggest(name + "_bot"),
- active: true,
+ active: enabled?,
approved: true,
trust_level: TrustLevel[4],
- id: DiscourseAi::BotUser.next_id,
+ id: ::BotUser.new(DiscourseAi::PLUGIN_NAME).next_id,
)
user.save!(validate: false)
diff --git a/plugins/discourse-ai/config/locales/client.en.yml b/plugins/discourse-ai/config/locales/client.en.yml
index 1a0fba98f1a..6e6600bb380 100644
--- a/plugins/discourse-ai/config/locales/client.en.yml
+++ b/plugins/discourse-ai/config/locales/client.en.yml
@@ -904,6 +904,9 @@ en:
finite: "Payloads kept %{detailed} days, summaries %{summary} days, then deleted"
ai_agent:
+ new_bot_option:
+ label: "AI agent"
+ description: "Creates the bot together with its language model, prompt, tools, and permissions."
ai_tools: "Tools"
native_tools_help: "Provider-native tools, such as web search or page fetch, appear when \"Always use default language model\" is enabled and the selected default language model supports them."
mcp_servers: "MCP servers"
diff --git a/plugins/discourse-ai/config/locales/server.en.yml b/plugins/discourse-ai/config/locales/server.en.yml
index 40f7b509de1..73c6c8a5874 100644
--- a/plugins/discourse-ai/config/locales/server.en.yml
+++ b/plugins/discourse-ai/config/locales/server.en.yml
@@ -510,6 +510,10 @@ en:
logging_subject: "Spam detection"
ai_bot:
+ sources:
+ historical: "Discourse AI"
+ spam_detection: "Spam detection"
+ plugin_disabled: "AI plugin disabled"
search_discourse_navigation:
not_allowed: "You are not allowed to search administration destinations."
invalid_query: "Enter a search query between 1 and %{max} characters."
diff --git a/plugins/discourse-ai/lib/ai_bot/sources.rb b/plugins/discourse-ai/lib/ai_bot/sources.rb
new file mode 100644
index 00000000000..9fee1536fcb
--- /dev/null
+++ b/plugins/discourse-ai/lib/ai_bot/sources.rb
@@ -0,0 +1,50 @@
+# frozen_string_literal: true
+
+module DiscourseAi::AiBot::Sources
+ def self.for_user_ids(user_ids)
+ return {} if user_ids.blank?
+
+ sources = Hash.new { |hash, user_id| hash[user_id] = [] }
+
+ AiAgent
+ .where(user_id: user_ids)
+ .order(:id)
+ .pluck(:user_id, :id, :name)
+ .each { |user_id, id, name| sources[user_id] << source(name, "ai-agents/#{id}/edit") }
+
+ LlmModel
+ .where(user_id: user_ids)
+ .order(:id)
+ .pluck(:user_id, :id, :display_name)
+ .each { |user_id, id, name| sources[user_id] << source(name, "ai-llms/#{id}/edit") }
+
+ spam_user_id = SiteSetting.ai_spam_detection_user_id.presence&.to_i
+ if spam_user_id && user_ids.include?(spam_user_id)
+ sources[spam_user_id] << source(
+ I18n.t("discourse_ai.ai_bot.sources.spam_detection"),
+ "ai-spam",
+ )
+ end
+
+ UserCustomField
+ .where(user_id: user_ids, name: DiscourseAi::AiBot::HISTORICAL_AI_USER_CUSTOM_FIELD)
+ .pluck(:user_id)
+ .each do |user_id|
+ if sources[user_id].empty?
+ sources[user_id] << { label: I18n.t("discourse_ai.ai_bot.sources.historical") }
+ end
+ end
+
+ sources
+ end
+
+ # Admin pages require the plugin, so a disabled plugin keeps the name but drops the link.
+ def self.source(label, admin_path)
+ if SiteSetting.discourse_ai_enabled
+ { label:, url: "#{Discourse.base_path}/admin/plugins/discourse-ai/#{admin_path}" }
+ else
+ { label:, note: I18n.t("discourse_ai.ai_bot.sources.plugin_disabled") }
+ end
+ end
+ private_class_method :source
+end
diff --git a/plugins/discourse-ai/lib/bot_user.rb b/plugins/discourse-ai/lib/bot_user.rb
deleted file mode 100644
index 18aa7a801fd..00000000000
--- a/plugins/discourse-ai/lib/bot_user.rb
+++ /dev/null
@@ -1,32 +0,0 @@
-# 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
-end
diff --git a/plugins/discourse-ai/lib/bot_user_extensions.rb b/plugins/discourse-ai/lib/bot_user_extensions.rb
new file mode 100644
index 00000000000..49aabf46fdd
--- /dev/null
+++ b/plugins/discourse-ai/lib/bot_user_extensions.rb
@@ -0,0 +1,27 @@
+# frozen_string_literal: true
+
+module DiscourseAi
+ module BotUserExtensions
+ # TODO: Remove after 2026-11-29 once the new allocator is deployed everywhere.
+ def next_id
+ # Keep reservations visible to both allocators while deployment versions overlap.
+ DistributedMutex.synchronize("#{DiscourseAi::PLUGIN_NAME}_#{::BotUser::FLOOR_KEY}") do
+ super.tap { |id| PluginStore.set(DiscourseAi::PLUGIN_NAME, ::BotUser::FLOOR_KEY, id) }
+ end
+ end
+
+ private
+
+ # Account references reserve IDs even while the feature is disabled.
+ def claimed_id
+ DB.query_single(<<~SQL, ::BotUser::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
+ end
+end
diff --git a/plugins/discourse-ai/plugin.rb b/plugins/discourse-ai/plugin.rb
index c9d4d2843b7..f978b0bd775 100644
--- a/plugins/discourse-ai/plugin.rb
+++ b/plugins/discourse-ai/plugin.rb
@@ -92,6 +92,39 @@ DiscourseAi::Configuration::Module::NAMES.each do |module_name|
end
after_initialize do
+ reloadable_patch { ::BotUser.prepend DiscourseAi::BotUserExtensions }
+
+ add_to_serializer(
+ :admin_user_list,
+ :sources,
+ respect_plugin_enabled: false,
+ include_condition: -> { scope.is_admin? && object.bot? && @options[:user_ids].present? },
+ ) do
+ # Collection serializers share options, keeping these lookups bounded to one batch per page.
+ sources_by_user_id =
+ @options[:discourse_ai_bot_sources] ||= DiscourseAi::AiBot::Sources.for_user_ids(
+ @options[:user_ids],
+ )
+ sources_by_user_id.fetch(object.id, [])
+ end
+
+ # Disabling an agent deactivates its bot; a disabled plugin only dims them in the list.
+ add_to_serializer(
+ :admin_user_list,
+ :bot_inactive,
+ respect_plugin_enabled: false,
+ include_condition: -> do
+ !SiteSetting.discourse_ai_enabled && scope.is_admin? && object.bot? &&
+ @options[:user_ids].present?
+ end,
+ ) do
+ sources_by_user_id =
+ @options[:discourse_ai_bot_sources] ||= DiscourseAi::AiBot::Sources.for_user_ids(
+ @options[:user_ids],
+ )
+ sources_by_user_id.fetch(object.id, []).present?
+ end
+
register_admin_dashboard_section(
id: "ask_ai",
enabled: -> { SiteSetting.ai_ask_ai_enabled },
diff --git a/plugins/discourse-ai/spec/lib/bot_user_spec.rb b/plugins/discourse-ai/spec/lib/bot_user_spec.rb
new file mode 100644
index 00000000000..1b8f8960f4b
--- /dev/null
+++ b/plugins/discourse-ai/spec/lib/bot_user_spec.rb
@@ -0,0 +1,69 @@
+# frozen_string_literal: true
+
+RSpec.describe ::BotUser do
+ subject(:allocator) { described_class.new(DiscourseAi::PLUGIN_NAME) }
+
+ before do
+ enable_current_plugin
+ PluginStoreRow.where(key: described_class::FLOOR_KEY).delete_all
+ end
+
+ describe "#next_id" do
+ it "shares reservations between core and plugin namespaces" do
+ PluginStore.set(DiscourseAi::PLUGIN_NAME, described_class::FLOOR_KEY, -5000)
+ core_allocator = described_class.new("core")
+
+ expect([core_allocator.next_id, allocator.next_id, core_allocator.next_id]).to eq(
+ [-5001, -5002, -5003],
+ )
+ expect(PluginStore.get("core", described_class::FLOOR_KEY)).to eq(-5003)
+ expect(PluginStore.get(DiscourseAi::PLUGIN_NAME, described_class::FLOOR_KEY)).to eq(-5003)
+ end
+
+ it "shares unpersisted reservations with workers using the legacy allocator" do
+ core_allocator = described_class.new("core")
+ ids = []
+
+ expect do
+ ids << core_allocator.next_id
+ expect(PluginStore.get(DiscourseAi::PLUGIN_NAME, described_class::FLOOR_KEY)).to eq(
+ ids.last,
+ )
+
+ legacy_id =
+ DistributedMutex.synchronize(
+ "#{DiscourseAi::PLUGIN_NAME}_#{described_class::FLOOR_KEY}",
+ ) do
+ legacy_floor = PluginStore.get(DiscourseAi::PLUGIN_NAME, described_class::FLOOR_KEY)
+ id = [User.minimum(:id), described_class::FIRST_ID, legacy_floor].compact.min - 1
+ PluginStore.set(DiscourseAi::PLUGIN_NAME, described_class::FLOOR_KEY, id)
+ id
+ end
+ ids << legacy_id
+ ids << allocator.next_id
+ ids << core_allocator.next_id
+ end.not_to change(User, :count)
+
+ expect(ids).to eq([-1201, -1202, -1203, -1204])
+ expect(PluginStore.get("core", described_class::FLOOR_KEY)).to eq(-1204)
+ expect(PluginStore.get(DiscourseAi::PLUGIN_NAME, described_class::FLOOR_KEY)).to eq(-1204)
+ end
+
+ it "reserves dangling agent references before either creation path allocates" do
+ agent = Fabricate(:ai_agent)
+ agent.update_columns(user_id: -6000)
+
+ expect(described_class.new("core").next_id).to eq(-6001)
+ expect(allocator.next_id).to eq(-6002)
+ end
+
+ it "reserves dangling model references even when the plugin is disabled" do
+ model = Fabricate(:llm_model)
+ model.update_columns(user_id: -9000)
+ SiteSetting.discourse_ai_enabled = false
+
+ expect(described_class.new("core").next_id).to eq(-9001)
+ expect(allocator.next_id).to eq(-9002)
+ end
+ end
+end
diff --git a/plugins/discourse-ai/spec/lib/modules/ai_bot/conversation_route_spec.rb b/plugins/discourse-ai/spec/lib/modules/ai_bot/conversation_route_spec.rb
index ed8fd14a44a..dac45924775 100644
--- a/plugins/discourse-ai/spec/lib/modules/ai_bot/conversation_route_spec.rb
+++ b/plugins/discourse-ai/spec/lib/modules/ai_bot/conversation_route_spec.rb
@@ -288,7 +288,7 @@ RSpec.describe DiscourseAi::AiBot::ConversationRoute do
end
it "treats a request-supplied legacy model recipient as a selectable model request" do
- legacy_user = Fabricate(:user, id: DiscourseAi::BotUser.next_id)
+ legacy_user = Fabricate(:user, id: ::BotUser.new(DiscourseAi::PLUGIN_NAME).next_id)
second_model.update_column(:user_id, legacy_user.id)
route =
@@ -315,6 +315,26 @@ RSpec.describe DiscourseAi::AiBot::ConversationRoute do
)
end
+ it "keeps legacy model selection independent from a deactivated recipient account" do
+ legacy_user = Fabricate(:user, id: ::BotUser.new(DiscourseAi::PLUGIN_NAME).next_id)
+ second_model.update_column(:user_id, legacy_user.id)
+ other_agent = Fabricate(:ai_agent, user: legacy_user)
+ other_agent.update!(enabled: false)
+ expect(legacy_user.reload).not_to be_active
+
+ route =
+ described_class.resolve(
+ authorization_user: user,
+ modality: :personal_message,
+ agent_id: agent.id,
+ recipient_user: legacy_user,
+ )
+
+ expect(route.speaker).to eq(agent.user)
+ expect(route.model).to eq(second_model)
+ expect(route.model_source).to eq(:request)
+ end
+
it "rejects a recipient that does not belong to the selected agent" do
expect do
described_class.resolve(
diff --git a/plugins/discourse-ai/spec/lib/modules/ai_bot/jobs/regular/create_ai_reply_spec.rb b/plugins/discourse-ai/spec/lib/modules/ai_bot/jobs/regular/create_ai_reply_spec.rb
index 8f10488869f..64df028e345 100644
--- a/plugins/discourse-ai/spec/lib/modules/ai_bot/jobs/regular/create_ai_reply_spec.rb
+++ b/plugins/discourse-ai/spec/lib/modules/ai_bot/jobs/regular/create_ai_reply_spec.rb
@@ -75,9 +75,11 @@ RSpec.describe Jobs::CreateAiReply do
expect(topic.posts.last.user).to eq(agent.user)
end
- it "fails visibly through the captured speaker when the queued agent is disabled" do
+ it "fails visibly through an active shared speaker when the queued agent is disabled" do
speaker = agent.user
+ Fabricate(:ai_agent, user: speaker, enabled: true)
agent.update!(enabled: false)
+ expect(speaker.reload).to be_active
expect do
job.execute(
@@ -93,6 +95,27 @@ RSpec.describe Jobs::CreateAiReply do
expect(topic.posts.last.raw).to include(I18n.t("discourse_ai.ai_bot.errors.invalid_agent_id"))
end
+ it "fails visibly through the system user when disabling the last agent deactivates its speaker" do
+ speaker = agent.user
+ agent.update!(enabled: false)
+ expect(speaker.reload).not_to be_active
+
+ expect do
+ job.execute(
+ post_id: topic.first_post.id,
+ bot_user_id: speaker.id,
+ agent_id: agent.id,
+ llm_model_id: gpt_35_bot.id,
+ authorization_user_id: topic.first_post.user_id,
+ )
+ end.to change { topic.posts.count }.by(1)
+
+ error_post = topic.posts.last
+ expect(error_post.user).to eq(Discourse.system_user)
+ expect(error_post.raw).to include(I18n.t("discourse_ai.ai_bot.errors.invalid_agent_id"))
+ expect(error_post.custom_fields).not_to have_key(DiscourseAi::AiBot::POST_AI_AGENT_ID_FIELD)
+ end
+
it "fails visibly through the system user when the queued agent is deleted" do
speaker = agent.user
agent.destroy!
@@ -115,7 +138,7 @@ RSpec.describe Jobs::CreateAiReply do
end
it "does not use a captured legacy model user to author a failure" do
- legacy_model_user = Fabricate(:user, id: DiscourseAi::BotUser.next_id)
+ legacy_model_user = Fabricate(:user, id: ::BotUser.new(DiscourseAi::PLUGIN_NAME).next_id)
gpt_35_bot.update_column(:user_id, legacy_model_user.id)
agent.update!(enabled: false)
diff --git a/plugins/discourse-ai/spec/lib/modules/ai_bot/playground_spec.rb b/plugins/discourse-ai/spec/lib/modules/ai_bot/playground_spec.rb
index 284f238d8f5..e282a73fb36 100644
--- a/plugins/discourse-ai/spec/lib/modules/ai_bot/playground_spec.rb
+++ b/plugins/discourse-ai/spec/lib/modules/ai_bot/playground_spec.rb
@@ -1060,7 +1060,9 @@ RSpec.describe DiscourseAi::AiBot::Playground do
message: "Hello",
)
speaker = agent.user
+ Fabricate(:ai_agent, user: speaker, enabled: true)
agent.update!(enabled: false)
+ expect(speaker.reload).to be_active
expect {
Jobs::CreateAiChatReply.new.execute(
@@ -1080,6 +1082,53 @@ RSpec.describe DiscourseAi::AiBot::Playground do
)
end
+ it "creates no queued chat message when disabling the last agent deactivates its speaker" do
+ message =
+ Fabricate(
+ :chat_message_without_service,
+ user:,
+ chat_channel: dm_channel,
+ message: "Hello",
+ )
+ speaker = agent.user
+ agent.update!(enabled: false)
+ expect(speaker.reload).not_to be_active
+
+ expect {
+ Jobs::CreateAiChatReply.new.execute(
+ channel_id: dm_channel.id,
+ message_id: message.id,
+ bot_user_id: speaker.id,
+ agent_id: agent.id,
+ llm_model_id: opus_model.id,
+ authorization_user_id: user.id,
+ )
+ }.not_to change { Chat::Message.where(chat_channel_id: dm_channel.id).count }
+ end
+
+ it "creates no queued chat message through an explicitly inactive speaker" do
+ message =
+ Fabricate(
+ :chat_message_without_service,
+ user:,
+ chat_channel: dm_channel,
+ message: "Hello",
+ )
+ speaker = agent.user
+ speaker.update!(active: false)
+
+ expect {
+ Jobs::CreateAiChatReply.new.execute(
+ channel_id: dm_channel.id,
+ message_id: message.id,
+ bot_user_id: speaker.id,
+ agent_id: agent.id,
+ llm_model_id: opus_model.id,
+ authorization_user_id: user.id,
+ )
+ }.not_to change { Chat::Message.where(chat_channel_id: dm_channel.id).count }
+ end
+
it "can run tools" do
agent.update!(tools: ["Time"])
@@ -1312,7 +1361,7 @@ RSpec.describe DiscourseAi::AiBot::Playground do
end
it "normalizes a public legacy model mention to the topic agent" do
- legacy_user = Fabricate(:user, id: DiscourseAi::BotUser.next_id)
+ legacy_user = Fabricate(:user, id: ::BotUser.new(DiscourseAi::PLUGIN_NAME).next_id)
claude_2.update_column(:user_id, legacy_user.id)
toggle_enabled_bots(bots: [claude_2])
agent.update!(allow_topic_mentions: true)
@@ -1341,7 +1390,7 @@ RSpec.describe DiscourseAi::AiBot::Playground do
end
it "preserves the conversation model for a per-turn legacy model mention" do
- legacy_user = Fabricate(:user, id: DiscourseAi::BotUser.next_id)
+ legacy_user = Fabricate(:user, id: ::BotUser.new(DiscourseAi::PLUGIN_NAME).next_id)
claude_2.update_column(:user_id, legacy_user.id)
agent.update!(allow_topic_mentions: true)
topic = Fabricate(:topic, user: admin)
@@ -1365,7 +1414,7 @@ RSpec.describe DiscourseAi::AiBot::Playground do
end
it "normalizes a reply to a public legacy model post to the topic agent" do
- legacy_user = Fabricate(:user, id: DiscourseAi::BotUser.next_id)
+ legacy_user = Fabricate(:user, id: ::BotUser.new(DiscourseAi::PLUGIN_NAME).next_id)
claude_2.update_column(:user_id, legacy_user.id)
toggle_enabled_bots(bots: [claude_2])
agent.update!(allow_topic_mentions: true)
@@ -1392,7 +1441,7 @@ RSpec.describe DiscourseAi::AiBot::Playground do
end
it "reports an unavailable public legacy model mention through the topic agent" do
- legacy_user = Fabricate(:user, id: DiscourseAi::BotUser.next_id)
+ legacy_user = Fabricate(:user, id: ::BotUser.new(DiscourseAi::PLUGIN_NAME).next_id)
claude_2.update_column(:user_id, legacy_user.id)
toggle_enabled_bots(bots: [opus_model])
agent.update!(allow_topic_mentions: true)
@@ -2478,9 +2527,9 @@ RSpec.describe DiscourseAi::AiBot::Playground do
describe ".legacy_recipient_for" do
it "rejects an ambiguous conversation when the preferred bot is no longer a participant" do
- first_model_user = Fabricate(:user, id: DiscourseAi::BotUser.next_id)
- second_model_user = Fabricate(:user, id: DiscourseAi::BotUser.next_id)
- former_model_user = Fabricate(:user, id: DiscourseAi::BotUser.next_id)
+ first_model_user = Fabricate(:user, id: ::BotUser.new(DiscourseAi::PLUGIN_NAME).next_id)
+ second_model_user = Fabricate(:user, id: ::BotUser.new(DiscourseAi::PLUGIN_NAME).next_id)
+ former_model_user = Fabricate(:user, id: ::BotUser.new(DiscourseAi::PLUGIN_NAME).next_id)
claude_2.update_column(:user_id, first_model_user.id)
opus_model.update_column(:user_id, second_model_user.id)
Fabricate(:llm_model).update_column(:user_id, former_model_user.id)
@@ -2496,8 +2545,8 @@ RSpec.describe DiscourseAi::AiBot::Playground do
end
it "continues a legacy conversation with its preferred model recipient" do
- first_model_user = Fabricate(:user, id: DiscourseAi::BotUser.next_id)
- preferred_model_user = Fabricate(:user, id: DiscourseAi::BotUser.next_id)
+ first_model_user = Fabricate(:user, id: ::BotUser.new(DiscourseAi::PLUGIN_NAME).next_id)
+ preferred_model_user = Fabricate(:user, id: ::BotUser.new(DiscourseAi::PLUGIN_NAME).next_id)
claude_2.update_column(:user_id, first_model_user.id)
opus_model.update_column(:user_id, preferred_model_user.id)
toggle_enabled_bots(bots: [claude_2, opus_model])
@@ -2824,7 +2873,7 @@ RSpec.describe DiscourseAi::AiBot::Playground do
end
it "preserves the existing author when retrying a historical reply" do
- historical_user = Fabricate(:user, id: DiscourseAi::BotUser.next_id)
+ historical_user = Fabricate(:user, id: ::BotUser.new(DiscourseAi::PLUGIN_NAME).next_id)
historical_model = Fabricate(:llm_model)
historical_model.update_column(:user_id, historical_user.id)
historical_reply =
diff --git a/plugins/discourse-ai/spec/models/ai_agent_spec.rb b/plugins/discourse-ai/spec/models/ai_agent_spec.rb
index 033d4cf56ce..0ccbab24ce1 100644
--- a/plugins/discourse-ai/spec/models/ai_agent_spec.rb
+++ b/plugins/discourse-ai/spec/models/ai_agent_spec.rb
@@ -16,6 +16,216 @@ RSpec.describe AiAgent do
before { enable_current_plugin }
+ describe "bot account activation" do
+ fab!(:agent, :ai_agent)
+
+ it "deactivates and reactivates the same account when the agent is toggled" do
+ bot = agent.create_user!
+
+ expect { agent.update!(enabled: false) }.not_to change(User, :count)
+ expect(bot.reload).not_to be_active
+ expect(agent.reload.user_id).to eq(bot.id)
+
+ expect { agent.update!(enabled: true) }.not_to change(User, :count)
+ expect(bot.reload).to be_active
+ expect(agent.reload.user_id).to eq(bot.id)
+ end
+
+ it "keeps a shared bot active while any linked agent is enabled" do
+ bot = agent.create_user!
+ other_agent = Fabricate(:ai_agent, user: bot)
+
+ agent.update!(enabled: false)
+ expect(bot.reload).to be_active
+
+ other_agent.update!(enabled: false)
+ expect(bot.reload).not_to be_active
+
+ agent.update!(enabled: true)
+ expect(bot.reload).to be_active
+ end
+
+ it "preserves the system account activation when linked to an agent" do
+ system_user = Discourse.system_user
+ agent.update!(user: system_user, enabled: false)
+ expect(system_user.reload).to be_active
+
+ system_user.update!(active: false)
+ agent.update!(enabled: true)
+ expect(system_user.reload).not_to be_active
+
+ system_user.update!(active: true)
+ agent.destroy!
+ expect(system_user.reload).to be_active
+ end
+
+ %i[admin moderator].each do |role|
+ it "preserves activation of a bot with the #{role} role" do
+ bot = agent.create_user!
+ bot.update!(role => true)
+
+ agent.update!(enabled: false)
+ expect(bot.reload).to be_active
+
+ bot.update!(active: false)
+ agent.update!(enabled: true)
+ expect(bot.reload).not_to be_active
+
+ bot.update!(active: true)
+ agent.destroy!
+ expect(bot.reload).to be_active
+ end
+ end
+
+ it "synchronizes both accounts when reassigned by user ID" do
+ bot = agent.create_user!
+ replacement =
+ Fabricate(:user, id: ::BotUser.new(DiscourseAi::PLUGIN_NAME).next_id, active: false)
+ expect(agent.user).to eq(bot)
+
+ agent.update!(user_id: replacement.id)
+
+ expect(bot.reload).not_to be_active
+ expect(replacement.reload).to be_active
+ end
+
+ it "keeps the previous bot active on reassignment while another linked agent is enabled" do
+ bot = agent.create_user!
+ Fabricate(:ai_agent, user: bot)
+ replacement =
+ Fabricate(:user, id: ::BotUser.new(DiscourseAi::PLUGIN_NAME).next_id, active: false)
+
+ agent.update!(user_id: replacement.id)
+
+ expect(bot.reload).to be_active
+ expect(replacement.reload).to be_active
+ end
+
+ it "deactivates the previous bot when its last agent reference is cleared" do
+ bot = agent.create_user!
+
+ agent.update!(user_id: nil)
+
+ expect(bot.reload).not_to be_active
+ expect(agent.reload.user_id).to be_nil
+ end
+
+ it "keeps a shared bot active when one agent reference is cleared" do
+ bot = agent.create_user!
+ Fabricate(:ai_agent, user: bot)
+
+ agent.update!(user_id: nil)
+
+ expect(bot.reload).to be_active
+ end
+
+ it "synchronizes the previous bot without changing a human target's activation" do
+ bot = agent.create_user!
+ human = Fabricate(:user)
+ agent.update!(user: human, enabled: false)
+ expect(bot.reload).not_to be_active
+ expect(human.reload).to be_active
+
+ human.update!(active: false)
+ agent.update!(enabled: true)
+ expect(human.reload).not_to be_active
+
+ agent.destroy!
+ expect(human.reload).not_to be_active
+ end
+
+ it "deactivates the bot when its last enabled agent is destroyed" do
+ bot = agent.create_user!
+ Fabricate(:ai_agent, user: bot, enabled: false)
+
+ agent.destroy!
+
+ expect(bot.reload).not_to be_active
+ end
+
+ it "keeps a shared bot active until its last enabled agent is destroyed" do
+ bot = agent.create_user!
+ other_agent = Fabricate(:ai_agent, user: bot)
+
+ agent.destroy!
+ expect(bot.reload).to be_active
+
+ other_agent.destroy!
+ expect(bot.reload).not_to be_active
+ end
+
+ it "keeps a shared bot inactive when a disabled agent is destroyed" do
+ bot = agent.create_user!
+ agent.update!(enabled: false)
+ Fabricate(:ai_agent, user: bot, enabled: false)
+
+ agent.destroy!
+
+ expect(bot.reload).not_to be_active
+ end
+
+ it "synchronizes only the current bot on destroy after reassignment" do
+ bot = agent.create_user!
+ replacement =
+ Fabricate(:user, id: ::BotUser.new(DiscourseAi::PLUGIN_NAME).next_id, active: false)
+ agent.update!(user_id: replacement.id)
+ bot.reload.update!(active: true)
+
+ agent.destroy!
+
+ expect(bot.reload).to be_active
+ expect(replacement.reload).not_to be_active
+ end
+
+ it "preserves both accounts' activation when reassignment fails validation" do
+ bot = agent.create_user!
+ replacement =
+ Fabricate(:user, id: ::BotUser.new(DiscourseAi::PLUGIN_NAME).next_id, active: false)
+
+ expect(agent.update(user_id: replacement.id, name: "")).to eq(false)
+
+ expect(bot.reload).to be_active
+ expect(replacement.reload).not_to be_active
+ end
+
+ it "preserves bot activation when destruction is aborted" do
+ bot = agent.create_user!
+ agent.update!(system: true)
+ bot.update!(active: false)
+
+ expect(agent.destroy).to eq(false)
+
+ expect(bot.reload).not_to be_active
+ expect(agent).to be_persisted
+ end
+
+ it "creates an inactive account for a disabled agent" do
+ agent.update!(enabled: false)
+
+ bot = agent.create_user!
+
+ expect(bot.reload).not_to be_active
+ end
+
+ it "preserves account activation when unrelated agent fields change or validation fails" do
+ bot = agent.create_user!
+ bot.update!(active: false)
+
+ agent.update!(description: "Updated description")
+ expect(bot.reload).not_to be_active
+
+ bot.update!(active: true)
+ expect(agent.update(enabled: false, name: "")).to eq(false)
+ expect(bot.reload).to be_active
+ end
+
+ it "does not create an account solely to synchronize activation" do
+ expect { agent.update!(enabled: false) }.not_to change(User, :count)
+ expect { agent.update!(enabled: true) }.not_to change(User, :count)
+ expect(agent.reload.user_id).to be_nil
+ end
+ end
+
describe "#allowed_group_ids" do
it "aliases Everyone while granular permissions are enabled without changing stored groups" do
group = Fabricate(:group)
@@ -446,7 +656,7 @@ RSpec.describe AiAgent do
expect(user.username).to eq("test_bot")
expect(user.name).to eq("Test")
expect(user.bot?).to be(true)
- expect(user.id).to be < DiscourseAi::BotUser::FIRST_ID
+ expect(user.id).to be < ::BotUser::FIRST_ID
end
it "does not recycle an id another agent still points at" do
@@ -454,7 +664,7 @@ RSpec.describe AiAgent do
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)
+ PluginStore.remove(DiscourseAi::PLUGIN_NAME, ::BotUser::FLOOR_KEY)
user = basic_agent.create_user!
@@ -463,7 +673,7 @@ RSpec.describe AiAgent do
it "does not recycle an id an llm model still points at" do
llm_model.update_columns(user_id: -5000)
- PluginStore.remove(DiscourseAi::PLUGIN_NAME, DiscourseAi::BotUser::FLOOR_KEY)
+ PluginStore.remove(DiscourseAi::PLUGIN_NAME, ::BotUser::FLOOR_KEY)
user = basic_agent.create_user!
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.rb
index c18d2cd218a..012f0941a32 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
@@ -492,6 +492,24 @@ RSpec.describe DiscourseAi::Admin::AiAgentsController do
end
describe "PUT #update" do
+ it "synchronizes the bot account activation when saving the enabled toggle" do
+ bot = ai_agent.create_user!
+
+ [false, true].each do |enabled|
+ put "/admin/plugins/discourse-ai/ai-agents/#{ai_agent.id}.json",
+ params: {
+ ai_agent: {
+ enabled:,
+ },
+ }
+
+ expect(response).to have_http_status(:ok)
+ expect(ai_agent.reload.enabled).to eq(enabled)
+ expect(bot.reload.active).to eq(enabled)
+ expect(ai_agent.user_id).to eq(bot.id)
+ end
+ end
+
context "with scoped api key" do
it "allows updates with a properly scoped API key" do
api_key = Fabricate(:api_key, user: admin, created_by: admin)
diff --git a/plugins/discourse-ai/spec/requests/admin/bot_sources_spec.rb b/plugins/discourse-ai/spec/requests/admin/bot_sources_spec.rb
new file mode 100644
index 00000000000..61af698ff6c
--- /dev/null
+++ b/plugins/discourse-ai/spec/requests/admin/bot_sources_spec.rb
@@ -0,0 +1,161 @@
+# frozen_string_literal: true
+
+RSpec.describe Admin::UsersController do
+ fab!(:admin)
+ fab!(:moderator)
+ fab!(:bot) { Fabricate(:user, id: -101, username: "source_bot", email: "[email protected]") }
+ fab!(:other_bot) { Fabricate(:user, id: -102) }
+ fab!(:unattributed_bot) { Fabricate(:user, id: -103) }
+ fab!(:agent) { Fabricate(:ai_agent, user: bot) }
+
+ before do
+ enable_current_plugin
+ sign_in(admin)
+ end
+
+ def listed_user(user)
+ response.parsed_body.find { |entry| entry["id"] == user.id }
+ end
+
+ it "links all associated agents and models, including disabled agents" do
+ disabled_agent = Fabricate(:ai_agent, user: bot, enabled: false)
+ model = Fabricate(:llm_model)
+ model.update_column(:user_id, bot.id)
+
+ get "/admin/users/list/bots.json"
+
+ expect(response.status).to eq(200)
+ expect(listed_user(bot)["sources"]).to eq(
+ [
+ {
+ "label" => agent.name,
+ "url" => "/admin/plugins/discourse-ai/ai-agents/#{agent.id}/edit",
+ },
+ {
+ "label" => disabled_agent.name,
+ "url" => "/admin/plugins/discourse-ai/ai-agents/#{disabled_agent.id}/edit",
+ },
+ {
+ "label" => model.display_name,
+ "url" => "/admin/plugins/discourse-ai/ai-llms/#{model.id}/edit",
+ },
+ ],
+ )
+ expect(listed_user(unattributed_bot)["sources"]).to eq([])
+ end
+
+ it "retains historical attribution without a configuration link or duplicate source" do
+ [bot, other_bot].each do |user|
+ Fabricate(
+ :user_custom_field,
+ user:,
+ name: DiscourseAi::AiBot::HISTORICAL_AI_USER_CUSTOM_FIELD,
+ value: "true",
+ )
+ end
+
+ get "/admin/users/list/bots.json"
+
+ expect(listed_user(other_bot)["sources"]).to eq(
+ [{ "label" => I18n.t("discourse_ai.ai_bot.sources.historical") }],
+ )
+ expect(listed_user(bot)["sources"].size).to eq(1)
+ expect(listed_user(bot)["sources"].first["url"]).to end_with("/#{agent.id}/edit")
+ end
+
+ it "omits configuration metadata for moderators" do
+ sign_in(moderator)
+
+ get "/admin/users/list/bots.json"
+
+ expect(response.status).to eq(200)
+ expect(listed_user(bot)).not_to have_key("sources")
+ end
+
+ it "omits configuration metadata for moderators while the plugin is disabled" do
+ SiteSetting.discourse_ai_enabled = false
+ sign_in(moderator)
+
+ get "/admin/users/list/bots.json"
+
+ expect(response.status).to eq(200)
+ expect(listed_user(bot)).not_to have_key("sources")
+ expect(listed_user(bot)).not_to have_key("bot_inactive")
+ end
+
+ it "keeps sources unlinked and noted when the plugin is disabled" do
+ SiteSetting.discourse_ai_enabled = false
+
+ get "/admin/users/list/bots.json"
+
+ expect(response.status).to eq(200)
+ expect(listed_user(bot)["sources"]).to eq(
+ [{ "label" => agent.name, "note" => I18n.t("discourse_ai.ai_bot.sources.plugin_disabled") }],
+ )
+ end
+
+ it "marks AI bots inactive only while the plugin is disabled" do
+ get "/admin/users/list/bots.json"
+ expect(listed_user(bot)).not_to have_key("bot_inactive")
+
+ SiteSetting.discourse_ai_enabled = false
+ get "/admin/users/list/bots.json"
+
+ expect(listed_user(bot)["bot_inactive"]).to eq(true)
+ expect(listed_user(unattributed_bot)["bot_inactive"]).to eq(false)
+ end
+
+ it "links the spam detection bot to its settings" do
+ SiteSetting.ai_spam_detection_user_id = other_bot.id
+
+ get "/admin/users/list/bots.json"
+
+ expect(response.status).to eq(200)
+ expect(listed_user(other_bot)["sources"]).to eq(
+ [
+ {
+ "label" => I18n.t("discourse_ai.ai_bot.sources.spam_detection"),
+ "url" => "/admin/plugins/discourse-ai/ai-spam",
+ },
+ ],
+ )
+ end
+
+ it "does not enrich other users lists" do
+ get "/admin/users/list/new.json"
+
+ expect(response.status).to eq(200)
+ expect(listed_user(bot)).not_to have_key("sources")
+ end
+
+ it "respects subfolder installations" do
+ set_subfolder "/forum"
+
+ get "/admin/users/list/bots.json"
+
+ expect(listed_user(bot)["sources"].first["url"]).to eq(
+ "/forum/admin/plugins/discourse-ai/ai-agents/#{agent.id}/edit",
+ )
+ end
+
+ it "loads source associations once for only the returned page" do
+ Fabricate(:ai_agent, user: other_bot)
+
+ queries =
+ track_sql_queries { get "/admin/users/list/bots.json", params: { filter: bot.username } }
+ source_queries =
+ queries.select { |sql| sql.match?(/FROM "(?:ai_agents|llm_models|user_custom_fields)"/) }
+
+ expect(listed_user(bot)["sources"].size).to eq(1)
+ expect(response.parsed_body.map { |entry| entry["id"] }).to eq([bot.id])
+ expect(source_queries.grep(/FROM "ai_agents"/).size).to eq(1)
+ expect(source_queries.grep(/FROM "llm_models"/).size).to eq(1)
+ expect(source_queries.grep(/FROM "user_custom_fields"/).size).to eq(1)
+
+ queries = track_sql_queries { get "/admin/users/list/bots.json" }
+ expect(listed_user(other_bot)["sources"].size).to eq(1)
+ expect(queries.grep(/FROM "ai_agents"/).size).to eq(1)
+ expect(queries.grep(/FROM "llm_models"/).size).to eq(1)
+ expect(queries.grep(/FROM "user_custom_fields"/).size).to eq(1)
+ end
+end
diff --git a/plugins/discourse-ai/spec/requests/ai_bot/artifact_shares_controller_spec.rb b/plugins/discourse-ai/spec/requests/ai_bot/artifact_shares_controller_spec.rb
index b174ac39632..3bc07a199d9 100644
--- a/plugins/discourse-ai/spec/requests/ai_bot/artifact_shares_controller_spec.rb
+++ b/plugins/discourse-ai/spec/requests/ai_bot/artifact_shares_controller_spec.rb
@@ -236,7 +236,7 @@ RSpec.describe DiscourseAi::AiBot::ArtifactSharesController do
end
it "permits the PM creator to share an artifact owned by a detached legacy bot" do
- legacy_bot = Fabricate(:user, id: DiscourseAi::BotUser.next_id)
+ legacy_bot = Fabricate(:user, id: ::BotUser.new(DiscourseAi::PLUGIN_NAME).next_id)
UserCustomField.create!(
user: legacy_bot,
name: DiscourseAi::AiBot::HISTORICAL_AI_USER_CUSTOM_FIELD,
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
index bf135628165..f520ccb4df6 100644
--- a/plugins/discourse-ai/spec/requests/ai_bot/conversation_creation_spec.rb
+++ b/plugins/discourse-ai/spec/requests/ai_bot/conversation_creation_spec.rb
@@ -123,7 +123,7 @@ RSpec.describe "AI bot conversation creation" do
end
it "normalizes a legacy model recipient to the General agent" do
- legacy_user = Fabricate(:user, id: DiscourseAi::BotUser.next_id)
+ legacy_user = Fabricate(:user, id: ::BotUser.new(DiscourseAi::PLUGIN_NAME).next_id)
llm_model.update_column(:user_id, legacy_user.id)
general_agent =
AiAgent.find(DiscourseAi::Agents::Agent.system_agents[DiscourseAi::Agents::General])
diff --git a/plugins/discourse-ai/spec/requests/ai_bot/topic_agent_field_spec.rb b/plugins/discourse-ai/spec/requests/ai_bot/topic_agent_field_spec.rb
index c43bcda63bc..311df473b9e 100644
--- a/plugins/discourse-ai/spec/requests/ai_bot/topic_agent_field_spec.rb
+++ b/plugins/discourse-ai/spec/requests/ai_bot/topic_agent_field_spec.rb
@@ -249,7 +249,7 @@ RSpec.describe "AI agent topic custom field" do
it "rejects a direct PM to a legacy LLM user" do
legacy_user =
User.new(
- id: DiscourseAi::BotUser.next_id,
+ id: ::BotUser.new(DiscourseAi::PLUGIN_NAME).next_id,
username: "retired_model",
active: true,
diff --git a/plugins/discourse-ai/spec/requests/ai_bot/topic_serialization_spec.rb b/plugins/discourse-ai/spec/requests/ai_bot/topic_serialization_spec.rb
index cc1b89b7da8..672a40fa2fa 100644
--- a/plugins/discourse-ai/spec/requests/ai_bot/topic_serialization_spec.rb
+++ b/plugins/discourse-ai/spec/requests/ai_bot/topic_serialization_spec.rb
@@ -2,7 +2,7 @@
RSpec.describe "AI Bot Post Serializer" do
fab!(:current_user, :user)
- fab!(:bot_user) { Fabricate(:user, id: DiscourseAi::BotUser.next_id) }
+ fab!(:bot_user) { Fabricate(:user, id: ::BotUser.new(DiscourseAi::PLUGIN_NAME).next_id) }
before do
enable_current_plugin
diff --git a/plugins/discourse-events/spec/lib/topics_filter_spec.rb b/plugins/discourse-events/spec/lib/topics_filter_spec.rb
index eea466bb2cd..6aa3d42b37b 100644
--- a/plugins/discourse-events/spec/lib/topics_filter_spec.rb
+++ b/plugins/discourse-events/spec/lib/topics_filter_spec.rb
@@ -86,7 +86,9 @@ RSpec.describe TopicsFilter do
expect(filtered_topic_ids("event-after:#{1.day.from_now.to_date}")).to contain_exactly(
upcoming_topic.id,
)
- expect(filtered_topic_ids("event-before:#{Date.current}")).to contain_exactly(past_topic.id)
+ expect(
+ filtered_topic_ids("event-before:#{ongoing_event.original_starts_at.to_date}"),
+ ).to contain_exactly(past_topic.id)
expect(
filtered_topic_ids(
"event-after:#{2.days.ago.to_date} event-before:#{1.day.from_now.to_date}",
diff --git a/spec/lib/admin_user_index_query_spec.rb b/spec/lib/admin_user_index_query_spec.rb
index 34852c554a9..edf984479ea 100644
--- a/spec/lib/admin_user_index_query_spec.rb
+++ b/spec/lib/admin_user_index_query_spec.rb
@@ -142,6 +142,43 @@ RSpec.describe AdminUserIndexQuery do
end
end
+ describe "bots" do
+ fab!(:bot) do
+ Fabricate(:user, id: -100, username: "searchable_bot", email: "[email protected]")
+ end
+ fab!(:human) do
+ Fabricate(:user, username: "searchable_human", email: "[email protected]")
+ end
+ fab!(:zero_id_user) { Fabricate(:user, id: 0) }
+
+ it "lists bot accounts using the bot scope, including non-staff bots" do
+ users = described_class.new(query: "bots").find_users
+
+ expect(users).to match_array(User.bot_users)
+ expect(users).to include(bot, Discourse.system_user, zero_id_user)
+ expect(users).not_to include(human)
+ end
+
+ it "sorts bot activity and creation dates in both directions" do
+ other_bot = Fabricate(:user, id: -102, created_at: 2.days.ago)
+ bot.update!(created_at: 1.day.ago)
+ bot.user_stat.update!(topics_entered: 2, posts_read_count: 4, post_count: 6)
+ other_bot.user_stat.update!(topics_entered: 1, posts_read_count: 3, post_count: 5)
+
+ %w[topics_viewed posts_read posts created].each do |order|
+ params = { query: "bots", filter: "#{bot.username},#{other_bot.username}", order: }
+
+ expect(described_class.new(params).find_users).to eq([bot, other_bot])
+ expect(described_class.new(params.merge(asc: true)).find_users).to eq([other_bot, bot])
+ end
+ end
+
+ it "searches within bot accounts" do
+ expect(described_class.new(query: "bots", filter: bot.username).find_users).to eq([bot])
+ expect(described_class.new(query: "bots", filter: human.username).find_users).to be_empty
+ end
+ end
+
describe "staff account types" do
fab!(:admin) { Fabricate(:admin, created_at: 2.days.ago) }
fab!(:moderator) { Fabricate(:moderator, created_at: 1.day.ago) }
@@ -190,6 +227,130 @@ RSpec.describe AdminUserIndexQuery do
end
end
+ describe "#bot_creators" do
+ fab!(:admin)
+ fab!(:creator, :admin)
+ fab!(:bot) { Fabricate(:user, id: -1300, username: "creator_page_bot_a") }
+
+ let!(:query) { described_class.new(query: "bots", guardian: admin.guardian) }
+
+ it "selects the earliest exact creation event deterministically when timestamps match" do
+ freeze_time
+ UserHistory.create!(
+ action: UserHistory.actions[:custom_staff],
+ custom_type: "another_event",
+ target_user_id: bot.id,
+ acting_user_id: admin.id,
+ )
+ UserHistory.create!(
+ action: UserHistory.actions[:custom],
+ custom_type: "create_bot",
+ target_user_id: bot.id,
+ acting_user_id: admin.id,
+ )
+ StaffActionLogger.new(creator).log_bot_creation(bot)
+ StaffActionLogger.new(admin).log_bot_creation(bot)
+
+ expect(query.bot_creators([bot.id])).to eq(
+ bot.id => {
+ id: creator.id,
+ username: creator.username,
+ uploaded_avatar_id: creator.uploaded_avatar_id,
+ },
+ )
+ end
+
+ it "omits unknown bots and deleted first actors rather than attributing a later duplicate" do
+ unknown_bot = Fabricate(:user, id: -1301)
+ StaffActionLogger.new(creator).log_bot_creation(bot)
+ StaffActionLogger.new(admin).log_bot_creation(bot)
+ creator.delete
+
+ expect(query.bot_creators([bot.id, unknown_bot.id])).to eq({})
+ end
+
+ it "returns an empty result without querying for empty pages or non-admin guardians" do
+ StaffActionLogger.new(creator).log_bot_creation(bot)
+ moderator = Fabricate(:moderator)
+
+ queries = track_sql_queries { expect(query.bot_creators([])).to eq({}) }
+ expect(queries).to be_empty
+
+ [nil, moderator.guardian].each do |guardian|
+ non_admin_query = described_class.new(query: "bots", guardian: guardian)
+ queries = track_sql_queries { expect(non_admin_query.bot_creators([bot.id])).to eq({}) }
+
+ expect(queries).to be_empty
+ end
+ end
+
+ it "returns only creators for the requested filtered page" do
+ page_bot = Fabricate(:user, id: -1301, username: "creator_page_bot_b")
+ excluded_bot = Fabricate(:user, id: -1302, username: "excluded_bot")
+ [bot, page_bot, excluded_bot].each do |target|
+ StaffActionLogger.new(creator).log_bot_creation(target)
+ end
+ page_query =
+ described_class.new(
+ query: "bots",
+ filter: "creator_page_bot",
+ order: "username",
+ asc: true,
+ page: 2,
+ guardian: admin.guardian,
+ )
+ page_ids = page_query.find_users(1).map(&:id)
+
+ expect(page_ids).to eq([page_bot.id])
+ expect(page_query.bot_creators(page_ids)).to eq(
+ page_bot.id => {
+ id: creator.id,
+ username: creator.username,
+ uploaded_avatar_id: creator.uploaded_avatar_id,
+ },
+ )
+ end
+
+ it "materializes creator data in one query regardless of the number of bots" do
+ StaffActionLogger.new(creator).log_bot_creation(bot)
+ queries_for_one =
+ track_sql_queries do
+ expect(query.bot_creators([bot.id])).to eq(
+ bot.id => {
+ id: creator.id,
+ username: creator.username,
+ uploaded_avatar_id: creator.uploaded_avatar_id,
+ },
+ )
+ end
+ expected_creators = {
+ bot.id => {
+ id: creator.id,
+ username: creator.username,
+ uploaded_avatar_id: creator.uploaded_avatar_id,
+ },
+ }
+ 4.times do |index|
+ additional_bot = Fabricate(:user, id: -1301 - index)
+ additional_creator = Fabricate(:admin)
+ StaffActionLogger.new(additional_creator).log_bot_creation(additional_bot)
+ expected_creators[additional_bot.id] = {
+ id: additional_creator.id,
+ username: additional_creator.username,
+ uploaded_avatar_id: additional_creator.uploaded_avatar_id,
+ }
+ end
+
+ queries_for_many =
+ track_sql_queries do
+ expect(query.bot_creators(expected_creators.keys)).to eq(expected_creators)
+ end
+
+ expect(queries_for_one.size).to eq(1)
+ expect(queries_for_many.size).to eq(1)
+ end
+ end
+
describe "with a moderator" do
fab!(:user) { Fabricate(:user, moderator: true) }
fab!(:user2) { Fabricate(:user, moderator: false) }
diff --git a/spec/lib/bot_user_spec.rb b/spec/lib/bot_user_spec.rb
new file mode 100644
index 00000000000..197ce10815f
--- /dev/null
+++ b/spec/lib/bot_user_spec.rb
@@ -0,0 +1,62 @@
+# frozen_string_literal: true
+
+RSpec.describe BotUser do
+ subject(:allocator) { described_class.new(:core) }
+
+ before { PluginStoreRow.where(key: described_class::FLOOR_KEY).delete_all }
+
+ describe "#next_id" do
+ it "allocates consecutive IDs below the reserved region without creating users" do
+ ids = nil
+ expect { ids = 2.times.map { allocator.next_id } }.not_to change(User, :count)
+
+ expect(ids).to eq([-1201, -1202])
+ expect(PluginStore.get("core", described_class::FLOOR_KEY)).to eq(-1202)
+ end
+
+ it "reserves distinct IDs across namespaces and instances before users are persisted" do
+ other_allocator = described_class.new("another-plugin")
+ ids = nil
+
+ expect do
+ ids = [allocator.next_id, other_allocator.next_id, described_class.new("core").next_id]
+ end.not_to change(User, :count)
+
+ expect(ids).to eq([-1201, -1202, -1203])
+ expect(PluginStore.get("core", described_class::FLOOR_KEY)).to eq(-1203)
+ expect(PluginStore.get("another-plugin", described_class::FLOOR_KEY)).to eq(-1202)
+ end
+
+ it "starts below existing users and does not reuse a deleted user's ID" do
+ existing_user = Fabricate(:user, id: -3000)
+ first_id = allocator.next_id
+ bot = Fabricate(:user, id: first_id)
+
+ bot.destroy!
+ existing_user.destroy!
+
+ expect(first_id).to eq(-3001)
+ expect(described_class.new("core").next_id).to eq(-3002)
+ end
+
+ it "continues below legacy reservations while storing new reservations in its namespace" do
+ PluginStore.set("legacy-plugin", described_class::FLOOR_KEY, -5000)
+ PluginStoreRow.where(
+ plugin_name: "legacy-plugin",
+ key: described_class::FLOOR_KEY,
+ ).update_all(type_name: "Fixnum")
+
+ expect(allocator.next_id).to eq(-5001)
+ expect(PluginStore.get("core", described_class::FLOOR_KEY)).to eq(-5001)
+ expect(PluginStore.get("legacy-plugin", described_class::FLOOR_KEY)).to eq(-5000)
+ end
+
+ it "uses the lowest integer reservation across namespaces" do
+ PluginStore.set("first-plugin", described_class::FLOOR_KEY, -9000)
+ PluginStore.set("second-plugin", described_class::FLOOR_KEY, -10_000)
+ PluginStore.set("unrelated-plugin", described_class::FLOOR_KEY, "-20000")
+
+ expect(allocator.next_id).to eq(-10_001)
+ end
+ end
+end
diff --git a/spec/models/api_key_scope_spec.rb b/spec/models/api_key_scope_spec.rb
index 7c8568d410d..8065d31e7a9 100644
--- a/spec/models/api_key_scope_spec.rb
+++ b/spec/models/api_key_scope_spec.rb
@@ -31,6 +31,44 @@ RSpec.describe ApiKeyScope do
end
end
+ describe ".build_from_params" do
+ it "builds scopes with their restrictable parameters split into lists" do
+ scopes =
+ described_class.build_from_params(
+ [{ "scope_id" => "topics:write", "topic_id" => "1,2", "unrelated" => "3" }],
+ )
+
+ expect(scopes.map(&:attributes)).to contain_exactly(
+ include(
+ "resource" => "topics",
+ "action" => "write",
+ "allowed_parameters" => {
+ "topic_id" => %w[1 2],
+ },
+ ),
+ )
+ end
+
+ it "drops blank parameters" do
+ scopes = described_class.build_from_params([{ scope_id: "topics:write", topic_id: "" }])
+
+ expect(scopes.first.allowed_parameters).to be_empty
+ end
+
+ it "rejects unknown and missing scopes" do
+ [
+ { scope_id: "topics:explode" },
+ { scope_id: "nope" },
+ {},
+ "topics:write",
+ ].each do |scope_params|
+ expect { described_class.build_from_params([scope_params]) }.to raise_error(
+ Discourse::InvalidParameters,
+ )
+ end
+ end
+ end
+
describe ".scope_mappings" do
it "does not define a granular scope for about requests" do
expect(described_class.scope_mappings).not_to have_key(:about)
diff --git a/spec/requests/admin/api_controller_spec.rb b/spec/requests/admin/api_controller_spec.rb
index 2a96799466d..94213e8fdaf 100644
--- a/spec/requests/admin/api_controller_spec.rb
+++ b/spec/requests/admin/api_controller_spec.rb
@@ -477,8 +477,11 @@ RSpec.describe Admin::ApiController do
get "/admin/api/keys/scopes.json"
scopes = response.parsed_body["scopes"]
+ # Plugins loaded in the same run add their own resources.
+ plugin_resources =
+ DiscoursePluginRegistry.api_key_scope_mappings.flat_map { it.keys.map(&:to_s) }
- expect(scopes.keys).to contain_exactly(
+ expect(scopes.keys - plugin_resources).to contain_exactly(
"topics",
"users",
"email",
diff --git a/spec/requests/admin/bot_creators_spec.rb b/spec/requests/admin/bot_creators_spec.rb
new file mode 100644
index 00000000000..4c1b2f4ba5b
--- /dev/null
+++ b/spec/requests/admin/bot_creators_spec.rb
@@ -0,0 +1,137 @@
+# frozen_string_literal: true
+
+RSpec.describe Admin::UsersController do
+ fab!(:admin)
+ fab!(:creator, :admin)
+ fab!(:moderator)
+ fab!(:bot) { Fabricate(:user, id: -1300, username: "attributed_bot", approved_by_id: admin.id) }
+
+ def creator_lookup_queries(queries)
+ queries.select do |sql|
+ sql.match?(/FROM\s+"?user_histories"?/i) &&
+ sql.match?(/JOIN\s+"?users"?\s+(?:AS\s+)?"?(?:bot_creators|creators)"?\b/i)
+ end
+ end
+
+ describe "#index" do
+ it "attributes a bot to its audit actor using the actor's current username, not its approver" do
+ StaffActionLogger.new(creator).log_bot_creation(bot)
+ creator.update!(username: "RenamedCreator")
+ sign_in(admin)
+
+ get "/admin/users/list/bots.json", params: { filter: bot.username }
+
+ expect(response.status).to eq(200)
+ expect(response.parsed_body).to contain_exactly(
+ a_hash_including(
+ "id" => bot.id,
+ "bot_creator" => {
+ "username" => creator.username,
+ "avatar_template" => creator.avatar_template,
+ "url" => "/admin/users/#{creator.id}/renamedcreator",
+ },
+ ),
+ )
+ end
+
+ it "includes the subfolder and encodes the lowercase Unicode creator username" do
+ SiteSetting.unicode_usernames = true
+ creator.update!(username: "Élève")
+ StaffActionLogger.new(creator).log_bot_creation(bot)
+ set_subfolder "/forum"
+ sign_in(admin)
+
+ get "/admin/users/list/bots.json", params: { filter: bot.username }
+
+ expect(response.status).to eq(200)
+ expect(response.parsed_body.first["bot_creator"]).to eq(
+ "username" => creator.username,
+ "avatar_template" => creator.avatar_template,
+ "url" => "/forum/admin/users/#{creator.id}/%C3%A9l%C3%A8ve",
+ )
+ end
+
+ it "omits attribution when no creation event is recorded, even when an approver exists" do
+ sign_in(admin)
+
+ get "/admin/users/list/bots.json", params: { filter: bot.username }
+
+ expect(response.status).to eq(200)
+ expect(response.parsed_body.map { |user| user["id"] }).to eq([bot.id])
+ expect(response.parsed_body.first).not_to have_key("bot_creator")
+ end
+
+ it "omits attribution when the first creator was deleted despite a later live actor" do
+ StaffActionLogger.new(creator).log_bot_creation(bot)
+ StaffActionLogger.new(admin).log_bot_creation(bot)
+ creator.delete
+ sign_in(admin)
+
+ get "/admin/users/list/bots.json", params: { filter: bot.username }
+
+ expect(response.status).to eq(200)
+ expect(response.parsed_body.map { |user| user["id"] }).to eq([bot.id])
+ expect(response.parsed_body.first).not_to have_key("bot_creator")
+ end
+
+ it "lets moderators list bots without exposing attribution or querying creators" do
+ StaffActionLogger.new(creator).log_bot_creation(bot)
+ sign_in(moderator)
+
+ queries =
+ track_sql_queries { get "/admin/users/list/bots.json", params: { filter: bot.username } }
+
+ expect(response.status).to eq(200)
+ expect(response.parsed_body.map { |user| user["id"] }).to eq([bot.id])
+ expect(response.parsed_body.first).not_to have_key("bot_creator")
+ expect(creator_lookup_queries(queries)).to be_empty
+ end
+
+ it "keeps creator metadata and creator lookups off the other user tabs" do
+ StaffActionLogger.new(creator).log_bot_creation(bot)
+ sign_in(admin)
+
+ %w[active new staff].each do |tab|
+ queries = track_sql_queries { get "/admin/users/list/#{tab}.json" }
+
+ expect(response.status).to eq(200)
+ expect(response.parsed_body).to be_present
+ expect(response.parsed_body).to all(satisfy { |user| !user.key?("bot_creator") })
+ expect(creator_lookup_queries(queries)).to be_empty
+ end
+ end
+
+ it "loads creators once for one or many bots without lazy creator queries while serializing" do
+ StaffActionLogger.new(creator).log_bot_creation(bot)
+ sign_in(admin)
+ get "/admin/users/list/bots.json", params: { filter: bot.username }
+
+ queries_for_one =
+ track_sql_queries { get "/admin/users/list/bots.json", params: { filter: bot.username } }
+ expect(response.status).to eq(200)
+ expect(response.parsed_body.first.dig("bot_creator", "username")).to eq(creator.username)
+
+ bots = [bot]
+ 4.times do |index|
+ additional_bot = Fabricate(:user, id: -1301 - index, username: "attributed_bot_#{index}")
+ additional_creator = Fabricate(:admin)
+ StaffActionLogger.new(additional_creator).log_bot_creation(additional_bot)
+ bots << additional_bot
+ end
+
+ queries_for_many =
+ track_sql_queries do
+ get "/admin/users/list/bots.json", params: { filter: "attributed_bot" }
+ end
+
+ expect(response.status).to eq(200)
+ expect(response.parsed_body.map { |user| user["id"] }).to match_array(bots.map(&:id))
+ expect(response.parsed_body).to all(include("bot_creator" => a_hash_including("username")))
+ expect(creator_lookup_queries(queries_for_one).size).to eq(1)
+ expect(creator_lookup_queries(queries_for_many).size).to eq(1)
+ expect(queries_for_many.count { |sql| sql.match?(/FROM\s+"?users"?\b/i) }).to eq(
+ queries_for_one.count { |sql| sql.match?(/FROM\s+"?users"?\b/i) },
+ )
+ end
+ end
+end
diff --git a/spec/requests/admin/bots_controller_spec.rb b/spec/requests/admin/bots_controller_spec.rb
new file mode 100644
index 00000000000..9cad46f65d1
--- /dev/null
+++ b/spec/requests/admin/bots_controller_spec.rb
@@ -0,0 +1,538 @@
+# frozen_string_literal: true
+
+RSpec.describe Admin::UsersController do
+ fab!(:admin)
+ fab!(:moderator)
+ fab!(:user)
+
+ describe "#new_bot" do
+ it "serves a directly loaded HTML form for admins" do
+ sign_in(admin)
+
+ get "/admin/users/bots/new"
+
+ expect(response.status).to eq(200)
+ expect(response.media_type).to eq("text/html")
+ end
+
+ it "returns the site's bot form defaults as JSON for admins" do
+ sign_in(admin)
+ SiteSetting.default_trust_level = 2
+ SiteSetting.full_name_requirement = "optional_at_signup"
+
+ get "/admin/users/bots/new.json"
+
+ expect(response.status).to eq(200)
+ expect(response.parsed_body).to eq("default_trust_level" => 2, "name_required" => false)
+ end
+
+ it "reports when the site's full-name policy requires a name" do
+ sign_in(admin)
+ SiteSetting.full_name_requirement = "required_at_signup"
+
+ get "/admin/users/bots/new.json"
+
+ expect(response.status).to eq(200)
+ expect(response.parsed_body["name_required"]).to eq(true)
+ end
+
+ it "rejects anonymous requests for JSON metadata" do
+ get "/admin/users/bots/new.json"
+
+ expect(response.status).to be_in([403, 404])
+ expect(response.parsed_body).not_to have_key("default_trust_level")
+ end
+
+ it "rejects regular users and moderators requesting JSON metadata" do
+ [user, moderator].each do |actor|
+ sign_in(actor)
+
+ get "/admin/users/bots/new.json"
+
+ expect(response.status).to be_in([403, 404])
+ expect(response.parsed_body).not_to have_key("default_trust_level")
+ end
+ end
+
+ it "rejects anonymous visitors" do
+ get "/admin/users/bots/new"
+
+ expect(response.status).to be_in([403, 404])
+ end
+
+ it "rejects regular users" do
+ sign_in(user)
+
+ get "/admin/users/bots/new"
+
+ expect(response.status).to be_in([403, 404])
+ end
+
+ it "rejects moderators" do
+ sign_in(moderator)
+
+ get "/admin/users/bots/new"
+
+ expect(response.status).to be_in([403, 404])
+ end
+ end
+
+ describe "#bot_username_suggestion" do
+ it "suggests an available username from the name for admins" do
+ Fabricate(:user, username: "release_helper")
+ sign_in(admin)
+
+ get "/admin/users/bots/username_suggestion.json", params: { name: "Release helper" }
+
+ expect(response.status).to eq(200)
+ expect(response.parsed_body["username"]).to eq("Release_helper1")
+ end
+
+ it "rejects moderators" do
+ sign_in(Fabricate(:moderator))
+
+ get "/admin/users/bots/username_suggestion.json", params: { name: "Release helper" }
+
+ expect(response.status).to eq(404)
+ end
+ end
+
+ describe "#create_bot" do
+ let(:bot_params) { { name: "Release helper", username: "release_helper", trust_level: 0 } }
+
+ it "rejects anonymous requests without creating a user" do
+ expect do post "/admin/users/bots.json", params: { bot: bot_params } end.not_to change(
+ User,
+ :count,
+ )
+
+ expect(response.status).to be_in([403, 404])
+ end
+
+ it "rejects regular users and moderators without creating a user" do
+ [user, moderator].each do |actor|
+ sign_in(actor)
+
+ expect do post "/admin/users/bots.json", params: { bot: bot_params } end.not_to change(
+ User,
+ :count,
+ )
+
+ expect(response.status).to be_in([403, 404])
+ end
+ end
+
+ context "when signed in as an admin" do
+ before { sign_in(admin) }
+
+ it "returns the created admin-user representation and a Location header" do
+ SiteSetting.default_trust_level = 4
+
+ expect do post "/admin/users/bots.json", params: { bot: bot_params } end.to change(
+ User,
+ :count,
+ ).by(1)
+
+ expect(response.status).to eq(201)
+ bot = User.find_by!(username: bot_params[:username])
+ expect(response.parsed_body.keys).to contain_exactly("user")
+ expect(response.parsed_body["user"]).to include(
+ "id" => bot.id,
+ "username" => bot.username,
+ "name" => bot.name,
+ "trust_level" => 0,
+ "admin" => false,
+ "moderator" => false,
+ "active" => true,
+ )
+ expect(response.headers["Location"]).to end_with("/admin/users/#{bot.id}/#{bot.username}")
+ end
+
+ it "accepts a JSON-encoded bot envelope through the real request parser" do
+ post "/admin/users/bots.json", params: { bot: bot_params }, as: :json
+
+ expect(response.status).to eq(201), response.body
+ bot = User.find_by!(username: bot_params[:username])
+ expect(response.parsed_body.dig("user", "id")).to eq(bot.id)
+ expect(bot).to have_attributes(
+ name: bot_params[:name],
+ username: bot_params[:username],
+ trust_level: bot_params[:trust_level],
+ admin: false,
+ moderator: false,
+ )
+ end
+
+ it "rejects creation on an archived site without persisting an account" do
+ SiteSetting.site_archived = true
+
+ expect do post "/admin/users/bots.json", params: { bot: bot_params } end.not_to change(
+ User,
+ :count,
+ )
+
+ expect(response.status).to eq(503)
+ expect(response.parsed_body["errors"]).to include(I18n.t("site_archived_error"))
+ end
+
+ it "returns normal validation errors for an invalid contract" do
+ expect do
+ post "/admin/users/bots.json", params: { bot: bot_params.merge(username: "") }
+ end.not_to change(User, :count)
+
+ expect(response.status).to eq(422)
+ expect(response.parsed_body["errors"]).to be_a(Array)
+ expect(response.parsed_body["errors"]).to be_present
+ end
+
+ it "rejects an omitted or blank required name without creating a user or audit entry" do
+ SiteSetting.full_name_requirement = "required_at_signup"
+
+ [{}, { name: nil }, { name: "" }, { name: " " }].each do |name_attributes|
+ expect do
+ post "/admin/users/bots.json",
+ params: {
+ bot: bot_params.except(:name).merge(name_attributes),
+ },
+ as: :json
+ end.to not_change(User, :count).and(not_change(UserHistory, :count))
+
+ expect(response.status).to eq(422), "Expected #{name_attributes.inspect} to be rejected"
+ expect(response.parsed_body["errors"]).to be_present
+ end
+ end
+
+ it "allows an omitted or blank name when full names are optional at signup" do
+ SiteSetting.full_name_requirement = "optional_at_signup"
+
+ [{}, { name: nil }, { name: "" }].each_with_index do |name_attributes, index|
+ attributes =
+ bot_params.except(:name).merge(name_attributes, username: "release_helper_#{index}")
+
+ expect do
+ post "/admin/users/bots.json", params: { bot: attributes }, as: :json
+ end.to change(User, :count).by(1)
+
+ expect(response.status).to eq(201), response.body
+ expect(User.find_by!(username: attributes[:username]).name).to be_blank
+ end
+ end
+
+ it "returns normal model errors and creates no duplicate account on retry" do
+ post "/admin/users/bots.json", params: { bot: bot_params }
+ expect(response.status).to eq(201)
+
+ expect do post "/admin/users/bots.json", params: { bot: bot_params } end.not_to change(
+ User,
+ :count,
+ )
+
+ expect(response.status).to eq(422)
+ expect(response.parsed_body["errors"]).to be_a(Array)
+ expect(response.parsed_body["errors"]).to be_present
+ end
+
+ it "accepts explicit admin provisioning when public signup and local login are disabled" do
+ SiteSetting.allow_new_registrations = false
+ SiteSetting.enable_local_logins = false
+ SiteSetting.must_approve_users = true
+ SiteSetting.allowed_email_domains = "company.example"
+
+ post "/admin/users/bots.json", params: { bot: bot_params }
+
+ expect(response.status).to eq(201)
+ expect(User.find_by!(username: bot_params[:username])).to have_attributes(
+ active: true,
+ approved: true,
+ )
+ end
+
+ it "accepts explicit admin provisioning when DiscourseConnect is enforced" do
+ SiteSetting.discourse_connect_url = "https://sso.example.com"
+ SiteSetting.discourse_connect_secret = "a-long-discourse-connect-secret"
+ SiteSetting.enable_discourse_connect = true
+
+ post "/admin/users/bots.json", params: { bot: bot_params }
+
+ expect(response.status).to eq(201)
+ end
+
+ it "logs the creating admin and bot in the staff audit history" do
+ post "/admin/users/bots.json", params: { bot: bot_params }
+
+ expect(response.status).to eq(201)
+ expect(UserHistory.find_by!(action: UserHistory.actions[:create_bot])).to have_attributes(
+ action: UserHistory.actions[:create_bot],
+ acting_user_id: admin.id,
+ target_user_id: response.parsed_body.dig("user", "id"),
+ )
+ end
+
+ it "ignores prohibited bot attributes while creating an unprivileged account" do
+ post "/admin/users/bots.json",
+ params: {
+ bot:
+ bot_params.merge(
+ admin: true,
+ moderator: true,
+ id: -9999,
+ active: false,
+ approved: false,
+ approved_by_id: user.id,
+ email: "[email protected]",
+ password: "a-secret-password",
+ api_key: "a-secret-api-key",
+ custom_fields: {
+ privileged: true,
+ },
+ user_fields: {
+ "1" => "forged",
+ },
+ ),
+ },
+ as: :json
+
+ expect(response.status).to eq(201)
+ bot = User.find(response.parsed_body.dig("user", "id"))
+ expect(bot).to have_attributes(
+ username: bot_params[:username],
+ admin: false,
+ moderator: false,
+ active: true,
+ approved: true,
+ approved_by_id: admin.id,
+ password_hash: nil,
+ )
+ expect(bot.id).not_to eq(-9999)
+ expect(bot.email).to match(/\A[0-9a-f]+@does-not-exist\.invalid\z/)
+ expect(bot.api_keys).to be_empty
+ expect(bot.custom_fields).to be_empty
+ expect(bot.user_fields).to be_blank
+ end
+
+ it "requires a username inside the bot envelope" do
+ expect do
+ post "/admin/users/bots.json",
+ params: {
+ bot: bot_params.except(:username),
+ username: "outside_bot",
+ },
+ as: :json
+ end.to not_change(User, :count).and(not_change(UserHistory, :count))
+
+ expect(response.status).to eq(422)
+ expect(response.parsed_body["errors"]).to be_present
+ end
+
+ it "ignores properties outside the bot envelope" do
+ expect do
+ post "/admin/users/bots.json",
+ params: {
+ bot: bot_params,
+ id: -9999,
+ username: "outside_bot",
+ trust_level: 4,
+ admin: true,
+ moderator: true,
+ active: false,
+ approved: false,
+ email: "[email protected]",
+ password: "a-secret-password",
+ api_key: "a-secret-api-key",
+ unexpected: "value",
+ }
+ end.to change(User, :count).by(1)
+
+ expect(response.status).to eq(201)
+ bot = User.find(response.parsed_body.dig("user", "id"))
+ expect(bot).to have_attributes(
+ username: bot_params[:username],
+ trust_level: bot_params[:trust_level],
+ admin: false,
+ moderator: false,
+ active: true,
+ approved: true,
+ password_hash: nil,
+ )
+ expect(bot.id).not_to eq(-9999)
+ expect(bot.email).to match(/\A[0-9a-f]+@does-not-exist\.invalid\z/)
+ expect(bot.api_keys).to be_empty
+ end
+
+ it "ignores a root user object in a JSON request" do
+ expect do
+ post "/admin/users/bots.json",
+ params: {
+ bot: bot_params,
+ user: {
+ username: "outside_bot",
+ trust_level: 4,
+ admin: true,
+ moderator: true,
+ email: "[email protected]",
+ password: "a-secret-password",
+ api_key: "a-secret-api-key",
+ },
+ },
+ as: :json
+ end.to change(User, :count).by(1)
+
+ expect(response.status).to eq(201)
+ bot = User.find(response.parsed_body.dig("user", "id"))
+ expect(bot).to have_attributes(
+ username: bot_params[:username],
+ trust_level: bot_params[:trust_level],
+ admin: false,
+ moderator: false,
+ password_hash: nil,
+ )
+ expect(bot.email).to match(/\A[0-9a-f]+@does-not-exist\.invalid\z/)
+ expect(bot.api_keys).to be_empty
+ end
+
+ it "requires an object-shaped bot envelope" do
+ [nil, "release_helper", [bot_params]].each do |value|
+ expect do
+ post "/admin/users/bots.json", params: { bot: value }, as: :json
+ end.not_to change(User, :count)
+
+ expect(response.status).to eq(400)
+ end
+ end
+
+ it "rejects missing and out-of-range trust levels without creating accounts" do
+ [nil, -1, 5, ""].each do |value|
+ expect do
+ post "/admin/users/bots.json",
+ params: {
+ bot: bot_params.merge(trust_level: value),
+ },
+ as: :json
+ end.not_to change(User, :count)
+
+ expect(response.status).to eq(422),
+ "Expected trust_level=#{value.inspect} to be rejected: #{response.body}"
+ expect(response.parsed_body["errors"]).to be_present
+ end
+ end
+
+ it "requires the normal CSRF token for creation" do
+ ActionController::Base.allow_forgery_protection = true
+
+ expect do post "/admin/users/bots.json", params: { bot: bot_params } end.not_to change(
+ User,
+ :count,
+ )
+
+ expect(response.status).to eq(403)
+ ensure
+ ActionController::Base.allow_forgery_protection = false
+ end
+
+ it "continues to reject bot targets in existing privilege-grant endpoints" do
+ post "/admin/users/bots.json", params: { bot: bot_params }
+ expect(response.status).to eq(201)
+ bot = User.find(response.parsed_body.dig("user", "id"))
+
+ %w[grant_admin grant_moderation].each do |action|
+ put "/admin/users/#{bot.id}/#{action}.json"
+
+ expect(response.status).to eq(403)
+ expect(bot.reload).to have_attributes(admin: false, moderator: false)
+ end
+ expect(AdminConfirmation.exists_for?(bot.id)).to eq(false)
+ end
+
+ context "with an API key" do
+ let(:key_params) do
+ {
+ description: "Release key",
+ scope_mode: "granular",
+ scopes: [{ scope_id: "topics:write", topic_id: "1" }],
+ }
+ end
+
+ it "creates a key for the bot and returns it once" do
+ expect do
+ post "/admin/users/bots.json", params: { bot: bot_params, key: key_params }, as: :json
+ end.to change(User, :count).by(1).and change(ApiKey, :count).by(1)
+
+ expect(response.status).to eq(201)
+ bot = User.find(response.parsed_body.dig("user", "id"))
+ api_key = ApiKey.last
+ expect(api_key).to have_attributes(user: bot, created_by: admin, scope_mode: "granular")
+ expect(response.parsed_body.dig("key", "key")).to be_present
+ expect(ApiKey.with_key(response.parsed_body.dig("key", "key")).first).to eq(api_key)
+ end
+
+ it "returns no key when none was requested" do
+ post "/admin/users/bots.json", params: { bot: bot_params }
+
+ expect(response.status).to eq(201)
+ expect(response.parsed_body).not_to have_key("key")
+ end
+
+ it "rejects an unknown scope without creating the bot" do
+ key_params[:scopes] = [{ scope_id: "topics:explode" }]
+
+ expect do
+ post "/admin/users/bots.json", params: { bot: bot_params, key: key_params }
+ end.to not_change(User, :count).and not_change(ApiKey, :count)
+ expect(response.status).to eq(400)
+ end
+
+ it "rejects malformed scopes without creating the bot" do
+ key_params[:scopes] = ["topics:write"]
+
+ expect do
+ post "/admin/users/bots.json", params: { bot: bot_params, key: key_params }, as: :json
+ end.to not_change(User, :count).and not_change(ApiKey, :count)
+ expect(response.status).to eq(400)
+ end
+
+ it "returns key validation errors without creating the bot" do
+ key_params[:scopes] = []
+
+ expect do
+ post "/admin/users/bots.json", params: { bot: bot_params, key: key_params }, as: :json
+ end.to not_change(User, :count).and not_change(ApiKey, :count)
+ expect(response.status).to eq(422)
+ end
+
+ it "requires an object-shaped key" do
+ expect do
+ post "/admin/users/bots.json", params: { bot: bot_params, key: "a-key" }
+ end.not_to change(User, :count)
+ expect(response.status).to eq(400)
+ end
+ end
+ end
+
+ context "with rate limiting enabled for the admin" do
+ before do
+ sign_in(admin)
+ RateLimiter.enable
+ end
+
+ after { RateLimiter.disable }
+
+ it "allows ten attempts per minute, blocks the eleventh, and allows creation after reset" do
+ freeze_time
+ 10.times do
+ post "/admin/users/bots.json", params: { bot: bot_params.merge(username: "") }
+ expect(response.status).to eq(422)
+ end
+
+ expect do post "/admin/users/bots.json", params: { bot: bot_params } end.not_to change(
+ User,
+ :count,
+ )
+ expect(response.status).to eq(429)
+
+ freeze_time 61.seconds.from_now
+ post "/admin/users/bots.json", params: { bot: bot_params }
+ expect(response.status).to eq(201)
+ end
+ end
+ end
+end
diff --git a/spec/requests/admin/staff_action_logs_controller_spec.rb b/spec/requests/admin/staff_action_logs_controller_spec.rb
index c08b2eaf62e..34dc5530dfb 100644
--- a/spec/requests/admin/staff_action_logs_controller_spec.rb
+++ b/spec/requests/admin/staff_action_logs_controller_spec.rb
@@ -94,6 +94,26 @@ RSpec.describe Admin::StaffActionLogsController do
include_examples "staff action logs accessible"
+ it "filters bot creation as a native staff action" do
+ bot = Fabricate(:user, id: -1234)
+ creation = StaffActionLogger.new(admin).log_bot_creation(bot)
+ StaffActionLogger.new(admin).log_site_setting_change("title", "old", "new")
+
+ get "/admin/logs/staff_action_logs.json",
+ params: {
+ action_id: UserHistory.actions[:create_bot],
+ }
+
+ expect(response.status).to eq(200)
+ expect(response.parsed_body["staff_action_logs"]).to contain_exactly(
+ include("id" => creation.id, "action_name" => "create_bot"),
+ )
+ expect(response.parsed_body["extras"]["user_history_actions"]).to include(
+ "id" => "create_bot",
+ "action_id" => UserHistory.actions[:create_bot],
+ )
+ end
+
it "generates logs with pages" do
4.times do |idx|
StaffActionLogger.new(Discourse.system_user).log_site_setting_change(
diff --git a/spec/services/staff_action_logger_spec.rb b/spec/services/staff_action_logger_spec.rb
index 8f34b3a76ba..424bd49e2df 100644
--- a/spec/services/staff_action_logger_spec.rb
+++ b/spec/services/staff_action_logger_spec.rb
@@ -47,6 +47,22 @@ RSpec.describe StaffActionLogger do
end
end
+ describe "#log_bot_creation" do
+ fab!(:bot) { Fabricate(:user, id: -1234, trust_level: 2) }
+
+ it "records the actor, bot target, username, and trust level" do
+ expect { logger.log_bot_creation(bot) }.to change(UserHistory, :count).by(1)
+
+ expect(UserHistory.last).to have_attributes(
+ action: UserHistory.actions[:create_bot],
+ acting_user_id: admin.id,
+ target_user_id: bot.id,
+ subject: bot.username,
+ details: "trust_level: #{bot.trust_level}",
+ )
+ end
+ end
+
describe "#log_assume_access_control_ownership" do
fab!(:deleted_user, :user)
fab!(:owner_acl) do
diff --git a/spec/services/user/create_bot_spec.rb b/spec/services/user/create_bot_spec.rb
new file mode 100644
index 00000000000..91954fd41a1
--- /dev/null
+++ b/spec/services/user/create_bot_spec.rb
@@ -0,0 +1,442 @@
+# frozen_string_literal: true
+
+RSpec.describe User::CreateBot do
+ describe described_class::Contract, type: :model do
+ it { is_expected.to validate_presence_of(:username) }
+ it { is_expected.to allow_values(*(0..4), *%w[0 1 2 3 4]).for(:trust_level) }
+
+ it { is_expected.not_to allow_values(nil, -1, 5, "").for(:trust_level) }
+
+ it "requires a name when full names are required at signup" do
+ SiteSetting.full_name_requirement = "required_at_signup"
+
+ [{}, { name: nil }, { name: "" }, { name: " " }].each do |name_attributes|
+ contract = described_class.new(username: "release_helper", **name_attributes)
+
+ expect(contract).not_to be_valid
+ expect(contract.errors.of_kind?(:name, :blank)).to eq(true)
+ end
+ end
+
+ it "allows an omitted or blank name when full names are optional at signup" do
+ SiteSetting.full_name_requirement = "optional_at_signup"
+
+ names = [{}, { name: nil }, { name: "" }, { name: " " }, { name: "Release helper" }]
+ names.each do |name_attributes|
+ contract = described_class.new(username: "release_helper", **name_attributes)
+
+ expect(contract).to be_valid
+ end
+ end
+
+ it "defaults to the site's current trust level" do
+ SiteSetting.default_trust_level = 2
+
+ contract = described_class.new(username: "release_helper")
+
+ expect(contract).to be_valid
+ expect(contract.trust_level).to eq(2)
+ end
+
+ context "with an API key" do
+ subject(:contract) do
+ described_class.new(username: "release_helper", api_key: api_key_attributes)
+ end
+
+ let(:api_key_attributes) { { description: "Release key", scope_mode: "global" } }
+
+ it { is_expected.to be_valid }
+
+ it "allows an omitted description" do
+ api_key_attributes.delete(:description)
+
+ expect(contract).to be_valid
+ end
+
+ it "limits the description length" do
+ api_key_attributes[:description] = "x" * 256
+
+ expect(contract).not_to be_valid
+ expect(contract.errors).to include(:"api_key.description")
+ end
+
+ it "requires a known scope mode" do
+ api_key_attributes[:scope_mode] = "everything"
+
+ expect(contract).not_to be_valid
+ expect(contract.errors).to include(:"api_key.scope_mode")
+ end
+ end
+ end
+
+ describe ".call" do
+ subject(:result) { described_class.call(params:, **dependencies) }
+
+ fab!(:actor, :admin)
+
+ let(:params) { { name: "Release helper", username: "release_helper", trust_level: 2 } }
+ let(:dependencies) { { guardian: actor.guardian } }
+
+ context "when the contract is invalid" do
+ let(:params) { { username: "" } }
+
+ it "rejects invalid input without reserving a bot ID" do
+ expect { result }.not_to change { PluginStore.get("core", BotUser::FLOOR_KEY) }
+ expect(result).to fail_a_contract
+ end
+ end
+
+ context "when the actor is anonymous" do
+ let(:dependencies) { { guardian: Guardian.new } }
+
+ it { is_expected.to fail_a_policy(:can_create_bot) }
+ end
+
+ context "when the actor is a regular user" do
+ fab!(:actor, :user)
+
+ it "rejects creation without reserving a bot ID" do
+ expect { result }.not_to change { PluginStore.get("core", BotUser::FLOOR_KEY) }
+ expect(result).to fail_a_policy(:can_create_bot)
+ end
+ end
+
+ context "when the actor is a moderator" do
+ fab!(:actor, :moderator)
+
+ it { is_expected.to fail_a_policy(:can_create_bot) }
+ end
+
+ context "when the site is archived" do
+ before { SiteSetting.site_archived = true }
+
+ it "rejects creation without persisting a user" do
+ expect { result }.not_to change(User, :count)
+ expect(result).to fail_a_policy(:site_not_archived)
+ end
+ end
+
+ context "when everything is valid" do
+ it { is_expected.to run_successfully }
+
+ it "creates an active, approved, non-staff bot without credentials" do
+ expect { result }.to change(User, :count).by(1)
+
+ bot = result.user.reload
+ expect(bot.id).to be < 0
+ expect(bot).to have_attributes(
+ username: params[:username],
+ name: params[:name],
+ trust_level: params[:trust_level],
+ admin: false,
+ moderator: false,
+ active: true,
+ approved: true,
+ approved_by_id: actor.id,
+ password_hash: nil,
+ )
+ expect(bot.approved_at).to be_present
+ expect(bot.email).to match(/\A[0-9a-f]+@does-not-exist\.invalid\z/)
+ expect(bot.user_auth_tokens).to be_empty
+ expect(bot.api_keys).to be_empty
+ expect(bot.user_api_keys).to be_empty
+ end
+
+ it "initializes normal user associations and automatic trust-level groups" do
+ User.set_callback(:create, :after, :ensure_in_trust_level_group)
+ bot = result.user.reload
+
+ expect(bot.user_stat).to be_persisted
+ expect(bot.user_option).to be_persisted
+ expect(bot.user_profile).to be_persisted
+ expect(bot.groups.where(automatic: true).pluck(:name)).to contain_exactly(
+ "trust_level_0",
+ "trust_level_1",
+ "trust_level_2",
+ )
+ ensure
+ User.skip_callback(:create, :after, :ensure_in_trust_level_group)
+ end
+
+ it "logs the actor and target as a bot creation staff action" do
+ expect { result }.to change {
+ UserHistory.where(action: UserHistory.actions[:create_bot]).count
+ }.by(1)
+
+ expect(UserHistory.last).to have_attributes(
+ action: UserHistory.actions[:create_bot],
+ acting_user_id: actor.id,
+ target_user_id: result.user.id,
+ subject: result.user.username,
+ )
+ end
+
+ it "generates distinct internal email addresses" do
+ second_result =
+ described_class.call(params: params.merge(username: "another_helper"), **dependencies)
+
+ expect(second_result).to run_successfully
+ expect(result.user.email).not_to eq(second_result.user.email)
+ end
+
+ it "queues no signup, invitation, or welcome messages" do
+ SiteSetting.send_welcome_message = true
+ SiteSetting.send_tl1_welcome_message = true
+ SiteSetting.send_tl2_promotion_message = true
+
+ expect { result }.to not_change { Jobs::CriticalUserEmail.jobs.size }
+ .and(not_change { Jobs::UserEmail.jobs.size })
+ .and(not_change { Jobs::InviteEmail.jobs.size })
+ .and(not_change { Jobs::InvitePasswordInstructionsEmail.jobs.size })
+ .and(not_change { Jobs::SendSystemMessage.jobs.size })
+ end
+ end
+
+ context "when an API key is requested" do
+ let(:params) do
+ {
+ username: "release_helper",
+ trust_level: 2,
+ api_key: {
+ description: "Release key",
+ scope_mode: "granular",
+ scopes: [{ scope_id: "topics:write", topic_id: "1,2" }],
+ },
+ }
+ end
+
+ context "with an unknown scope" do
+ before { params[:api_key][:scopes] = [{ scope_id: "topics:explode" }] }
+
+ it "creates neither the bot nor the key" do
+ expect { result }.to not_change(User, :count).and(not_change(ApiKey, :count)).and(
+ not_change(UserHistory, :count),
+ )
+ expect(result).to fail_to_find_a_model(:api_key)
+ end
+ end
+
+ context "with an invalid key" do
+ before { params[:api_key][:scopes] = [] }
+
+ it "creates neither the bot nor the key" do
+ expect { result }.to not_change(User, :count).and(not_change(ApiKey, :count)).and(
+ not_change(UserHistory, :count),
+ )
+ expect(result).to fail_with_an_invalid_model(:api_key)
+ end
+ end
+
+ context "when everything is valid" do
+ it { is_expected.to run_successfully }
+
+ it "creates a key for the bot with the requested scopes" do
+ expect(result.api_key).to have_attributes(
+ user: result.user,
+ created_by: actor,
+ description: "Release key",
+ scope_mode: "granular",
+ )
+ expect(result.api_key).to be_key_available
+ expect(result.api_key.api_key_scopes.map(&:attributes)).to contain_exactly(
+ include(
+ "resource" => "topics",
+ "action" => "write",
+ "allowed_parameters" => {
+ "topic_id" => %w[1 2],
+ },
+ ),
+ )
+ end
+
+ context "without a description" do
+ before { params[:api_key].delete(:description) }
+
+ it "describes the key with the bot's username" do
+ expect(result.api_key.description).to eq("release_helper")
+ end
+ end
+
+ it "logs the key creation" do
+ expect { result }.to change {
+ UserHistory.where(action: UserHistory.actions[:api_key_create]).count
+ }.by(1)
+
+ expect(UserHistory.last).to have_attributes(
+ acting_user_id: actor.id,
+ subject: result.api_key.truncated_key,
+ )
+ end
+ end
+ end
+
+ it "honors trust level zero when the site default is four" do
+ SiteSetting.default_trust_level = 4
+ params[:trust_level] = 0
+
+ expect(result).to run_successfully
+ expect(result.user.trust_level).to eq(0)
+ end
+
+ it "uses the site default when the trust level is omitted" do
+ SiteSetting.default_trust_level = 1
+ params.delete(:trust_level)
+
+ expect(result).to run_successfully
+ expect(result.user.trust_level).to eq(1)
+ end
+
+ it "skips signup email policy only for the explicitly created bot" do
+ SiteSetting.allowed_email_domains = "company.example"
+ ordinary_user = User.new(username: "ordinary_user", email: "[email protected]")
+
+ expect(result).to run_successfully
+ expect(ordinary_user).not_to be_valid
+ expect(ordinary_user.errors[:primary_email]).to include(I18n.t("user.email.not_allowed"))
+ end
+
+ {
+ "invalid characters" => "invalid!username",
+ "a reserved username" => "reserved_helper",
+ "an existing route" => "admin",
+ "a username shorter than the site minimum" => "bot",
+ "a username longer than the site maximum" => "x" * 21,
+ }.each do |description, username|
+ it "rejects #{description} without creating a user or audit entry" do
+ SiteSetting.reserved_usernames = "reserved_helper"
+ SiteSetting.min_username_length = 4
+ SiteSetting.max_username_length = 20
+ params[:username] = username
+
+ expect { result }.to not_change(User, :count).and(not_change(UserHistory, :count))
+ expect(result).to fail_with_an_invalid_model(:user)
+ expect(result.user.errors[:username]).to be_present
+ end
+ end
+
+ it "rejects a case-insensitive duplicate username without creating a user or audit entry" do
+ Fabricate(:user, username: params[:username].upcase)
+
+ expect { result }.to not_change(User, :count).and(not_change(UserHistory, :count))
+ expect(result).to fail_with_an_invalid_model(:user)
+ expect(result.user.errors[:username]).to include(I18n.t("user.username.unique"))
+ end
+
+ it "rejects usernames already used by a group" do
+ Fabricate(:group, name: params[:username])
+
+ expect { result }.not_to change(User, :count)
+ expect(result).to fail_with_an_invalid_model(:user)
+ end
+
+ it "enforces the existing full-name length limit" do
+ params[:name] = "x" * 256
+
+ expect { result }.not_to change(User, :count)
+ expect(result).to fail_with_an_invalid_model(:user)
+ expect(result.user.errors[:name]).to be_present
+ end
+
+ it "enforces the site's full-name requirement in the contract" do
+ SiteSetting.full_name_requirement = "required_at_signup"
+ params[:name] = ""
+
+ expect { result }.to not_change(User, :count).and(not_change(UserHistory, :count))
+ expect(result).to fail_a_contract
+ end
+ end
+end
+
+RSpec.describe User::CreateBot, ".call" do
+ self.use_transactional_tests = false
+
+ let(:actor) { Fabricate(:admin) }
+ let(:usernames) do
+ token = SecureRandom.hex(3)
+ ["race_bot_#{token}_a", "race_bot_#{token}_b"]
+ end
+
+ before do
+ @saved_floors = PluginStoreRow.where(key: BotUser::FLOOR_KEY).map(&:attributes)
+ PluginStoreRow.where(key: BotUser::FLOOR_KEY).delete_all
+ end
+
+ after do
+ UserHistory.where(acting_user_id: actor.id).delete_all
+ User.where(username: usernames, approved_by_id: actor.id).find_each(&:destroy!)
+ actor.destroy!
+ PluginStoreRow.where(key: BotUser::FLOOR_KEY).delete_all
+ PluginStoreRow.insert_all!(@saved_floors) if @saved_floors.present?
+ end
+
+ [nil, -5000].each do |floor|
+ context "with concurrent creation and #{floor ? "an existing" : "no"} allocation floor" do
+ it "creates distinct bots while another creation transaction is still open" do
+ PluginStore.set("core", BotUser::FLOOR_KEY, floor) if floor
+ actor_id = actor.id
+ first_username, second_username = usernames
+ first_started = Queue.new
+ release_first = Queue.new
+ first_result = Queue.new
+ second_result = Queue.new
+ threads = []
+ pool = ActiveRecord::Base.connection_pool
+ service_class = described_class
+ pause_first =
+ lambda do |user|
+ if user.username == first_username
+ first_started << true
+ unless release_first.pop(timeout: 10)
+ raise "Timed out waiting to finish the first bot"
+ end
+ end
+ end
+ create_bot =
+ lambda do |username, result_queue|
+ pool.with_connection do |connection|
+ connection.execute("SET lock_timeout = '2s'")
+ result_queue << service_class.call(
+ params: {
+ username: username,
+ },
+ guardian: User.find(actor_id).guardian,
+ )
+ ensure
+ connection.execute("SET lock_timeout = DEFAULT")
+ end
+ rescue => exception
+ result_queue << exception
+ end
+
+ User.set_callback(:create, :before, pause_first)
+ pool.release_connection
+
+ begin
+ threads << Thread.new { create_bot.call(first_username, first_result) }
+ expect(first_started.pop(timeout: 5)).to eq(true)
+ threads << Thread.new { create_bot.call(second_username, second_result) }
+ second_outcome = second_result.pop(timeout: 5)
+ expect(second_outcome).to run_successfully
+ ensure
+ release_first << true
+ threads.each do |thread|
+ thread.kill unless thread.join(5)
+ thread.join
+ end
+ User.skip_callback(:create, :before, pause_first)
+ end
+
+ first_outcome = first_result.pop(timeout: 1)
+ expect(first_outcome).to run_successfully
+ expect(second_outcome.user.id).to be < first_outcome.user.id
+ expect(User.where(username: usernames).pluck(:username)).to contain_exactly(*usernames)
+ expect(
+ UserHistory.where(
+ acting_user_id: actor_id,
+ action: UserHistory.actions[:create_bot],
+ ).count,
+ ).to eq(2)
+ end
+ end
+ end
+end
diff --git a/spec/system/admin_users_list_spec.rb b/spec/system/admin_users_list_spec.rb
index d568cb9bc6e..cd4f591298b 100644
--- a/spec/system/admin_users_list_spec.rb
+++ b/spec/system/admin_users_list_spec.rb
@@ -280,12 +280,6 @@ describe "Admin Users Page" do
expect(admin_users_page).to have_emails
end
- it "redirects to groups page" do
- admin_users_page.visit
- admin_users_page.click_tab("groups")
- expect(page).to have_current_path("/admin/groups")
- end
-
it "redirect to invites page" do
admin_users_page.visit
admin_users_page.click_tab("settings")