A platform for community discussion. Free, open, simple.
FEATURE: Add verified navigation lookup for the Admin Assistant (#43542)
Penar Musaraj37bc6b75421b
diff --git a/lib/discourse_plugin_registry.rb b/lib/discourse_plugin_registry.rbindex be6fcec0f56..328390c5b1c 100644--- a/lib/discourse_plugin_registry.rb+++ b/lib/discourse_plugin_registry.rb@@ -147,6 +147,8 @@ class DiscoursePluginRegistrydefine_filtered_register :homepage_options+ define_filtered_register :navigation_destinations+define_filtered_register :custom_filter_mappingsdefine_filtered_register :acl_target_classesdiff --git a/lib/navigation_destination.rb b/lib/navigation_destination.rbnew file mode 100644index 00000000000..17a04fe9aa0--- /dev/null+++ b/lib/navigation_destination.rb@@ -0,0 +1,42 @@+# frozen_string_literal: true++class NavigationDestination+ attr_reader :id, :path++ def initialize(id:, path:, title:, description:, keywords: [], &available)+ if !path.match?(%r{\A/(?!/)[a-zA-Z0-9/_-]*\z})+ raise ArgumentError, "navigation destination must use a static local path without a base path"+ end+ raise ArgumentError, "navigation destination requires an availability block" if !available++ @id = id+ @path = path+ @title = title+ @description = description+ @keywords = keywords+ @available = available+ end++ def available?(guardian)+ @available.call(guardian)+ end++ def search_text+ [+ I18n.t(@title),+ I18n.t(@description),+ I18n.t(@title, locale: :en),+ I18n.t(@description, locale: :en),+ *@keywords,+ ].join(" ").downcase+ end++ def to_h+ {+ id: id,+ title: I18n.t(@title),+ description: I18n.t(@description),+ url: "#{Discourse.base_url}#{path}",+ }+ end+enddiff --git a/lib/plugin/instance.rb b/lib/plugin/instance.rbindex 797447bb766..26d9b6e7ba4 100644--- a/lib/plugin/instance.rb+++ b/lib/plugin/instance.rb@@ -1,5 +1,7 @@# frozen_string_literal: true+require_relative "../navigation_destination"+require "digest/sha1"require "fileutils"require "plugin/metadata"@@ -429,6 +431,21 @@ class Plugin::InstanceDiscoursePluginRegistry.register_problem_check(klass, self)end+ # Title and description are server translation keys. Paths omit the installation+ # base path; availability is evaluated for the requesting Guardian on each lookup.+ def register_navigation_destination(id, path:, title:, description:, keywords: [], &available)+ destination =+ NavigationDestination.new(+ id: "#{name}:#{id}",+ path: path,+ title: title,+ description: description,+ keywords: keywords,+ &available+ )+ DiscoursePluginRegistry.register_navigation_destination(destination, self)+ end+def register_upcoming_change_conditional_display(setting_name, &block)raise ArgumentError, "block is required" if block.blank?diff --git a/plugins/discourse-ai/config/locales/server.en.yml b/plugins/discourse-ai/config/locales/server.en.ymlindex 5adfe69cde6..4b66e23ad52 100644--- a/plugins/discourse-ai/config/locales/server.en.yml+++ b/plugins/discourse-ai/config/locales/server.en.yml@@ -456,6 +456,40 @@ en:logging_subject: "Spam detection"ai_bot:+ search_discourse_navigation:+ not_allowed: "You are not allowed to search administration destinations."+ invalid_query: "Enter a search query between 1 and %{max} characters."+ navigation:+ settings:+ title: "Site settings"+ description: "Search and change all site configuration settings."+ users:+ title: "Users"+ description: "Find and manage member accounts and user permissions."+ groups:+ title: "Groups"+ description: "Manage groups and group membership."+ review:+ title: "Review queue"+ description: "Moderate flagged posts and approve pending users and content."+ invites:+ title: "Create an invite"+ description: "Invite people to join this community."+ categories:+ title: "Categories"+ description: "Browse, create, and manage discussion categories."+ tags:+ title: "Tags"+ description: "Browse and manage topic tags."+ themes:+ title: "Themes"+ description: "Install and customize themes to change the site's appearance and design."+ authentication:+ title: "Login and authentication"+ description: "Configure login, signup, authentication, and single sign-on."+ backups:+ title: "Backups"+ description: "Create, download, and restore site backups."ai_users: "AI users"ai_users_bio: "Automatic group of AI bot accounts"errors:@@ -769,6 +803,7 @@ en:setting_context: "Look up site setting context"schema: "Look up database schema"search_settings: "Searching site settings"+ search_discourse_navigation: "Searching site navigation"read_site_setting: "Read site setting"change_site_setting: "Change site setting"dall_e: "Generate image"@@ -830,6 +865,7 @@ en:setting_context: "Look up site setting context"schema: "Look up database schema"search_settings: "Search site settings"+ search_discourse_navigation: "Find verified links to available pages on this site"read_site_setting: "Read the current value of a site setting"change_site_setting: "Change the value of a site setting"dall_e: "Generate image using DALL-E 3"@@ -912,6 +948,9 @@ en:search_settings:one: "Found %{count} result for '%{query}'"other: "Found %{count} results for '%{query}'"+ search_discourse_navigation:+ one: "Found %{count} destination"+ other: "Found %{count} destinations"read_site_setting: "Reading site setting %{setting_name}"change_site_setting: "Changing site setting %{setting_name} to '%{value}'"discoveries:diff --git a/plugins/discourse-ai/lib/agents/agent.rb b/plugins/discourse-ai/lib/agents/agent.rbindex ead15feaf14..1d5519f457c 100644--- a/plugins/discourse-ai/lib/agents/agent.rb+++ b/plugins/discourse-ai/lib/agents/agent.rb@@ -128,6 +128,7 @@ module DiscourseAiTools::AddReviewableNote,Tools::DbSchema,Tools::SearchSettings,+ Tools::SearchDiscourseNavigation,Tools::SettingContext,Tools::ReadSiteSetting,Tools::ChangeSiteSetting,diff --git a/plugins/discourse-ai/lib/agents/discourse_admin_assistant.rb b/plugins/discourse-ai/lib/agents/discourse_admin_assistant.rbindex 741b2564f27..eb4a343eafd 100644--- a/plugins/discourse-ai/lib/agents/discourse_admin_assistant.rb+++ b/plugins/discourse-ai/lib/agents/discourse_admin_assistant.rb@@ -19,6 +19,7 @@ module DiscourseAiTools::ListTags,Tools::SettingContext,Tools::SearchSettings,+ Tools::SearchDiscourseNavigation,Tools::ReadSiteSetting,Tools::ChangeSiteSetting,Tools::ListReviewables,@@ -44,12 +45,13 @@ module DiscourseAi<<~PROMPTYou are the Discourse Admin Assistant, an AI bot tasked with helping Discourse administrators. Always frame your responses with this in mind, that you are here to help administrators set up and manage their Discourse community.- - For questions about official Discourse hosting plans, pricing, or billing, call `load_discourse_website_page` with `page_name` set to `pricing` and treat its result as the primary source. Do not search Meta unless the pricing page does not answer the question.+ - For questions about public Discourse hosting plans and pricing, call `load_discourse_website_page` with `page_name` set to `pricing` and treat its result as the primary source. Do not search Meta unless the pricing page does not answer the question.+ - For managing this site's hosting account, subscription, invoices, or billing, use `search_discourse_navigation` to find an available local destination. The public pricing page does not manage this site's account.- For general questions about Discourse, call `search_meta_discourse` twice before answering: first with precise keywords, then with a broader query. Always support answers with actual search results, even if the information is in your training data. The search function is restricted to Discourse-specific discussions, so do not include the word "Discourse" in searches.- For questions about this site's configuration or content, use the relevant site and administration tools instead of the website page or Meta tools.- Give practical, concise answers that help an administrator complete the task. Start with the direct answer and do not describe your search process.- For "how do I" questions, use a short numbered list of the relevant steps. Include alternative workflows only when they are materially useful.- - When directing an administrator to an area of this site, use a descriptive Markdown link with an absolute URL based on {site_url}. For example: [Create an invite]({site_url}/new-invite). Never respond with a bare URL.+ - When directing an administrator to an area of this site, use a descriptive Markdown link with the exact absolute URL returned by a site tool. Use `search_discourse_navigation` when you do not already have a URL from a tool. Never invent a path, rewrite a Meta URL onto this site's hostname, or respond with a bare URL. If no verified destination is found, explain that you could not find a link instead of guessing one.- Use Meta search results to support factual guidance and link to the most useful source with descriptive link text. Do not overwhelm the answer with sources.- Mention permission requirements, trade-offs, or relevant site settings only when they affect the requested action.- Prefer a compact answer: a direct recommendation, two to five actionable steps, and at most one short note for an important caveat.diff --git a/plugins/discourse-ai/lib/agents/tools/read_site_setting.rb b/plugins/discourse-ai/lib/agents/tools/read_site_setting.rbindex aae113c213c..6e7bdae3cf3 100644--- a/plugins/discourse-ai/lib/agents/tools/read_site_setting.rb+++ b/plugins/discourse-ai/lib/agents/tools/read_site_setting.rb@@ -31,7 +31,12 @@ module DiscourseAireturn validation_resultend- { setting_name: setting_name, value: SiteSetting.get(setting_sym) }+ {+ setting_name: setting_name,+ value: SiteSetting.get(setting_sym),+ url:+ "#{Discourse.base_url}/admin/site_settings/category/all_results?#{Rack::Utils.build_query(filter: setting_name)}",+ }enddef validation_errordiff --git a/plugins/discourse-ai/lib/agents/tools/search_discourse_navigation.rb b/plugins/discourse-ai/lib/agents/tools/search_discourse_navigation.rbnew file mode 100644index 00000000000..4408f2ae107--- /dev/null+++ b/plugins/discourse-ai/lib/agents/tools/search_discourse_navigation.rb@@ -0,0 +1,109 @@+# frozen_string_literal: true++module DiscourseAi+ module Agents+ module Tools+ class SearchDiscourseNavigation < Tool+ MAX_RESULTS = 8+ MAX_QUERY_LENGTH = 200++ CORE_PATHS = {+ settings: "/admin/site_settings/category/all_results",+ users: "/admin/users/list/active",+ groups: "/admin/groups",+ review: "/review",+ invites: "/new-invite",+ categories: "/categories",+ tags: "/tags",+ themes: "/admin/config/customize/themes",+ authentication: "/admin/config/login-and-authentication",+ backups: "/admin/backups",+ }.freeze++ def self.signature+ {+ name: name,+ description:+ "Find verified navigation URLs on this site, including available plugin pages. Use concise keywords for the destination or task, such as 'billing subscription' or 'themes'. Reuse returned URLs exactly. No results means no verified destination was found; never invent a URL.",+ parameters: [+ {+ name: "query",+ description: "Keywords describing the page or task",+ type: "string",+ required: true,+ },+ ],+ }+ end++ def self.name+ "search_discourse_navigation"+ end++ def invoke+ if !guardian.is_admin?+ return(+ error_response(I18n.t("discourse_ai.ai_bot.search_discourse_navigation.not_allowed"))+ )+ end++ query = parameters[:query].to_s.strip+ if query.blank? || query.length > MAX_QUERY_LENGTH+ return(+ error_response(+ I18n.t(+ "discourse_ai.ai_bot.search_discourse_navigation.invalid_query",+ max: MAX_QUERY_LENGTH,+ ),+ )+ )+ end++ terms = query.downcase.split(/\s+/).uniq+ matches =+ destinations.filter_map do |destination|+ next if !destination.available?(guardian)++ search_text = destination.search_text+ score = terms.count { |term| search_text.include?(term) }+ next if score.zero?++ [score, destination]+ end++ results =+ matches+ .sort_by { |score, destination| [-score, destination.id] }+ .first(MAX_RESULTS)+ .map { |_, destination| destination.to_h }+ @result_count = results.length++ { destinations: results }+ end++ private++ def destinations+ core =+ CORE_PATHS.map do |id, path|+ NavigationDestination.new(+ id: "core:#{id}",+ path: path,+ title: "discourse_ai.ai_bot.navigation.#{id}.title",+ description: "discourse_ai.ai_bot.navigation.#{id}.description",+ ) do |requesting_guardian|+ requesting_guardian.is_admin? && (id != :tags || SiteSetting.tagging_enabled) &&+ (id != :invites || requesting_guardian.can_invite_to_forum?)+ end+ end++ core + DiscoursePluginRegistry.navigation_destinations+ end++ def description_args+ { count: @result_count || 0 }+ end+ end+ end+ end+enddiff --git a/plugins/discourse-ai/lib/agents/tools/search_settings.rb b/plugins/discourse-ai/lib/agents/tools/search_settings.rbindex 68e84fbb4d1..e79996acdf8 100644--- a/plugins/discourse-ai/lib/agents/tools/search_settings.rb+++ b/plugins/discourse-ai/lib/agents/tools/search_settings.rb@@ -87,6 +87,9 @@ module DiscourseAiresult[:description] = setting[:description]result[:plugin] = setting[:plugin]end+ result[+ :url+ ] = "#{Discourse.base_url}/admin/site_settings/category/all_results?#{Rack::Utils.build_query(filter: setting[:setting])}"resultendenddiff --git a/plugins/discourse-ai/spec/lib/agents/discourse_admin_assistant_spec.rb b/plugins/discourse-ai/spec/lib/agents/discourse_admin_assistant_spec.rbindex 48f982a3f12..6376e643f5d 100644--- a/plugins/discourse-ai/spec/lib/agents/discourse_admin_assistant_spec.rb+++ b/plugins/discourse-ai/spec/lib/agents/discourse_admin_assistant_spec.rb@@ -17,6 +17,7 @@ RSpec.describe DiscourseAi::Agents::DiscourseAdminAssistant doDiscourseAi::Agents::Tools::ListTags,DiscourseAi::Agents::Tools::SettingContext,DiscourseAi::Agents::Tools::SearchSettings,+ DiscourseAi::Agents::Tools::SearchDiscourseNavigation,DiscourseAi::Agents::Tools::ReadSiteSetting,DiscourseAi::Agents::Tools::ChangeSiteSetting,DiscourseAi::Agents::Tools::ListReviewables,@@ -63,13 +64,16 @@ RSpec.describe DiscourseAi::Agents::DiscourseAdminAssistant doprompt = assistant.craft_prompt(DiscourseAi::Agents::BotContext.new)expect(prompt.system_message_text).to include(- "For questions about official Discourse hosting plans, pricing, or billing, call `load_discourse_website_page` with `page_name` set to `pricing`",+ "For questions about public Discourse hosting plans and pricing, call `load_discourse_website_page` with `page_name` set to `pricing`",+ "For managing this site's hosting account, subscription, invoices, or billing, use `search_discourse_navigation`",+ "Never invent a path","For general questions about Discourse, call `search_meta_discourse` twice before answering","For questions about this site's configuration or content, use the relevant site and administration tools",)expect(prompt.tools.map(&:name)).to include("load_discourse_website_page","search_meta_discourse",+ "search_discourse_navigation",)enddiff --git a/plugins/discourse-ai/spec/lib/agents/tools/read_site_setting_spec.rb b/plugins/discourse-ai/spec/lib/agents/tools/read_site_setting_spec.rbindex dd823f8653d..f050b1b0296 100644--- a/plugins/discourse-ai/spec/lib/agents/tools/read_site_setting_spec.rb+++ b/plugins/discourse-ai/spec/lib/agents/tools/read_site_setting_spec.rb@@ -23,7 +23,11 @@ RSpec.describe DiscourseAi::Agents::Tools::ReadSiteSetting doit "returns the current value for an administrator" doSiteSetting.min_post_length = 42- expect(tool("min_post_length").invoke).to eq(setting_name: "min_post_length", value: 42)+ expect(tool("min_post_length").invoke).to eq(+ setting_name: "min_post_length",+ value: 42,+ url: "#{Discourse.base_url}/admin/site_settings/category/all_results?filter=min_post_length",+ )endit "returns an error when the acting user is not an administrator" dodiff --git a/plugins/discourse-ai/spec/lib/agents/tools/search_discourse_navigation_spec.rb b/plugins/discourse-ai/spec/lib/agents/tools/search_discourse_navigation_spec.rbnew file mode 100644index 00000000000..6153094a8c6--- /dev/null+++ b/plugins/discourse-ai/spec/lib/agents/tools/search_discourse_navigation_spec.rb@@ -0,0 +1,118 @@+# frozen_string_literal: true++RSpec.describe DiscourseAi::Agents::Tools::SearchDiscourseNavigation do+ fab!(:admin)+ fab!(:user)++ before { enable_current_plugin }++ def search(query, user: admin)+ described_class.new(+ { query: query },+ bot_user: Discourse.system_user,+ llm: nil,+ context: DiscourseAi::Agents::BotContext.new(user: user),+ ).invoke+ end++ describe "#invoke" do+ it "returns canonical destinations for task keywords" do+ expect(search("themes")[:destinations]).to contain_exactly(+ {+ id: "core:themes",+ title: "Themes",+ description: I18n.t("discourse_ai.ai_bot.navigation.themes.description"),+ url: "#{Discourse.base_url}/admin/config/customize/themes",+ },+ )+ expect(search("invite")[:destinations].pluck(:url)).to eq(+ ["#{Discourse.base_url}/new-invite"],+ )+ end++ it "uses the current installation base path without caching resolved URLs" do+ original_url = search("backups")[:destinations].first[:url]+ set_subfolder "/community"++ expect(search("backups")[:destinations].first[:url]).to eq(+ "#{Discourse.base_url}/admin/backups",+ )+ expect(search("backups")[:destinations].first[:url]).not_to eq(original_url)+ end++ it "omits destinations disabled on this site" do+ SiteSetting.tagging_enabled = false++ expect(search("tags")[:destinations]).to eq([])+ end++ it "searches translated titles as well as English metadata" do+ TranslationOverride.upsert!("fr", "discourse_ai.ai_bot.navigation.themes.title", "Apparence")++ I18n.with_locale(:fr) do+ expect(search("apparence")[:destinations].pluck(:id, :title)).to eq(+ [%w[core:themes Apparence]],+ )+ expect(search("themes")[:destinations].pluck(:id)).to eq(["core:themes"])+ end+ end++ it "uses the requesting user's permissions instead of the bot's" do+ expect(search("themes", user: user)[:status]).to eq("error")+ end++ it "returns no destination for an unknown page" do+ expect(search("nonexistent-destination")[:destinations]).to eq([])+ end++ it "rejects empty and oversized queries" do+ [nil, " ", "a" * (described_class::MAX_QUERY_LENGTH + 1)].each do |query|+ expect(search(query)[:status]).to eq("error")+ end+ end++ it "bounds results and ranks destinations matching more keywords first" do+ results =+ search(+ "themes appearance design site manage users groups review invite categories tags backups",+ )[+ :destinations+ ]++ expect(results.size).to eq(described_class::MAX_RESULTS)+ expect(results.first[:id]).to eq("core:themes")+ end++ it "finds plugin aliases only while the plugin and its destination are available" do+ plugin = Plugin::Instance.new(Plugin::Metadata.parse("# name: navigation-test"))+ plugin.enabled_site_setting(:discourse_sample_plugin_enabled)+ registry = DiscoursePluginRegistry._raw_navigation_destinations+ original_entries = registry.dup++ begin+ plugin.register_navigation_destination(+ "portal",+ path: "/admin/example-portal",+ title: "discourse_ai.ai_bot.navigation.settings.title",+ description: "discourse_ai.ai_bot.navigation.settings.description",+ keywords: ["example-subscription"],+ ) { |guardian| guardian.user.id == admin.id && SiteSetting.allow_user_locale }++ SiteSetting.discourse_sample_plugin_enabled = true+ SiteSetting.allow_user_locale = true+ expect(search("example-subscription")[:destinations].pluck(:id, :url)).to eq(+ [["navigation-test:portal", "#{Discourse.base_url}/admin/example-portal"]],+ )++ SiteSetting.allow_user_locale = false+ expect(search("example-subscription")[:destinations]).to eq([])++ SiteSetting.allow_user_locale = true+ SiteSetting.discourse_sample_plugin_enabled = false+ expect(search("example-subscription")[:destinations]).to eq([])+ ensure+ registry.replace(original_entries)+ end+ end+ end+enddiff --git a/plugins/discourse-ai/spec/lib/agents/tools/search_settings_spec.rb b/plugins/discourse-ai/spec/lib/agents/tools/search_settings_spec.rbindex 1af551411b1..3e38a43b947 100644--- a/plugins/discourse-ai/spec/lib/agents/tools/search_settings_spec.rb+++ b/plugins/discourse-ai/spec/lib/agents/tools/search_settings_spec.rb@@ -53,7 +53,7 @@ RSpec.describe DiscourseAi::Agents::Tools::SearchSettings doresults = search_settings("a", mock: false).invokeexpect(results[:rows].length).to be > 30- expect(results[:rows][0].length).to eq(1)+ expect(results[:rows][0].length).to eq(2)endit "can return descriptions if there are few matches" do@@ -63,5 +63,16 @@ RSpec.describe DiscourseAi::Agents::Tools::SearchSettings doexpect(results[:rows][0][1]).not_to eq(nil)end++ it "returns a setting link with the installation base path" do+ set_subfolder "/community"++ results = search_settings("default_locale").invoke++ url_column = results[:column_names].index("url")+ expect(results[:rows][0][url_column]).to eq(+ "#{Discourse.base_url}/admin/site_settings/category/all_results?filter=default_locale",+ )+ endendenddiff --git a/spec/lib/navigation_destination_spec.rb b/spec/lib/navigation_destination_spec.rbnew file mode 100644index 00000000000..36abdfd76cd--- /dev/null+++ b/spec/lib/navigation_destination_spec.rb@@ -0,0 +1,28 @@+# frozen_string_literal: true++RSpec.describe NavigationDestination do+ describe "#initialize" do+ it "rejects external, dynamic, and ambiguous paths" do+ [+ "https://example.com",+ "//example.com",+ "/\\example.com",+ "/users/:id",+ "/../admin",+ "/admin?redirect=elsewhere",+ ].each do |path|+ expect {+ described_class.new(id: "test", path: path, title: "title", description: "description") do+ true+ end+ }.to raise_error(ArgumentError)+ end+ end++ it "requires an explicit availability predicate" do+ expect {+ described_class.new(id: "test", path: "/admin", title: "title", description: "description")+ }.to raise_error(ArgumentError, /availability/)+ end+ end+enddiff --git a/spec/lib/plugin/instance_spec.rb b/spec/lib/plugin/instance_spec.rbindex 9656d5c2737..b2736677790 100644--- a/spec/lib/plugin/instance_spec.rb+++ b/spec/lib/plugin/instance_spec.rb@@ -21,6 +21,26 @@ TEXTafter { DiscoursePluginRegistry.reset! }+ describe "#register_navigation_destination" do+ it "namespaces destinations and filters disabled plugins at lookup time" do+ plugin_instance.enabled_site_setting(:discourse_sample_plugin_enabled)+ plugin_instance.register_navigation_destination(+ "example",+ path: "/admin/example",+ title: "example.title",+ description: "example.description",+ ) { |guardian| guardian.is_admin? }++ SiteSetting.discourse_sample_plugin_enabled = true+ expect(DiscoursePluginRegistry.navigation_destinations.map(&:id)).to eq(+ ["discourse-sample-plugin:example"],+ )++ SiteSetting.discourse_sample_plugin_enabled = false+ expect(DiscoursePluginRegistry.navigation_destinations).to eq([])+ end+ end+# NOTE: sample_plugin_site_settings.yml is always loaded in tests in site_setting.rbdescribe ".humanized_name" do