A platform for community discussion. Free, open, simple.
FEATURE: Add user mentions to review queue notes (#44383)
Gabriel Grubbab1a0af17849a
diff --git a/app/controllers/notifications_controller.rb b/app/controllers/notifications_controller.rbindex 2c9f691d549..7f219ac1233 100644--- a/app/controllers/notifications_controller.rb+++ b/app/controllers/notifications_controller.rb@@ -57,6 +57,11 @@ class NotificationsController < ApplicationControllernotifications =Notification.filter_inaccessible_topic_notifications(current_user.guardian, notifications)+ notifications =+ Notification.filter_inaccessible_reviewable_notifications(+ current_user.guardian,+ notifications,+ )notifications = Notification.filter_disabled_badge_notifications(notifications)notifications = Notification.populate_acting_user(notifications)@@ -89,6 +94,11 @@ class NotificationsController < ApplicationControllernotifications = notifications.offset(offset).limit(limit)notifications =Notification.filter_inaccessible_topic_notifications(current_user.guardian, notifications)+ notifications =+ Notification.filter_inaccessible_reviewable_notifications(+ current_user.guardian,+ notifications,+ )notifications = Notification.filter_disabled_badge_notifications(notifications)notifications = Notification.populate_acting_user(notifications)diff --git a/app/controllers/reviewable_notes_controller.rb b/app/controllers/reviewable_notes_controller.rbindex 7bd21f463df..553ee6ee4d7 100644--- a/app/controllers/reviewable_notes_controller.rb+++ b/app/controllers/reviewable_notes_controller.rb@@ -11,7 +11,11 @@ class ReviewableNotesController < ApplicationControllerif note.save# Reload to ensure associations are loadednote.reload- render json: ReviewableNoteSerializer.new(note, scope: guardian, root: false)+ render json:+ ReviewableNoteSerializer+ .new(note, scope: guardian, root: false)+ .as_json+ .merge(unnotified_usernames: note.unnotified_usernames)elserender json: { errors: note.errors.full_messages }, status: :unprocessable_entityenddiff --git a/app/models/notification.rb b/app/models/notification.rbindex e21b8828866..506120ff725 100644--- a/app/models/notification.rb+++ b/app/models/notification.rb@@ -252,6 +252,31 @@ class Notification < ActiveRecord::Basenotifications.select { |n| n.topic_id.blank? || accessible_topic_ids.include?(n.topic_id) }end+ def self.filter_inaccessible_reviewable_notifications(guardian, notifications)+ reviewable_ids =+ notifications+ .select(&:reviewable_mention?)+ .map { |notification| notification.data_hash[:reviewable_id].to_i }+ .uniq+ return notifications if reviewable_ids.empty?++ accessible_ids =+ if guardian.can_see_review_queue?+ Reviewable+ .viewable_by(guardian.user, preload: false)+ .where(id: reviewable_ids)+ .pluck(:id)+ .to_set+ else+ Set.new+ end++ notifications.reject do |notification|+ notification.reviewable_mention? &&+ !accessible_ids.include?(notification.data_hash[:reviewable_id].to_i)+ end+ end+def self.filter_disabled_badge_notifications(notifications)return notifications if notifications.blank?@@ -287,7 +312,13 @@ class Notification < ActiveRecord::Baseendend+ def reviewable_mention?+ notification_type == Notification.types[:mentioned] && data_hash[:reviewable_id].present?+ end+def url+ return "#{Discourse.base_path}/review/#{data_hash[:reviewable_id]}" if reviewable_mention?+return if topic.blank?return consolidated_nested_replied_url if consolidated_nested_replied?diff --git a/app/models/reviewable.rb b/app/models/reviewable.rbindex 394dc752d49..73d14d6f3ec 100644--- a/app/models/reviewable.rb+++ b/app/models/reviewable.rb@@ -150,6 +150,14 @@ class Reviewable < ActiveRecord::Baseself.type_source = Reviewable.source_for(type)end+ def title_for_notification(user)+ topic&.title.presence || payload&.dig("title").presence ||+ I18n.t(+ topic_id ? "js.review.topics.deleted" : "js.review.title",+ locale: user.effective_locale,+ )+ end+def created_new!self.created_new = trueself.topic = target.topic if topic.blank? && target.is_a?(Post)diff --git a/app/models/reviewable_note.rb b/app/models/reviewable_note.rbindex faa168f3e1b..1d8dc1a550e 100644--- a/app/models/reviewable_note.rb+++ b/app/models/reviewable_note.rb@@ -9,8 +9,70 @@ class ReviewableNote < ActiveRecord::Basevalidates :content, presence: true, length: { minimum: 1, maximum: MAX_CONTENT_LENGTH }validates :reviewable_id, presence: truevalidates :user_id, presence: true+ validate :mention_limitscope :ordered, -> { order(:created_at) }++ attr_reader :unnotified_usernames++ after_create :notify_mentions++ private++ def mentioned_usernames+ if @analyzed_content != content+ @analyzed_content = content.dup+ @mentioned_usernames = PlaintextMentions.new(content).usernames+ end+ @mentioned_usernames || []+ end++ def mention_limit+ return if !SiteSetting.enable_mentions || user.nil? || user.staff? || content.blank?++ trusted = user.has_trust_level?(TrustLevel[1])+ limit = trusted ? SiteSetting.max_mentions_per_post : SiteSetting.newuser_max_mentions_per_post+ return if mentioned_usernames.size <= limit++ key = limit.zero? ? "no_mentions_allowed" : "too_many_mentions"+ key += "_newuser" if !trusted+ errors.add(:base, I18n.t(key, count: limit))+ end++ def notify_mentions+ @unnotified_usernames = []+ return if !SiteSetting.enable_mentions++ usernames = mentioned_usernames+ return if usernames.empty?++ mentioned_users =+ User.where(username_lower: usernames, staged: false).where.not(id: user_id).to_a+ screener = UserCommScreener.new(acting_user: user, target_user_ids: mentioned_users.map(&:id))++ mentioned_users.each do |mentioned_user|+ next if mentioned_user.bot?++ if !mentioned_user.guardian.can_see_review_queue? ||+ !Reviewable.viewable_by(mentioned_user, preload: false).exists?(id: reviewable_id)+ @unnotified_usernames << mentioned_user.username+ next+ end++ next if screener.ignoring_or_muting_actor?(mentioned_user.id)++ mentioned_user.notifications.create!(+ notification_type: Notification.types[:mentioned],+ data: {+ reviewable_id: reviewable_id,+ reviewable_note_id: id,+ topic_title: reviewable.title_for_notification(mentioned_user),+ display_username: user.username,+ }.to_json,+ skip_send_email: true,+ )+ end+ endend# == Schema Informationdiff --git a/app/models/reviewable_user.rb b/app/models/reviewable_user.rbindex 8cb8e9a8e8f..1bfcc3b3390 100644--- a/app/models/reviewable_user.rb+++ b/app/models/reviewable_user.rb@@ -9,6 +9,11 @@ class ReviewableUser < Reviewableafter_create :retain_avatar_snapshot+ def title_for_notification(user)+ target&.username || payload&.dig("username") ||+ I18n.t("js.review.user_label", locale: user.effective_locale)+ end+def self.payload_for(user)profile = user.user_profileavatar = user.uploaded_avatardiff --git a/app/serializers/reviewable_note_serializer.rb b/app/serializers/reviewable_note_serializer.rbindex 54a5858b1a3..5ec64ad6211 100644--- a/app/serializers/reviewable_note_serializer.rb+++ b/app/serializers/reviewable_note_serializer.rb@@ -1,7 +1,13 @@# frozen_string_literal: trueclass ReviewableNoteSerializer < ApplicationSerializer- attributes :id, :content, :created_at, :updated_at+ attributes :id, :content, :cooked, :created_at, :updated_athas_one :user, serializer: BasicUserSerializer, embed: :objects++ def cooked+ PlaintextMentions.new(object.content).render(+ known_usernames: @options[:reviewable_note_mention_usernames],+ )+ endenddiff --git a/app/serializers/reviewable_serializer.rb b/app/serializers/reviewable_serializer.rbindex 6c17aa84d57..d79a70619ac 100644--- a/app/serializers/reviewable_serializer.rb+++ b/app/serializers/reviewable_serializer.rb@@ -41,6 +41,17 @@ class ReviewableSerializer < ApplicationSerializer# Used to keep track of our payload attributesclass_attribute :_payload_for_serialization+ def initialize(object, options = {})+ if SiteSetting.enable_mentions+ options =+ options.merge(+ reviewable_note_mention_usernames:+ PlaintextMentions.known_usernames(object.reviewable_notes.map(&:content)),+ )+ end+ super(object, options)+ end+def bundled_actionsargs = {}args[:claimed_by] = claimed_by if @options[:claimed_topics]diff --git a/config/locales/client.en.yml b/config/locales/client.en.ymlindex ad20db2e7c5..d420489d0ef 100644--- a/config/locales/client.en.yml+++ b/config/locales/client.en.yml@@ -1258,6 +1258,9 @@ en:chars_remaining: "%{count} characters remaining"delete_note: "Delete this note"delete: "Delete"+ mentions_not_notified:+ one: "%{usernames} will not be notified because they do not have access to this reviewable."+ other: "%{usernames} will not be notified because they do not have access to this reviewable."topic_label: "Topic"queued_user: "Queued user"posted_in: "Posted in"diff --git a/frontend/discourse/app/components/reviewable/note-form.gjs b/frontend/discourse/app/components/reviewable/note-form.gjsindex 1facba1d94d..69f2cb33852 100644--- a/frontend/discourse/app/components/reviewable/note-form.gjs+++ b/frontend/discourse/app/components/reviewable/note-form.gjs@@ -1,14 +1,21 @@import Component from "@glimmer/component";+import { destroy } from "@ember/destroyable";import { hash } from "@ember/helper";import { action } from "@ember/object";+import { getOwner } from "@ember/owner";import { service } from "@ember/service";import { isEmpty } from "@ember/utils";+import { modifier } from "ember-modifier";import Form from "discourse/components/form";import PluginOutlet from "discourse/components/plugin-outlet";+import UserAutocompleteResults from "discourse/components/user-autocomplete-results";import lazyHash from "discourse/helpers/lazy-hash";import { ajax } from "discourse/lib/ajax";import { popupAjaxError } from "discourse/lib/ajax-error";import { bind } from "discourse/lib/decorators";+import { TextareaAutocompleteHandler } from "discourse/lib/textarea-text-manipulation";+import userSearch, { validateSearchResult } from "discourse/lib/user-search";+import dAutocomplete from "discourse/ui-kit/modifiers/d-autocomplete";import { i18n } from "discourse-i18n";/**@@ -20,7 +27,37 @@ import { i18n } from "discourse-i18n";* @param {Function} [onNoteCreated] - Callback function called when a note is successfully created.*/export default class ReviewableNoteForm extends Component {+ @service a11y;@service appEvents;+ @service siteSettings;+ @service toasts;++ mentionAutocomplete = modifier((textarea) => {+ if (!this.siteSettings.enable_mentions) {+ return;+ }++ const textHandler = new TextareaAutocompleteHandler(textarea);+ const autocomplete = dAutocomplete.setupAutocomplete(+ getOwner(this),+ textarea,+ textHandler,+ {+ component: UserAutocompleteResults,+ key: UserAutocompleteResults.TRIGGER_KEY,+ dataSource: (term) => userSearch({ term, includeGroups: false }),+ transformComplete: (user) => {+ validateSearchResult(user);+ return user.username;+ },+ afterComplete: () => {+ textarea.focus({ preventScroll: true });+ },+ }+ );++ return () => destroy(autocomplete);+ });/*** Registers the Form API reference.@@ -61,6 +98,20 @@ export default class ReviewableNoteForm extends Component {// Clear the submitted contentawait this.formApi.set("content", "");+ if (response.unnotified_usernames?.length) {+ const message = i18n("review.notes.mentions_not_notified", {+ count: response.unnotified_usernames.length,+ usernames: response.unnotified_usernames+ .map((username) => `@${username}`)+ .join(", "),+ });+ this.toasts.warning({+ duration: "long",+ data: { message },+ });+ this.a11y.announce(message, "polite");+ }+// Notify any interested plugins that a note has been created.this.appEvents.trigger("reviewablenote:created",@@ -101,6 +152,7 @@ export default class ReviewableNoteForm extends Component {class="reviewable-note-form__textarea"placeholder={{i18n "review.notes.placeholder"}}@height={{80}}+ {{this.mentionAutocomplete}}/><PluginOutlet@connectorTagName="div"diff --git a/frontend/discourse/app/components/reviewable/timeline.gjs b/frontend/discourse/app/components/reviewable/timeline.gjsindex 2f03d029a29..283496a10f2 100644--- a/frontend/discourse/app/components/reviewable/timeline.gjs+++ b/frontend/discourse/app/components/reviewable/timeline.gjs@@ -174,7 +174,7 @@ export default class ReviewableTimeline extends Component {user: note.user,icon: "far-pen-to-square",titleKey: "review.timeline.note_added_by",- description: trustHTML(`<p>${escape(note.content)}</p>`),+ description: trustHTML(note.cooked ?? `<p>${escape(note.content)}</p>`),noteId: note.id,canDelete:this.currentUser &&diff --git a/frontend/discourse/app/lib/notification-types-manager.js b/frontend/discourse/app/lib/notification-types-manager.jsindex 58171d52e14..bf31d6895d2 100644--- a/frontend/discourse/app/lib/notification-types-manager.js+++ b/frontend/discourse/app/lib/notification-types-manager.js@@ -12,6 +12,7 @@ import LikedConsolidated from "discourse/lib/notification-types/liked-consolidatimport LinkedConsolidated from "discourse/lib/notification-types/linked-consolidated";import MembershipRequestAccepted from "discourse/lib/notification-types/membership-request-accepted";import MembershipRequestConsolidated from "discourse/lib/notification-types/membership-request-consolidated";+import Mentioned from "discourse/lib/notification-types/mentioned";import MovedPost from "discourse/lib/notification-types/moved-post";import NewFeatures from "discourse/lib/notification-types/new-features";import Replied from "discourse/lib/notification-types/replied";@@ -32,6 +33,7 @@ const CLASS_FOR_TYPE = {linked_consolidated: LinkedConsolidated,membership_request_accepted: MembershipRequestAccepted,membership_request_consolidated: MembershipRequestConsolidated,+ mentioned: Mentioned,moved_post: MovedPost,new_features: NewFeatures,admin_problems: AdminProblems,diff --git a/frontend/discourse/app/lib/notification-types/mentioned.js b/frontend/discourse/app/lib/notification-types/mentioned.jsnew file mode 100644index 00000000000..cbd2bf1e902--- /dev/null+++ b/frontend/discourse/app/lib/notification-types/mentioned.js@@ -0,0 +1,20 @@+import getURL from "discourse/lib/get-url";+import NotificationTypeBase from "discourse/lib/notification-types/base";++export default class Mentioned extends NotificationTypeBase {+ get description() {+ if (this.notification.data.reviewable_id) {+ return this.notification.data.topic_title;+ }++ return super.description;+ }++ get linkHref() {+ if (this.notification.data.reviewable_id) {+ return getURL(`/review/${this.notification.data.reviewable_id}`);+ }++ return super.linkHref;+ }+}diff --git a/frontend/discourse/tests/integration/components/reviewable/note-form-test.gjs b/frontend/discourse/tests/integration/components/reviewable/note-form-test.gjsnew file mode 100644index 00000000000..5a3d85acdac--- /dev/null+++ b/frontend/discourse/tests/integration/components/reviewable/note-form-test.gjs@@ -0,0 +1,203 @@+import { render, triggerKeyEvent } from "@ember/test-helpers";+import { module, test } from "qunit";+import LiveRegions from "discourse/components/a11y/live-regions";+import ReviewableNoteForm from "discourse/components/reviewable/note-form";+import DDefaultToast from "discourse/float-kit/components/d-default-toast";+import DMenus from "discourse/float-kit/components/d-menus";+import { disableClearA11yAnnouncementsInTests } from "discourse/services/a11y";+import { setupRenderingTest } from "discourse/tests/helpers/component-test";+import pretender, { response } from "discourse/tests/helpers/create-pretender";+import form from "discourse/tests/helpers/form-kit-helper";+import { i18n } from "discourse-i18n";++module("Integration | Component | Reviewable | NoteForm", function (hooks) {+ setupRenderingTest(hooks);++ hooks.beforeEach(function () {+ this.siteSettings.enable_mentions = true;+ this.reviewable = { id: 1 };+ this.toasts = this.owner.lookup("service:toasts");+ });++ test("autocompletes all users and submits the completed mention", async function (assert) {+ let submittedContent;+ pretender.get("/u/search/users", (request) => {+ assert.strictEqual(+ request.queryParams.term,+ "alex",+ "searches the typed term"+ );+ assert.strictEqual(+ request.queryParams.include_groups,+ "false",+ "does not include groups"+ );+ assert.strictEqual(+ request.queryParams.groups,+ undefined,+ "does not restrict results to staff groups"+ );+ return response({+ users: [+ {+ username: "alex",+ name: "Alex",+ avatar_template: "/images/avatar.png",+ moderator: true,+ },+ {+ username: "alex_regular",+ name: "Alex Regular",+ avatar_template: "/images/avatar.png",+ moderator: false,+ },+ ],+ });+ });+ pretender.post("/review/1/notes", (request) => {+ submittedContent = request.requestBody;+ return response({ id: 2, unnotified_usernames: [] });+ });++ await render(+ <template>+ <ReviewableNoteForm @reviewable={{this.reviewable}} />+ <DMenus />+ </template>+ );++ await form().field("content").fillIn("Hello @alex");+ await triggerKeyEvent("textarea", "keyup", 88);++ assert+ .dom(".ac-user .username")+ .exists({ count: 2 }, "offers staff and regular users");+ await triggerKeyEvent("textarea", "keydown", "Enter");++ assert+ .dom("textarea")+ .hasValue("Hello @alex ", "inserts the selected mention");+ assert.dom(".ac-user").doesNotExist("closes the autocomplete");+ await form().submit();++ assert.strictEqual(+ new URLSearchParams(submittedContent).get("reviewable_note[content]"),+ "Hello @alex",+ "updates FormKit with the completed mention"+ );+ assert.dom("textarea").hasValue("", "clears the saved note");+ });++ test("autocompletes mentions inside literal code syntax", async function (assert) {+ pretender.get("/u/search/users", () =>+ response({+ users: [{ username: "alex", avatar_template: "/images/avatar.png" }],+ })+ );++ await render(+ <template>+ <ReviewableNoteForm @reviewable={{this.reviewable}} />+ <DMenus />+ </template>+ );++ await form().field("content").fillIn("```\n@alex");+ await triggerKeyEvent("textarea", "keyup", 88);+ assert+ .dom(".ac-user .username")+ .hasText("alex", "offers mentions in plaintext code syntax");++ await triggerKeyEvent("textarea", "keydown", "Enter");+ assert+ .dom("textarea")+ .hasValue("```\n@alex ", "inserts the completed mention");+ });++ test("does not autocomplete when mentions are disabled", async function (assert) {+ this.siteSettings.enable_mentions = false;+ await render(+ <template>+ <ReviewableNoteForm @reviewable={{this.reviewable}} />+ <DMenus />+ </template>+ );++ await form().field("content").fillIn("@alex");+ await triggerKeyEvent("textarea", "keyup", 88);++ assert.dom(".ac-user").doesNotExist("respects the mentions site setting");+ });++ for (const usernames of [+ ["regular_user"],+ ["regular_user", "another_user"],+ ]) {+ test(`warns after saving about ${usernames.length} inaccessible mentions`, async function (assert) {+ disableClearA11yAnnouncementsInTests();+ pretender.post("/review/1/notes", () =>+ response({+ id: 2,+ unnotified_usernames: usernames,+ })+ );++ await render(+ <template>+ <ReviewableNoteForm @reviewable={{this.reviewable}} />+ {{#each this.toasts.activeToasts as |toast|}}+ <DDefaultToast @data={{toast.options.data}} />+ {{/each}}+ <LiveRegions />+ </template>+ );+ await form()+ .field("content")+ .fillIn(usernames.map((username) => `@${username}`).join(" "));+ await form().submit();++ assert.dom(".fk-d-default-toast__message").hasText(+ i18n("review.notes.mentions_not_notified", {+ count: usernames.length,+ usernames: usernames.map((username) => `@${username}`).join(", "),+ }),+ "explains that users without reviewable access will not be notified"+ );+ assert+ .dom(".fk-d-default-toast.-warning")+ .exists("shows a warning toast");+ assert.dom("#a11y-announcements-polite").hasText(+ i18n("review.notes.mentions_not_notified", {+ count: usernames.length,+ usernames: usernames.map((username) => `@${username}`).join(", "),+ }),+ "announces the warning to screen readers"+ );+ assert.dom("textarea").hasValue("", "still saves the note successfully");+ });+ }++ test("does not warn when all mentioned users can access the review queue", async function (assert) {+ pretender.post("/review/1/notes", () =>+ response({+ id: 2,+ unnotified_usernames: [],+ })+ );++ await render(+ <template>+ <ReviewableNoteForm @reviewable={{this.reviewable}} />+ {{#each this.toasts.activeToasts as |toast|}}+ <DDefaultToast @data={{toast.options.data}} />+ {{/each}}+ </template>+ );+ await form().field("content").fillIn("@moderator");+ await form().submit();++ assert+ .dom(".fk-d-default-toast")+ .doesNotExist("does not show an unnecessary warning");+ });+});diff --git a/frontend/discourse/tests/integration/components/reviewable/timeline-test.gjs b/frontend/discourse/tests/integration/components/reviewable/timeline-test.gjsindex 7b860c6307b..1812bc6c570 100644--- a/frontend/discourse/tests/integration/components/reviewable/timeline-test.gjs+++ b/frontend/discourse/tests/integration/components/reviewable/timeline-test.gjs@@ -3,6 +3,8 @@ import { getOwner } from "@ember/owner";import { click, render, settled } from "@ember/test-helpers";import { module, test } from "qunit";import ReviewableTimeline from "discourse/components/reviewable/timeline";+import UserCardContents from "discourse/components/user-card-contents";+import DMenus from "discourse/float-kit/components/d-menus";import { CLAIMED, UNCLAIMED } from "discourse/models/reviewable-history";import { setupRenderingTest } from "discourse/tests/helpers/component-test";import pretender, { response } from "discourse/tests/helpers/create-pretender";@@ -151,6 +153,42 @@ module("Integration | Component | Reviewable | Timeline", function (hooks) {.hasText("A note added from the form", "appends the pushed note");});+ test("opens the user card when clicking a mention in a saved note", async function (assert) {+ const savedNote = {+ ...note(10, "Please ask @charlie for help."),+ cooked:+ '<p>Please ask <a class="mention" href="/u/charlie">@charlie</a> for help.</p>',+ };+ const reviewable = storedReviewable(this, [savedNote]);++ await render(+ <template>+ <div id="main-outlet">+ <ReviewableTimeline @reviewable={{reviewable}} />+ </div>+ <UserCardContents />+ <DMenus />+ </template>+ );++ assert+ .dom(".timeline-event__description a.mention")+ .hasAttribute(+ "href",+ "/u/charlie",+ "the mention links to the user profile"+ );++ await click(".timeline-event__description a.mention");++ assert+ .dom(".user-card .card-content")+ .exists("clicking the mention opens the user card");+ assert+ .dom(".user-card .username")+ .hasText("charlie", "shows the mentioned user's profile");+ });+test("removes a deleted note from the timeline", async function (assert) {const reviewable = storedReviewable(this, [note(10, "A note that stays"),diff --git a/frontend/discourse/tests/unit/lib/notification-types/mentioned-test.js b/frontend/discourse/tests/unit/lib/notification-types/mentioned-test.jsnew file mode 100644index 00000000000..88efb6aeefc--- /dev/null+++ b/frontend/discourse/tests/unit/lib/notification-types/mentioned-test.js@@ -0,0 +1,81 @@+import { setupTest } from "ember-qunit";+import { module, test } from "qunit";+import { setPrefix } from "discourse/lib/get-url";+import Notification from "discourse/models/notification";+import { NOTIFICATION_TYPES } from "discourse/tests/fixtures/concerns/notification-types";+import { createRenderDirector } from "discourse/tests/helpers/notification-types-helper";++module("Unit | Notification Types | mentioned", function (hooks) {+ setupTest(hooks);++ test("reviewable mentions retain the regular mention appearance", function (assert) {+ const notification = Notification.create({+ notification_type: NOTIFICATION_TYPES.mentioned,+ topic_id: null,+ post_number: null,+ data: {+ reviewable_id: 123,+ reviewable_note_id: 456,+ topic_title: "Review <script>alert('title')</script>",+ display_username: "moderator",+ },+ });+ const director = createRenderDirector(+ notification,+ "mentioned",+ this.owner.lookup("service:site-settings")+ );++ assert.strictEqual(+ director.linkHref,+ "/review/123",+ "the mention links to its reviewable"+ );+ assert.strictEqual(+ director.description,+ notification.data.topic_title,+ "the reviewable title is plain text for escaped rendering"+ );+ assert.strictEqual(director.label, "moderator", "the author is the label");+ assert.strictEqual(+ director.icon,+ "notification.mentioned",+ "the regular mention icon is retained"+ );++ setPrefix("/forum");++ assert.strictEqual(+ director.linkHref,+ "/forum/review/123",+ "the link respects the site base path"+ );+ });++ test("topic mentions continue to link to their post", function (assert) {+ const notification = Notification.create({+ notification_type: NOTIFICATION_TYPES.mentioned,+ topic_id: 100,+ post_number: 5,+ slug: "test-topic",+ fancy_title: "Test <topic>",+ data: { topic_title: "Test <topic>", display_username: "author" },+ });+ const director = createRenderDirector(+ notification,+ "mentioned",+ this.owner.lookup("service:site-settings")+ );++ assert.strictEqual(+ director.linkHref,+ "/t/test-topic/100/5",+ "the mention links to the original post"+ );+ assert.strictEqual(+ director.description.toString(),+ notification.fancy_title,+ "the topic's formatted title is retained"+ );+ });+});diff --git a/lib/discourse_mcp/tools/notifications.rb b/lib/discourse_mcp/tools/notifications.rbindex b2a11de3ae9..7c3a4f4b854 100644--- a/lib/discourse_mcp/tools/notifications.rb+++ b/lib/discourse_mcp/tools/notifications.rb@@ -27,6 +27,12 @@ module DiscourseMcprequest_context.guardian,notifications,)+ notifications =+ Notification.filter_inaccessible_reviewable_notifications(+ request_context.guardian,+ notifications,+ )+ notifications = filter_reviewable_mentions_by_scope(notifications, request_context)notifications = Notification.filter_disabled_badge_notifications(notifications)notifications = Notification.populate_acting_user(notifications)serialized =@@ -39,6 +45,48 @@ module DiscourseMcpendToolHelpers.text_and_structured(notifications: serialized)end++ # Reviewable mentions carry no topic, so the PM gate above never sees them;+ # hold them to the scopes the moderation tools require instead.+ def self.filter_reviewable_mentions_by_scope(notifications, request_context)+ reviewable_ids =+ notifications+ .select(&:reviewable_mention?)+ .map { |notification| notification.data_hash[:reviewable_id].to_i }+ .uniq+ return notifications if reviewable_ids.empty?++ allowed_ids =+ if request_context.has_scopes?(Scopes::MODERATION_READ)+ topic_id_by_reviewable_id =+ Reviewable.where(id: reviewable_ids).pluck(:id, :topic_id).to_h+ private_message_topic_ids =+ if request_context.has_scopes?(Scopes::PRIVATE_MESSAGES_READ)+ []+ else+ # Unscoped so trashed private messages stay hidden too.+ Topic+ .unscoped+ .where(+ id: topic_id_by_reviewable_id.values.compact,+ archetype: Archetype.private_message,+ )+ .pluck(:id)+ end+ topic_id_by_reviewable_id+ .reject { |_, topic_id| private_message_topic_ids.include?(topic_id) }+ .keys+ .to_set+ else+ Set.new+ end++ notifications.reject do |notification|+ notification.reviewable_mention? &&+ !allowed_ids.include?(notification.data_hash[:reviewable_id].to_i)+ end+ end+ private_class_method :filter_reviewable_mentions_by_scopeendendenddiff --git a/lib/plaintext_mentions.rb b/lib/plaintext_mentions.rbnew file mode 100644index 00000000000..41721b87614--- /dev/null+++ b/lib/plaintext_mentions.rb@@ -0,0 +1,55 @@+# frozen_string_literal: true++# Notes remain plaintext, so literal code and quote syntax use the same mention rules.+class PlaintextMentions+ MENTION_PATTERN =+ /(?<![^\p{Space}\p{P}\p{S}])@(\w[\w.-]{0,58}[^\W_]|\w)(?![^\p{Space}\p{P}\p{S}])/+ UNICODE_MENTION_PATTERN =+ /(?<![^\p{Space}\p{P}\p{S}])@([\p{Alphabetic}\p{M}\p{Nd}_][\p{Alphabetic}\p{M}\p{Nd}._-]{0,58}[\p{Alphabetic}\p{M}\p{Nd}]|[\p{Alphabetic}\p{M}\p{Nd}_])(?![^\p{Space}\p{P}\p{S}])/++ def self.known_usernames(contents)+ usernames = contents.flat_map { |content| new(content).usernames }.uniq+ User.where(username_lower: usernames, staged: false).pluck(:username_lower).to_set+ end++ def initialize(content)+ @content = content.to_s+ end++ def usernames+ matches.map { |match| User.normalize_username(match[1]) }.uniq+ end++ def render(known_usernames: nil)+ content = @content+ return "<p>#{ERB::Util.html_escape(content)}</p>" if !SiteSetting.enable_mentions++ users = known_usernames || self.class.known_usernames([content])+ result = +"<p>"+ cursor = 0+ matches.each do |match|+ result << ERB::Util.html_escape(content[cursor...match.begin(0)])+ username = User.normalize_username(match[1])+ if users.include?(username)+ href = "#{Discourse.base_path}/u/#{UrlHelper.encode_component(username)}"+ label = PrettyText::Helpers.format_username(match[0])+ result << "<a class=\"mention\" href=\"#{ERB::Util.html_escape(href)}\">#{ERB::Util.html_escape(label)}</a>"+ else+ result << ERB::Util.html_escape(match[0])+ end+ cursor = match.end(0)+ end+ result << ERB::Util.html_escape(content[cursor..])+ result << "</p>"+ end++ private++ def matches+ @matches ||=+ begin+ pattern = SiteSetting.unicode_usernames ? UNICODE_MENTION_PATTERN : MENTION_PATTERN+ @content.to_enum(:scan, pattern).map { Regexp.last_match.dup }+ end+ end+enddiff --git a/plugins/chat/app/models/chat/reviewable_message.rb b/plugins/chat/app/models/chat/reviewable_message.rbindex fb47611836f..9e02edce09e 100644--- a/plugins/chat/app/models/chat/reviewable_message.rb+++ b/plugins/chat/app/models/chat/reviewable_message.rb@@ -11,6 +11,11 @@ module ChatChat::ReviewableMessageSerializerend+ def title_for_notification(user)+ channel = chat_message&.chat_channel+ channel&.name || channel&.title(user) || super+ end+def self.action_aliases{agree_and_keep_hidden: :agree_and_delete,diff --git a/plugins/chat/spec/models/chat/reviewable_chat_message_spec.rb b/plugins/chat/spec/models/chat/reviewable_chat_message_spec.rbindex 09cd9a68e1a..0701b322030 100644--- a/plugins/chat/spec/models/chat/reviewable_chat_message_spec.rb+++ b/plugins/chat/spec/models/chat/reviewable_chat_message_spec.rb@@ -12,6 +12,23 @@ RSpec.describe Chat::ReviewableMessage, type: :model doit { is_expected.to validate_length_of(:type).is_at_most(100) }it { is_expected.to validate_length_of(:target_type).is_at_most(100) }+ it "uses the channel title in reviewable note mention notifications" do+ SiteSetting.enable_mentions = true+ recipient = Fabricate(:admin)+ chat_channel.update!(name: "Reviewable mention testing")++ ReviewableNote.create!(+ reviewable: reviewable,+ user: moderator,+ content: "@#{recipient.username}",+ )++ notification =+ recipient.notifications.find_by!(notification_type: Notification.types[:mentioned])+ expect(notification.data_hash["topic_title"]).to eq(chat_channel.name)+ expect(notification.url).to eq("/review/#{reviewable.id}")+ end+it "agree_and_keep agrees with the flag and doesn't delete the message" doreviewable.perform(moderator, :agree_and_keep_message)diff --git a/plugins/discourse-ai/lib/agents/tools/perform_reviewable_action.rb b/plugins/discourse-ai/lib/agents/tools/perform_reviewable_action.rbindex 10fac26cbee..a54d2b48e35 100644--- a/plugins/discourse-ai/lib/agents/tools/perform_reviewable_action.rb+++ b/plugins/discourse-ai/lib/agents/tools/perform_reviewable_action.rb@@ -86,7 +86,15 @@ module DiscourseAi)end- reviewable.reviewable_notes.create!(user: acting_user, content: reason)+ note = reviewable.reviewable_notes.build(user: acting_user, content: reason)+ if !note.save+ return(+ error_response(+ note.errors.full_messages.join(", ").presence ||+ I18n.t("discourse_ai.ai_bot.perform_reviewable_action.errors.action_failed"),+ )+ )+ endbeginresult =diff --git a/plugins/discourse-ai/spec/lib/agents/tools/perform_reviewable_action_spec.rb b/plugins/discourse-ai/spec/lib/agents/tools/perform_reviewable_action_spec.rbindex d679811d4ec..71da6d4c62b 100644--- a/plugins/discourse-ai/spec/lib/agents/tools/perform_reviewable_action_spec.rb+++ b/plugins/discourse-ai/spec/lib/agents/tools/perform_reviewable_action_spec.rb@@ -90,6 +90,29 @@ RSpec.describe DiscourseAi::Agents::Tools::PerformReviewableAction doexpect(note.content).to eq("AI determined this violates policy")end+ it "returns the note validation error without performing the action" do+ SiteSetting.max_mentions_per_post = 1+ agent_bot_user = Fabricate(:bot, trust_level: TrustLevel[4])+ ctx = DiscourseAi::Agents::BotContext.new(user: admin)++ result =+ described_class.new(+ {+ reviewable_id: flagged_reviewable.id,+ action_id: "agree_and_keep",+ reason: "Reported by @alice and @bob",+ },+ bot_user: agent_bot_user,+ llm: llm,+ context: ctx,+ ).invoke++ expect(result[:status]).to eq("error")+ expect(result[:error]).to eq(I18n.t("too_many_mentions", count: 1))+ expect(flagged_reviewable.reload.status).to eq("pending")+ expect(flagged_reviewable.reviewable_notes).to be_empty+ end+it "successfully performs agree_and_hide" doPostActionCreator.inappropriate(Fabricate(:user, refresh_auto_groups: true), post)diff --git a/spec/lib/discourse_mcp/regular_user_tools_spec.rb b/spec/lib/discourse_mcp/regular_user_tools_spec.rbindex dd8ef10cb8b..4c697f52296 100644--- a/spec/lib/discourse_mcp/regular_user_tools_spec.rb+++ b/spec/lib/discourse_mcp/regular_user_tools_spec.rb@@ -235,6 +235,74 @@ describe DiscourseMcp::Tools doenddescribe DiscourseMcp::Tools::ListNotifications do+ it "hides reviewable mentions after moderator access is revoked" do+ SiteSetting.enable_mentions = true+ reviewable = Fabricate(:reviewable_flagged_post)+ ReviewableNote.create!(reviewable: reviewable, user: admin, content: "@#{moderator.username}")+ context = request_context(moderator)+ allow(context).to receive(:has_scopes?).and_return(true)+ result =+ described_class.call(arguments: {}, request_context: context).fetch(:structuredContent)+ expect(result.fetch(:notifications).size).to eq(1)++ reviewable.update!(reviewable_by_moderator: false)+ result =+ described_class.call(arguments: {}, request_context: context).fetch(:structuredContent)+ expect(result.fetch(:notifications)).to be_empty+ end++ it "lists reviewable mentions only for tokens with the moderation scope" do+ SiteSetting.enable_mentions = true+ reviewable = Fabricate(:reviewable_flagged_post)+ ReviewableNote.create!(reviewable: reviewable, user: admin, content: "@#{moderator.username}")+ topic_notification = Fabricate(:notification, user: moderator)+ context = request_context(moderator)+ allow(context).to receive(:has_scopes?).and_return(true)+ allow(context).to receive(:has_scopes?).with(+ DiscourseMcp::Scopes::MODERATION_READ,+ ).and_return(false)++ result =+ described_class.call(arguments: {}, request_context: context).fetch(:structuredContent)++ expect(result.fetch(:notifications).pluck(:id)).to contain_exactly(topic_notification.id)+ end++ it "hides mentions on private message reviewables from tokens without the private messages scope" do+ SiteSetting.enable_mentions = true+ private_message_reviewable, trashed_private_message_reviewable =+ Array.new(2) do+ private_message_post = Fabricate(:private_message_post)+ Fabricate(+ :reviewable_flagged_post,+ target: private_message_post,+ topic: private_message_post.topic,+ )+ end+ trashed_private_message_reviewable.topic.trash!+ topic_reviewable = Fabricate(:reviewable_flagged_post)+ other_admin = Fabricate(:admin)+ [+ private_message_reviewable,+ trashed_private_message_reviewable,+ topic_reviewable,+ ].each do |reviewable|+ ReviewableNote.create!(reviewable:, user: admin, content: "@#{other_admin.username}")+ end+ context = request_context(other_admin)+ allow(context).to receive(:has_scopes?).and_return(true)+ allow(context).to receive(:has_scopes?).with(+ DiscourseMcp::Scopes::PRIVATE_MESSAGES_READ,+ ).and_return(false)++ result =+ described_class.call(arguments: {}, request_context: context).fetch(:structuredContent)++ expect(+ result.fetch(:notifications).map { |notification| notification[:data][:reviewable_id] },+ ).to contain_exactly(topic_reviewable.id)+ end+it "lists only the caller's notifications from visible topics" dovisible_notification = Fabricate(:notification, user:)Fabricate(:notification, user: other_user)diff --git a/spec/lib/plaintext_mentions_spec.rb b/spec/lib/plaintext_mentions_spec.rbnew file mode 100644index 00000000000..ef8089f547b--- /dev/null+++ b/spec/lib/plaintext_mentions_spec.rb@@ -0,0 +1,35 @@+# frozen_string_literal: true++RSpec.describe PlaintextMentions do+ describe "#usernames" do+ it "treats Unicode whitespace and punctuation as mention boundaries" do+ content = "hi\u00A0@sam, @alex\u3000ok (@kim) [email protected] x@lee"++ [false, true].each do |unicode_usernames|+ SiteSetting.unicode_usernames = unicode_usernames++ expect(described_class.new(content).usernames).to contain_exactly("sam", "alex", "kim")+ end+ end++ it "normalizes usernames the same way as stored usernames" do+ SiteSetting.unicode_usernames = true+ content = "@E\u0301le\u0300ve @\u00E9l\u00E8ve"++ expect(described_class.new(content).usernames).to eq(["\u00E9l\u00E8ve"])+ end+ end++ describe "#render" do+ it "links a decomposed Unicode mention to the stored username" do+ SiteSetting.unicode_usernames = true+ user = Fabricate(:user, username: "\u00E9l\u00E8ve")++ cooked = Nokogiri::HTML5.fragment(described_class.new("Ask @e\u0301le\u0300ve").render)++ expect(cooked.at_css("a.mention")["href"]).to eq(+ "/u/#{UrlHelper.encode_component(user.username_lower)}",+ )+ end+ end+enddiff --git a/spec/models/notification_spec.rb b/spec/models/notification_spec.rbindex 26c5c4a8fb9..47f588c60d8 100644--- a/spec/models/notification_spec.rb+++ b/spec/models/notification_spec.rb@@ -1,6 +1,72 @@# frozen_string_literal: trueRSpec.describe Notification do+ describe ".filter_inaccessible_reviewable_notifications" do+ fab!(:admin)+ fab!(:moderator)+ fab!(:reviewable, :reviewable_flagged_post)++ it "preserves regular mentions and filters reviewable mentions after access changes or deletion" do+ SiteSetting.enable_mentions = true+ ReviewableNote.create!(reviewable: reviewable, user: admin, content: "@#{moderator.username}")+ mention = moderator.notifications.find_by!(notification_type: Notification.types[:mentioned])+ regular =+ Fabricate(:notification, user: moderator, notification_type: Notification.types[:mentioned])+ notifications = [mention, regular]++ expect(+ described_class.filter_inaccessible_reviewable_notifications(+ moderator.guardian,+ notifications,+ ),+ ).to eq(notifications)++ reviewable.update!(reviewable_by_moderator: false)+ expect(+ described_class.filter_inaccessible_reviewable_notifications(+ moderator.guardian,+ notifications,+ ),+ ).to eq([regular])+ expect(+ described_class.filter_inaccessible_reviewable_notifications(admin.guardian, notifications),+ ).to eq(notifications)++ reviewable.destroy!+ expect(+ described_class.filter_inaccessible_reviewable_notifications(admin.guardian, notifications),+ ).to eq([regular])+ end++ it "filters mentions after category moderation membership is revoked" do+ SiteSetting.enable_mentions = true+ SiteSetting.enable_category_group_moderation = true+ recipient = Fabricate(:user)+ group = Fabricate(:group)+ group.add(recipient)+ category = reviewable.topic.category+ reviewable.update!(category: category)+ Fabricate(:category_moderation_group, category: category, group: group)+ ReviewableNote.create!(reviewable: reviewable, user: admin, content: "@#{recipient.username}")+ notifications = recipient.notifications.to_a++ expect(+ described_class.filter_inaccessible_reviewable_notifications(+ recipient.guardian,+ notifications,+ ),+ ).to eq(notifications)++ group.remove(recipient)+ expect(+ described_class.filter_inaccessible_reviewable_notifications(+ recipient.reload.guardian,+ notifications,+ ),+ ).to be_empty+ end+ end+context "with the notification observer enabled" dofab!(:user)fab!(:coding_horror)@@ -308,6 +374,34 @@ RSpec.describe Notification dofab!(:topic)fab!(:post) { Fabricate(:post, topic: topic, post_number: 5) }+ it "returns the reviewable URL for a note mention without a topic" do+ notification =+ Fabricate(+ :notification,+ notification_type: Notification.types[:mentioned],+ topic: nil,+ data: { reviewable_id: 123, reviewable_note_id: 456 }.to_json,+ )++ expect(notification.url).to eq("/review/123")++ set_subfolder("/forum")++ expect(notification.url).to eq("/forum/review/123")+ end++ it "returns the relative topic URL for a regular mention" do+ notification =+ Fabricate(+ :notification,+ notification_type: Notification.types[:mentioned],+ topic: topic,+ post_number: post.post_number,+ )++ expect(notification.url).to eq(topic.relative_url(post.post_number))+ end+it "returns the relative topic url for a regular reply notification" donotification =Fabricate(diff --git a/spec/models/reviewable_note_spec.rb b/spec/models/reviewable_note_spec.rbindex 84bf67d8078..6f3689617bc 100644--- a/spec/models/reviewable_note_spec.rb+++ b/spec/models/reviewable_note_spec.rb@@ -83,4 +83,291 @@ RSpec.describe ReviewableNote doexpect(note.user).to eq(admin)endend++ describe ".create!" do+ before { SiteSetting.enable_mentions = true }++ it "notifies mentioned reviewers once and reports users who cannot see the reviewable" do+ other_admin = Fabricate(:admin)++ note =+ ReviewableNote.create!(+ reviewable: reviewable,+ user: admin,+ content:+ "@#{moderator.username.upcase} @#{moderator.username} @#{other_admin.username} @#{user.username} @#{admin.username}",+ )++ notifications = Notification.where(notification_type: Notification.types[:mentioned])+ expect(notifications.pluck(:user_id)).to contain_exactly(moderator.id, other_admin.id)+ expect(note.unnotified_usernames).to eq([user.username])+ expect(notifications.first.data_hash).to include(+ "reviewable_id" => reviewable.id,+ "reviewable_note_id" => note.id,+ "topic_title" => reviewable.topic.title,+ "display_username" => admin.username,+ )+ expect(notifications.first.topic_id).to be_nil+ expect(notifications.first.post_number).to be_nil+ end++ it "warns about a moderator who cannot see an admin-only reviewable" do+ reviewable.update!(reviewable_by_moderator: false)++ note =+ ReviewableNote.create!(+ reviewable: reviewable,+ user: admin,+ content: "@#{moderator.username}",+ )++ expect(+ moderator.notifications.where(notification_type: Notification.types[:mentioned]),+ ).to be_empty+ expect(note.unnotified_usernames).to eq([moderator.username])+ end++ it "notifies category moderators only about reviewables in their category" do+ SiteSetting.enable_category_group_moderation = true+ group = Fabricate(:group)+ group.add(user)+ category = reviewable.topic.category+ reviewable.update!(category: category)+ Fabricate(:category_moderation_group, category: category, group: group)+ other_reviewable = Fabricate(:reviewable_flagged_post, category: Fabricate(:category))++ visible_note =+ ReviewableNote.create!(reviewable: reviewable, user: admin, content: "@#{user.username}")+ hidden_note =+ ReviewableNote.create!(+ reviewable: other_reviewable,+ user: admin,+ content: "@#{user.username}",+ )++ notifications = user.notifications.where(notification_type: Notification.types[:mentioned])+ expect(notifications.size).to eq(1)+ expect(notifications.first.data_hash["reviewable_note_id"]).to eq(visible_note.id)+ expect(visible_note.unnotified_usernames).to be_empty+ expect(hidden_note.unnotified_usernames).to eq([user.username])+ end++ it "uses the submitted title for a queued new topic" do+ queued_topic = Fabricate(:reviewable_queued_post_topic)++ ReviewableNote.create!(+ reviewable: queued_topic,+ user: admin,+ content: "@#{moderator.username}",+ )++ notification =+ moderator.notifications.find_by!(notification_type: Notification.types[:mentioned])+ expect(notification.data_hash["topic_title"]).to eq(queued_topic.payload["title"])+ end++ it "uses a neutral title for reviewables without topic or title metadata" do+ reviewable.update!(topic: nil, target: nil)++ ReviewableNote.create!(reviewable: reviewable, user: admin, content: "@#{moderator.username}")++ notification =+ moderator.notifications.find_by!(notification_type: Notification.types[:mentioned])+ expect(notification.data_hash["topic_title"]).to eq(I18n.t("js.review.title"))+ end++ it "identifies deleted topics when the topic association is missing" do+ reviewable.update_columns(topic_id: -123)+ reviewable.reload++ ReviewableNote.create!(reviewable: reviewable, user: admin, content: "@#{moderator.username}")++ notification =+ moderator.notifications.find_by!(notification_type: Notification.types[:mentioned])+ expect(notification.data_hash["topic_title"]).to eq(I18n.t("js.review.topics.deleted"))+ end++ it "respects recipients muting or ignoring a non-staff author" do+ other_admin = Fabricate(:admin)+ Fabricate(:muted_user, user: moderator, muted_user: user)+ Fabricate(:ignored_user, user: other_admin, ignored_user: user)+ user.update!(trust_level: 1)++ note =+ ReviewableNote.create!(+ reviewable: reviewable,+ user: user,+ content: "@#{moderator.username} @#{other_admin.username}",+ )++ expect(Notification.where(notification_type: Notification.types[:mentioned])).to be_empty+ expect(note.unnotified_usernames).to be_empty+ end++ it "allows staff authors to notify recipients who muted them" do+ Fabricate(:muted_user, user: moderator, muted_user: admin)++ ReviewableNote.create!(reviewable: reviewable, user: admin, content: "@#{moderator.username}")++ expect(+ moderator.notifications.where(notification_type: Notification.types[:mentioned]).count,+ ).to eq(1)+ end++ it "skips bot recipients" do+ note =+ ReviewableNote.create!(+ reviewable: reviewable,+ user: admin,+ content: "@#{Discourse.system_user.username}",+ )++ expect(Notification.where(notification_type: Notification.types[:mentioned])).to be_empty+ expect(note.unnotified_usernames).to be_empty+ end++ it "enforces the mention limit for non-staff authors before creating notifications" do+ user.update!(trust_level: 1)+ SiteSetting.max_mentions_per_post = 1+ note =+ ReviewableNote.new(+ reviewable: reviewable,+ user: user,+ content: "@#{moderator.username} @#{admin.username}",+ )++ expect(note.save).to eq(false)+ expect(note.errors[:base]).to eq([I18n.t("too_many_mentions", count: 1)])+ expect(Notification.where(notification_type: Notification.types[:mentioned])).to be_empty++ note.content = "@#{moderator.username} @#{moderator.username.upcase}"+ expect(note.save).to eq(true)+ expect(+ moderator.notifications.where(notification_type: Notification.types[:mentioned]).count,+ ).to eq(1)+ end++ it "applies the new-user mention limit and exempts staff" do+ user.update!(trust_level: 0)+ SiteSetting.newuser_max_mentions_per_post = 0+ note =+ ReviewableNote.new(reviewable: reviewable, user: user, content: "@#{moderator.username}")++ expect(note.save).to eq(false)+ expect(note.errors[:base]).to eq([I18n.t("no_mentions_allowed_newuser")])++ note.user = admin+ expect(note.save).to eq(true)+ expect(+ moderator.notifications.where(notification_type: Notification.types[:mentioned]).count,+ ).to eq(1)+ end++ it "uses the topic title for a queued reply" do+ queued_reply = Fabricate(:reviewable_queued_post)++ ReviewableNote.create!(+ reviewable: queued_reply,+ user: admin,+ content: "@#{moderator.username}",+ )++ notification =+ moderator.notifications.find_by!(notification_type: Notification.types[:mentioned])+ expect(notification.data_hash["topic_title"]).to eq(queued_reply.topic.title)+ end++ it "uses the username for a reviewable user" do+ reviewable_user = Fabricate(:reviewable_user)++ ReviewableNote.create!(+ reviewable: reviewable_user,+ user: admin,+ content: "@#{moderator.username}",+ )++ notification =+ moderator.notifications.find_by!(notification_type: Notification.types[:mentioned])+ expect(notification.data_hash["topic_title"]).to eq(reviewable_user.target.username)+ end++ it "warns about moderators who cannot access a private category" do+ group = Fabricate(:group)+ private_category = Fabricate(:private_category, group: group)+ reviewable.topic.update!(category: private_category)+ reviewable.update!(category: private_category)++ note =+ ReviewableNote.create!(+ reviewable: reviewable,+ user: admin,+ content: "@#{moderator.username}",+ )++ expect(+ moderator.notifications.where(notification_type: Notification.types[:mentioned]),+ ).to be_empty+ expect(note.unnotified_usernames).to eq([moderator.username])+ end++ it "notifies plaintext mentions inside literal code and quote syntax" do+ note =+ ReviewableNote.create!(+ reviewable: reviewable,+ user: admin,+ content:+ "`@#{moderator.username}`\n\n[quote]\n@#{user.username}\n[/quote]\n\n@nonexistent_reviewer",+ )++ expect(+ Notification.where(notification_type: Notification.types[:mentioned]).pluck(:user_id),+ ).to contain_exactly(moderator.id)+ expect(note.unnotified_usernames).to eq([user.username])+ end++ it "uses the same individual mentions for links and notifications" do+ other_admin = Fabricate(:admin)+ group = Fabricate(:group)+ content =+ "(@#{moderator.username.upcase}), <b>@#{other_admin.username}</b> person@#{user.username}.com @#{group.name} @nonexistent_reviewer"+ note = ReviewableNote.create!(reviewable: reviewable, user: admin, content: content)+ cooked =+ Nokogiri::HTML5.fragment(ReviewableNoteSerializer.new(note, root: false).as_json[:cooked])++ expect(cooked.text).to eq(content)+ expect(+ cooked.css("a.mention").map { |mention| mention.text[1..].downcase },+ ).to contain_exactly(moderator.username_lower, other_admin.username_lower)+ expect(+ Notification.where(notification_type: Notification.types[:mentioned]).pluck(:user_id),+ ).to contain_exactly(moderator.id, other_admin.id)+ expect(note.unnotified_usernames).to be_empty+ end++ it "respects disabled mentions" do+ SiteSetting.enable_mentions = false++ note =+ ReviewableNote.create!(+ reviewable: reviewable,+ user: admin,+ content: "@#{moderator.username}",+ )++ expect(Notification.where(notification_type: Notification.types[:mentioned])).to be_empty+ expect(note.unnotified_usernames).to be_empty+ end++ it "creates no notifications for an invalid note" do+ note =+ ReviewableNote.new(+ reviewable: reviewable,+ user: admin,+ content: "@#{moderator.username} " * 2000,+ )++ expect(note.save).to eq(false)+ expect(Notification.where(notification_type: Notification.types[:mentioned])).to be_empty+ end+ endenddiff --git a/spec/requests/notifications_controller_spec.rb b/spec/requests/notifications_controller_spec.rbindex cfb188c9532..9a2cb54998a 100644--- a/spec/requests/notifications_controller_spec.rb+++ b/spec/requests/notifications_controller_spec.rb@@ -29,6 +29,32 @@ def delete_notification(resp_code, matcher)endRSpec.describe NotificationsController do+ describe "#index" do+ it "hides reviewable titles in recent notifications and history after losing category access" do+ SiteSetting.enable_mentions = true+ admin = Fabricate(:admin)+ moderator = Fabricate(:moderator)+ reviewable = Fabricate(:reviewable_flagged_post)+ ReviewableNote.create!(reviewable: reviewable, user: admin, content: "@#{moderator.username}")+ sign_in(moderator)++ get "/notifications.json", params: { recent: true }+ expect(response.status).to eq(200)+ expect(response.parsed_body["notifications"].size).to eq(1)++ category = Fabricate(:private_category, group: Fabricate(:group))+ reviewable.topic.update!(category: category)+ reviewable.update!(category: category)++ [true, false].each do |recent|+ get "/notifications.json", params: { recent: recent ? true : nil }+ expect(response.status).to eq(200)+ expect(response.parsed_body["notifications"]).to be_empty+ expect(response.body).not_to include(reviewable.topic.title)+ end+ end+ end+context "when logged in" docontext "as normal user" dofab!(:user) { sign_in(Fabricate(:user)) }diff --git a/spec/requests/reviewable_notes_controller_spec.rb b/spec/requests/reviewable_notes_controller_spec.rbindex 75410ca2d9e..06be34e1c3d 100644--- a/spec/requests/reviewable_notes_controller_spec.rb+++ b/spec/requests/reviewable_notes_controller_spec.rb@@ -48,6 +48,21 @@ RSpec.describe ReviewableNotesController doexpect(json["user"]["id"]).to eq(moderator.id)end+ it "returns usernames that could not be notified along with the saved note" do+ SiteSetting.enable_mentions = true++ post "/review/#{reviewable.id}/notes.json",+ params: {+ reviewable_note: {+ content: "@#{user.username} @#{moderator.username}",+ },+ }++ expect(response.status).to eq(200)+ expect(response.parsed_body["unnotified_usernames"]).to eq([user.username])+ expect(response.parsed_body["id"]).to eq(ReviewableNote.last.id)+ end+it "returns validation errors for invalid content" dopost "/review/#{reviewable.id}/notes.json", params: { reviewable_note: { content: "" } }diff --git a/spec/serializers/reviewable_note_serializer_spec.rb b/spec/serializers/reviewable_note_serializer_spec.rbindex e2e199bcc2d..a4daa5a411d 100644--- a/spec/serializers/reviewable_note_serializer_spec.rb+++ b/spec/serializers/reviewable_note_serializer_spec.rb@@ -25,5 +25,98 @@ RSpec.describe ReviewableNoteSerializer doexpect(json[:user][:id]).to eq(admin.id)expect(json[:user][:username]).to eq(admin.username)end++ it "renders mentions as user profile links, including in existing notes" do+ SiteSetting.enable_mentions = true+ note.update!(content: "Please ask @#{user.username} for help.")++ cooked = Nokogiri::HTML5.fragment(serialized_note(note.reload)[:cooked])+ mention = cooked.at_css("a.mention")++ expect(mention["href"]).to eq("/u/#{user.username_lower}")+ expect(mention.text).to eq("@#{user.username}")+ end++ it "preserves HTML and Markdown as literal text" do+ note.update!(content: '<script>alert(1)</script><img src="x" onerror="alert(2)">')++ cooked = Nokogiri::HTML5.fragment(serialized_note(note)[:cooked])++ expect(cooked.css("script, [onerror]")).to be_empty+ expect(cooked.text).to eq(note.content)++ note.update_columns(+ content:+ " **bold** _italic_\n\n\nhttps://example.com <b>HTML</b> & \"quotes\"",+ )++ cooked = Nokogiri::HTML5.fragment(serialized_note(note)[:cooked])++ expect(cooked.children.map(&:name)).to eq(["p"])+ expect(cooked.at_css("p").children.map(&:name)).to eq(["text"])+ expect(cooked.text).to eq(note.content)+ end++ it "preserves plaintext around mentions, including literal code and quotes" do+ SiteSetting.enable_mentions = true+ note.update_columns(+ content:+ "**Ask** @#{user.username}\n\n`@#{user.username}` > @#{user.username}\n<img src=x> & https://example.com",+ )++ cooked = Nokogiri::HTML5.fragment(serialized_note(note)[:cooked])++ expect(cooked.text).to eq(note.content)+ expect(cooked.css("a.mention").map(&:text)).to eq(["@#{user.username}"] * 3)+ expect(cooked.css("img, strong, code, blockquote")).to be_empty+ end++ it "links case-insensitive usernames with punctuation and the site base path" do+ SiteSetting.enable_mentions = true+ Discourse.stubs(:base_path).returns("/forum")+ note.update_columns(content: "(@#{user.username.upcase}), @#{user.username}.")++ cooked = Nokogiri::HTML5.fragment(serialized_note(note)[:cooked])++ expect(cooked.text).to eq(note.content)+ expect(cooked.css("a.mention").map { |mention| mention["href"] }).to eq(+ ["/forum/u/#{user.username_lower}"] * 2,+ )+ end++ it "keeps email addresses, unknown users, and groups literal" do+ SiteSetting.enable_mentions = true+ group = Fabricate(:group)+ note.update_columns(content: "person@#{user.username}.com @nonexistent_user @#{group.name}")++ cooked = Nokogiri::HTML5.fragment(serialized_note(note)[:cooked])++ expect(cooked.text).to eq(note.content)+ expect(cooked.css("a")).to be_empty+ end++ it "links Unicode usernames when enabled" do+ SiteSetting.enable_mentions = true+ SiteSetting.unicode_usernames = true+ unicode_user = Fabricate(:user, username: "élève")+ note.update_columns(content: "Ask @#{unicode_user.username}")++ cooked = Nokogiri::HTML5.fragment(serialized_note(note)[:cooked])++ expect(cooked.text).to eq(note.content)+ expect(cooked.at_css("a.mention")["href"]).to eq(+ "/u/#{UrlHelper.encode_component(unicode_user.username_lower)}",+ )+ end++ it "preserves mentions as literal text when mentions are disabled" do+ SiteSetting.enable_mentions = false+ note.update_columns(content: "Ask @#{user.username} <b>here</b>")++ cooked = Nokogiri::HTML5.fragment(serialized_note(note)[:cooked])++ expect(cooked.text).to eq(note.content)+ expect(cooked.css("a, b")).to be_empty+ endendenddiff --git a/spec/serializers/reviewable_serializer_spec.rb b/spec/serializers/reviewable_serializer_spec.rbindex 02e98201b3d..981868a3f9c 100644--- a/spec/serializers/reviewable_serializer_spec.rb+++ b/spec/serializers/reviewable_serializer_spec.rb@@ -33,6 +33,46 @@ RSpec.describe ReviewableSerializer doexpect(json["payload"]).to be_blankend+ it "resolves note mentions in a constant number of queries" do+ SiteSetting.enable_mentions = true+ users = Fabricate.times(3, :user)+ Fabricate(+ :reviewable_note,+ reviewable: reviewable,+ user: admin,+ content: "@#{users.first.username}",+ )+ loaded_reviewable = Reviewable.viewable_by(admin).find(reviewable.id)+ described_class.new(loaded_reviewable, scope: admin.guardian).as_json+ queries_for_one =+ track_sql_queries { described_class.new(loaded_reviewable, scope: admin.guardian).as_json }++ users+ .drop(1)+ .each do |user|+ Fabricate(+ :reviewable_note,+ reviewable: reviewable,+ user: admin,+ content: "@#{user.username}",+ )+ end+ loaded_reviewable = Reviewable.viewable_by(admin).find(reviewable.id)+ described_class.new(loaded_reviewable, scope: admin.guardian).as_json+ json = nil+ queries_for_many =+ track_sql_queries do+ json = described_class.new(loaded_reviewable, scope: admin.guardian).as_json+ end++ expect(queries_for_many.size).to eq(queries_for_one.size)+ mentions =+ json+ .fetch(:reviewable_notes)+ .flat_map { |note| Nokogiri::HTML5.fragment(note[:cooked]).css("a.mention").map(&:text) }+ expect(mentions).to contain_exactly(*users.map { |user| "@#{user.username}" })+ end+describe "urls" doit "links to the flagged post" dofp = Fabricate(:reviewable_flagged_post)