FEATURE: per-topic unsubscribe option in emails
Tier 2 easy ruby · local · real merged PR from ai-code-review-evaluation/discourse-graphite #2
Ground-truth defects
logic: Potential nil pointer exception - if no TopicUser record exists, tu will be nil and calling methods on it will crash
topics#unsubscribe mutates and saves notification_level but is wired to a GET route with check_xhr skipped and no CSRF token, so a cross-site <img>/prefetch or email scanner GET to .../unsubscribe carries the victim's session cookie and silently toggles their topic notification level to muted.
The change under review
diff (truncated — full diff)
@@ -24,8 +24,11 @@ export default Ember.Component.extend(StringBuffer, { }.on('willDestroyElement'), renderString(buffer) { + const title = this.get('title'); + if (title) { + buffer.push("<h4 class='title'>" + title + "</h4>"); + } - buffer.push("<h4 class='title'>" + this.get('title') + "</h4>"); buffer.push("<button class='btn standard dropdown-toggle' data-toggle='dropdown'>"); buffer.push(this.get('text')); buffer.push("</button>"); new file mode 100644 @@ -0,0 +1,9 @@ +import ObjectController from "discourse/controllers/object"; + +export default ObjectController.extend({ + + stopNotificiationsText: function() { + return I18n.t("topic.unsubscribe.stop_notifications", { title: this.get("model.fancyTitle") }); + }.property("model.fancyTitle"), + +}) @@ -10,6 +10,7 @@ export default function() { this.route('fromParamsNear', { path: '/:nearPost' }); }); this.resource('topicBySlug', { path: '/t/:slug' }); + this.route('topicUnsubscribe', { path: '/t/:slug/:id/unsubscribe' }); this.resource('discovery', { path: '/' }, function() { // top @@ -2,32 +2,32 @@ export default Discourse.Route.extend({ // Avoid default model hook - model: function(p) { return p; }, + model(params) { return params; }, - setupController: function(controller, params) { + setupController(controller, params) { params = params || {}; params.track_visit = true; - var topic = this.modelFor('topic'), - postStream = topic.get('postStream'); - var topicController = this.controllerFor('topic'), - topicProgressController = this.controllerFor('topic-progress'), - composerController = this.controllerFor('composer'); + const self = this, + topic = this.modelFor('topic'), + postStream = topic.get('postStream'), + topicController = this.controllerFor('topic'), + topicProgressController = this.controllerFor('topic-progress'), + composerController = this.controllerFor('composer'); // I sincerely hope no topic gets this many posts if (params.nearPost === "last") { params.nearPost = 999999999; } - var self = this; params.forceLoad = true; - postStream.refresh(params).then(function () { + postStream.refresh(params).then(function () { // TODO we are seeing errors where closest post is null and this is exploding // we need better handling and logging for this condition. // The post we requested might not exist. Let's find the closest post - var closestPost = postStream.closestPostForPostNumber(params.nearPost || 1), - closest = closestPost.get('post_number'), - progress = postStream.progressIndexOfPost(closestPost); + const closestPost = postStream.closestPostForPostNumber(params.nearPost || 1), + closest = closestPost.get('post_number'), + progress = postStream.progressIndexOfPost(closestPost); topicController.setProperties({ 'model.currentPost': closest, @@ -43,6 +43,7 @@ export default Discourse.Route.extend({ Ember.run.scheduleOnce('afterRender', function() { self.appEvents.trigger('post:highlight', closest); }); + Discourse.URL.jumpToPost(closest); if (topic.present('draft')) { new file mode 100644 @@ -0,0 +1,23 @@ +import PostStream from "discourse/models/post-stream"; + +export default Discourse.Route.extend({ + model(params) { + const topic = this.store.createRecord("topic", { id: params.id }); + return PostStream.loadTopicView(params.id).then(json => { + topic.updateFromJson(json); + return topic; + }); + }, + + afterModel(topic) { + // hide the notification reason text + topic.set("details.notificationReasonText", null); + }, + + actions: { + didTransition() { + this.controllerFor("application").set("showFooter", true); + return true; + } + } +}); new file mode 100644 @@ -0,0 +1,8 @@ +<div class="container"> + <p> + {{{stopNotificiationsText}}} + </p> + <p> + {{i18n "topic.unsubscribe.change_notification_state"}} {{topic-notifications-button topic=model}} + </p> +</div> new file mode 100644 @@ -0,0 +1,3 @@ +export default Discourse.View.extend({ + classNames: ["topic-unsubscribe"] +}); @@ -63,3 +63,15 @@ // Top of bullet aligns with top of line - adjust line height to vertically align bullet. line-height: 0.8; } + +.topic-unsubscribe { + .notification-options { + display: inline-block; + .dropdown-toggle { + float: none; + } + .dropdown-menu { + bottom: initial; + } + } +} @@ -24,11 +24,12 @@ class TopicsController < ApplicationController :bulk, :reset_new, :change_post_owners, - :bookmark] + :bookmark, + :unsubscribe] before_filter :consider_user_for_promotion, only: :show - skip_before_filter :check_xhr, only: [:show, :feed] + skip_before_filter :check_xhr, only: [:show, :unsubscribe, :feed] def id_for_slug topic = Topic.find_by(slug: params[:slug].downcase) @@ -94,6 +95,26 @@ class TopicsController < ApplicationController raise ex end + def unsubscribe + @topic_view = TopicView.new(params[:topic_id], current_user) + + if slugs_do_not_match || (!request.format.json? && params[:slug].blank?) + return redirect_to @topic_view.topic.unsubscribe_url, status: 301 + end + + tu = TopicUser.find_by(user_id: current_user.id, topic_id: params[:topic_id]) + + if tu.notification_level > TopicUser.notification_levels[:regular] + tu.notification_level = TopicUser.notification_levels[:regular] + else + tu.notification_level = TopicUser.notification_levels[:muted] + end + + tu.save! + + perform_show_response + end + def wordpress params.require(:best) params.require(:topic_id) @@ -476,6 +497,7 @@ class TopicsController < ApplicationController format.html do @description_meta = @topic_view.topic.excerpt store_preloaded("topic_#{@topic_view.topic.id}", MultiJson.dump(topic_view_serializer)) + render :show end format.json do @@ -292,6 +292,7 @@ class UserNotifications < ActionMailer::Base context: context, username: username, add_unsubscribe_link: true, + unsubscribe_url: post.topic.unsubscribe_url, allow_reply_by_email: allow_reply_by_email, use_site_subject: use_site_subject, add_re_to_subject: add_re_to_subject, @@ -306,9 +307,7 @@ class UserNotifications < ActionMailer::Base } # If we have a display name, change the from address - if from_alias.present? - email_opts[:from_alias] = from_alias - end + email_opts[:from_alias] = from_alias if from_alias.present? TopicUser.change(user.id, post.topic_id, last_emailed_post_number: post.post_number) @@ -716,6 +716,10 @@ class Topic < ActiveRecord::Base url end + def unsubscribe_url + "#{url}/unsubscribe" + end + def clear_pin_for(user) return unless user.present? TopicUser.change(user.id, id, cleared_pinned_at: Time.now) @@ -7,8 +7,9 @@ class TopicUser < ActiveRecord::Base scope :tracking, lambda { |topic_id| where(topic_id: topic_id) - .where("COALESCE(topic_users.notification_level, :regular) >= :tracking", - regular: TopicUser.notification_levels[:regular], tracking: TopicUser.notification_levels[:tracking]) + .where("COALESCE(topic_users.notification_level, :regular) >= :tracking", + regular: TopicUser.notification_levels[:regular], + tracking: TopicUser.notification_levels[:tracking]) } # Class methods @@ -58,13 +59,9 @@ class TopicUser < ActiveRecord::Base def create_lookup(topic_users) topic_users = topic_users.to_a - result = {} return result if topic_users.blank? - - topic_users.each do |ftu| - result[ftu.topic_id] = ftu - end + topic_users.each { |ftu| result[ftu.topic_id] = ftu } result end @@ -113,11 +110,9 @@ class TopicUser < ActiveRecord::Base end if attrs[:notification_level] - MessageBus.publish("/topic/#{topic_id}", - {notification_level_change: attrs[:notification_level]}, user_ids: [user_id]) + MessageBus.publish("/topic/#{topic_id}", { notification_level_change: attrs[:notification_level] }, user_ids: [user_id]) end - rescue ActiveRecord::RecordNotUnique # In case of a race condition to insert, do nothing end @@ -127,7 +122,7 @@ class TopicUser < ActiveRecord::Base user_id = user.is_a?(User) ? user.id : topic now = DateTime.now - rows = TopicUser.where({topic_id: topic_id, user_id: user_id}).update_all({last_visited_at: now}) + rows = TopicUser.where(topic_id: topic_id, user_id: user_id).update_all(last_visited_at: now) if rows == 0 TopicUser.create(topic_id: topic_id, user_id: user_id, last_visited_at: now, first_visited_at: now) else @@ -196,7 +191,7 @@ class TopicUser < ActiveRecord::Base end if before != after - MessageBus.publish("/topic/#{topic_id}", {notification_level_change: after}, user_ids: [user.id]) + MessageBus.publish("/topic/#{topic_id}", { notification_level_change: after }, user_ids: [user.id]) end end @@ -220,7 +215,7 @@ class TopicUser < ActiveRecord::Base WHERE ftu.user_id = :user_id and ftu.topic_id = :topic_id)", args) - MessageBus.publish("/topic/#{topic_id}", {notification_level_change: args[:new_status]}, user_ids: [user.id]) + MessageBus.publish("/topic/#{topic_id}", { notification_level_change: args[:new_status] }, user_ids: [user.id]) end end @@ -1,31 +1,29 @@ <div id='main' class=<%= classes %>> -<%= render :partial => 'email/post', :locals => {:post => post} %> + <%= render partial: 'email/post', locals: { post: post } %> -<% if context_posts.present? %> - <div class='footer'> - %{respond_instructions} - </div> - <hr> - <h4 class='.previous-discussion'><%= t "user_notifications.previous_discussion" %></h4> + <% if context_posts.present? %> + <div class='footer'>%{respond_instructions}</div> + + <hr> - <% context_posts.each do |p| %> - <%= render :partial => 'email/post', :locals => {:post => p} %> + <h4 class='.previous-discussion'><%= t "user_notifications.previous_discussion" %></h4> + + <% context_posts.each do |p| %> + <%= render partial: 'email/post', locals: { post: p } %> + <% end %> <% end %> -<% end %> -<hr> + <hr> + + <div class='footer'>%{respond_instructions}</div> + <div class='footer'>%{unsubscribe_link}</div> -<div class='footer'> -%{respond_instructions} -</div> -<div class='footer'> -%{unsubscribe_link} -</div> </div> + <div itemscope itemtype="http://schema.org/EmailMessage" style="display:none"> - <div itemprop="action" itemscope itemtype="http://schema.org/ViewAction"> - <link itemprop="url" href="<%= Discourse.base_url %><%= post.url %>" /> - <meta itemprop="name" content="<%= t 'read_full_topic' %>"/> - </div> + <div itemprop="action" itemscope itemtype="http://schema.org/ViewAction"> + <link itemprop="url" href="<%= Discourse.base_url %><%= post.url %>" /> + <meta itemprop="name" content="<%= t 'read_full_topic' %>"/> + </div> </div> @@ -981,6 +981,9 @@ en: search: "There are no more search results." topic: + unsubscribe: + stop_notifications: "You will stop receiving notifications for <strong>{{title}}</strong>." + change_notification_state: "You can change your notification state" filter_to: "{{post_count}} posts in topic" create: 'New Topic' create_long: 'Create a new Topic' @@ -1014,7 +1017,6 @@ en: new_posts: one: "there is 1 new post in this topic since you last read it" other: "there are {{count}} new posts in this topic since you last read it" - likes: one: "there is 1 like in this topic" other: "there are {{count}} likes in this topic" @@ -1849,7 +1849,10 @@ en: subject_template: "Downloading remote images disabled" text_body_template: "The `download_remote_images_to_local` setting was disabled because the disk space limit at `download_remote_images_threshold` was reached." - unsubscribe_link: "To unsubscribe from these emails, visit your [user preferences](%{user_preferences_url})." + unsubscribe_link: | + To unsubscribe from these emails, visit your [user preferences](%{user_preferences_url}). + + To stop receiving notifications about this particular topic, [click here](%{unsubscribe_url}). subject_re: "Re: " subject_pm: "[PM] " @@ -434,10 +434,12 @@ Discourse::Application.routes.draw do # Topic routes get "t/id_for/:slug" => "topics#id_for_slug" get "t/:slug/:topic_id/wordpress" => "topics#wordpress", constraints: {topic_id: /\d+/} - get "t/:slug/:topic_id/moderator-liked" => "topics#moderator_liked", constraints: {topic_id: /\d+/} get "t/:topic_id/wordpress" => "topics#wordpress", constraints: {topic_id: /\d+/} - get "t/:slug/:topic_id/summary" => "topics#show", defaults: {summary: true}, constraints: {topic_id: /\d+/, post_number: /\d+/} - get "t/:topic_id/summary" => "topics#show", constraints: {topic_id: /\d+/, post_number: /\d+/} + get "t/:slug/:topic_id/moderator-liked" => "topics#moderator_liked", constraints: {topic_id: /\d+/} + get "t/:slug/:topic_id/summary" => "topics#show", defaults: {summary: true}, constraints: {topic_id: /\d+/} + get "t/:slug/:topic_id/unsubscribe" => "topics#unsubscribe", constraints: {topic_id: /\d+/} + get "t/:topic_id/unsubscribe" => "topics#unsubscribe", constraints: {topic_id: /\d+/} + get "t/:topic_id/summary" => "topics#show", constraints: {topic_id: /\d+/} put "t/:slug/:topic_id" => "topics#update", constraints: {topic_id: /\d+/} put "t/:slug/:topic_id/star" => "topics#star", constraints: {topic_id: /\d+/} put "t/:topic_id/star" => "topics#star", constraints: {topic_id: /\d+/} @@ -21,20 +21,21 @@ module Email @to = to @opts = opts || {} - @template_args = {site_name: SiteSetting.email_prefix.presence || SiteSetting.title, - base_url: Discourse.base_url, - user_preferences_url: "#{Discourse.base_url}/my/preferences" }.merge!(@opts) + @template_args = { + site_name: SiteSetting.email_prefix.presence || SiteSetting.title, + base_url: Discourse.base_url, + user_preferences_url: "#{Discourse.base_url}/my/preferences", + }.merge!(@opts) if @template_args[:url].present? if @opts[:include_respond_instructions] == false @template_args[:respond_instructions] = '' else - @template_args[:respond_instructions] = - if allow_reply_by_email? - I18n.t('user_notifications.reply_by_email', @template_args) - else - I18n.t('user_notifications.visit_link_to_respond', @template_args) - end + @template_args[:respond_instructions] = if allow_reply_by_email? + I18n.t('user_notifications.reply_by_email', @template_args) + else + I18n.t('user_notifications.visit_link_to_respond', @template_args) + end end end end @@ -56,15 +57,15 @@ module Email def html_part return unless html_override = @opts[:html_override] - if @opts[:add_unsubscribe_link] + if @opts[:add_unsubscribe_link] if response_instructions = @template_args[:respond_instructions] respond_instructions = PrettyText.cook(response_instructions).html_safe html_override.gsub!("%{respond_instructions}", respond_instructions) end unsubscribe_link = PrettyText.cook(I18n.t('unsubscribe_link', template_args)).html_safe - html_override.gsub!("%{unsubscribe_link}",unsubscribe_link) + html_override.gsub!("%{unsubscribe_link}", unsubscribe_link) end
Leaderboard for this case
easy · 7 of 9 bots fully caught it (78% solve rate) · 89% avg coverage.
| # | Bot | Result | Caught | Coverage | Findings | False alarms |
|---|---|---|---|---|---|---|
| 1 | cursor | solved | 2/2 | 100.0% | 3 | 0 |
| 2 | Drape (Deep Review) | solved | 2/2 | 100.0% | 5 | 0 |
| 3 | Drape (Review) | solved | 2/2 | 100.0% | 2 | 0 |
| 4 | Mjolnir (Opus 5.5) | solved | 2/2 | 100.0% | 4 | 0 |
| 5 | Mjolnir (Sonnet 5.5) | solved | 2/2 | 100.0% | 4 | 0 |
| 6 | Claude Code (Opus 5.5) | solved | 2/2 | 100.0% | 5 | 1 |
| 7 | qodo | solved | 2/2 | 100.0% | 6 | 2 |
| 8 | Cubic | partial | 1/2 | 66.7% | 7 | 0 |
| 9 | greptile | partial | 1/2 | 33.3% | 1 | 0 |
Bot results
Claude Code (Opus 5.5) · cross-file engine perris 0.11.1+proven.tiered0.25.call.read.subclass.type
| Defect | Severity | Found | Grade |
|---|---|---|---|
| d1 | medium | ✓ | off by one |
| d2 | low | ✓ | wrong severity |
TopicView#initialize never loads topic_user. It is memoized lazily and first read by the serializer inside perform_show_response, which runs after tu.save!, so the preloaded notification_level is the new value. [invalid: contradiction] [consensus 3/3: invalid=3]
The server lowers watching/tracking users only to regular, and regular users are still notified of mentions and replies. The page shows the 'stop receiving notifications' text no matter which level was set, so the message is misleading. [grounded: diff] [consensus 3/3: valid=3]
The Ember route's model hook only loads the topic view JSON and never calls the server's unsubscribe action. Reaching the route by client-side navigation (for example, an internal link that Discourse routes in-app) shows the 'stop notifications' page without changing anything. [grounded: diff] [consensus 3/3: valid=3]
raw comments (5)
`TopicUser.find_by(...)` can return nil, for example when a user gets a notification email for a topic they never visited, or when their TopicUser row is missing. Calling `tu.notification_level` then raises NoMethodError and the unsubscribe link returns a 500. The code needs to handle nil, for example by using `TopicUser.change` or creating the row first.
The new GET endpoint changes state, and every visit toggles the level down a step. The first visit takes a watching/tracking user to regular; the next visit (reload, revisit, or mail scanners and link prefetchers following the email link) mutes the topic. As a result, users can end up muted without meaning to. Because it is a plain GET with no token, any third-party page can also trigger it for a logged-in user (CSRF via img/link), muting or downgrading notifications on arbitrary topics. A state change like this should be idempotent and protected, for example a signed per-user key in the URL or a confirmation POST.
`@topic_view` is built before the notification level changes, so `perform_show_response` preloads serialized topic data with the old `notification_level`. The client route loads from that preloaded data, so the notifications dropdown shows the previous state, not the level that was just set.
The page always says 'You will stop receiving notifications', but for watching/tracking users the server only lowers the level to regular, so they will still get notifications for replies and mentions. The message is misleading.
The client-side route only loads the topic and never calls the unsubscribe endpoint. If a user reaches `/t/:slug/:id/unsubscribe` by in-app (pushState) navigation, nothing changes, even though the page says they are unsubscribed.
Cubic · cross-file engine perris 0.11.1+proven.tiered0.25.call.read.subclass.type
| Defect | Severity | Found | Grade |
|---|---|---|---|
| d1 | medium | ✓ | exact |
| d2 | low | ✗ | — |
Removing the bogus post_number constraint makes the summary routes matchable. TopicView only filters when @filter == 'summary', and show only slices :filter (not :summary) from params, so these routes serve the full topic. [grounded: tree config/routes.rb] [consensus 4/5: valid=4, invalid=1]
MessageBuilder interpolates unsubscribe_link with template_args whenever add_unsubscribe_link is set. Any caller of the public builder that sets the flag without unsubscribe_url now raises MissingInterpolationArgument. The only in-repo caller passes the URL, so the impact falls on plugins and custom mailers. [grounded: tree config/locales/server.en.yml] [consensus 4/5: valid=4, uncertain=1]
save! leaves notifications_reason_id unset. update_last_read switches the level back to tracking when notifications_reason_id is null and the read-time threshold is exceeded, so the unsubscribe can be undone automatically. [grounded: diff] [consensus 5/5: valid=5]
IE11 does not support the `initial` keyword, so the rule is dropped there. This is a minor compatibility issue. [grounded: diff] [consensus 5/5: valid=5]
This is a naming typo. The name matches in both files, so nothing is broken today. [grounded: diff] [consensus 5/5: minor=5]
This asks for better test coverage. It does not claim the code misbehaves. [grounded: diff] [consensus 5/5: minor=5]
raw comments (8)
<!-- cubic:v=89c1a4ae-c5e4-4860-a93d-a728a30d78e5 -->
<!-- cubic:review-run=c429ec63-c8ee-5669-acb5-9361796360d7 -->
<!-- metadata:{"confidence":8} -->
P2: Requests to either newly matchable `/summary` route render the normal topic because `TopicsController#show` never passes `params[:summary]` to `TopicView`. Set the route default to `filter: "summary"` or explicitly propagate the summary parameter so the endpoint performs its advertised summary filtering.
<details>
<summary>Prompt for AI agents</summary>
```text
Check if this issue is valid — if so, understand the root cause and fix it. At config/routes.rb, line 439:
<comment>Requests to either newly matchable `/summary` route render the normal topic because `TopicsController#show` never passes `params[:summary]` to `TopicView`. Set the route default to `filter: "summary"` or explicitly propagate the summary parameter so the endpoint performs its advertised summary filtering.</comment>
<file context>
@@ -434,10 +434,12 @@
- get "t/:slug/:topic_id/summary" => "topics#show", defaults: {summary: true}, constraints: {topic_id: /\d+/, post_number: /\d+/}
- get "t/:topic_id/summary" => "topics#show", constraints: {topic_id: /\d+/, post_number: /\d+/}
+ get "t/:slug/:topic_id/moderator-liked" => "topics#moderator_liked", constraints: {topic_id: /\d+/}
+ get "t/:slug/:topic_id/summary" => "topics#show", defaults: {summary: true}, constraints: {topic_id: /\d+/}
+ get "t/:slug/:topic_id/unsubscribe" => "topics#unsubscribe", constraints: {topic_id: /\d+/}
+ get "t/:topic_id/unsubscribe" => "topics#unsubscribe", constraints: {topic_id: /\d+/}
</file context>
```
</details>
<!-- cubic:v=80d56fe1-2757-4fdd-af37-b830e702de5d -->
<!-- cubic:review-run=c429ec63-c8ee-5669-acb5-9361796360d7 -->
<!-- metadata:{"confidence":5} -->
P2: This change makes the shared `unsubscribe_link` translation require a new `%{unsubscribe_url}` interpolation. `lib/email/message_builder.rb` renders this key via `I18n.t('unsubscribe_link', template_args)` whenever `add_unsubscribe_link` is set, and I18n's default handler raises `MissingInterpolationArgument` when the placeholder is absent. The only in-repo caller passes `unsubscribe_url`, but any existing consumer of the public `build_email`/`MessageBuilder` helper (plugins, custom mailers) that set `add_unsubscribe_link: true` without this arg will now raise instead of sending. Consider guarding the second line with a blank check, or keeping the topic link in a separate key that callers opt into.
<details>
<summary>Prompt for AI agents</summary>
```text
Check if this issue is valid — if so, understand the root cause and fix it. At config/locales/server.en.yml, line 1855:
<comment>This change makes the shared `unsubscribe_link` translation require a new `%{unsubscribe_url}` interpolation. `lib/email/message_builder.rb` renders this key via `I18n.t('unsubscribe_link', template_args)` whenever `add_unsubscribe_link` is set, and I18n's default handler raises `MissingInterpolationArgument` when the placeholder is absent. The only in-repo caller passes `unsubscribe_url`, but any existing consumer of the public `build_email`/`MessageBuilder` helper (plugins, custom mailers) that set `add_unsubscribe_link: true` without this arg will now raise instead of sending. Consider guarding the second line with a blank check, or keeping the topic link in a separate key that callers opt into.</comment>
<file context>
@@ -1849,7 +1849,10 @@ en:
+ unsubscribe_link: |
+ To unsubscribe from these emails, visit your [user preferences](%{user_preferences_url}).
+
+ To stop receiving notifications about this particular topic, [click here](%{unsubscribe_url}).
subject_re: "Re: "
</file context>
```
</details>
<!-- cubic:v=fd1d70c0-11bf-46b0-aac3-23b473e27028 -->
<!-- cubic:review-run=c429ec63-c8ee-5669-acb5-9361796360d7 -->
<!-- metadata:{"confidence":8} -->
P2: Saving the level directly bypasses `TopicUser.change`, so the unsubscribe is not marked as a user change and can be re-enabled by automatic tracking. Use `TopicUser.change` here instead of `save!`.
<details>
<summary>Prompt for AI agents</summary>
```text
Check if this issue is valid — if so, understand the root cause and fix it. At app/controllers/topics_controller.rb, line 113:
<comment>Saving the level directly bypasses `TopicUser.change`, so the unsubscribe is not marked as a user change and can be re-enabled by automatic tracking. Use `TopicUser.change` here instead of `save!`.</comment>
<file context>
@@ -94,6 +95,26 @@ def show
+ tu.notification_level = TopicUser.notification_levels[:muted]
+ end
+
+ tu.save!
+
+ perform_show_response
</file context>
```
</details>
```suggestion
TopicUser.change(current_user.id, params[:topic_id], notification_level: tu.notification_level)
```
<!-- cubic:v=518b5431-f88a-442e-a5c9-6663d16a4da2 -->
<!-- cubic:review-run=c429ec63-c8ee-5669-acb5-9361796360d7 -->
<!-- metadata:{"confidence":9} -->
P2: When an authenticated user unsubscribes from a visible topic without an existing `TopicUser` row, `tu` is nil and this action returns a 500. Handle the missing row and persist the new level through `TopicUser.change`, which creates it.
<details>
<summary>Prompt for AI agents</summary>
```text
Check if this issue is valid — if so, understand the root cause and fix it. At app/controllers/topics_controller.rb, line 107:
<comment>When an authenticated user unsubscribes from a visible topic without an existing `TopicUser` row, `tu` is nil and this action returns a 500. Handle the missing row and persist the new level through `TopicUser.change`, which creates it.</comment>
<file context>
@@ -94,6 +95,26 @@ def show
+
+ tu = TopicUser.find_by(user_id: current_user.id, topic_id: params[:topic_id])
+
+ if tu.notification_level > TopicUser.notification_levels[:regular]
+ tu.notification_level = TopicUser.notification_levels[:regular]
+ else
</file context>
```
</details>
```suggestion
notification_level = if tu && tu.notification_level > TopicUser.notification_levels[:regular]
TopicUser.notification_levels[:regular]
else
TopicUser.notification_levels[:muted]
end
TopicUser.change(current_user.id, params[:topic_id], notification_level: notification_level)
```
<!-- cubic:v=14409c16-1267-4d48-a3cd-fa0c4a272ff1 -->
<!-- cubic:review-run=c429ec63-c8ee-5669-acb5-9361796360d7 -->
<!-- metadata:{"confidence":6} -->
P3: Use `bottom: auto` instead of `bottom: initial`. They resolve to the same value, `auto` is the convention already used in this codebase (desktop/topic-list.scss:277), and the `initial` keyword is unsupported in IE 11 and earlier, where this declaration is silently dropped and the menu keeps opening above the button.
<details>
<summary>Prompt for AI agents</summary>
```text
Check if this issue is valid — if so, understand the root cause and fix it. At app/assets/stylesheets/common/base/topic.scss, line 74:
<comment>Use `bottom: auto` instead of `bottom: initial`. They resolve to the same value, `auto` is the convention already used in this codebase (desktop/topic-list.scss:277), and the `initial` keyword is unsupported in IE 11 and earlier, where this declaration is silently dropped and the menu keeps opening above the button.</comment>
<file context>
@@ -63,3 +63,15 @@
+ float: none;
+ }
+ .dropdown-menu {
+ bottom: initial;
+ }
+ }
</file context>
```
</details>
```suggestion
bottom: auto;
```
<!-- cubic:v=8f3e9c5b-64b1-401c-ae66-00dab76ee98f -->
<!-- cubic:review-run=c429ec63-c8ee-5669-acb5-9361796360d7 -->
<!-- metadata:{"confidence":9} -->
P3: The property name `stopNotificiationsText` is misspelled ("Notificiations"). It currently works only because the controller defines the same typo, but anyone later renaming it to the correct spelling in one file will silently break the other. Rename to `stopNotificationsText` in both this template and `controllers/topic-unsubscribe.js.es6`.
<details>
<summary>Prompt for AI agents</summary>
```text
Check if this issue is valid — if so, understand the root cause and fix it. At app/assets/javascripts/discourse/templates/topic/unsubscribe.hbs, line 3:
<comment>The property name `stopNotificiationsText` is misspelled ("Notificiations"). It currently works only because the controller defines the same typo, but anyone later renaming it to the correct spelling in one file will silently break the other. Rename to `stopNotificationsText` in both this template and `controllers/topic-unsubscribe.js.es6`.</comment>
<file context>
@@ -0,0 +1,8 @@
+<div class="container">
+ <p>
+ {{{stopNotificiationsText}}}
+ </p>
+ <p>
</file context>
```
</details>
<!-- cubic:v=ca1644a0-be81-49b1-81d9-45bb2e211cc0 -->
<!-- cubic:review-run=c429ec63-c8ee-5669-acb5-9361796360d7 -->
<!-- metadata:{"confidence":8} -->
P3: The added unsubscribe_url option is never asserted, so the spec verifies none of the behavior it enables. Both existing tests pass whether or not the builder renders the topic-specific %{unsubscribe_url} link in the body, and the fixture uses a relative path (/t/1234/unsubscribe) instead of the absolute URL production sends (topic.unsubscribe_url = #{Discourse.base_url}/t/...), which is also invalid as an email link. Add an assertion that the body contains the unsubscribe link (e.g. expect(message_with_unsubscribe.body).to match('/t/1234/unsubscribe')) and mirror production by using an absolute fixture URL, so a regression that drops or relativizes the link is caught.
<details>
<summary>Prompt for AI agents</summary>
```text
Check if this issue is valid — if so, understand the root cause and fix it. At spec/components/email/message_builder_spec.rb, line 172:
<comment>The added unsubscribe_url option is never asserted, so the spec verifies none of the behavior it enables. Both existing tests pass whether or not the builder renders the topic-specific %{unsubscribe_url} link in the body, and the fixture uses a relative path (/t/1234/unsubscribe) instead of the absolute URL production sends (topic.unsubscribe_url = #{Discourse.base_url}/t/...), which is also invalid as an email link. Add an assertion that the body contains the unsubscribe link (e.g. expect(message_with_unsubscribe.body).to match('/t/1234/unsubscribe')) and mirror production by using an absolute fixture URL, so a regression that drops or relativizes the link is caught.</comment>
<file context>
@@ -168,7 +168,8 @@
body: 'hello world',
- add_unsubscribe_link: true) }
+ add_unsubscribe_link: true,
+ unsubscribe_url: "/t/1234/unsubscribe") }
it "has an List-Unsubscribe header" do
</file context>
```
</details>
<!-- cubic:review-summary:start -->
**7 issues found** across 18 files
<!-- cubic:review-summary:end -->
<details>
<summary>Prompt for AI agents (unresolved issues)</summary>
```text
Check if these issues are valid — if so, understand the root cause of each and fix them. If appropriate, use sub-agents to investigate and fix each issue separately.
<file name="config/routes.rb">
<violation number="1" location="config/routes.rb:439">
P2: Requests to either newly matchable `/summary` route render the normal topic because `TopicsController#show` never passes `params[:summary]` to `TopicView`. Set the route default to `filter: "summary"` or explicitly propagate the summary parameter so the endpoint performs its advertised summary filtering.</violation>
</file>
<file name="app/assets/stylesheets/common/base/topic.scss">
<violation number="1" location="app/assets/stylesheets/common/base/topic.scss:74">
P3: Use `bottom: auto` instead of `bottom: initial`. They resolve to the same value, `auto` is the convention already used in this codebase (desktop/topic-list.scss:277), and the `initial` keyword is unsupported in IE 11 and earlier, where this declaration is silently dropped and the menu keeps opening above the button.</violation>
</file>
<file name="config/locales/server.en.yml">
<violation number="1" location="config/locales/server.en.yml:1855">
P2: This change makes the shared `unsubscribe_link` translation require a new `%{unsubscribe_url}` interpolation. `lib/email/message_builder.rb` renders this key via `I18n.t('unsubscribe_link', template_args)` whenever `add_unsubscribe_link` is set, and I18n's default handler raises `MissingInterpolationArgument` when the placeholder is absent. The only in-repo caller passes `unsubscribe_url`, but any existing consumer of the public `build_email`/`MessageBuilder` helper (plugins, custom mailers) that set `add_unsubscribe_link: true` without this arg will now raise instead of sending. Consider guarding the second line with a blank check, or keeping the topic link in a separate key that callers opt into.</violation>
</file>
<file name="app/assets/javascripts/discourse/templates/topic/unsubscribe.hbs">
<violation number="1" location="app/assets/javascripts/discourse/templates/topic/unsubscribe.hbs:3">
P3: The property name `stopNotificiationsText` is misspelled ("Notificiations"). It currently works only because the controller defines the same typo, but anyone later renaming it to the correct spelling in one file will silently break the other. Rename to `stopNotificationsText` in both this template and `controllers/topic-unsubscribe.js.es6`.</violation>
</file>
<file name="app/controllers/topics_controller.rb">
<violation number="1" location="app/controllers/topics_controller.rb:107">
P2: When an authenticated user unsubscribes from a visible topic without an existing `TopicUser` row, `tu` is nil and this action returns a 500. Handle the missing row and persist the new level through `TopicUser.change`, which creates it.</violation>
<violation number="2" location="app/controllers/topics_controller.rb:113">
P2: Saving the level directly bypasses `TopicUser.change`, so the unsubscribe is not marked as a user change and can be re-enabled by automatic tracking. Use `TopicUser.change` here instead of `save!`.</violation>
</file>
<file name="spec/components/email/message_builder_spec.rb">
<violation number="1" location="spec/components/email/message_builder_spec.rb:172">
P3: The added unsubscribe_url option is never asserted, so the spec verifies none of the behavior it enables. Both existing tests pass whether or not the builder renders the topic-specific %{unsubscribe_url} link in the body, and the fixture uses a relative path (/t/1234/unsubscribe) instead of the absolute URL production sends (topic.unsubscribe_url = #{Discourse.base_url}/t/...), which is also invalid as an email link. Add an assertion that the body contains the unsubscribe link (e.g. expect(message_with_unsubscribe.body).to match('/t/1234/unsubscribe')) and mirror production by using an absolute fixture URL, so a regression that drops or relativizes the link is caught.</violation>
</file>
```
</details>
<sub>Reply with feedback, questions, or to request a fix.<br /><br />[Re-trigger cubic](https://www.cubic.dev/action/re-review/pr/drape-io/crbench-cubic-2026-09/31/ai_pr_review_github_delivery_8c6d166d88e5fc64358f3cd0a1c7ec3fa91e219663e66702781be903d2c29554?returnTo=https%3A%2F%2Fgithub.com%2Fdrape-io%2Fcrbench-cubic-2026-09%2Fpull%2F31)</sub>
<!-- cubic:review-post:ai_pr_review_github_delivery_8c6d166d88e5fc64358f3cd0a1c7ec3fa91e219663e66702781be903d2c29554:1ace5cfaf82bc675acdcefaace1eee21f9a73501:c429ec63-c8ee-5669-acb5-9361796360d7 -->
cursor · cross-file engine perris 0.11.1+proven.tiered0.25.call.read.subclass.type
| Defect | Severity | Found | Grade |
|---|---|---|---|
| d1 | medium | ✓ | off by one |
| d2 | low | ✓ | wrong severity |
The new unsubscribe action is added to ensure_logged_in. ApplicationController's NotLoggedIn handler redirects HTML GET requests with `redirect_to path("/")` and gives no login prompt, so a logged-out user who clicks the email link is sent to the homepage and the topic level is never changed. [grounded: diff] [consensus 5/5: valid=5]
raw comments (4)
### Unsubscribe crashes without TopicUser
**High Severity**
<!-- DESCRIPTION START -->
`unsubscribe` loads a `TopicUser` with `find_by` and immediately reads `notification_level` with no nil check. Visiting `/t/:slug/:id/unsubscribe` without an existing `topic_users` row raises `NoMethodError` and returns 500 instead of creating or updating the notification level. `TopicUser.change` already handles the missing-row case used elsewhere.
<!-- DESCRIPTION END -->
<!-- BUGBOT_BUG_ID: dfab66af-413d-4d6b-8e4f-71dba42b1c3c -->
<!-- LOCATIONS START
app/controllers/topics_controller.rb#L104-L113
LOCATIONS END -->
<div><a href="https://cursor.com/open?link=eyJ2ZXJzaW9uIjoxLCJ0eXBlIjoiQlVHQk9UX0ZJWF9JTl9DVVJTT1IiLCJkYXRhIjp7InJlZGlzS2V5IjoiYnVnYm90OmYzMTU1MTBjLWUxYTctNDA4My1hOWI4LWM5OGM1MTdhMWYwNSIsImVuY3J5cHRpb25LZXkiOiJnUDlZbExWcVl0NENzbU55YUQxN0VpaUpnUVIyenh6SjVocC1ZeUNaVUMwIiwiYnJhbmNoIjoidDItZGlzY291cnNlLWdyYXBoaXRlLTIiLCJyZXBvT3duZXIiOiJkcmFwZS1pbyIsInJlcG9OYW1lIjoiY3JiZW5jaC1jdXJzb3ItMjAyNi0wOSIsInByb3ZpZGVyIjoiZ2l0aHViIn19" target="_blank" rel="noopener noreferrer"><picture><source media="(prefers-color-scheme: dark)" srcset="https://cursor.com/assets/images/fix-in-cursor-dark.png"><source media="(prefers-color-scheme: light)" srcset="https://cursor.com/assets/images/fix-in-cursor-light.png"><img alt="Fix in Cursor" width="115" height="28" src="https://cursor.com/assets/images/fix-in-cursor-dark.png"></picture></a> <a href="https://cursor.com/agents?link=eyJ2ZXJzaW9uIjoxLCJ0eXBlIjoiQlVHQk9UX0ZJWF9JTl9XRUIiLCJkYXRhIjp7InJlZGlzS2V5IjoiYnVnYm90OmYzMTU1MTBjLWUxYTctNDA4My1hOWI4LWM5OGM1MTdhMWYwNSIsImVuY3J5cHRpb25LZXkiOiJnUDlZbExWcVl0NENzbU55YUQxN0VpaUpnUVIyenh6SjVocC1ZeUNaVUMwIiwiYnJhbmNoIjoidDItZGlzY291cnNlLWdyYXBoaXRlLTIiLCJyZXBvT3duZXIiOiJkcmFwZS1pbyIsInJlcG9OYW1lIjoiY3JiZW5jaC1jdXJzb3ItMjAyNi0wOSIsInByTnVtYmVyIjozMiwiY29tbWl0U2hhIjoiNzVjMzc0ZTIxOTU0NWYwMTNmMzlkMGNjZDhmNDY3YjM3NjBlYzg4ZiIsInByb3ZpZGVyIjoiZ2l0aHViIn19" target="_blank" rel="noopener noreferrer"><picture><source media="(prefers-color-scheme: dark)" srcset="https://cursor.com/assets/images/fix-in-web-dark.png"><source media="(prefers-color-scheme: light)" srcset="https://cursor.com/assets/images/fix-in-web-light.png"><img alt="Fix in Web" width="99" height="28" src="https://cursor.com/assets/images/fix-in-web-dark.png"></picture></a></div>
<sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit 75c374e219545f013f39d0ccd8f467b3760ec88f. Configure [here](https://www.cursor.com/dashboard/bugbot).</sup>
### Unsubscribe GET is not idempotent
**High Severity**
<!-- DESCRIPTION START -->
Every GET to `unsubscribe` steps the notification level down again: watching or tracking becomes regular, and any later request (refresh, prefetch, or a second click of the email link) then mutes the topic. A single intended unsubscribe can therefore overshoot to muted.
<!-- DESCRIPTION END -->
<!-- BUGBOT_BUG_ID: 00e9818f-5083-4939-935c-bdbfbe235ce9 -->
<!-- LOCATIONS START
app/controllers/topics_controller.rb#L106-L113
LOCATIONS END -->
<div><a href="https://cursor.com/open?link=eyJ2ZXJzaW9uIjoxLCJ0eXBlIjoiQlVHQk9UX0ZJWF9JTl9DVVJTT1IiLCJkYXRhIjp7InJlZGlzS2V5IjoiYnVnYm90OmQ2NzhjYTVkLTRjMGEtNDAyOC1hMjA0LTJmNzE5Mzk1MzMxYyIsImVuY3J5cHRpb25LZXkiOiJUVFpoeXpjbE5JZ1JBMG01NS1yaUNnY0h0alRDR2ZRNWpqWGxBUFNueHhVIiwiYnJhbmNoIjoidDItZGlzY291cnNlLWdyYXBoaXRlLTIiLCJyZXBvT3duZXIiOiJkcmFwZS1pbyIsInJlcG9OYW1lIjoiY3JiZW5jaC1jdXJzb3ItMjAyNi0wOSIsInByb3ZpZGVyIjoiZ2l0aHViIn19" target="_blank" rel="noopener noreferrer"><picture><source media="(prefers-color-scheme: dark)" srcset="https://cursor.com/assets/images/fix-in-cursor-dark.png"><source media="(prefers-color-scheme: light)" srcset="https://cursor.com/assets/images/fix-in-cursor-light.png"><img alt="Fix in Cursor" width="115" height="28" src="https://cursor.com/assets/images/fix-in-cursor-dark.png"></picture></a> <a href="https://cursor.com/agents?link=eyJ2ZXJzaW9uIjoxLCJ0eXBlIjoiQlVHQk9UX0ZJWF9JTl9XRUIiLCJkYXRhIjp7InJlZGlzS2V5IjoiYnVnYm90OmQ2NzhjYTVkLTRjMGEtNDAyOC1hMjA0LTJmNzE5Mzk1MzMxYyIsImVuY3J5cHRpb25LZXkiOiJUVFpoeXpjbE5JZ1JBMG01NS1yaUNnY0h0alRDR2ZRNWpqWGxBUFNueHhVIiwiYnJhbmNoIjoidDItZGlzY291cnNlLWdyYXBoaXRlLTIiLCJyZXBvT3duZXIiOiJkcmFwZS1pbyIsInJlcG9OYW1lIjoiY3JiZW5jaC1jdXJzb3ItMjAyNi0wOSIsInByTnVtYmVyIjozMiwiY29tbWl0U2hhIjoiNzVjMzc0ZTIxOTU0NWYwMTNmMzlkMGNjZDhmNDY3YjM3NjBlYzg4ZiIsInByb3ZpZGVyIjoiZ2l0aHViIn19" target="_blank" rel="noopener noreferrer"><picture><source media="(prefers-color-scheme: dark)" srcset="https://cursor.com/assets/images/fix-in-web-dark.png"><source media="(prefers-color-scheme: light)" srcset="https://cursor.com/assets/images/fix-in-web-light.png"><img alt="Fix in Web" width="99" height="28" src="https://cursor.com/assets/images/fix-in-web-dark.png"></picture></a></div>
<sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit 75c374e219545f013f39d0ccd8f467b3760ec88f. Configure [here](https://www.cursor.com/dashboard/bugbot).</sup>
### Logged-out email unsubscribe does nothing
**High Severity**
<!-- DESCRIPTION START -->
`unsubscribe` is behind `ensure_logged_in`, but the new email link is meant to be clicked from a notification. On public sites a logged-out GET raises `NotLoggedIn` and redirects to `/` with no login prompt, so the topic is never unsubscribed and the user gets no confirmation.
<!-- DESCRIPTION END -->
<!-- BUGBOT_BUG_ID: e1b394e2-eb07-4a8b-ab53-5c4efc733afe -->
<!-- LOCATIONS START
app/controllers/topics_controller.rb#L7-L28
app/controllers/topics_controller.rb#L97-L116
LOCATIONS END -->
<details>
<summary>Additional Locations (1)</summary>
- [`app/controllers/topics_controller.rb#L97-L116`](https://github.com/drape-io/crbench-cursor-2026-09/blob/75c374e219545f013f39d0ccd8f467b3760ec88f/app/controllers/topics_controller.rb#L97-L116)
</details>
<div><a href="https://cursor.com/open?link=eyJ2ZXJzaW9uIjoxLCJ0eXBlIjoiQlVHQk9UX0ZJWF9JTl9DVVJTT1IiLCJkYXRhIjp7InJlZGlzS2V5IjoiYnVnYm90Ojc3Nzc2ZTJlLTQwNDQtNDAwNi1hMjhlLTdmYzQ1MzA0YTk5NyIsImVuY3J5cHRpb25LZXkiOiJuSEV0aXM3SHVCT1YtUUVZNTJwQ253YTJkLVRKbGt5UTB1RkdyY2RKVzBBIiwiYnJhbmNoIjoidDItZGlzY291cnNlLWdyYXBoaXRlLTIiLCJyZXBvT3duZXIiOiJkcmFwZS1pbyIsInJlcG9OYW1lIjoiY3JiZW5jaC1jdXJzb3ItMjAyNi0wOSIsInByb3ZpZGVyIjoiZ2l0aHViIn19" target="_blank" rel="noopener noreferrer"><picture><source media="(prefers-color-scheme: dark)" srcset="https://cursor.com/assets/images/fix-in-cursor-dark.png"><source media="(prefers-color-scheme: light)" srcset="https://cursor.com/assets/images/fix-in-cursor-light.png"><img alt="Fix in Cursor" width="115" height="28" src="https://cursor.com/assets/images/fix-in-cursor-dark.png"></picture></a> <a href="https://cursor.com/agents?link=eyJ2ZXJzaW9uIjoxLCJ0eXBlIjoiQlVHQk9UX0ZJWF9JTl9XRUIiLCJkYXRhIjp7InJlZGlzS2V5IjoiYnVnYm90Ojc3Nzc2ZTJlLTQwNDQtNDAwNi1hMjhlLTdmYzQ1MzA0YTk5NyIsImVuY3J5cHRpb25LZXkiOiJuSEV0aXM3SHVCT1YtUUVZNTJwQ253YTJkLVRKbGt5UTB1RkdyY2RKVzBBIiwiYnJhbmNoIjoidDItZGlzY291cnNlLWdyYXBoaXRlLTIiLCJyZXBvT3duZXIiOiJkcmFwZS1pbyIsInJlcG9OYW1lIjoiY3JiZW5jaC1jdXJzb3ItMjAyNi0wOSIsInByTnVtYmVyIjozMiwiY29tbWl0U2hhIjoiNzVjMzc0ZTIxOTU0NWYwMTNmMzlkMGNjZDhmNDY3YjM3NjBlYzg4ZiIsInByb3ZpZGVyIjoiZ2l0aHViIn19" target="_blank" rel="noopener noreferrer"><picture><source media="(prefers-color-scheme: dark)" srcset="https://cursor.com/assets/images/fix-in-web-dark.png"><source media="(prefers-color-scheme: light)" srcset="https://cursor.com/assets/images/fix-in-web-light.png"><img alt="Fix in Web" width="99" height="28" src="https://cursor.com/assets/images/fix-in-web-dark.png"></picture></a></div>
<sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit 75c374e219545f013f39d0ccd8f467b3760ec88f. Configure [here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- BUGBOT_REVIEW -->
Cursor Bugbot has reviewed your changes using high effort and found 3 potential issues.
<!-- BUGBOT_FIX_ALL -->
<a href="https://cursor.com/open?link=eyJ2ZXJzaW9uIjoxLCJ0eXBlIjoiQlVHQk9UX0ZJWF9BTExfSU5fQ1VSU09SIiwiZGF0YSI6eyJyZWRpc0tleSI6ImJ1Z2JvdC1tdWx0aTpkNzFkODcxNS0zYmYxLTQ5YjYtOTdlNC05MDY4Yjk0Y2M2OWYiLCJlbmNyeXB0aW9uS2V5IjoiTVFnMkFRTWNhMlduNzhQbUlZOUl1X3RaYW53YTJsX1NlVXp3Vy1MM0E0YyIsImJyYW5jaCI6InQyLWRpc2NvdXJzZS1ncmFwaGl0ZS0yIiwicmVwb093bmVyIjoiZHJhcGUtaW8iLCJyZXBvTmFtZSI6ImNyYmVuY2gtY3Vyc29yLTIwMjYtMDkiLCJwcm92aWRlciI6ImdpdGh1YiJ9fQ" target="_blank" rel="noopener noreferrer"><picture><source media="(prefers-color-scheme: dark)" srcset="https://cursor.com/assets/images/fix-in-cursor-dark.png"><source media="(prefers-color-scheme: light)" srcset="https://cursor.com/assets/images/fix-in-cursor-light.png"><img alt="Fix All in Cursor" width="115" height="28" src="https://cursor.com/assets/images/fix-in-cursor-dark.png"></picture></a>
<!-- /BUGBOT_FIX_ALL -->
<!-- BUGBOT_AUTOFIX_REVIEW_FOOTNOTE_BEGIN -->
<sup>❌ Bugbot Autofix is OFF. To automatically fix reported issues with cloud agents, enable autofix in the [Cursor dashboard](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- BUGBOT_AUTOFIX_REVIEW_FOOTNOTE_END -->
<sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit 75c374e219545f013f39d0ccd8f467b3760ec88f. Configure [here](https://www.cursor.com/dashboard/bugbot).</sup>
Drape (Deep Review) · cross-file engine perris 0.11.1+proven.tiered0.25.call.read.subclass.type
| Defect | Severity | Found | Grade |
|---|---|---|---|
| d1 | medium | ✓ | exact |
| d2 | low | ✓ | off by one |
The GET unsubscribe action steps the level down by one on every request (watching/tracking→regular, regular→muted), so a page reload or a second email link mutes the topic. [grounded: diff] [consensus 3/3: valid=3]
The new action sets notification_level and calls tu.save! directly. That skips TopicUser.change, which sets notifications_reason_id and notifications_changed_at and publishes the MessageBus update, as set_notifications does. [grounded: diff] [consensus 3/3: valid=3]
Watched or tracked topics only drop to regular, and regular still notifies on mentions and replies. The new page text says the user 'will stop receiving notifications', which is untrue for these users. [grounded: diff] [consensus 3/3: valid=3]
raw comments (5)
**Unsubscribe crashes when user has no TopicUser row**
If the user never had a TopicUser row for this topic (e.g. only @mentioned, never opened it), `find_by` returns nil and `tu.notification_level` raises a 500. Use `TopicUser.change` and treat a missing row as regular.
```
app/controllers/topics_controller.rb:105 tu = TopicUser.find_by(user_id: current_user.id, topic_id: params[:topic_id])
app/controllers/topics_controller.rb:107 if tu.notification_level > TopicUser.notification_levels[:regular]
app/controllers/topics_controller.rb:108 tu.notification_level = TopicUser.notification_levels[:regular]
app/controllers/topics_controller.rb:109 else
app/models/topic_user.rb:120 def track_visit!(topic,user)
app/models/topic_user.rb:121 topic_id = topic.is_a?(Topic) ? topic.id : topic
app/models/topic_user.rb:122 user_id = user.is_a?(User) ? user.id : topic
app/models/topic_user.rb:124 now = DateTime.now
app/models/topic_user.rb:125 rows = TopicUser.where(topic_id: topic_id, user_id: user_id).update_all(last_visited_at: now)
app/models/topic_user.rb:126 if rows == 0
```
**Image or cross-site GET unsubscribes users**
A plain GET with no token changes the notification level. An `<img>` pointing at this URL, in a post or on another site, or a link prefetcher mutes the topic for whoever loads it. Have the GET only show the page, and make the change through a CSRF-protected POST/PUT.
```
app/controllers/topics_controller.rb:98 def unsubscribe
app/controllers/topics_controller.rb:99 @topic_view = TopicView.new(params[:topic_id], current_user)
app/controllers/topics_controller.rb:101 if slugs_do_not_match || (!request.format.json? && params[:slug].blank?)
app/controllers/topics_controller.rb:102 return redirect_to @topic_view.topic.unsubscribe_url, status: 301
app/controllers/topics_controller.rb:107 if tu.notification_level > TopicUser.notification_levels[:regular]
app/controllers/topics_controller.rb:108 tu.notification_level = TopicUser.notification_levels[:regular]
app/controllers/topics_controller.rb:109 else
app/controllers/topics_controller.rb:110 tu.notification_level = TopicUser.notification_levels[:muted]
app/controllers/topics_controller.rb:111 end
app/controllers/topics_controller.rb:113 tu.save!
```
**Reloading unsubscribe page mutes the topic**
Each visit lowers the level one more step. Watching drops to regular, then a refresh or a second email's link mutes the topic, which the user never chose. Set one fixed target level so repeat visits change nothing.
```
app/controllers/topics_controller.rb:107 if tu.notification_level > TopicUser.notification_levels[:regular]
app/controllers/topics_controller.rb:108 tu.notification_level = TopicUser.notification_levels[:regular]
app/controllers/topics_controller.rb:109 else
app/controllers/topics_controller.rb:110 tu.notification_level = TopicUser.notification_levels[:muted]
app/controllers/topics_controller.rb:111 end
```
**Unsubscribe skips the usual notification bookkeeping**
This saves the record directly, unlike `set_notifications`, which goes through `TopicUser.change`. So `notifications_reason_id` and `notifications_changed_at` are never set, and no MessageBus update reaches the user's open tabs. Use `TopicUser.change(current_user, topic_id, notification_level: ...)`.
```
app/controllers/topics_controller.rb:107 if tu.notification_level > TopicUser.notification_levels[:regular]
app/controllers/topics_controller.rb:108 tu.notification_level = TopicUser.notification_levels[:regular]
app/controllers/topics_controller.rb:109 else
app/controllers/topics_controller.rb:110 tu.notification_level = TopicUser.notification_levels[:muted]
app/models/topic_user.rb:87 if attrs[:notification_level]
app/models/topic_user.rb:88 attrs[:notifications_changed_at] ||= DateTime.now
app/models/topic_user.rb:89 attrs[:notifications_reason_id] ||= TopicUser.notification_reasons[:user_changed]
app/models/topic_user.rb:90 end
app/models/topic_user.rb:112 if attrs[:notification_level]
app/models/topic_user.rb:113 MessageBus.publish("/topic/#{topic_id}", { notification_level_change: attrs[:notification_level] }, user_ids: [user_id])
```
**Unsubscribing from a watched topic still sends notifications**
For tracking or watching users, `unsubscribe` only drops the level to regular. Regular users still get reply and mention notifications, yet the page says they will stop receiving notifications. Mute the topic, or change the page text to say what really happens.
```
app/controllers/topics_controller.rb:107 if tu.notification_level > TopicUser.notification_levels[:regular]
app/controllers/topics_controller.rb:108 tu.notification_level = TopicUser.notification_levels[:regular]
app/controllers/topics_controller.rb:109 else
app/controllers/topics_controller.rb:110 tu.notification_level = TopicUser.notification_levels[:muted]
app/controllers/topics_controller.rb:111 end
config/locales/client.en.yml:985 stop_notifications: "You will stop receiving notifications for <strong>{{title}}</strong>."
```
Drape (Review) · cross-file engine perris 0.11.1+proven.tiered0.25.call.read.subclass.type
| Defect | Severity | Found | Grade |
|---|---|---|---|
| d1 | medium | ✓ | exact |
| d2 | low | ✓ | off by one |
raw comments (2)
**Reloading unsubscribe page mutes the topic**
`unsubscribe` toggles state on a plain GET. The first visit lowers the level to regular; any repeat visit (refresh, link prefetch) sets it to muted. Make the action idempotent, and don't change state on GET.
```
app/controllers/topics_controller.rb:107 if tu.notification_level > TopicUser.notification_levels[:regular]
app/controllers/topics_controller.rb:108 tu.notification_level = TopicUser.notification_levels[:regular]
app/controllers/topics_controller.rb:109 else
app/controllers/topics_controller.rb:110 tu.notification_level = TopicUser.notification_levels[:muted]
```
**Unsubscribe link returns 500 without topic_users row**
A logged-in user with no topic_users row for the topic gets a 500, because `TopicUser.find_by` returns nil and `tu.notification_level` is then called on nil. This happens, for example, with a forwarded unsubscribe link. Use `TopicUser.change`, or handle the nil case, before reading the level.
```
app/controllers/topics_controller.rb:105 tu = TopicUser.find_by(user_id: current_user.id, topic_id: params[:topic_id])
app/controllers/topics_controller.rb:107 if tu.notification_level > TopicUser.notification_levels[:regular]
app/controllers/topics_controller.rb:108 tu.notification_level = TopicUser.notification_levels[:regular]
app/controllers/topics_controller.rb:109 else
```
greptile · cross-file engine perris 0.11.1+proven.tiered0.25.call.read.subclass.type
| Defect | Severity | Found | Grade |
|---|---|---|---|
| d1 | medium | ✗ | — |
| d2 | low | ✓ | wrong severity |
raw comments (2)
<a href="#"><img alt="P1" src="https://greptile-static-assets.s3.amazonaws.com/badges/p1.svg?v=9" align="top"></a> <a href="#"><img alt="security" src="https://greptile-static-assets.s3.amazonaws.com/badges/Security.svg?v=2" align="top"></a> **GET Mutates Notification Settings**
These GET routes reach an authenticated action that changes and saves the current user's topic notification level. Because GET requests do not require an authenticity token and this action allows non-XHR navigation, another site or an automated email-link fetch can request the URL with the user's active session and change their notification settings without consent. The mutation should use a CSRF-protected, non-GET request, with GET reserved for displaying a confirmation page.
**How this was verified:** The GET route reaches an authenticated action that directly persists the current user's notification level without any request-integrity check.
<h3>Greptile Summary</h3>
This PR adds per-topic unsubscribe links to notification emails and a dedicated page for managing the resulting notification state.
- Adds server and client routes, controller logic, UI, styling, and localized text for topic unsubscribe.
- Adds the topic-specific URL to notification emails and updates email rendering.
- Refactors several adjacent JavaScript, Ruby, template, and model sections.
- The new endpoint currently performs its state change through a cross-site-triggerable GET request.
<h3>Confidence Score: 3/5</h3>
This PR is not safe to merge until the notification mutation is moved behind a CSRF-protected, non-GET request.
The new public GET route performs an authenticated notification-setting mutation, so cross-site requests and automated email-link fetches can change user preferences without authorization.
**Files Needing Attention:** config/routes.rb, app/controllers/topics_controller.rb
<details open><summary><h3>Security Review</h3></summary>
The new GET unsubscribe endpoint persists notification-setting changes without request integrity, allowing forced changes through cross-site navigation or automated link fetching.
</details>
<details><summary><h3>Important Files Changed</h3></summary>
| Filename | Overview |
|----------|----------|
| app/controllers/topics_controller.rb | Adds the unsubscribe action, but directly persists notification state from a GET request. |
| config/routes.rb | Exposes both canonical and slugless unsubscribe mutations as GET routes. |
| app/mailers/user_notifications.rb | Adds the generated topic-specific unsubscribe URL to notification-email options. |
| lib/email/message_builder.rb | Renders the expanded unsubscribe translation into HTML and text email parts. |
| app/assets/javascripts/discourse/templates/topic/unsubscribe.hbs | Adds the unsubscribe explanation and topic-notification selector UI. |
| app/models/topic.rb | Adds an absolute topic unsubscribe URL derived from the canonical topic URL. |
</details>
<details open><summary><h3>Sequence Diagram</h3></summary>
```mermaid
sequenceDiagram
participant A as External site / link preview
participant B as Authenticated browser
participant R as GET unsubscribe route
participant C as TopicsController
participant DB as TopicUser
A->>B: Request unsubscribe URL
B->>R: GET with session cookie
R->>C: unsubscribe(topic_id)
C->>DB: Change notification_level
DB-->>C: Persisted
C-->>B: Render topic page
```
</details>
<!-- greptile_other_comments_section -->
<sub>Reviews (1): Last reviewed commit: ["Update app/assets/javascripts/discourse/..."](https://github.com/drape-io/crbench-greptile-2026-09/commit/a0bb59591c23fc114a98e03312dcdab7c08eb1df) | [Re-trigger Greptile](https://app.greptile.com/api/retrigger?id=64284356)</sub>
Mjolnir (Opus 5.5) · cross-file engine perris 0.11.1+proven.tiered0.25.call.read.subclass.type
| Defect | Severity | Found | Grade |
|---|---|---|---|
| d1 | medium | ✓ | exact |
| d2 | low | ✓ | off by one |
The new action dereferences the result of TopicUser.find_by without a nil check. The specific example is weak, because send_notification_email calls TopicUser.change, which creates the row when the email is sent. The crash is still reachable when the row is missing: for example, after reset_read/destroy_timings deletes topic_users rows, or when a logged-in user opens the public URL for a topic they have no row for. [grounded: diff] [consensus 3/3: valid=3]
The GET action steps the level down from what it currently is rather than setting a fixed target. A second request on a topic already at regular therefore mutes it, so a reload or a link prefetch silently mutes the topic. [grounded: diff] [consensus 3/3: valid=3]
raw comments (4)
[P1] Unsubscribe crashes when the user has no TopicUser row for the topic
app/controllers/topics_controller.rb:105-107 `TopicUser.find_by(...)` returns nil when the user has never had a `topic_users` row for the topic, and `tu.notification_level` then raises `NoMethodError`, so the request fails with a 500. Every notification email now includes the "click here" unsubscribe link, so this happens to real users. One example is someone who is @mentioned or quoted in a topic they have never visited: they get the email, click the link, and see an error page instead of being unsubscribed. The action should create the row if it is missing (for example via `TopicUser.change`/`find_or_initialize_by`) or handle nil.
[P2] Loading the unsubscribe URL again lowers the level a second time and mutes the topic
app/controllers/topics_controller.rb:107-111 This GET action switches the level instead of setting it to a fixed target value. A watching or tracking user is set to regular on the first visit. If they reload the page, open the email link again, or a mail client's link scanner or prefetcher fetches the URL, a second request sees `regular` and sets the topic to `muted`. The user ends up fully muted without choosing that, and the confirmation page does not tell them. The result should be the same no matter how many times the URL is requested.
[P2] Unsubscribe crashes when the user has no TopicUser row
`TopicUser.find_by(...)` returns nil when the logged-in user has no `topic_users` row for the topic. The next line, `tu.notification_level`, then raises NoMethodError and the user gets a 500 instead of the unsubscribe page. This happens when a user opens `/t/:slug/:id/unsubscribe` for a topic they have never interacted with, for example from an email that was forwarded to them or by typing the URL. Using `TopicUser.change`, or handling the nil case (create the row or default to regular), would avoid the error.
[P2] Each load of the unsubscribe URL lowers the notification level again
The GET action reads the current level and moves it down one step every time it runs: watching/tracking become regular, and regular becomes muted. A user who is watching a topic and clicks the email link ends up at regular. If they reload the page, open the link a second time, or the browser restores the tab, the topic silently becomes muted. Because a plain GET changes state, any page that embeds the URL (for example in an `‹img›` tag) can also make a logged-in user's request mute the topic. The level change should be idempotent: compute it once, for example always set it to regular or muted. Better still, do it through a non-GET or tokenized request.
Mjolnir (Sonnet 5.5) · cross-file engine perris 0.11.1+proven.tiered0.25.call.read.subclass.type
| Defect | Severity | Found | Grade |
|---|---|---|---|
| d1 | medium | ✓ | exact |
| d2 | low | ✓ | off by one |
The new GET action lowers the level from above-regular to regular, and otherwise to muted. A second visit to the same link therefore mutes a user who was originally watching or tracking. [grounded: diff] [consensus 3/3: valid=3]
`find_by` can return nil, for example when any logged-in user opens a topic's unsubscribe URL without having a topic_users row. Nothing guards against nil before `tu.notification_level`, so the request raises NoMethodError. [grounded: diff] [consensus 3/3: valid=3]
raw comments (4)
[P2] Unsubscribe GET is non-idempotent and can mute the topic
The action lowers the level from above-regular to regular, otherwise sets it to muted, on every GET. If a user follows the email link and the page is reloaded, the link is opened twice, or a mail client or link scanner prefetches the URL, a watching or tracking user ends up muted instead of regular. The second request sees "regular" and escalates to "muted". The state change should be idempotent, for example only drop to regular, or only mute from an explicit action.
[P2] Unsubscribe crashes when the user has no TopicUser row
`TopicUser.find_by(user_id:, topic_id:)` returns nil when the user has no TopicUser record for the topic. This can happen if the user got the email through category or global watching and never visited the topic, or if the link is opened by a different logged-in user. `tu.notification_level` then raises NoMethodError and the page returns a 500. A nil `notification_level` would also raise on the `›` comparison. Use `TopicUser.change` or handle the missing-record case.
[P2] Unsubscribe GET toggles state on every request
The action changes the notification level on each GET: anything above regular drops to regular, anything else (including regular, which is what the first visit just produced) goes to muted. A page reload, a second click on the email link, or an email client or security scanner pre-fetching the link will therefore silently escalate "stop notifications" into fully muting the topic. The page text only promises "You will stop receiving notifications", and the page doesn't reflect that a second visit mutes. The state change should be idempotent, for example by only lowering levels above regular. It also arguably shouldn't happen on a GET.
[P2] Missing TopicUser row raises NoMethodError
`TopicUser.find_by(...)` can return nil, for example when a logged-in user opens another user's unsubscribe link, or when the user has no topic_users row for that topic. `tu.notification_level` then raises NoMethodError and returns a 500 instead of handling the missing record. Use `TopicUser.change`, or guard for nil.
qodo · cross-file engine perris 0.11.1+proven.tiered0.25.call.read.subclass.type
| Defect | Severity | Found | Grade |
|---|---|---|---|
| d1 | medium | ✓ | off by one |
| d2 | low | ✓ | wrong severity |
Discourse's custom resolver decamelizes 'topicUnsubscribe' to 'topic_unsubscribe' and also tries replacing the first underscore with '/', which gives 'topic/unsubscribe'. That matches the new template's path, so the template does resolve. [invalid: contradiction] [consensus 3/3: invalid=3]
Muted is 0 and regular is 1. For a muted user, `0 > 1` is false, so the else branch keeps the level at muted. The claimed muted→regular flip cannot happen. [invalid: contradiction] [consensus 3/3: invalid=3]
Only server.en.yml was updated. Other locales such as pt_BR, nl and ro still define unsubscribe_link with only %{user_preferences_url}, so emails in those locales won't show the per-topic link. Translations are normally synced later, so the impact is low. [grounded: diff] [consensus 3/3: valid=3]
The unsubscribe action is behind ensure_logged_in, and unsubscribe_url carries no token. ApplicationController handles NotLoggedIn on a non-xhr GET with `redirect_to path("/")`, so a signed-out recipient who clicks the email link lands on the home page and stays subscribed. [grounded: diff] [consensus 3/3: valid=3]
raw comments (8)
<img src="https://img.shields.io/badge/High-634FD1?style=flat-square" height="20px" alt="Action required">
1\. Users cannot see unsubscribe controls <code>🐞 Bug</code> <code>≡ Correctness</code>
<pre>
<b><i>topicUnsubscribe</i></b> is declared as a top-level route, but its markup is stored under the nested
<b><i>topic/unsubscribe</i></b> template name. When Ember enters the new URL it resolves the top-level
<b><i>topic-unsubscribe</i></b> template instead, so the explanatory text and notification button are not
rendered.
</pre>
<details>
<summary><strong>Agent Prompt</strong></summary>
```
## Issue description
The top-level topicUnsubscribe route does not resolve the nested topic/unsubscribe template added by this change.
## Fix Focus Areas
- app/assets/javascripts/discourse/routes/app-route-map.js.es6[8-13]
- app/assets/javascripts/discourse/templates/topic/unsubscribe.hbs[1-8]
- app/assets/javascripts/discourse/routes/topic-unsubscribe.js.es6[1-23]
## Recommended Fix
Move the template to `app/assets/javascripts/discourse/templates/topic-unsubscribe.hbs` so it matches the existing top-level route, controller, and view names, or redefine all of those components consistently as a nested topic route.
```
<code>ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools</code>
</details>
<img src="https://img.shields.io/badge/High-634FD1?style=flat-square" height="20px" alt="Action required">
2\. Other sites can disable a member's topic alerts <code>🐞 Bug</code> <code>⛨ Security</code>
<pre>
<b><i>TopicsController#unsubscribe</i></b> changes and saves the current user’s <b><i>tu.notification_level</i></b> through
predictable GET routes while explicitly bypassing the XHR check. A cross-site navigation, embedded
request, or automatic link fetch carrying an authenticated session can trigger either the
regular-to-muted or watching-to-regular transition without an intentional in-app action or CSRF
validation.
</pre>
<details>
<summary><strong>Agent Prompt</strong></summary>
```
## Issue description
The unsubscribe endpoint persists notification-level changes through GET URLs, allowing authenticated cross-site requests and automatic link fetching to modify a member’s topic notification state.
## Fix Focus Areas
- app/controllers/topics_controller.rb[98-115]
- config/routes.rb[440-441]
## Recommended Fix
Keep the GET or email landing URL read-only and have it render a confirmation page without modifying state. Apply the notification-level update only after an explicit POST or PUT submission protected by the normal CSRF checks, or use another signed, user-bound mechanism before performing the change.
```
<code>ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools</code>
</details>
<img src="https://img.shields.io/badge/High-634FD1?style=flat-square" height="20px" alt="Action required">
3\. Some members hit an error instead of unsubscribing <code>🐞 Bug</code> <code>☼ Reliability</code>
<pre>
<b><i>TopicsController#unsubscribe</i></b> uses nullable <b><i>TopicUser.find_by</i></b>, then immediately reads
<b><i>notification_level</i></b> from and saves the result without handling a missing row. Any authenticated
member who can view the topic but lacks a corresponding <b><i>TopicUser</i></b> row reaches this path and raises
<b><i>NoMethodError</i></b> before the page is returned or the requested notification state is persisted.
</pre>
<details>
<summary><strong>Agent Prompt</strong></summary>
```
## Issue description
The unsubscribe action assumes every authorized user already has a `TopicUser` row, although `find_by` can return nil, causing a nil dereference instead of applying the requested notification-state change.
## Fix Focus Areas
- app/controllers/topics_controller.rb[105-113]
- app/models/topic_user.rb[74-117]
## Recommended Fix
Resolve a missing record to the default regular notification level and persist the target state through `TopicUser.change`, or use an equivalent create-or-update operation before reading and updating the level. Do not directly dereference the result of `find_by`; ensure absent rows are handled while preserving the normal notification metadata and publication behavior.
```
<code>ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools</code>
</details>
<img src="https://img.shields.io/badge/High-634FD1?style=flat-square" height="20px" alt="Action required">
4\. Repeated unsubscribe links restore topic alerts <code>🐞 Bug</code> <code>≡ Correctness</code>
<pre>
<b><i>TopicsController#unsubscribe</i></b> treats every level at or below <b><i>regular</i></b>, including <b><i>muted</i></b>, as a
request to set the level back to <b><i>muted</i></b> only after first setting higher levels to <b><i>regular</i></b>. When a
member who is already muted follows the same email link again, the condition selects <b><i>regular</i></b>, so
the persisted state re-enables normal topic notifications.
</pre>
<details>
<summary><strong>Agent Prompt</strong></summary>
```
## Issue description
Following an unsubscribe URL more than once can change an already-muted topic back to regular notifications, making the unsubscribe operation non-idempotent.
## Fix Focus Areas
- app/controllers/topics_controller.rb[107-113]
- app/models/topic_user.rb[18-21]
## Recommended Fix
Set the intended unsubscribe notification level unconditionally, rather than toggling based on the current level. Use the standard TopicUser update path so repeated requests preserve the same final state.
```
<code>ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools</code>
</details>
<img src="https://img.shields.io/badge/Medium-634FD1?style=flat-square" height="20px" alt="Remediation recommended">
5\. Non-english emails omit the topic unsubscribe link <code>🐞 Bug</code> <code>≡ Correctness</code>
<pre>
Only the English <b><i>unsubscribe_link</i></b> translation adds <b><i>%{unsubscribe_url}</i></b>, while the existing
localized translations retain only <b><i>%{user_preferences_url}</i></b>. When notification mail is generated
under those locales, <b><i>MessageBuilder</i></b> selects that locale's existing key and the newly supplied
topic URL is never rendered in either email body.
</pre>
<details>
<summary><strong>Agent Prompt</strong></summary>
```
## Issue description
The topic-specific unsubscribe URL is present only in the English `unsubscribe_link` translation, so localized notification emails do not include the new per-topic action.
## Fix Focus Areas
- config/locales/server.en.yml[1852-1855]
- config/locales/server.de.yml[1343-1343]
- config/locales/server.es.yml[1515-1515]
## Recommended Fix
Add the `%{unsubscribe_url}` topic-unsubscribe sentence to every locale that defines `unsubscribe_link`, preserving each locale's existing global preferences link. Add or update translation checks so localized variants continue to include the new interpolation.
```
<code>ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools</code>
</details>
<img src="https://img.shields.io/badge/Medium-634FD1?style=flat-square" height="20px" alt="Remediation recommended">
6\. Signed-out email recipients cannot unsubscribe <code>🐞 Bug</code> <code>≡ Correctness</code>
<pre>
The new <b><i>unsubscribe</i></b> action is protected by <b><i>ensure_logged_in</i></b>, but <b><i>Topic#unsubscribe_url</i></b> embeds
no recipient-bound authentication information. When an email recipient has no active session, the
raised <b><i>Discourse::NotLoggedIn</i></b> is redirected to the site root, leaving the topic notification state
unchanged.
</pre>
<details>
<summary><strong>Agent Prompt</strong></summary>
```
## Issue description
The topic-specific unsubscribe link sent in notification emails cannot change preferences unless the recipient is already authenticated, despite being presented as a direct unsubscribe action.
## Fix Focus Areas
- app/controllers/topics_controller.rb[8-32]
- app/controllers/topics_controller.rb[98-115]
- app/models/topic.rb[719-721]
- app/mailers/user_notifications.rb[292-295]
## Recommended Fix
Provide a signed, expiring, recipient-bound unsubscribe URL for email recipients and validate it before applying the change, or change the email flow to explicitly require sign-in and preserve the destination through authentication. Do not remove authentication without adding a user-bound authorization mechanism.
```
<code>ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools</code>
</details>
<h3>PR Summary by Qodo</h3>
Add per-topic unsubscribe links to notification emails
<code>✨ Enhancement</code> <code>🧪 Tests</code> <code>🕐 20-40 Minutes</code>
<img src="https://www.qodo.ai/wp-content/uploads/2025/11/light-grey-line.svg" height="10%" alt="Grey Divider">
<details>
<summary>AI Description</summary>
<dl>
<dd>
<br/>
><pre>
>• Adds topic-specific unsubscribe links to notification emails.
>• Introduces authenticated routes that lower topic notification levels.
>• Presents localized controls for reviewing or changing the resulting notification state.
></pre>
</dd>
</dl>
</details>
<details>
<summary>Diagram</summary>
<dl>
<dd>
<br/>
```mermaid
sequenceDiagram
actor U as User
participant E as Notification Email
participant R as Topic Routes
participant C as TopicsController
participant T as TopicUser Model
participant V as Unsubscribe UI
E-->>U: Provide topic link
U->>R: GET unsubscribe URL
R->>C: Dispatch unsubscribe
C->>T: Lower notification level
T-->>C: Persist state
C-->>V: Render topic view
V-->>U: Show notification controls
```
</dd>
</dl>
</details>
<details>
<summary>High-Level Assessment</summary>
<dl>
<dd>
<br/>
>The following are alternative approaches to this PR:
<details>
<summary><b>1. Confirmation page followed by POST</b></summary>
<dl>
<dd>
- ➕ Avoids changing user state through an unsafe GET request
- ➕ Reduces accidental unsubscriptions caused by email link scanners or prefetchers
- ➕ Preserves the existing authenticated notification controls
- ➖ Requires an additional confirmation action
- ➖ Needs a dedicated mutation endpoint and client action
</dd>
</dl>
</details>
<details>
<summary><b>2. Signed one-click unsubscribe token</b></summary>
<dl>
<dd>
- ➕ Allows standards-friendly one-click unsubscribe without an existing login session
- ➕ Can scope authorization to one user and topic
- ➖ Requires token generation, validation, expiration, and revocation
- ➖ Forwarded emails could expose a valid unsubscribe capability
</dd>
</dl>
</details>
>**Recommendation:** Prefer an authenticated GET landing page followed by an explicit POST or PATCH mutation. This retains the new UI and topic-level behavior while avoiding state changes during link navigation; use signed tokens only if login-free one-click unsubscribe is a requirement.
</dd>
</dl>
</details>
<details>
<summary> Files changed (18) <code> +156 / -69 </code> </summary>
<dl>
<dd>
<br/>
<details>
<summary>Enhancement (14) <code> +121 / -32 </code></summary>
<dl>
<dd>
<details>
<summary>dropdown-button.js.es6<code>Render dropdown titles only when provided</code> <code>+4/-1</code></summary>
<br/>
>Render dropdown titles only when provided
>
><pre>
>• Guards title markup so titleless dropdowns, including the unsubscribe notification control, do not render an empty heading.
></pre>
>
><a href='https://github.com/drape-io/crbench-qodo-2026-09/pull/31/files#diff-7d81c91fa56796637c237b445239de5663a7808892aa7808f55be51d849bd188'>app/assets/javascripts/discourse/components/dropdown-button.js.es6</a>
</details>
<details>
<summary>topic-unsubscribe.js.es6<code>Add unsubscribe page presentation text</code> <code>+9/-0</code></summary>
<br/>
>Add unsubscribe page presentation text
>
><pre>
>• Introduces an object controller that interpolates the topic's display title into localized unsubscribe confirmation copy.
></pre>
>
><a href='https://github.com/drape-io/crbench-qodo-2026-09/pull/31/files#diff-b5dd8481a0fdab2d81b881004cb6cf5e6c2e8c5ce23b3a6093512f3b987b11df'>app/assets/javascripts/discourse/controllers/topic-unsubscribe.js.es6</a>
</details>
<details>
<summary>app-route-map.js.es6<code>Register the client-side unsubscribe route</code> <code>+1/-0</code></summary>
<br/>
>Register the client-side unsubscribe route
>
><pre>
>• Maps topic unsubscribe URLs to the new Ember route using slug and topic ID parameters.
></pre>
>
><a href='https://github.com/drape-io/crbench-qodo-2026-09/pull/31/files#diff-b16ca8ad4e61ae3156c5018333ab78ceaf8cc26448af010f6849d2d20084237f'>app/assets/javascripts/discourse/routes/app-route-map.js.es6</a>
</details>
<details>
<summary>topic-unsubscribe.js.es6<code>Load topic data for the unsubscribe page</code> <code>+23/-0</code></summary>
<br/>
>Load topic data for the unsubscribe page
>
><pre>
>• Loads the topic view, suppresses notification-reason text, and enables the application footer after transition.
></pre>
>
><a href='https://github.com/drape-io/crbench-qodo-2026-09/pull/31/files#diff-4cea28fb750078125e0dff150c4b4a101791a36361528f843da3cfaa7af13def'>app/assets/javascripts/discourse/routes/topic-unsubscribe.js.es6</a>
</details>
<details>
<summary>unsubscribe.hbs<code>Add the topic unsubscribe page template</code> <code>+8/-0</code></summary>
<br/>
>Add the topic unsubscribe page template
>
><pre>
>• Displays localized confirmation copy and the existing topic notification selector for subsequent state changes.
></pre>
>
><a href='https://github.com/drape-io/crbench-qodo-2026-09/pull/31/files#diff-bfe585d0ffda930236f0ef0fb721762e974c33dcda272f8cdd62f557a1d0ace2'>app/assets/javascripts/discourse/templates/topic/unsubscribe.hbs</a>
</details>
<details>
<summary>topic-unsubscribe.js.es6<code>Add the unsubscribe page view class</code> <code>+3/-0</code></summary>
<br/>
>Add the unsubscribe page view class
>
><pre>
>• Defines the view and applies a dedicated CSS class for page-specific styling.
></pre>
>
><a href='https://github.com/drape-io/crbench-qodo-2026-09/pull/31/files#diff-dd758ef6872689e8267c53b5cc1be95e3e82a78aa7d96fcf7cf7a33cdf71d494'>app/assets/javascripts/discourse/views/topic-unsubscribe.js.es6</a>
</details>
<details>
<summary>topic.scss<code>Style notification controls on unsubscribe pages</code> <code>+12/-0</code></summary>
<br/>
>Style notification controls on unsubscribe pages
>
><pre>
>• Keeps the notification selector inline and corrects dropdown positioning within the unsubscribe page.
></pre>
>
><a href='https://github.com/drape-io/crbench-qodo-2026-09/pull/31/files#diff-22f83714205833ae94503688bf93285bbd6983883a3b0a1b13d25091d2942e5b'>app/assets/stylesheets/common/base/topic.scss</a>
</details>
<details>
<summary>topics_controller.rb<code>Implement authenticated topic unsubscribe handling</code> <code>+24/-2</code></summary>
<br/>
>Implement authenticated topic unsubscribe handling
>
><pre>
>• Adds an authenticated, non-XHR action that canonicalizes the URL and lowers the user's topic notification level to regular or muted. The action then renders the standard topic response.
></pre>
>
><a href='https://github.com/drape-io/crbench-qodo-2026-09/pull/31/files#diff-a672ba5c68f4e7842932ef4e0c0893ef55b981e205a2b85490c4ff4363760811'>app/controllers/topics_controller.rb</a>
</details>
<details>
<summary>user_notifications.rb<code>Pass topic unsubscribe URLs into notification emails</code> <code>+2/-3</code></summary>
<br/>
>Pass topic unsubscribe URLs into notification emails
>
><pre>
>• Adds the topic-specific unsubscribe URL to email template arguments and simplifies conditional sender alias assignment.
></pre>
>
><a href='https://github.com/drape-io/crbench-qodo-2026-09/pull/31/files#diff-a1528161f4cf3f108f71f97127f83af6e226e12ba7cf311424522bf66d6f8e20'>app/mailers/user_notifications.rb</a>
</details>
<details>
<summary>topic.rb<code>Expose a canonical topic unsubscribe URL</code> <code>+4/-0</code></summary>
<br/>
>Expose a canonical topic unsubscribe URL
>
><pre>
>• Adds a model helper that appends the unsubscribe path to the topic's absolute URL.
></pre>
>
><a href='https://github.com/drape-io/crbench-qodo-2026-09/pull/31/files#diff-b3c70feba88e3827d9d1f8d6aed4b97adad78fb3c4f532d6b98183f1b56458c5'>app/models/topic.rb</a>
</details>
<details>
<summary>notification.html.erb<code>Reorganize notification email footer markup</code> <code>+19/-21</code></summary>
<br/>
>Reorganize notification email footer markup
>
><pre>
>• Modernizes partial rendering syntax and consistently places response instructions and unsubscribe content in the email footer.
></pre>
>
><a href='https://github.com/drape-io/crbench-qodo-2026-09/pull/31/files#diff-1b8508fec1c958364487379c8a844933b9459839945ac9932edcd336e140dfc5'>app/views/email/notification.html.erb</a>
</details>
<details>
<summary>client.en.yml<code>Add client unsubscribe page translations</code> <code>+3/-1</code></summary>
<br/>
>Add client unsubscribe page translations
>
><pre>
>• Adds English confirmation and notification-state guidance for the topic unsubscribe page.
></pre>
>
><a href='https://github.com/drape-io/crbench-qodo-2026-09/pull/31/files#diff-d311cd526428b83a1ebb9ed9b457fb210800cc5f0e8188af7de7b5ce86aa5315'>config/locales/client.en.yml</a>
</details>
<details>
<summary>server.en.yml<code>Add topic-specific email unsubscribe copy</code> <code>+4/-1</code></summary>
<br/>
>Add topic-specific email unsubscribe copy
>
><pre>
>• Extends the email unsubscribe text with a link for stopping notifications from the current topic.
></pre>
>
><a href='https://github.com/drape-io/crbench-qodo-2026-09/pull/31/files#diff-333c4c8cacc2f84633d4894f2aaddb130a6d74f42dd63199462b3d66278f6ce8'>config/locales/server.en.yml</a>
</details>
<details>
<summary>routes.rb<code>Expose topic unsubscribe endpoints</code> <code>+5/-3</code></summary>
<br/>
>Expose topic unsubscribe endpoints
>
><pre>
>• Adds slugged and topic-ID-only GET routes for the unsubscribe controller action while reorganizing adjacent topic routes.
></pre>
>
><a href='https://github.com/drape-io/crbench-qodo-2026-09/pull/31/files#diff-959bc9abc46a55332bb64d5155a79323afa75a50ec1a2137ddd22d926f62c6c5'>config/routes.rb</a>
</details>
</dd>
</dl>
</details>
<details>
<summary>Refactor (3) <code> +33 / -36 </code></summary>
<dl>
<dd>
<details>
<summary>topic-from-params.js.es6<code>Modernize topic parameter route syntax</code> <code>+13/-12</code></summary>
<br/>
>Modernize topic parameter route syntax
>
><pre>
>• Converts function and variable declarations to concise method syntax and constants without changing route behavior.
></pre>
>
><a href='https://github.com/drape-io/crbench-qodo-2026-09/pull/31/files#diff-0d16865f4d3d1a54901feb89b5ab3c248114c0e1e52ed4237b890ade47aae6d4'>app/assets/javascripts/discourse/routes/topic-from-params.js.es6</a>
</details>
<details>
<summary>topic_user.rb<code>Simplify topic-user notification code</code> <code>+8/-13</code></summary>
<br/>
>Simplify topic-user notification code
>
><pre>
>• Reformats queries and MessageBus payloads while condensing lookup construction. Notification behavior remains unchanged.
></pre>
>
><a href='https://github.com/drape-io/crbench-qodo-2026-09/pull/31/files#diff-94a17ebd5fec7b95f6eb1bb1576a8e15c52f992367c56e94640a8834b31615a9'>app/models/topic_user.rb</a>
</details>
<details>
<summary>message_builder.rb<code>Support topic unsubscribe template arguments</code> <code>+12/-11</code></summary>
<br/>
>Support topic unsubscribe template arguments
>
><pre>
>• Reformats template argument construction and unsubscribe placeholder substitution so caller-provided URLs are available to localized email content.
></pre>
>
><a href='https://github.com/drape-io/crbench-qodo-2026-09/pull/31/files#diff-5a02f05ebdacfb1b37a180939d6bce119b4350615edb94d6756ae33c6ef6e712'>lib/email/message_builder.rb</a>
</details>
</dd>
</dl>
</details>
<details>
<summary>Tests (1) <code> +2 / -1 </code></summary>
<dl>
<dd>
<details>
<summary>message_builder_spec.rb<code>Supply unsubscribe URL in message builder coverage</code> <code>+2/-1</code></summary>
<br/>
>Supply unsubscribe URL in message builder coverage
>
><pre>
>• Updates the unsubscribe-enabled message fixture with a topic URL while retaining List-Unsubscribe header coverage.
></pre>
>
><a href='https://github.com/drape-io/crbench-qodo-2026-09/pull/31/files#diff-f0da3633053aa4d50b3892858122493fb1a30ee7111544f9ce3b9c94d61c64f6'>spec/components/email/message_builder_spec.rb</a>
</details>
</dd>
</dl>
</details>
</dd>
</dl>
</details>
<h3>Code Review by Qodo</h3>
<code>🐞 Bugs (6)</code> <code>📘 Rule violations (0)</code> <code>📜 Skill insights (0)</code>
<img src="https://www.qodo.ai/wp-content/uploads/2025/11/light-grey-line.svg" height="10%" alt="Grey Divider">
<br/>
<img src="https://img.shields.io/badge/High-634FD1?style=flat-square" height="20px" alt="Action required">
<details>
<summary> 1. Users cannot see unsubscribe controls <code>🐞 Bug</code> <code>≡ Correctness</code></summary>
<br/>
> <details open>
><summary>Description</summary>
><br/>
>
><pre>
><b><i>topicUnsubscribe</i></b> is declared as a top-level route, but its markup is stored under the nested
><b><i>topic/unsubscribe</i></b> template name. When Ember enters the new URL it resolves the top-level
><b><i>topic-unsubscribe</i></b> template instead, so the explanatory text and notification button are not
>rendered.
></pre>
></details>
> <details>
><summary>Code</summary>
><br/>
>
><code>[app/assets/javascripts/discourse/routes/app-route-map.js.es6[13]](https://github.com/drape-io/crbench-qodo-2026-09/pull/31/files#diff-b16ca8ad4e61ae3156c5018333ab78ceaf8cc26448af010f6849d2d20084237fR13-R13)</code>
>
>```diff
>+ this.route('topicUnsubscribe', { path: '/t/:slug/:id/unsubscribe' });
>```
></details>
> <details>
><summary>Evidence</summary>
><br/>
>
><pre>
>The route is declared outside the <b><i>topic</i></b> resource and its route implementation is named
><b><i>topic-unsubscribe</i></b>, while the only supplied template is nested at
><b><i>templates/topic/unsubscribe.hbs</i></b>.
></pre>
>
> <code>[app/assets/javascripts/discourse/routes/app-route-map.js.es6[8-13]](https://github.com/drape-io/crbench-qodo-2026-09/blob/3788b4a56104574be75ea46730512cd0f22dc979/app/assets/javascripts/discourse/routes/app-route-map.js.es6/#L8-L13)</code>
> <code>[app/assets/javascripts/discourse/routes/topic-unsubscribe.js.es6[1-23]](https://github.com/drape-io/crbench-qodo-2026-09/blob/3788b4a56104574be75ea46730512cd0f22dc979/app/assets/javascripts/discourse/routes/topic-unsubscribe.js.es6/#L1-L23)</code>
> <code>[app/assets/javascripts/discourse/templates/topic/unsubscribe.hbs[1-8]](https://github.com/drape-io/crbench-qodo-2026-09/blob/3788b4a56104574be75ea46730512cd0f22dc979/app/assets/javascripts/discourse/templates/topic/unsubscribe.hbs/#L1-L8)</code>
></details>
> <details>
><summary>Agent prompt</summary>
><br/>
>
>```
>The issue below was found during a code review. Follow the provided context and guidance below and implement a solution
>
>## Issue description
>The top-level topicUnsubscribe route does not resolve the nested topic/unsubscribe template added by this change.
>
>## Fix Focus Areas
>- app/assets/javascripts/discourse/routes/app-route-map.js.es6[8-13]
>- app/assets/javascripts/discourse/templates/topic/unsubscribe.hbs[1-8]
>- app/assets/javascripts/discourse/routes/topic-unsubscribe.js.es6[1-23]
>
>## Recommended Fix
>Move the template to `app/assets/javascripts/discourse/templates/topic-unsubscribe.hbs` so it matches the existing top-level route, controller, and view names, or redefine all of those components consistently as a nested topic route.
>```
> <code>ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools</code>
></details>
<hr/>
</details>
<details>
<summary> 2. Other sites can disable a member's topic alerts <code>🐞 Bug</code> <code>⛨ Security</code></summary>
<br/>
> <details open>
><summary>Description</summary>
><br/>
>
><pre>
><b><i>TopicsController#unsubscribe</i></b> changes and saves the current user’s <b><i>tu.notification_level</i></b> through
>predictable GET routes while explicitly bypassing the XHR check. A cross-site navigation, embedded
>request, or automatic link fetch carrying an authenticated session can trigger either the
>regular-to-muted or watching-to-regular transition without an intentional in-app action or CSRF
>validation.
></pre>
></details>
> <details>
><summary>Code</summary>
><br/>
>
><code>[app/controllers/topics_controller.rb[R107-110]](https://github.com/drape-io/crbench-qodo-2026-09/pull/31/files#diff-a672ba5c68f4e7842932ef4e0c0893ef55b981e205a2b85490c4ff4363760811R107-R110)</code>
>
>```diff
>+ if tu.notification_level > TopicUser.notification_levels[:regular]
>+ tu.notification_level = TopicUser.notification_levels[:regular]
>+ else
>+ tu.notification_level = TopicUser.notification_levels[:muted]
>```
></details>
> <details>
><summary>Evidence</summary>
><br/>
>
><pre>
>Both newly added routes expose the action through GET, while the controller locates the current
>user’s topic record, changes its <b><i>notification_level</i></b>, and calls <b><i>save!</i></b>. Although the controller
>generally protects against forged requests, this action explicitly bypasses the XHR filter and
>requires only an authenticated session; the URL contains public topic identity components rather
>than a signed, user-bound credential.
></pre>
>
> <code>[app/controllers/application_controller.rb[21-32]](https://github.com/drape-io/crbench-qodo-2026-09/blob/3788b4a56104574be75ea46730512cd0f22dc979/app/controllers/application_controller.rb/#L21-L32)</code>
> <code>[app/controllers/topics_controller.rb[98-115]](https://github.com/drape-io/crbench-qodo-2026-09/blob/3788b4a56104574be75ea46730512cd0f22dc979/app/controllers/topics_controller.rb/#L98-L115)</code>
> <code>[config/routes.rb[440-441]](https://github.com/drape-io/crbench-qodo-2026-09/blob/3788b4a56104574be75ea46730512cd0f22dc979/config/routes.rb/#L440-L441)</code>
> <code>[app/models/topic.rb[703-721]](https://github.com/drape-io/crbench-qodo-2026-09/blob/3788b4a56104574be75ea46730512cd0f22dc979/app/models/topic.rb/#L703-L721)</code>
> <code>[app/controllers/topics_controller.rb[8-32]](https://github.com/drape-io/crbench-qodo-2026-09/blob/3788b4a56104574be75ea46730512cd0f22dc979/app/controllers/topics_controller.rb/#L8-L32)</code>
></details>
> <details>
><summary>Agent prompt</summary>
><br/>
>
>```
>The issue below was found during a code review. Follow the provided context and guidance below and implement a solution
>
>## Issue description
>The unsubscribe endpoint persists notification-level changes through GET URLs, allowing authenticated cross-site requests and automatic link fetching to modify a member’s topic notification state.
>
>## Fix Focus Areas
>- app/controllers/topics_controller.rb[98-115]
>- config/routes.rb[440-441]
>
>## Recommended Fix
>Keep the GET or email landing URL read-only and have it render a confirmation page without modifying state. Apply the notification-level update only after an explicit POST or PUT submission protected by the normal CSRF checks, or use another signed, user-bound mechanism before performing the change.
>```
> <code>ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools</code>
></details>
<hr/>
</details>
<details>
<summary> 3. Some members hit an error instead of unsubscribing <code>🐞 Bug</code> <code>☼ Reliability</code></summary>
<br/>
> <details open>
><summary>Description</summary>
><br/>
>
><pre>
><b><i>TopicsController#unsubscribe</i></b> uses nullable <b><i>TopicUser.find_by</i></b>, then immediately reads
><b><i>notification_level</i></b> from and saves the result without handling a missing row. Any authenticated
>member who can view the topic but lacks a corresponding <b><i>TopicUser</i></b> row reaches this path and raises
><b><i>NoMethodError</i></b> before the page is returned or the requested notification state is persisted.
></pre>
></details>
> <details>
><summary>Code</summary>
><br/>
>
><code>[app/controllers/topics_controller.rb[R105-113]](https://github.com/drape-io/crbench-qodo-2026-09/pull/31/files#diff-a672ba5c68f4e7842932ef4e0c0893ef55b981e205a2b85490c4ff4363760811R105-R113)</code>
>
>```diff
>+ tu = TopicUser.find_by(user_id: current_user.id, topic_id: params[:topic_id])
>+
>+ if tu.notification_level > TopicUser.notification_levels[:regular]
>+ tu.notification_level = TopicUser.notification_levels[:regular]
>+ else
>+ tu.notification_level = TopicUser.notification_levels[:muted]
>+ end
>+
>+ tu.save!
>```
></details>
> <details>
><summary>Evidence</summary>
><br/>
>
><pre>
>The action dereferences and saves the nullable result of <b><i>find_by</i></b> without a nil check. The
>established <b><i>TopicUser.change</i></b> lifecycle helper handles this case by creating a record when an
>update affects zero rows, but the new action bypasses that create-or-update path.
></pre>
>
> <code>[app/controllers/topics_controller.rb[105-113]](https://github.com/drape-io/crbench-qodo-2026-09/blob/3788b4a56104574be75ea46730512cd0f22dc979/app/controllers/topics_controller.rb/#L105-L113)</code>
> <code>[app/models/topic_user.rb[68-71]](https://github.com/drape-io/crbench-qodo-2026-09/blob/3788b4a56104574be75ea46730512cd0f22dc979/app/models/topic_user.rb/#L68-L71)</code>
> <code>[app/models/topic_user.rb[74-117]](https://github.com/drape-io/crbench-qodo-2026-09/blob/3788b4a56104574be75ea46730512cd0f22dc979/app/models/topic_user.rb/#L74-L117)</code>
> <code>[app/models/topic_user.rb[74-106]](https://github.com/drape-io/crbench-qodo-2026-09/blob/3788b4a56104574be75ea46730512cd0f22dc979/app/models/topic_user.rb/#L74-L106)</code>
></details>
> <details>
><summary>Agent prompt</summary>
><br/>
>
>```
>The issue below was found during a code review. Follow the provided context and guidance below and implement a solution
>
>## Issue description
>The unsubscribe action assumes every authorized user already has a `TopicUser` row, although `find_by` can return nil, causing a nil dereference instead of applying the requested notification-state change.
>
>## Fix Focus Areas
>- app/controllers/topics_controller.rb[105-113]
>- app/models/topic_user.rb[74-117]
>
>## Recommended Fix
>Resolve a missing record to the default regular notification level and persist the target state through `TopicUser.change`, or use an equivalent create-or-update operation before reading and updating the level. Do not directly dereference the result of `find_by`; ensure absent rows are handled while preserving the normal notification metadata and publication behavior.
>```
> <code>ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools</code>
></details>
<hr/>
</details>
<details><summary><ins><strong>View high (1)</strong></ins></summary><br/>
<details>
<summary> 4. Repeated unsubscribe links restore topic alerts <code>🐞 Bug</code> <code>≡ Correctness</code></summary>
<br/>
> <details open>
><summary>Description</summary>
><br/>
>
><pre>
><b><i>TopicsController#unsubscribe</i></b> treats every level at or below <b><i>regular</i></b>, including <b><i>muted</i></b>, as a
>request to set the level back to <b><i>muted</i></b> only after first setting higher levels to <b><i>regular</i></b>. When a
>member who is already muted follows the same email link again, the condition selects <b><i>regular</i></b>, so
>the persisted state re-enables normal topic notifications.
></pre>
></details>
> <details>
><summary>Code</summary>
><br/>
>
><code>[app/controllers/topics_controller.rb[R107-111]](https://github.com/drape-io/crbench-qodo-2026-09/pull/31/files#diff-a672ba5c68f4e7842932ef4e0c0893ef55b981e205a2b85490c4ff4363760811R107-R111)</code>
>
>```diff
>+ if tu.notification_level > TopicUser.notification_levels[:regular]
>+ tu.notification_level = TopicUser.notification_levels[:regular]
>+ else
>+ tu.notification_level = TopicUser.notification_levels[:muted]
>+ end
>```
></details>
> <details>
><summary>Evidence</summary>
><br/>
>
><pre>
><b><i>muted</i></b> is numerically below <b><i>regular</i></b>. The new condition maps notification levels above regular to
>regular and every other level—including muted—to muted, so a second invocation on a muted row writes
>regular.
></pre>
>
> <code>[app/controllers/topics_controller.rb[107-113]](https://github.com/drape-io/crbench-qodo-2026-09/blob/3788b4a56104574be75ea46730512cd0f22dc979/app/controllers/topics_controller.rb/#L107-L113)</code>
> <code>[app/models/topic_user.rb[18-21]](https://github.com/drape-io/crbench-qodo-2026-09/blob/3788b4a56104574be75ea46730512cd0f22dc979/app/models/topic_user.rb/#L18-L21)</code>
></details>
> <details>
><summary>Agent prompt</summary>
><br/>
>
>```
>The issue below was found during a code review. Follow the provided context and guidance below and implement a solution
>
>## Issue description
>Following an unsubscribe URL more than once can change an already-muted topic back to regular notifications, making the unsubscribe operation non-idempotent.
>
>## Fix Focus Areas
>- app/controllers/topics_controller.rb[107-113]
>- app/models/topic_user.rb[18-21]
>
>## Recommended Fix
>Set the intended unsubscribe notification level unconditionally, rather than toggling based on the current level. Use the standard TopicUser update path so repeated requests preserve the same final state.
>```
> <code>ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools</code>
></details>
<hr/>
</details>
</details>
<br/>
<img src="https://img.shields.io/badge/Medium-634FD1?style=flat-square" height="20px" alt="Remediation recommended">
<details>
<summary> 5. Non-English emails omit the topic unsubscribe link <code>🐞 Bug</code> <code>≡ Correctness</code></summary>
<br/>
> <details open>
><summary>Description</summary>
><br/>
>
><pre>
>Only the English <b><i>unsubscribe_link</i></b> translation adds <b><i>%{unsubscribe_url}</i></b>, while the existing
>localized translations retain only <b><i>%{user_preferences_url}</i></b>. When notification mail is generated
>under those locales, <b><i>MessageBuilder</i></b> selects that locale's existing key and the newly supplied
>topic URL is never rendered in either email body.
></pre>
></details>
> <details>
><summary>Code</summary>
><br/>
>
><code>[config/locales/server.en.yml[R1852-1855]](https://github.com/drape-io/crbench-qodo-2026-09/pull/31/files#diff-333c4c8cacc2f84633d4894f2aaddb130a6d74f42dd63199462b3d66278f6ce8R1852-R1855)</code>
>
>```diff
>+ unsubscribe_link: |
>+ To unsubscribe from these emails, visit your [user preferences](%{user_preferences_url}).
>+
>+ To stop receiving notifications about this particular topic, [click here](%{unsubscribe_url}).
>```
></details>
> <details>
><summary>Evidence</summary>
><br/>
>
><pre>
>The mail builder renders the current locale's <b><i>unsubscribe_link</i></b> value. German and Spanish define
>that same key without the newly added interpolation, demonstrating that I18n resolves their local
>strings instead of the updated English text.
></pre>
>
> <code>[lib/email/message_builder.rb[61-68]](https://github.com/drape-io/crbench-qodo-2026-09/blob/3788b4a56104574be75ea46730512cd0f22dc979/lib/email/message_builder.rb/#L61-L68)</code>
> <code>[lib/email/message_builder.rb[84-93]](https://github.com/drape-io/crbench-qodo-2026-09/blob/3788b4a56104574be75ea46730512cd0f22dc979/lib/email/message_builder.rb/#L84-L93)</code>
> <code>[config/locales/server.de.yml[1343-1343]](https://github.com/drape-io/crbench-qodo-2026-09/blob/3788b4a56104574be75ea46730512cd0f22dc979/config/locales/server.de.yml/#L1343-L1343)</code>
> <code>[config/locales/server.es.yml[1515-1515]](https://github.com/drape-io/crbench-qodo-2026-09/blob/3788b4a56104574be75ea46730512cd0f22dc979/config/locales/server.es.yml/#L1515-L1515)</code>
></details>
> <details>
><summary>Agent prompt</summary>
><br/>
>
>```
>The issue below was found during a code review. Follow the provided context and guidance below and implement a solution
>
>## Issue description
>The topic-specific unsubscribe URL is present only in the English `unsubscribe_link` translation, so localized notification emails do not include the new per-topic action.
>
>## Fix Focus Areas
>- config/locales/server.en.yml[1852-1855]
>- config/locales/server.de.yml[1343-1343]
>- config/locales/server.es.yml[1515-1515]
>
>## Recommended Fix
>Add the `%{unsubscribe_url}` topic-unsubscribe sentence to every locale that defines `unsubscribe_link`, preserving each locale's existing global preferences link. Add or update translation checks so localized variants continue to include the new interpolation.
>```
> <code>ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools</code>
></details>
<hr/>
</details>
<details>
<summary> 6. Signed-out email recipients cannot unsubscribe <code>🐞 Bug</code> <code>≡ Correctness</code></summary>
<br/>
> <details open>
><summary>Description</summary>
><br/>
>
><pre>
>The new <b><i>unsubscribe</i></b> action is protected by <b><i>ensure_logged_in</i></b>, but <b><i>Topic#unsubscribe_url</i></b> embeds
>no recipient-bound authentication information. When an email recipient has no active session, the
>raised <b><i>Discourse::NotLoggedIn</i></b> is redirected to the site root, leaving the topic notification state
>unchanged.
></pre>
></details>
> <details>
><summary>Code</summary>
><br/>
>
><code>[app/controllers/topics_controller.rb[R98-102]](https://github.com/drape-io/crbench-qodo-2026-09/pull/31/files#diff-a672ba5c68f4e7842932ef4e0c0893ef55b981e205a2b85490c4ff4363760811R98-R102)</code>
>
>```diff
>+ def unsubscribe
>+ @topic_view = TopicView.new(params[:topic_id], current_user)
>+
>+ if slugs_do_not_match || (!request.format.json? && params[:slug].blank?)
>+ return redirect_to @topic_view.topic.unsubscribe_url, status: 301
>```
></details>
> <details>
><summary>Evidence</summary>
><br/>
>
><pre>
>The new action is added to the authenticated-only filter, whereas the generated email URL is just
>the canonical topic URL plus <b><i>/unsubscribe</i></b>. The application's unauthenticated exception handler
>redirects ordinary GET requests to <b><i>/</i></b>, so no deferred action is performed after the recipient
>follows the email link signed out.
></pre>
>
> <code>[app/controllers/topics_controller.rb[8-32]](https://github.com/drape-io/crbench-qodo-2026-09/blob/3788b4a56104574be75ea46730512cd0f22dc979/app/controllers/topics_controller.rb/#L8-L32)</code>
> <code>[app/controllers/topics_controller.rb[98-115]](https://github.com/drape-io/crbench-qodo-2026-09/blob/3788b4a56104574be75ea46730512cd0f22dc979/app/controllers/topics_controller.rb/#L98-L115)</code>
> <code>[app/models/topic.rb[719-721]](https://github.com/drape-io/crbench-qodo-2026-09/blob/3788b4a56104574be75ea46730512cd0f22dc979/app/models/topic.rb/#L719-L721)</code>
> <code>[app/mailers/user_notifications.rb[292-295]](https://github.com/drape-io/crbench-qodo-2026-09/blob/3788b4a56104574be75ea46730512cd0f22dc979/app/mailers/user_notifications.rb/#L292-L295)</code>
> <code>[app/controllers/application_controller.rb[97-105]](https://github.com/drape-io/crbench-qodo-2026-09/blob/3788b4a56104574be75ea46730512cd0f22dc979/app/controllers/application_controller.rb/#L97-L105)</code>
></details>
> <details>
><summary>Agent prompt</summary>
><br/>
>
>```
>The issue below was found during a code review. Follow the provided context and guidance below and implement a solution
>
>## Issue description
>The topic-specific unsubscribe link sent in notification emails cannot change preferences unless the recipient is already authenticated, despite being presented as a direct unsubscribe action.
>
>## Fix Focus Areas
>- app/controllers/topics_controller.rb[8-32]
>- app/controllers/topics_controller.rb[98-115]
>- app/models/topic.rb[719-721]
>- app/mailers/user_notifications.rb[292-295]
>
>## Recommended Fix
>Provide a signed, expiring, recipient-bound unsubscribe URL for email recipients and validate it before applying the change, or change the email flow to explicitly require sign-in and preserve the destination through authentication. Do not remove authentication without adding a user-bound authorization mechanism.
>```
> <code>ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools</code>
></details>
<hr/>
</details>
<img src="https://www.qodo.ai/wp-content/uploads/2025/11/light-grey-line.svg" height="10%" alt="Grey Divider">
<!-- qodo-context:start -->
<details><summary><strong>Context sources</strong></summary>
<div>Review mode: <code>🧠 Deep</code>: This adds a new email-driven unsubscribe flow spanning frontend routing, controllers, models, routes, templates, localization, and email rendering, with many independent behavior changes and several easy-to-miss authorization, nil-handling, and URL/format defects.</div>
<!-- qodo-context:end -->
</details>
<img src="https://www.qodo.ai/wp-content/uploads/2025/11/light-grey-line.svg" height="10%" alt="Grey Divider">
<!-- qodo-daily-tip:start -->
<details>
<summary><strong>Tip of the day</strong></summary>
<br/>
<pre>💡 Did you know, you can reply 'qodo' on any finding to push back, ask questions, or dig deeper</pre>
<a href="https://docs.qodo.ai/tips-and-tricks">More tips ↗</a> | <a href="https://app.qodo.ai/configurations?tab=display-preferences">Customize Qodo ↗</a> | <a href="https://docs.qodo.ai">Qodo docs ↗</a>
</details>
<img src="https://www.qodo.ai/wp-content/uploads/2025/11/light-grey-line.svg" height="10%" alt="Grey Divider">
<!-- qodo-daily-tip:end -->
<!-- https://github.com/drape-io/crbench-qodo-2026-09/commit/3788b4a56104574be75ea46730512cd0f22dc979 -->
<a href="https://www.qodo.ai"><img src="https://www.qodo.ai/wp-content/uploads/2025/03/qodo-logo.svg" width="80" alt="Qodo Logo"></a>