Skip to content

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

FEATURE: Add query and workflow authoring to Admin Assistant (#44770)

Keegan George87774ac1bddb
diff --git a/plugins/discourse-ai/lib/agents/admin_assistant_access.rb b/plugins/discourse-ai/lib/agents/admin_assistant_access.rb
new file mode 100644
index 00000000000..de77276dc37
--- /dev/null
+++ b/plugins/discourse-ai/lib/agents/admin_assistant_access.rb
@@ -0,0 +1,36 @@
+# frozen_string_literal: true
+
+module DiscourseAi
+ module Agents
+ module AdminAssistantAccess
+ Request = Data.define(:feature, :user, :phase)
+ Result = Data.define(:allowed, :message)
+
+ class Decision
+ attr_reader :message
+
+ def initialize
+ @allowed = true
+ end
+
+ def allowed?
+ @allowed
+ end
+
+ def deny!(message = nil)
+ @allowed = false
+ @message ||= message
+ self
+ end
+ end
+
+ def self.check(feature:, user:, phase:)
+ decision = Decision.new
+ request = Request.new(feature: feature, user: user, phase: phase)
+ DiscoursePluginRegistry.apply_modifier(:admin_assistant_feature_access, decision, request)
+
+ Result.new(allowed: decision.allowed?, message: decision.message)
+ end
+ end
+ end
+end
diff --git a/plugins/discourse-ai/lib/agents/agent.rb b/plugins/discourse-ai/lib/agents/agent.rb
index e75e195f297..11d61c2bd66 100644
--- a/plugins/discourse-ai/lib/agents/agent.rb
+++ b/plugins/discourse-ai/lib/agents/agent.rb
@@ -392,7 +392,7 @@ module DiscourseAi
tools =
available_tools.reject do |tool|
tool_name = tool.signature[:name]
- tool_name == Tools::ViewImage.name ||
+ !tool.available_for_context?(context) || tool_name == Tools::ViewImage.name ||
reserved_spawn_agent && tool_name.to_s.casecmp(Tools::SpawnAgent.name).zero?
end
diff --git a/plugins/discourse-ai/lib/agents/discourse_admin_assistant.rb b/plugins/discourse-ai/lib/agents/discourse_admin_assistant.rb
index c8fd6c43198..61585b55bcd 100644
--- a/plugins/discourse-ai/lib/agents/discourse_admin_assistant.rb
+++ b/plugins/discourse-ai/lib/agents/discourse_admin_assistant.rb
@@ -12,7 +12,7 @@ module DiscourseAi
end
def tools
- [
+ base_tools = [
Tools::LoadDiscourseWebsitePage,
Tools::DiscourseMetaSearch,
Tools::ListCategories,
@@ -39,6 +39,8 @@ module DiscourseAi
Tools::SilenceUser,
Tools::MarkAsSolved,
]
+
+ DiscoursePluginRegistry.apply_modifier(:admin_assistant_tools, base_tools, self).uniq
end
def system_prompt
diff --git a/plugins/discourse-ai/lib/agents/tools/draft_reference.rb b/plugins/discourse-ai/lib/agents/tools/draft_reference.rb
new file mode 100644
index 00000000000..28e36e40336
--- /dev/null
+++ b/plugins/discourse-ai/lib/agents/tools/draft_reference.rb
@@ -0,0 +1,174 @@
+# frozen_string_literal: true
+
+module DiscourseAi
+ module Agents
+ module Tools
+ class DraftReference
+ LIFETIME = 1.day
+ MAX_PAYLOAD_BYTES = 64.kilobytes
+
+ class ClaimRollback
+ def initialize(reference_class:, reference:, reviewable_id:)
+ @reference_class = reference_class
+ @reference = reference
+ @reviewable_id = reviewable_id
+ end
+
+ def before_committed!(*args)
+ end
+
+ def committed!(*args)
+ ActiveRecord::Base.connection.add_transaction_record(self) if DB.transaction_open?
+ end
+
+ def rolledback!(*args)
+ @reference_class.release(@reference, reviewable_id: @reviewable_id)
+ rescue => error
+ Discourse.warn_exception(error, message: "failed to release an assistant draft claim")
+ end
+
+ def trigger_transactional_callbacks?
+ true
+ end
+ end
+
+ class << self
+ def sign(payload, user:)
+ serialized =
+ payload.deep_stringify_keys.merge(
+ "user_id" => user.id,
+ "site" => Discourse.current_hostname,
+ )
+ if JSON.generate(serialized).bytesize > self::MAX_PAYLOAD_BYTES
+ raise Discourse::InvalidParameters
+ end
+
+ signed = verifier.generate(serialized, expires_in: self::LIFETIME, purpose: purpose)
+ reference = "#{reference_prefix}#{SecureRandom.hex(16)}"
+ Discourse.redis.setex(draft_key(reference), self::LIFETIME.to_i, signed)
+ reference
+ end
+
+ def read(reference)
+ return if !reference_pattern.match?(reference.to_s)
+
+ signed = Discourse.redis.get(draft_key(reference))
+ return if signed.blank?
+
+ verify(signed)
+ end
+
+ def read_with_compatibility(reference)
+ draft = read(reference)
+ draft ||=
+ DiscoursePluginRegistry.apply_modifier(
+ :admin_assistant_legacy_draft,
+ nil,
+ draft_kind.to_sym,
+ reference,
+ )
+ draft&.symbolize_keys
+ end
+
+ def claim(reference, reviewable_id:)
+ return false if !read_with_compatibility(reference)
+
+ value = claim_value(reviewable_id, "creating")
+ !!Discourse.redis.set(claim_key(reference), value, nx: true, ex: self::LIFETIME.to_i)
+ end
+
+ def complete_after_transaction(reference, reviewable_id:, resource_id:)
+ if DB.transaction_open?
+ ActiveRecord::Base.connection.add_transaction_record(
+ ClaimRollback.new(
+ reference_class: self,
+ reference: reference,
+ reviewable_id: reviewable_id,
+ ),
+ )
+ end
+
+ DB.after_commit do
+ complete(reference, reviewable_id: reviewable_id, resource_id: resource_id)
+ end
+ end
+
+ def release(reference, reviewable_id:)
+ expected = claim_value(reviewable_id, "creating")
+ Discourse.redis.eval(
+ <<~LUA,
+ if redis.call("get", KEYS[1]) == ARGV[1] then
+ return redis.call("del", KEYS[1])
+ end
+ return 0
+ LUA
+ keys: [Discourse.redis.namespace_key(claim_key(reference))],
+ argv: [expected],
+ )
+ end
+
+ private
+
+ def complete(reference, reviewable_id:, resource_id:)
+ expected = claim_value(reviewable_id, "creating")
+ value = claim_value(reviewable_id, "created", resource_id: resource_id)
+ result =
+ Discourse.redis.eval(
+ <<~LUA,
+ if redis.call("get", KEYS[1]) == ARGV[1] then
+ redis.call("setex", KEYS[1], ARGV[2], ARGV[3])
+ return 1
+ end
+ return 0
+ LUA
+ keys: [Discourse.redis.namespace_key(claim_key(reference))],
+ argv: [expected, self::LIFETIME.to_i, value],
+ )
+ raise "assistant draft claim changed before commit" if result != 1
+ rescue => error
+ Discourse.warn_exception(error, message: "failed to finalize an assistant draft")
+ end
+
+ def claim_value(reviewable_id, state, resource_id: nil)
+ { reviewable_id: reviewable_id, state: state, resource_id: resource_id }.compact.to_json
+ end
+
+ def draft_key(reference)
+ "admin-assistant:draft:#{draft_kind}:#{reference}"
+ end
+
+ def claim_key(reference)
+ "admin-assistant:claim:#{draft_kind}:#{Digest::SHA256.hexdigest(reference.to_s)}"
+ end
+
+ def reference_pattern
+ /\A#{Regexp.escape(reference_prefix)}[0-9a-f]{32}\z/
+ end
+
+ def verify(signed)
+ draft = verifier.verified(signed, purpose: purpose)
+ return unless draft.is_a?(Hash) && draft["site"] == Discourse.current_hostname
+
+ draft.symbolize_keys
+ end
+
+ def verifier
+ Rails.application.message_verifier("admin-assistant-#{draft_kind}")
+ end
+
+ def draft_kind
+ raise NotImplementedError
+ end
+
+ def purpose
+ "admin_assistant_#{draft_kind}"
+ end
+
+ def reference_prefix
+ "#{draft_kind}_draft_"
+ end
+ end
+ end
+ end
+ end
+end
diff --git a/plugins/discourse-ai/lib/agents/tools/tool.rb b/plugins/discourse-ai/lib/agents/tools/tool.rb
index 398fa9fd9a2..a0bb44c114f 100644
--- a/plugins/discourse-ai/lib/agents/tools/tool.rb
+++ b/plugins/discourse-ai/lib/agents/tools/tool.rb
@@ -51,6 +51,10 @@ module DiscourseAi
false
end
+ def available_for_context?(_context)
+ true
+ end
+
# When true, the replayed tool (after approval) is given the
# approving moderator as context.user, so guardian checks and
# downstream audit logs (StaffActionLogger, UserHistory) credit
diff --git a/plugins/discourse-ai/spec/lib/agents/admin_assistant_access_spec.rb b/plugins/discourse-ai/spec/lib/agents/admin_assistant_access_spec.rb
new file mode 100644
index 00000000000..547a1e1144a
--- /dev/null
+++ b/plugins/discourse-ai/spec/lib/agents/admin_assistant_access_spec.rb
@@ -0,0 +1,30 @@
+# frozen_string_literal: true
+
+RSpec.describe DiscourseAi::Agents::AdminAssistantAccess do
+ fab!(:admin)
+
+ it "is permissive by default and threads user and phase through restrictive modifiers" do
+ expect(described_class.check(feature: :reports, user: admin, phase: :generation).allowed).to eq(
+ true,
+ )
+
+ plugin = Plugin::Instance.new
+ modifier =
+ lambda do |decision, request|
+ expect([request.feature, request.user, request.phase]).to eq([:reports, admin, :approval])
+ decision.deny!("Unavailable")
+ end
+ DiscoursePluginRegistry.register_modifier(plugin, :admin_assistant_feature_access, &modifier)
+
+ result = described_class.check(feature: :reports, user: admin, phase: :approval)
+ expect(result).to have_attributes(allowed: false, message: "Unavailable")
+ ensure
+ if plugin && modifier
+ DiscoursePluginRegistry.unregister_modifier(
+ plugin,
+ :admin_assistant_feature_access,
+ &modifier
+ )
+ end
+ end
+end
diff --git a/plugins/discourse-ai/spec/lib/agents/discourse_admin_assistant_spec.rb b/plugins/discourse-ai/spec/lib/agents/discourse_admin_assistant_spec.rb
index 6376e643f5d..c74e31aaa50 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
@@ -9,8 +9,8 @@ RSpec.describe DiscourseAi::Agents::DiscourseAdminAssistant do
before { enable_current_plugin }
it "combines Discourse knowledge, general administration, and site-setting tools" do
- expect(assistant.tools).to eq(
- [
+ expect(assistant.tools).to start_with(
+ *[
DiscourseAi::Agents::Tools::LoadDiscourseWebsitePage,
DiscourseAi::Agents::Tools::DiscourseMetaSearch,
DiscourseAi::Agents::Tools::ListCategories,
diff --git a/plugins/discourse-ai/spec/lib/agents/tools/draft_reference_spec.rb b/plugins/discourse-ai/spec/lib/agents/tools/draft_reference_spec.rb
new file mode 100644
index 00000000000..1ffa2f7ca08
--- /dev/null
+++ b/plugins/discourse-ai/spec/lib/agents/tools/draft_reference_spec.rb
@@ -0,0 +1,61 @@
+# frozen_string_literal: true
+
+RSpec.describe DiscourseAi::Agents::Tools::DraftReference do
+ fab!(:admin)
+
+ let(:draft_class) do
+ Class.new(described_class) do
+ def self.draft_kind
+ "spec"
+ end
+ private_class_method :draft_kind
+ end
+ end
+
+ it "round-trips a short user-bound and site-bound payload" do
+ reference = draft_class.sign({ value: "safe" }, user: admin)
+
+ expect(reference).to match(/\Aspec_draft_[0-9a-f]{32}\z/)
+ expect(draft_class.read(reference)).to include(value: "safe", user_id: admin.id)
+
+ Discourse.stubs(:current_hostname).returns("another.example.com")
+ expect(draft_class.read(reference)).to be_nil
+ end
+
+ it "rejects malformed, tampered, expired, and oversized drafts" do
+ reference = draft_class.sign({ value: "safe" }, user: admin)
+ expect(draft_class.read("#{reference}tampered")).to be_nil
+
+ freeze_time 2.days.from_now
+ expect(draft_class.read(reference)).to be_nil
+
+ freeze_time 2.days.ago
+ expect { draft_class.sign({ value: "x" * 65.kilobytes }, user: admin) }.to raise_error(
+ Discourse::InvalidParameters,
+ )
+ end
+
+ it "releases a claim when a surrounding transaction rolls back" do
+ reference = draft_class.sign({ value: "safe" }, user: admin)
+
+ ActiveRecord::Base.transaction do
+ ActiveRecord::Base.transaction(requires_new: true) do
+ expect(draft_class.claim(reference, reviewable_id: 1)).to eq(true)
+ draft_class.complete_after_transaction(reference, reviewable_id: 1, resource_id: 2)
+ end
+ raise ActiveRecord::Rollback
+ end
+
+ expect(draft_class.claim(reference, reviewable_id: 2)).to eq(true)
+ draft_class.release(reference, reviewable_id: 2)
+ end
+
+ it "blocks concurrent claims and replay after completion" do
+ reference = draft_class.sign({ value: "safe" }, user: admin)
+ expect(draft_class.claim(reference, reviewable_id: 1)).to eq(true)
+ expect(draft_class.claim(reference, reviewable_id: 2)).to eq(false)
+
+ draft_class.complete_after_transaction(reference, reviewable_id: 1, resource_id: 3)
+ expect(draft_class.claim(reference, reviewable_id: 4)).to eq(false)
+ end
+end
diff --git a/plugins/discourse-ai/spec/lib/modules/ai_bot/jobs/regular/resume_ai_tool_approval_spec.rb b/plugins/discourse-ai/spec/lib/modules/ai_bot/jobs/regular/resume_ai_tool_approval_spec.rb
index 13d0f108940..e5a4968a6e1 100644
--- a/plugins/discourse-ai/spec/lib/modules/ai_bot/jobs/regular/resume_ai_tool_approval_spec.rb
+++ b/plugins/discourse-ai/spec/lib/modules/ai_bot/jobs/regular/resume_ai_tool_approval_spec.rb
@@ -175,7 +175,7 @@ RSpec.describe Jobs::ResumeAiToolApproval do
topic.update!(archetype: Archetype.default)
original_raw = approval_post.raw
previous_prompt = [["I will create the category.", ai_agent.user.username]]
- approval_post.create_post_custom_prompt!(custom_prompt: previous_prompt)
+ PostCustomPrompt.create!(post: approval_post, custom_prompt: previous_prompt)
reviewable.perform(admin, :approve, post_id: approval_post.id)
expect {
diff --git a/plugins/discourse-data-explorer/config/locales/server.en.yml b/plugins/discourse-data-explorer/config/locales/server.en.yml
index ffa3deea4b9..72b2214bca6 100644
--- a/plugins/discourse-data-explorer/config/locales/server.en.yml
+++ b/plugins/discourse-data-explorer/config/locales/server.en.yml
@@ -21,6 +21,24 @@ en:
run_sql: "Ran SQL query"
submit_query: "Submitted generated query %{name}"
discourse_data_explorer:
+ admin_assistant:
+ generating: "Generating and testing a query draft"
+ create_summary: "Save this Data Explorer query?"
+ not_allowed: "Only administrators can create Data Explorer queries."
+ invalid_request: "The query request is empty or too long. Please provide a shorter description."
+ invalid_draft: "This query draft reference is invalid, unavailable, or expired. Please generate a new draft."
+ incomplete_draft: "The generated query draft is missing its name or SQL. Please generate a new draft."
+ requester_not_admin: "The administrator who requested this query no longer has admin access. Please request a new draft from an admin account."
+ approval_required: "Saving this query requires human approval."
+ draft_used: "This query draft has already been used or is being saved. Please generate a new draft."
+ generation_failed: "The query could not be generated. Please try again or refine your request."
+ creation_failed: "The query could not be saved. No query was created."
+ availability:
+ available: "Data Explorer query creation is available. Saving requires explicit approval."
+ restricted: "Data Explorer query creation is unavailable on this site."
+ disabled: "Data Explorer or Discourse AI is disabled. An administrator needs to enable the required plugins before creating queries."
+ generation_disabled: "AI query generation is disabled. An administrator needs to enable it before creating queries through chat."
+ unconfigured: "Data Explorer's query-generation AI model is not configured or usable."
mcp:
query_failed: "The query could not be run: %{message}"
query_not_found: "Query not found"
diff --git a/plugins/discourse-data-explorer/lib/discourse_data_explorer/admin_assistant/capability.rb b/plugins/discourse-data-explorer/lib/discourse_data_explorer/admin_assistant/capability.rb
new file mode 100644
index 00000000000..b6036104458
--- /dev/null
+++ b/plugins/discourse-data-explorer/lib/discourse_data_explorer/admin_assistant/capability.rb
@@ -0,0 +1,53 @@
+# frozen_string_literal: true
+
+module DiscourseDataExplorer
+ module AdminAssistant
+ class Capability
+ FEATURE = :data_explorer_query_authoring
+
+ def self.status(user:, phase:)
+ access =
+ DiscourseAi::Agents::AdminAssistantAccess.check(
+ feature: FEATURE,
+ user: user,
+ phase: phase,
+ )
+ return :restricted if !access.allowed
+ public_status
+ end
+
+ def self.public_status
+ unless SiteSetting.discourse_ai_enabled && SiteSetting.data_explorer_enabled
+ return :disabled
+ end
+ return :generation_disabled unless SiteSetting.data_explorer_ai_queries_enabled
+
+ agent_id =
+ DiscourseAi::Agents::Agent.external_agent_id(DiscourseDataExplorer::AiQueryGenerator)
+ agent = AiAgent.find_by(id: agent_id)
+ return :unconfigured if !agent&.enabled?
+
+ model_id = agent.default_llm_id || SiteSetting.ai_default_llm_model.presence
+ model = LlmModel.find_by(id: model_id)
+ return :unconfigured if !model&.valid?
+
+ :available
+ end
+ private_class_method :public_status
+
+ def self.message(user:, phase:)
+ access =
+ DiscourseAi::Agents::AdminAssistantAccess.check(
+ feature: FEATURE,
+ user: user,
+ phase: phase,
+ )
+ return access.message if !access.allowed && access.message.present?
+
+ I18n.t(
+ "discourse_data_explorer.admin_assistant.availability.#{status(user: user, phase: phase)}",
+ )
+ end
+ end
+ end
+end
diff --git a/plugins/discourse-data-explorer/lib/discourse_data_explorer/admin_assistant/create_query.rb b/plugins/discourse-data-explorer/lib/discourse_data_explorer/admin_assistant/create_query.rb
new file mode 100644
index 00000000000..bf7a408ba58
--- /dev/null
+++ b/plugins/discourse-data-explorer/lib/discourse_data_explorer/admin_assistant/create_query.rb
@@ -0,0 +1,159 @@
+# frozen_string_literal: true
+
+module DiscourseDataExplorer
+ module AdminAssistant
+ class CreateQuery < DiscourseAi::Agents::Tools::Tool
+ def self.name
+ "create_data_explorer_query"
+ end
+
+ def self.signature
+ {
+ name: name,
+ description:
+ "Request human approval to save an exact generated Data Explorer query draft. Never invent, alter, or reuse the draft token.",
+ parameters: [
+ {
+ name: "draft_token",
+ type: "string",
+ required: true,
+ description: "The draft token returned by generate_data_explorer_query",
+ },
+ ],
+ }
+ end
+
+ def self.requires_approval?
+ true
+ end
+
+ def self.mandatory_approval?
+ true
+ end
+
+ def self.attribute_to_approver?
+ true
+ end
+
+ def self.help
+ I18n.t("discourse_data_explorer.admin_assistant.create_summary")
+ end
+
+ def self.available_for_context?(context)
+ context&.user&.admin? &&
+ Capability.status(user: context.user, phase: :visibility) == :available
+ end
+
+ def summary
+ self.class.help
+ end
+
+ def approval_parameters
+ []
+ end
+
+ def details
+ return I18n.t("discourse_data_explorer.admin_assistant.invalid_draft") unless draft
+
+ [draft[:name], draft[:description], draft[:sql]].map do |text|
+ text.to_s.lines.map { |line| " #{line}" }.join
+ end
+ .join("\n\n")
+ end
+
+ def validation_error
+ if !context.user&.admin?
+ return error_response(I18n.t("discourse_data_explorer.admin_assistant.not_allowed"))
+ end
+ if Capability.status(user: context.user, phase: execution_phase) != :available
+ return error_response(Capability.message(user: context.user, phase: execution_phase))
+ end
+ if !draft
+ return error_response(I18n.t("discourse_data_explorer.admin_assistant.invalid_draft"))
+ end
+ if draft[:sql].blank? || draft[:name].blank?
+ return error_response(I18n.t("discourse_data_explorer.admin_assistant.incomplete_draft"))
+ end
+
+ requester = User.find_by(id: draft[:user_id], admin: true)
+ if requester.blank?
+ return(
+ error_response(I18n.t("discourse_data_explorer.admin_assistant.requester_not_admin"))
+ )
+ end
+ if context.reviewable_id.blank? && draft[:user_id] != context.user.id
+ return error_response(I18n.t("discourse_data_explorer.admin_assistant.not_allowed"))
+ end
+ parameters[:requester_id] = draft[:user_id] if context.reviewable_id.blank?
+
+ nil
+ end
+
+ def invoke
+ validation_failure = validation_error
+ return validation_failure if validation_failure
+ return approval_required if context.reviewable_id.blank?
+
+ reviewable = matching_reviewable
+ return approval_required if reviewable.blank?
+
+ reviewable.with_lock do
+ return approval_required if !reviewable.pending?
+ unless QueryDraft.claim(parameters[:draft_token], reviewable_id: reviewable.id)
+ return error_response(I18n.t("discourse_data_explorer.admin_assistant.draft_used"))
+ end
+
+ begin
+ query = nil
+ DiscourseDataExplorer::Query.transaction do
+ query =
+ DiscourseDataExplorer::QueryCreator.create(
+ query_params: draft.slice(:name, :description, :sql),
+ group_ids: [],
+ user: context.user,
+ )
+ QueryDraft.complete_after_transaction(
+ parameters[:draft_token],
+ reviewable_id: reviewable.id,
+ resource_id: query.id,
+ )
+ end
+ { status: "success", query_id: query.id, url: query_url(query) }
+ rescue => error
+ QueryDraft.release(parameters[:draft_token], reviewable_id: reviewable.id)
+ raise error
+ end
+ end
+ rescue ActiveRecord::ActiveRecordError, Discourse::InvalidParameters
+ error_response(I18n.t("discourse_data_explorer.admin_assistant.creation_failed"))
+ end
+
+ private
+
+ def approval_required
+ error_response(I18n.t("discourse_data_explorer.admin_assistant.approval_required"))
+ end
+
+ def draft
+ QueryDraft.read_with_compatibility(parameters[:draft_token])
+ end
+
+ def execution_phase
+ context.reviewable_id.present? ? :approval : :request
+ end
+
+ def matching_reviewable
+ item = ReviewableAiToolAction.find_by(id: context.reviewable_id)
+ return if !item || item.target&.tool_name != self.class.name
+ return if item.target.tool_parameters["draft_token"] != parameters[:draft_token]
+ return if item.target.tool_parameters["requester_id"].to_i != draft[:user_id]
+
+ item
+ end
+
+ def query_url(query)
+ "#{Discourse.base_url}/admin/plugins/discourse-data-explorer/queries/#{query.id}"
+ end
+ end
+ end
+end
diff --git a/plugins/discourse-data-explorer/lib/discourse_data_explorer/admin_assistant/generate_query.rb b/plugins/discourse-data-explorer/lib/discourse_data_explorer/admin_assistant/generate_query.rb
new file mode 100644
index 00000000000..0f1daf819d3
--- /dev/null
+++ b/plugins/discourse-data-explorer/lib/discourse_data_explorer/admin_assistant/generate_query.rb
@@ -0,0 +1,75 @@
+# frozen_string_literal: true
+
+module DiscourseDataExplorer
+ module AdminAssistant
+ class GenerateQuery < DiscourseAi::Agents::Tools::Tool
+ MAX_DESCRIPTION_LENGTH = 4000
+
+ def self.name
+ "generate_data_explorer_query"
+ end
+
+ def self.signature
+ {
+ name: name,
+ description:
+ "Generate and test a Data Explorer query draft without saving it. Use create_data_explorer_query with the returned draft token to request approval to save the exact draft. For revisions, describe the complete revised request.",
+ parameters: [
+ {
+ name: "description",
+ type: "string",
+ required: true,
+ description: "The complete report or query requested by the administrator",
+ },
+ ],
+ }
+ end
+
+ def self.help
+ I18n.t("discourse_data_explorer.admin_assistant.generating")
+ end
+
+ def self.custom_system_message
+ <<~TEXT
+ When an administrator asks to create a Data Explorer query, first call generate_data_explorer_query with the complete request. If generation succeeds, call create_data_explorer_query with the exact returned draft token. Saving always requires explicit human approval.
+ TEXT
+ end
+
+ def self.available_for_context?(context)
+ context&.user&.admin? &&
+ Capability.status(user: context.user, phase: :visibility) == :available
+ end
+
+ def summary
+ self.class.help
+ end
+
+ def details
+ summary
+ end
+
+ def invoke
+ if !context.user&.admin?
+ return error_response(I18n.t("discourse_data_explorer.admin_assistant.not_allowed"))
+ end
+ if Capability.status(user: context.user, phase: :generation) != :available
+ return error_response(Capability.message(user: context.user, phase: :generation))
+ end
+
+ description = parameters[:description].to_s.strip
+ if description.blank? || description.length > MAX_DESCRIPTION_LENGTH
+ return error_response(I18n.t("discourse_data_explorer.admin_assistant.invalid_request"))
+ end
+
+ query =
+ DiscourseDataExplorer::QueryGeneration.call(
+ user: context.user,
+ ai_description: description,
+ )
+ query.merge(status: "success", draft_token: QueryDraft.sign(query, user: context.user))
+ rescue DiscourseDataExplorer::QueryGeneration::Error, Discourse::InvalidParameters
+ error_response(I18n.t("discourse_data_explorer.admin_assistant.generation_failed"))
+ end
+ end
+ end
+end
diff --git a/plugins/discourse-data-explorer/lib/discourse_data_explorer/admin_assistant/query_draft.rb b/plugins/discourse-data-explorer/lib/discourse_data_explorer/admin_assistant/query_draft.rb
new file mode 100644
index 00000000000..5a4974512a0
--- /dev/null
+++ b/plugins/discourse-data-explorer/lib/discourse_data_explorer/admin_assistant/query_draft.rb
@@ -0,0 +1,15 @@
+# frozen_string_literal: true
+
+module DiscourseDataExplorer
+ module AdminAssistant
+ class QueryDraft < DiscourseAi::Agents::Tools::DraftReference
+ class << self
+ private
+
+ def draft_kind
+ "data_explorer_query"
+ end
+ end
+ end
+ end
+end
diff --git a/plugins/discourse-data-explorer/plugin.rb b/plugins/discourse-data-explorer/plugin.rb
index 4c4c9bae782..9509e6fed26 100644
--- a/plugins/discourse-data-explorer/plugin.rb
+++ b/plugins/discourse-data-explorer/plugin.rb
@@ -282,6 +282,17 @@ after_initialize do
require_relative "lib/discourse_data_explorer/tools/submit_query"
require_relative "lib/discourse_data_explorer/ai_query_generator"
require_relative "lib/discourse_data_explorer/query_generation"
+ require_relative "lib/discourse_data_explorer/admin_assistant/capability"
+ require_relative "lib/discourse_data_explorer/admin_assistant/query_draft"
+ require_relative "lib/discourse_data_explorer/admin_assistant/generate_query"
+ require_relative "lib/discourse_data_explorer/admin_assistant/create_query"
+
+ admin_assistant_tools = [
+ DiscourseDataExplorer::AdminAssistant::GenerateQuery,
+ DiscourseDataExplorer::AdminAssistant::CreateQuery,
+ ]
+ register_modifier(:ai_agent_available_tools) { |tools| tools + admin_assistant_tools }
+ register_modifier(:admin_assistant_tools) { |tools, _agent| tools + admin_assistant_tools }
DiscourseAi.register_feature(
module_name: :data_explorer,
diff --git a/plugins/discourse-data-explorer/spec/lib/discourse_data_explorer/admin_assistant/capability_spec.rb b/plugins/discourse-data-explorer/spec/lib/discourse_data_explorer/admin_assistant/capability_spec.rb
new file mode 100644
index 00000000000..08f9da091c0
--- /dev/null
+++ b/plugins/discourse-data-explorer/spec/lib/discourse_data_explorer/admin_assistant/capability_spec.rb
@@ -0,0 +1,31 @@
+# frozen_string_literal: true
+
+RSpec.describe DiscourseDataExplorer::AdminAssistant::Capability do
+ fab!(:admin)
+
+ before do
+ SiteSetting.discourse_ai_enabled = true
+ SiteSetting.data_explorer_enabled = true
+ SiteSetting.data_explorer_ai_queries_enabled = true
+ end
+
+ it "reports disabled public settings without relying on an external policy" do
+ SiteSetting.data_explorer_enabled = false
+ expect(described_class.status(user: admin, phase: :visibility)).to eq(:disabled)
+ end
+
+ it "reports an unusable model configuration" do
+ AiAgent.stubs(:find_by).returns(nil)
+ expect(described_class.status(user: admin, phase: :visibility)).to eq(:unconfigured)
+ end
+
+ it "stops before model lookup when a generic policy denies access" do
+ DiscourseAi::Agents::AdminAssistantAccess.stubs(:check).returns(
+ DiscourseAi::Agents::AdminAssistantAccess::Result.new(allowed: false, message: "No"),
+ )
+ AiAgent.expects(:find_by).never
+
+ expect(described_class.status(user: admin, phase: :generation)).to eq(:restricted)
+ expect(described_class.message(user: admin, phase: :generation)).to eq("No")
+ end
+end
diff --git a/plugins/discourse-data-explorer/spec/lib/discourse_data_explorer/admin_assistant/completion_spec.rb b/plugins/discourse-data-explorer/spec/lib/discourse_data_explorer/admin_assistant/completion_spec.rb
new file mode 100644
index 00000000000..967a55b5101
--- /dev/null
+++ b/plugins/discourse-data-explorer/spec/lib/discourse_data_explorer/admin_assistant/completion_spec.rb
@@ -0,0 +1,83 @@
+# frozen_string_literal: true
+
+RSpec.describe DiscourseDataExplorer::AdminAssistant::CreateQuery do
+ fab!(:admin)
+ fab!(:llm_model) { Fabricate(:llm_model, name: "gpt-3.5-turbo") }
+ fab!(:ai_agent) do
+ Fabricate(
+ :ai_agent,
+ allowed_group_ids: [Group::AUTO_GROUPS[:admins]],
+ require_approval: true,
+ ).tap(&:create_user!)
+ end
+ fab!(:topic) do
+ Fabricate(:private_message_topic, user: admin, recipient: Discourse.system_user).tap do |topic|
+ topic.allowed_users << ai_agent.user
+ end
+ end
+ fab!(:source_post) { Fabricate(:post, topic: topic, user: admin) }
+
+ before do
+ prepare_ai_bot_fixtures(bots: [llm_model])
+ SiteSetting.data_explorer_enabled = true
+ DiscourseDataExplorer::AdminAssistant::Capability.stubs(:status).returns(:available)
+ end
+
+ it "approves in a PM and appends a completion containing the saved query URL" do
+ token =
+ DiscourseDataExplorer::AdminAssistant::QueryDraft.sign(
+ {
+ name: "Recent users",
+ description: "Lists recent users",
+ sql: "SELECT id AS user_id FROM users",
+ },
+ user: admin,
+ )
+ action =
+ AiToolAction.create!(
+ tool_name: DiscourseDataExplorer::AdminAssistant::CreateQuery.name,
+ tool_parameters: {
+ draft_token: token,
+ requester_id: admin.id,
+ },
+ ai_agent: ai_agent,
+ bot_user_id: ai_agent.user_id,
+ post_id: source_post.id,
+ )
+ reviewable =
+ ReviewableAiToolAction.needs_review!(
+ target: action,
+ created_by: ai_agent.user,
+ reviewable_by_moderator: true,
+ payload: {
+ llm_model_id: llm_model.id,
+ },
+ )
+ approval_post =
+ Fabricate(
+ :post,
+ topic: topic,
+ user: ai_agent.user,
+ raw: "<div data-ai-tool-approval-reviewable-id='#{reviewable.id}'></div>",
+ custom_fields: {
+ DiscourseAi::AiBot::POST_AI_AGENT_AUTHORIZATION_USER_ID_FIELD => admin.id,
+ },
+ )
+
+ reviewable.perform(admin, :approve, post_id: approval_post.id)
+ query = DiscourseDataExplorer::Query.order(:id).last
+ url = "#{Discourse.base_url}/admin/plugins/discourse-data-explorer/queries/#{query.id}"
+ prompts = nil
+
+ DiscourseAi::Completions::Llm.with_prepared_responses(
+ ["[Open the query](#{url})."],
+ ) do |_, _, captured_prompts|
+ Jobs::ResumeAiToolApproval.new.execute(reviewable_id: reviewable.id)
+ prompts = captured_prompts
+ end
+
+ result = JSON.parse(prompts.first.messages.last[:content]).fetch("result")
+ expect(result).to eq("status" => "success", "url" => url, "query_id" => query.id)
+ expect(approval_post.reload.raw).to end_with("[Open the query](#{url}).")
+ end
+end
diff --git a/plugins/discourse-data-explorer/spec/lib/discourse_data_explorer/admin_assistant/query_tools_spec.rb b/plugins/discourse-data-explorer/spec/lib/discourse_data_explorer/admin_assistant/query_tools_spec.rb
new file mode 100644
index 00000000000..0e6ad8df9d6
--- /dev/null
+++ b/plugins/discourse-data-explorer/spec/lib/discourse_data_explorer/admin_assistant/query_tools_spec.rb
@@ -0,0 +1,213 @@
+# frozen_string_literal: true
+
+RSpec.describe DiscourseDataExplorer::AdminAssistant::CreateQuery do
+ fab!(:admin)
+ fab!(:other_admin, :admin)
+ fab!(:user)
+ fab!(:ai_agent)
+
+ let(:query) do
+ {
+ name: "Recent users",
+ description: "Lists recent users",
+ sql: "SELECT id AS user_id FROM users",
+ }
+ end
+ let(:token) { DiscourseDataExplorer::AdminAssistant::QueryDraft.sign(query, user: admin) }
+ let(:context) { DiscourseAi::Agents::BotContext.new(user: admin, messages: []) }
+ let(:tool) do
+ described_class.new(
+ { draft_token: token },
+ bot_user: Discourse.system_user,
+ llm: nil,
+ context: context,
+ )
+ end
+
+ before do
+ SiteSetting.discourse_ai_enabled = true
+ SiteSetting.data_explorer_enabled = true
+ SiteSetting.data_explorer_ai_queries_enabled = true
+ DiscourseDataExplorer::AdminAssistant::Capability.stubs(:status).returns(:available)
+ end
+
+ def build_reviewable(draft_token = token, requester_id: admin.id)
+ action =
+ AiToolAction.create!(
+ tool_name: described_class.name,
+ tool_parameters: {
+ draft_token: draft_token,
+ requester_id: requester_id,
+ },
+ ai_agent: ai_agent,
+ bot_user_id: Discourse.system_user.id,
+ )
+ ReviewableAiToolAction
+ .needs_review!(
+ target: action,
+ created_by: Discourse.system_user,
+ reviewable_by_moderator: true,
+ )
+ .tap do |reviewable|
+ reviewable.add_score(
+ Discourse.system_user,
+ ReviewableScore.types[:needs_approval],
+ force_review: true,
+ )
+ end
+ end
+
+ it "requires approval and shows the exact query without its token" do
+ expect(described_class.mandatory_approval?).to eq(true)
+ expect(tool.details).to include(query[:name], query[:description], query[:sql])
+ expect(tool.details).not_to include(token)
+ expect(tool.approval_parameters).to be_empty
+ expect { tool.invoke }.not_to change { DiscourseDataExplorer::Query.count }
+ end
+
+ it "saves the approved draft unchanged with the approver as owner and returns its URL" do
+ reviewable = build_reviewable
+
+ expect { reviewable.perform(other_admin, :approve) }.to change {
+ DiscourseDataExplorer::Query.count
+ }.by(1)
+ saved = DiscourseDataExplorer::Query.order(:id).last
+ expect(saved).to have_attributes(query.merge(user_id: other_admin.id))
+ expect(saved.query_groups).to be_empty
+ expect(reviewable.payload&.dig("continuation", "tool_result")).to be_nil
+ end
+
+ it "binds approval to the signed requester and exact draft token" do
+ wrong_requester = build_reviewable(requester_id: other_admin.id)
+ wrong_token = build_reviewable("#{token}tampered")
+
+ expect { wrong_requester.perform(other_admin, :approve) }.to raise_error(
+ Discourse::InvalidAccess,
+ )
+ expect { wrong_token.perform(other_admin, :approve) }.to raise_error(Discourse::InvalidAccess)
+ expect(DiscourseDataExplorer::Query.count).to eq(0)
+ end
+
+ it "rejects unauthorized, expired, tampered, and cross-site drafts" do
+ context.user = user
+ expect(tool.validation_error[:status]).to eq("error")
+
+ context.user = admin
+ tool.parameters[:draft_token] = "#{token}tampered"
+ expect(tool.validation_error[:status]).to eq("error")
+
+ tool.parameters[:draft_token] = token
+ freeze_time 2.days.from_now
+ expect(tool.validation_error[:status]).to eq("error")
+
+ freeze_time 2.days.ago
+ Discourse.stubs(:current_hostname).returns("another.example.com")
+ expect(DiscourseDataExplorer::AdminAssistant::QueryDraft.read(token)).to be_nil
+ end
+
+ it "rechecks public capability and requester authorization at approval time" do
+ reviewable = build_reviewable
+ DiscourseDataExplorer::AdminAssistant::Capability.stubs(:status).returns(:restricted)
+
+ expect { reviewable.perform(other_admin, :approve) }.to raise_error(Discourse::InvalidAccess)
+ expect(reviewable.reload).to be_pending
+
+ DiscourseDataExplorer::AdminAssistant::Capability.stubs(:status).returns(:available)
+ admin.update!(admin: false)
+ expect { reviewable.perform(other_admin, :approve) }.to raise_error(Discourse::InvalidAccess)
+ expect(DiscourseDataExplorer::Query.count).to eq(0)
+ end
+
+ it "prevents replay through another approval" do
+ first = build_reviewable
+ second = build_reviewable
+
+ first.perform(admin, :approve)
+ expect { second.perform(other_admin, :approve) }.to raise_error(Discourse::InvalidAccess)
+ expect(DiscourseDataExplorer::Query.count).to eq(1)
+ end
+
+ it "releases the replay claim when the approval transaction rolls back" do
+ reviewable = build_reviewable
+ replay_context = DiscourseAi::Agents::BotContext.new(user: other_admin, messages: [])
+ replay_context.reviewable_id = reviewable.id
+ replay_tool =
+ described_class.new(
+ { draft_token: token, requester_id: admin.id },
+ bot_user: Discourse.system_user,
+ llm: nil,
+ context: replay_context,
+ )
+
+ expect do
+ DiscourseDataExplorer::Query.transaction(requires_new: true) do
+ expect(replay_tool.invoke[:status]).to eq("success")
+ raise ActiveRecord::Rollback
+ end
+ end.not_to change { DiscourseDataExplorer::Query.count }
+ expect(
+ DiscourseDataExplorer::AdminAssistant::QueryDraft.claim(token, reviewable_id: reviewable.id),
+ ).to eq(true)
+ DiscourseDataExplorer::AdminAssistant::QueryDraft.release(token, reviewable_id: reviewable.id)
+ end
+
+ it "reconstructs a pending tool even when runtime policy now hides it" do
+ reviewable = build_reviewable
+ DiscourseDataExplorer::AdminAssistant::Capability.stubs(:status).returns(:restricted)
+ runtime_context = DiscourseAi::Agents::BotContext.new(user: admin, messages: [])
+
+ expect(
+ DiscourseAi::Agents::DiscourseAdminAssistant.new.runtime_tools(context: runtime_context),
+ ).not_to include(described_class)
+ expect(DiscourseAi::Agents::Agent.all_available_tools).to include(described_class)
+ expect { reviewable.perform(other_admin, :approve) }.to raise_error(Discourse::InvalidAccess)
+ end
+end
+
+RSpec.describe DiscourseDataExplorer::AdminAssistant::GenerateQuery do
+ fab!(:admin)
+
+ let(:context) { DiscourseAi::Agents::BotContext.new(user: admin, messages: []) }
+ let(:tool) do
+ described_class.new(
+ { description: "Recent users" },
+ bot_user: Discourse.system_user,
+ llm: nil,
+ context: context,
+ )
+ end
+ let(:query) do
+ {
+ name: "Recent users",
+ description: "Lists recent users",
+ sql: "SELECT id AS user_id FROM users",
+ }
+ end
+
+ before { DiscourseDataExplorer::AdminAssistant::Capability.stubs(:status).returns(:available) }
+
+ it "generates a bounded signed draft without saving a query" do
+ DiscourseDataExplorer::QueryGeneration
+ .expects(:call)
+ .with(user: admin, ai_description: "Recent users")
+ .returns(query)
+
+ result = nil
+ expect { result = tool.invoke }.not_to change { DiscourseDataExplorer::Query.count }
+ expect(result[:status]).to eq("success")
+ expect(DiscourseDataExplorer::AdminAssistant::QueryDraft.read(result[:draft_token])).to include(
+ query.merge(user_id: admin.id),
+ )
+ end
+
+ it "denies policy before query generation and rejects oversized requests" do
+ DiscourseDataExplorer::AdminAssistant::Capability.stubs(:status).returns(:restricted)
+ allow(DiscourseDataExplorer::QueryGeneration).to receive(:call)
+ expect(tool.invoke[:status]).to eq("error")
+
+ DiscourseDataExplorer::AdminAssistant::Capability.stubs(:status).returns(:available)
+ tool.parameters[:description] = "x" * 4001
+ expect(tool.invoke[:status]).to eq("error")
+ expect(DiscourseDataExplorer::QueryGeneration).not_to have_received(:call)
+ end
+end
diff --git a/plugins/discourse-workflows/assets/javascripts/discourse/components/admin-assistant/workflow-preview.gjs b/plugins/discourse-workflows/assets/javascripts/discourse/components/admin-assistant/workflow-preview.gjs
new file mode 100644
index 00000000000..72cd140e1db
--- /dev/null
+++ b/plugins/discourse-workflows/assets/javascripts/discourse/components/admin-assistant/workflow-preview.gjs
@@ -0,0 +1,235 @@
+import Component from "@glimmer/component";
+import { cached } from "@glimmer/tracking";
+import { trustHTML } from "@ember/template";
+import { bind } from "discourse/lib/decorators";
+import dIcon from "discourse/ui-kit/helpers/d-icon";
+import { i18n } from "discourse-i18n";
+import {
+ extractWorkflowPreview,
+ layoutWorkflowPreview,
+} from "../../lib/admin-assistant/workflow-preview.js";
+
+function nodeIcon(type) {
+ if (type.startsWith("trigger:")) {
+ return "bolt";
+ }
+ if (type.includes("condition") || type.includes("branch")) {
+ return "code-branch";
+ }
+ return "gear";
+}
+
+function connectionLabel(connection) {
+ if (connection.connectionType && connection.connectionType !== "main") {
+ return connection.connectionType;
+ }
+ if (connection.branchNumber) {
+ return i18n("discourse_workflows.admin_assistant.preview.branch", {
+ number: connection.branchNumber,
+ });
+ }
+ return null;
+}
+
+export default class AdminAssistantWorkflowPreview extends Component {
+ @cached
+ get preview() {
+ const hasConfirmation = this.args.message?.blocks?.some(
+ (block) => block.type === "confirmation"
+ );
+ if (!hasConfirmation) {
+ return null;
+ }
+
+ return extractWorkflowPreview(this.args.message?.cooked);
+ }
+
+ @cached
+ get layout() {
+ return this.preview?.nodes ? layoutWorkflowPreview(this.preview) : null;
+ }
+
+ get hasFailedScripts() {
+ const validations = this.preview?.configuration?.script_validations;
+ return (
+ Array.isArray(validations) &&
+ validations.some((validation) => validation?.valid === false)
+ );
+ }
+
+ get exactConfiguration() {
+ return JSON.stringify(this.preview.configuration, null, 2);
+ }
+
+ get markerId() {
+ return `assistant-workflow-preview-arrow-${this.args.message?.id ?? "draft"}`;
+ }
+
+ get markerUrl() {
+ return `url(#${this.markerId})`;
+ }
+
+ get viewportStyle() {
+ return trustHTML(
+ `width: ${this.layout.width}px; height: ${this.layout.height}px;`
+ );
+ }
+
+ @bind
+ nodeConnections(node) {
+ return this.layout.connections
+ .filter((connection) => connection.from === node.id)
+ .map((connection) => {
+ const target = this.preview.nodes.find(
+ (candidate) => candidate.id === connection.to
+ );
+ if (!target) {
+ return null;
+ }
+
+ return connectionLabel(connection)
+ ? `${connectionLabel(connection)}: ${target.name}`
+ : target.name;
+ })
+ .filter(Boolean)
+ .join(", ");
+ }
+
+ @bind
+ nodeStyle(node) {
+ return trustHTML(
+ `left: ${node.x}px; top: ${node.y}px; width: ${this.layout.nodeWidth}px; height: ${this.layout.nodeHeight}px;`
+ );
+ }
+
+ <template>
+ {{#if this.preview}}
+ <section
+ aria-label={{i18n "discourse_workflows.admin_assistant.preview.label"}}
+ class="assistant-workflow-preview"
+ >
+ <header class="assistant-workflow-preview__header">
+ <span class="assistant-workflow-preview__heading">
+ {{dIcon "code-branch"}}
+ <span>{{this.preview.name}}</span>
+ </span>
+ <span class="assistant-workflow-preview__badge">
+ {{i18n "discourse_workflows.admin_assistant.preview.read_only"}}
+ </span>
+ </header>
+
+ {{#if this.hasFailedScripts}}
+ <p class="assistant-workflow-preview__warning" role="status">
+ {{i18n
+ "discourse_workflows.admin_assistant.preview.script_validation_warning"
+ }}
+ </p>
+ {{/if}}
+
+ {{#if this.layout}}
+ <div class="assistant-workflow-preview__scroller" tabindex="0">
+ <div
+ class="assistant-workflow-preview__viewport"
+ style={{this.viewportStyle}}
+ >
+ <svg
+ aria-hidden="true"
+ class="assistant-workflow-preview__connections"
+ height={{this.layout.height}}
+ viewBox="0 0 {{this.layout.width}} {{this.layout.height}}"
+ width={{this.layout.width}}
+ >
+ <defs>
+ <marker
+ id={{this.markerId}}
+ markerHeight="7"
+ markerWidth="7"
+ orient="auto"
+ refX="6"
+ refY="3.5"
+ >
+ <path d="M 0 0 L 7 3.5 L 0 7 z" />
+ </marker>
+ </defs>
+ {{#each this.layout.connections as |connection|}}
+ <path
+ class="assistant-workflow-preview__connection"
+ d={{connection.path}}
+ marker-end={{this.markerUrl}}
+ />
+ {{#if (connectionLabel connection)}}
+ <text
+ class="assistant-workflow-preview__connection-label"
+ data-connection-type={{connection.connectionType}}
+ data-output-index={{connection.outputIndex}}
+ x={{connection.labelX}}
+ y={{connection.labelY}}
+ >{{connectionLabel connection}}</text>
+ {{/if}}
+ {{/each}}
+ </svg>
+
+ {{#each this.layout.nodes as |node|}}
+ <article
+ class="assistant-workflow-preview__node"
+ data-node-type={{node.type}}
+ style={{this.nodeStyle node}}
+ >
+ <span class="assistant-workflow-preview__node-icon">
+ {{dIcon (nodeIcon node.type)}}
+ </span>
+ <span class="assistant-workflow-preview__node-copy">
+ <strong title={{node.name}}>{{node.name}}</strong>
+ <small>{{node.type}}</small>
+ {{#if (this.nodeConnections node)}}
+ <span class="sr-only">
+ {{i18n
+ "discourse_workflows.admin_assistant.preview.connects_to"
+ nodes=(this.nodeConnections node)
+ }}
+ </span>
+ {{/if}}
+ </span>
+ </article>
+ {{/each}}
+ </div>
+ </div>
+ {{else}}
+ <p class="assistant-workflow-preview__fallback">
+ {{i18n "discourse_workflows.admin_assistant.preview.unavailable"}}
+ </p>
+ {{/if}}
+ <details class="assistant-workflow-preview__details">
+ <summary class="assistant-workflow-preview__footer">
+ {{#if this.layout}}
+ <span class="assistant-workflow-preview__counts">
+ {{i18n
+ "discourse_workflows.admin_assistant.preview.node_count"
+ count=this.preview.nodes.length
+ }}
+ ·
+ {{i18n
+ "discourse_workflows.admin_assistant.preview.connection_count"
+ count=this.preview.connections.length
+ }}
+ {{#if this.layout.hasCycle}}
+ <span>
+ {{dIcon "arrow-rotate-right"}}
+ {{i18n "discourse_workflows.admin_assistant.preview.cycle"}}
+ </span>
+ {{/if}}
+ </span>
+ {{/if}}
+ <span class="assistant-workflow-preview__details-label">
+ {{dIcon "caret-right"}}
+ {{i18n
+ "discourse_workflows.admin_assistant.preview.exact_configuration"
+ }}
+ </span>
+ </summary>
+ <pre><code>{{this.exactConfiguration}}</code></pre>
+ </details>
+ </section>
+ {{/if}}
+ </template>
+}
diff --git a/plugins/discourse-workflows/assets/javascripts/discourse/initializers/assistant-workflow-preview.gjs b/plugins/discourse-workflows/assets/javascripts/discourse/initializers/assistant-workflow-preview.gjs
new file mode 100644
index 00000000000..3784c69872a
--- /dev/null
+++ b/plugins/discourse-workflows/assets/javascripts/discourse/initializers/assistant-workflow-preview.gjs
@@ -0,0 +1,32 @@
+import { apiInitializer } from "discourse/lib/api";
+import AdminAssistantWorkflowPreview from "../components/admin-assistant/workflow-preview.gjs";
+import { extractWorkflowPreview } from "../lib/admin-assistant/workflow-preview.js";
+
+export function decorateWorkflowPreview(element, helper, message) {
+ if (
+ !helper.renderGlimmer ||
+ !message?.blocks?.some((block) => block.type === "confirmation") ||
+ !extractWorkflowPreview(element.innerHTML)
+ ) {
+ return;
+ }
+
+ const code = element.querySelector("pre code.lang-admin-assistant-workflow");
+ const source = new DOMParser()
+ .parseFromString(message.cooked ?? "", "text/html")
+ .querySelector("pre code.lang-admin-assistant-workflow");
+ if (!code || !source || code.textContent !== source.textContent) {
+ return;
+ }
+
+ const target = element.ownerDocument.createElement("div");
+ code.closest("pre").replaceWith(target);
+ helper.renderGlimmer(
+ target,
+ <template><AdminAssistantWorkflowPreview @message={{message}} /></template>
+ );
+}
+
+export default apiInitializer((api) => {
+ api.decorateChatMessage?.(decorateWorkflowPreview);
+});
diff --git a/plugins/discourse-workflows/assets/javascripts/discourse/lib/admin-assistant/workflow-preview.js b/plugins/discourse-workflows/assets/javascripts/discourse/lib/admin-assistant/workflow-preview.js
new file mode 100644
index 00000000000..26f0ad64265
--- /dev/null
+++ b/plugins/discourse-workflows/assets/javascripts/discourse/lib/admin-assistant/workflow-preview.js
@@ -0,0 +1,394 @@
+const CODE_SELECTOR = "pre code";
+const WORKFLOW_PREVIEW_KIND = "discourse_admin_assistant_workflow_preview_v1";
+const MAX_PREVIEW_NODES = 24;
+const MAX_PREVIEW_CONNECTIONS = 48;
+const MAX_PREVIEW_OPERATIONS = 200;
+
+function normalizeOperation(operation) {
+ if (typeof operation !== "string") {
+ return operation;
+ }
+
+ try {
+ return JSON.parse(operation);
+ } catch {
+ return null;
+ }
+}
+
+function nodeReference(operation, primary, fallback) {
+ return operation[primary] ?? operation[fallback];
+}
+
+function stronglyConnectedComponents(nodes, connections) {
+ const nodeIds = new Set(nodes.map((node) => node.id));
+ const outgoing = new Map(nodes.map((node) => [node.id, []]));
+
+ for (const connection of connections) {
+ if (nodeIds.has(connection.from) && nodeIds.has(connection.to)) {
+ outgoing.get(connection.from).push(connection.to);
+ }
+ }
+
+ let nextIndex = 0;
+ const components = [];
+ const indexes = new Map();
+ const lowLinks = new Map();
+ const stack = [];
+ const stacked = new Set();
+
+ const visit = (nodeId) => {
+ indexes.set(nodeId, nextIndex);
+ lowLinks.set(nodeId, nextIndex);
+ nextIndex++;
+ stack.push(nodeId);
+ stacked.add(nodeId);
+
+ for (const targetId of outgoing.get(nodeId)) {
+ if (!indexes.has(targetId)) {
+ visit(targetId);
+ lowLinks.set(
+ nodeId,
+ Math.min(lowLinks.get(nodeId), lowLinks.get(targetId))
+ );
+ } else if (stacked.has(targetId)) {
+ lowLinks.set(
+ nodeId,
+ Math.min(lowLinks.get(nodeId), indexes.get(targetId))
+ );
+ }
+ }
+
+ if (lowLinks.get(nodeId) !== indexes.get(nodeId)) {
+ return;
+ }
+
+ const component = [];
+ let currentId;
+ do {
+ currentId = stack.pop();
+ stacked.delete(currentId);
+ component.push(currentId);
+ } while (currentId !== nodeId);
+ components.push(component);
+ };
+
+ for (const node of nodes) {
+ if (!indexes.has(node.id)) {
+ visit(node.id);
+ }
+ }
+
+ return components;
+}
+
+function assignColumns(nodes, connections) {
+ const components = stronglyConnectedComponents(nodes, connections);
+ const componentByNode = new Map();
+ components.forEach((component, componentIndex) => {
+ component.forEach((nodeId) => componentByNode.set(nodeId, componentIndex));
+ });
+
+ const incoming = new Map(components.map((_, index) => [index, new Set()]));
+ const outgoing = new Map(components.map((_, index) => [index, new Set()]));
+
+ for (const connection of connections) {
+ const source = componentByNode.get(connection.from);
+ const target = componentByNode.get(connection.to);
+ if (source === undefined || target === undefined || source === target) {
+ continue;
+ }
+ outgoing.get(source).add(target);
+ incoming.get(target).add(source);
+ }
+
+ const componentColumns = new Map();
+ const queue = components
+ .map((_, index) => index)
+ .filter((index) => incoming.get(index).size === 0);
+
+ while (queue.length) {
+ const componentIndex = queue.shift();
+ const column = componentColumns.get(componentIndex) ?? 0;
+
+ for (const target of outgoing.get(componentIndex)) {
+ componentColumns.set(
+ target,
+ Math.max(componentColumns.get(target) ?? 0, column + 1)
+ );
+ incoming.get(target).delete(componentIndex);
+ if (incoming.get(target).size === 0) {
+ queue.push(target);
+ }
+ }
+ }
+
+ return {
+ columns: new Map(
+ nodes.map((node) => [
+ node.id,
+ componentColumns.get(componentByNode.get(node.id)) ?? 0,
+ ])
+ ),
+ hasCycle:
+ components.some((component) => component.length > 1) ||
+ connections.some((connection) => connection.from === connection.to),
+ };
+}
+
+function graphFromOperations(operations) {
+ const nodes = [];
+ const nodesByReference = new Map();
+ let nextNodeId = 0;
+ let connections = [];
+
+ const resolveNode = (reference) => nodesByReference.get(String(reference));
+
+ for (const rawOperation of operations) {
+ const operation = normalizeOperation(rawOperation);
+ if (!operation || typeof operation !== "object") {
+ return null;
+ }
+
+ switch (operation.op) {
+ case "create_ai_agent":
+ case "update_node_parameters":
+ break;
+ case "add_node": {
+ const node = operation.node;
+ if (!node || typeof node !== "object" || !node.name || !node.type) {
+ return null;
+ }
+
+ const id = `node-${nextNodeId++}`;
+ const previewNode = {
+ id,
+ name: String(node.name),
+ type: String(node.type),
+ };
+ nodes.push(previewNode);
+ nodesByReference.set(String(operation.client_id ?? id), previewNode);
+ if (node.id) {
+ nodesByReference.set(String(node.id), previewNode);
+ }
+ break;
+ }
+ case "rename_node": {
+ const node = resolveNode(
+ nodeReference(operation, "node_id", "client_id")
+ );
+ if (!node || !operation.name) {
+ return null;
+ }
+ node.name = String(operation.name);
+ break;
+ }
+ case "remove_node": {
+ const node = resolveNode(
+ nodeReference(operation, "node_id", "client_id")
+ );
+ if (!node) {
+ return null;
+ }
+ nodes.splice(nodes.indexOf(node), 1);
+ for (const [reference, referencedNode] of nodesByReference) {
+ if (referencedNode === node) {
+ nodesByReference.delete(reference);
+ }
+ }
+ connections = connections.filter(
+ (connection) =>
+ connection.from !== node.id && connection.to !== node.id
+ );
+ break;
+ }
+ case "add_connection": {
+ const source = resolveNode(
+ nodeReference(operation, "from", "from_node_id")
+ );
+ const target = resolveNode(
+ nodeReference(operation, "to", "to_node_id")
+ );
+ if (!source || !target) {
+ return null;
+ }
+ connections.push({
+ from: source.id,
+ to: target.id,
+ connectionType: String(operation.connection_type ?? "main"),
+ outputIndex: Number(operation.output_index ?? 0),
+ inputIndex: Number(operation.input_index ?? 0),
+ });
+ break;
+ }
+ case "remove_connection": {
+ const source = resolveNode(
+ nodeReference(operation, "from", "from_node_id")
+ );
+ const target = resolveNode(
+ nodeReference(operation, "to", "to_node_id")
+ );
+ if (!source || !target) {
+ return null;
+ }
+ connections = connections.filter((connection) => {
+ if (connection.from !== source.id || connection.to !== target.id) {
+ return true;
+ }
+ if (
+ operation.output_index !== undefined &&
+ connection.outputIndex !== Number(operation.output_index)
+ ) {
+ return true;
+ }
+ return (
+ operation.input_index !== undefined &&
+ connection.inputIndex !== Number(operation.input_index)
+ );
+ });
+ break;
+ }
+ default:
+ return null;
+ }
+ }
+
+ if (!nodes.length) {
+ return null;
+ }
+
+ return { nodes, connections };
+}
+
+export function extractWorkflowPreview(cooked) {
+ if (!cooked || typeof DOMParser === "undefined") {
+ return null;
+ }
+
+ const document = new DOMParser().parseFromString(cooked, "text/html");
+ const code = document.querySelector(CODE_SELECTOR);
+ if (!code) {
+ return null;
+ }
+
+ try {
+ const payload = JSON.parse(code.textContent);
+ if (payload?.kind !== WORKFLOW_PREVIEW_KIND) {
+ return null;
+ }
+ const configuration = payload.configuration;
+ if (
+ !configuration ||
+ typeof configuration.name !== "string" ||
+ !Array.isArray(configuration.operations)
+ ) {
+ return null;
+ }
+ if (configuration.operations.length > MAX_PREVIEW_OPERATIONS) {
+ return { name: configuration.name, configuration, unavailable: true };
+ }
+
+ const graph = graphFromOperations(configuration.operations);
+ if (!graph) {
+ return { name: configuration.name, configuration, unavailable: true };
+ }
+ if (
+ graph.nodes.length > MAX_PREVIEW_NODES ||
+ graph.connections.length > MAX_PREVIEW_CONNECTIONS
+ ) {
+ return {
+ name: configuration.name,
+ configuration,
+ nodeCount: graph.nodes.length,
+ unavailable: true,
+ };
+ }
+
+ return { name: configuration.name, configuration, ...graph };
+ } catch {
+ return null;
+ }
+}
+
+export function layoutWorkflowPreview(preview) {
+ const nodeWidth = 176;
+ const nodeHeight = 96;
+ const horizontalGap = 32;
+ const verticalGap = 28;
+ const padding = 20;
+ const { columns, hasCycle } = assignColumns(
+ preview.nodes,
+ preview.connections
+ );
+ const rowsByColumn = new Map();
+
+ for (const node of preview.nodes) {
+ const column = columns.get(node.id);
+ const columnNodes = rowsByColumn.get(column) ?? [];
+ columnNodes.push(node);
+ rowsByColumn.set(column, columnNodes);
+ }
+
+ const positionedNodes = preview.nodes.map((node) => {
+ const column = columns.get(node.id);
+ const row = rowsByColumn.get(column).indexOf(node);
+ return {
+ ...node,
+ x: padding + column * (nodeWidth + horizontalGap),
+ y: padding + row * (nodeHeight + verticalGap),
+ };
+ });
+ const positionedById = new Map(
+ positionedNodes.map((node) => [node.id, node])
+ );
+ const maxColumn = Math.max(...columns.values());
+ const maxRows = Math.max(
+ ...[...rowsByColumn.values()].map((nodes) => nodes.length)
+ );
+ const width =
+ padding * 2 + (maxColumn + 1) * nodeWidth + maxColumn * horizontalGap;
+ const height =
+ padding * 2 + maxRows * nodeHeight + (maxRows - 1) * verticalGap;
+
+ const connections = preview.connections.map((connection, index) => {
+ const sourceOutputIndexes = new Set(
+ preview.connections
+ .filter((candidate) => candidate.from === connection.from)
+ .map((candidate) => candidate.outputIndex)
+ );
+ const branchNumber =
+ sourceOutputIndexes.size > 1 ? connection.outputIndex + 1 : null;
+ const source = positionedById.get(connection.from);
+ const target = positionedById.get(connection.to);
+ const startX = source.x + nodeWidth;
+ const startY = source.y + nodeHeight / 2;
+ const endX = target.x;
+ const endY = target.y + nodeHeight / 2;
+ let path;
+ let labelX = (startX + endX) / 2;
+ let labelY = (startY + endY) / 2 - 8;
+
+ if (endX > startX) {
+ const controlOffset = Math.max(28, (endX - startX) / 2);
+ path = `M ${startX} ${startY} C ${startX + controlOffset} ${startY}, ${endX - controlOffset} ${endY}, ${endX} ${endY}`;
+ } else {
+ const loopOffset = 22 + (index % 4) * 8;
+ const bottom = Math.max(startY, endY) + nodeHeight / 2 + loopOffset;
+ labelX = (startX + endX) / 2;
+ labelY = bottom - 6;
+ path = `M ${startX} ${startY} C ${startX + loopOffset} ${startY}, ${startX + loopOffset} ${bottom}, ${startX} ${bottom} L ${endX - loopOffset} ${bottom} C ${endX - loopOffset * 2} ${bottom}, ${endX - loopOffset * 2} ${endY}, ${endX} ${endY}`;
+ }
+
+ return { ...connection, branchNumber, labelX, labelY, path };
+ });
+
+ return {
+ connections,
+ hasCycle,
+ height,
+ nodes: positionedNodes,
+ nodeHeight,
+ nodeWidth,
+ width,
+ };
+}
diff --git a/plugins/discourse-workflows/assets/stylesheets/common/admin-assistant-workflow-preview.scss b/plugins/discourse-workflows/assets/stylesheets/common/admin-assistant-workflow-preview.scss
new file mode 100644
index 00000000000..5806dd8eeb3
--- /dev/null
+++ b/plugins/discourse-workflows/assets/stylesheets/common/admin-assistant-workflow-preview.scss
@@ -0,0 +1,231 @@
+.assistant-workflow-preview {
+ background: var(--secondary);
+ border: 1px solid var(--primary-low);
+ border-radius: var(--d-border-radius-large);
+ box-sizing: border-box;
+ margin-block-start: var(--space-2);
+ max-width: min(100%, 40em);
+ overflow: hidden;
+
+ &__header,
+ &__footer {
+ align-items: center;
+ display: flex;
+ flex-wrap: wrap;
+ gap: var(--space-2) var(--space-4);
+ justify-content: space-between;
+ padding: var(--space-3) var(--space-4);
+ }
+
+ &__header {
+ border-block-end: 1px solid var(--primary-low);
+ }
+
+ &__heading {
+ align-items: center;
+ display: inline-flex;
+ gap: var(--space-2);
+ min-width: 0;
+
+ .d-icon {
+ color: var(--tertiary);
+ flex: 0 0 auto;
+ }
+
+ span {
+ font-weight: 700;
+ overflow-wrap: anywhere;
+ }
+ }
+
+ &__badge {
+ background: var(--primary-very-low);
+ border-radius: 999px;
+ color: var(--primary-high);
+ font-size: var(--font-down-2);
+ line-height: var(--line-height-small);
+ padding: var(--space-half) var(--space-2);
+ }
+
+ &__scroller {
+ background-color: var(--primary-very-low);
+ background-image: radial-gradient(
+ circle,
+ var(--primary-low) 1px,
+ transparent 1px
+ );
+ background-size: 16px 16px;
+ max-width: 100%;
+ overflow: auto;
+
+ &:focus-visible {
+ outline: 2px solid var(--tertiary);
+ outline-offset: -2px;
+ }
+ }
+
+ &__viewport {
+ min-height: 9rem;
+ min-width: 100%;
+ position: relative;
+ }
+
+ &__connections {
+ /*! rtl:ignore */
+ left: 0;
+ top: 0;
+ overflow: visible;
+ pointer-events: none;
+ position: absolute;
+
+ marker path {
+ fill: var(--primary-medium);
+ }
+ }
+
+ &__connection {
+ fill: none;
+ stroke: var(--primary-medium);
+ stroke-width: 2;
+ vector-effect: non-scaling-stroke;
+ }
+
+ &__node {
+ align-items: center;
+ background: var(--secondary);
+ border: 1px solid var(--primary-low-mid);
+ border-radius: var(--d-border-radius-large);
+ box-shadow: 0 1px 3px rgb(0 0 0 / 12%);
+ box-sizing: border-box;
+ display: grid;
+ gap: var(--space-2);
+ grid-template-columns: auto minmax(0, 1fr);
+ padding: var(--space-2) var(--space-3);
+ position: absolute;
+ }
+
+ &__node-icon {
+ align-items: center;
+ background: var(--tertiary-low);
+ border-radius: 50%;
+ color: var(--tertiary);
+ display: inline-flex;
+ height: 2rem;
+ justify-content: center;
+ width: 2rem;
+ }
+
+ &__node-copy {
+ display: flex;
+ flex-direction: column;
+ min-width: 0;
+
+ strong {
+ display: -webkit-box;
+ -webkit-box-orient: vertical;
+ -webkit-line-clamp: 3;
+ font-size: var(--font-down-1);
+ line-height: var(--line-height-small);
+ overflow: hidden;
+ overflow-wrap: anywhere;
+ }
+
+ small {
+ overflow: hidden;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+ color: var(--primary-high);
+ font-family: var(--d-font-family--monospace);
+ font-size: var(--font-down-2);
+ }
+ }
+
+ &__footer {
+ color: var(--primary-high);
+ font-size: var(--font-down-1);
+
+ span {
+ align-items: center;
+ display: inline-flex;
+ flex-wrap: wrap;
+ gap: var(--space-1);
+ }
+ }
+
+ &__warning {
+ background: var(--highlight-bg);
+ color: var(--primary);
+ margin: 0;
+ padding: var(--space-3) var(--space-4);
+ }
+
+ &__fallback {
+ color: var(--primary-high);
+ margin: 0;
+ padding: var(--space-4);
+ }
+}
+
+.assistant-workflow-preview__details {
+ border-block-start: 1px solid var(--primary-low);
+
+ summary.assistant-workflow-preview__footer {
+ cursor: pointer;
+ display: flex;
+ list-style: none;
+
+ &::before {
+ display: none;
+ }
+
+ &:focus-visible {
+ outline: 2px solid var(--tertiary);
+ outline-offset: -2px;
+ }
+
+ &::-webkit-details-marker {
+ display: none;
+ }
+ }
+
+ &[open] .assistant-workflow-preview__details-label .d-icon {
+ transform: rotate(90deg);
+ }
+
+ pre {
+ margin: 0 var(--space-4) var(--space-3);
+ max-height: 20em;
+ overflow: auto;
+ white-space: pre;
+ }
+
+ code {
+ font-size: var(--font-down-2);
+ }
+}
+
+.assistant-workflow-preview__connection-label {
+ fill: var(--primary-high);
+ font-size: var(--font-down-2);
+ paint-order: stroke;
+ stroke: var(--primary-very-low);
+ stroke-width: 3px;
+ text-anchor: middle;
+}
+
+.chat-confirmation__description:has(.assistant-workflow-preview) {
+ max-height: none;
+ overflow: visible;
+ padding: 0;
+
+ .assistant-workflow-preview {
+ border: 0;
+ border-radius: 0;
+ margin: 0;
+ max-width: 100%;
+ }
+
+ .assistant-workflow-preview__scroller {
+ max-height: 24em;
+ }
+}
diff --git a/plugins/discourse-workflows/assets/stylesheets/common/index.scss b/plugins/discourse-workflows/assets/stylesheets/common/index.scss
index 1e3457d1fa6..7537248eb30 100644
--- a/plugins/discourse-workflows/assets/stylesheets/common/index.scss
+++ b/plugins/discourse-workflows/assets/stylesheets/common/index.scss
@@ -29,3 +29,4 @@
@import "templates";
@import "admin-table";
@import "admin-page";
+@import "admin-assistant-workflow-preview";
diff --git a/plugins/discourse-workflows/config/locales/client.en.yml b/plugins/discourse-workflows/config/locales/client.en.yml
index 45a88117b5b..a8dd5b46f25 100644
--- a/plugins/discourse-workflows/config/locales/client.en.yml
+++ b/plugins/discourse-workflows/config/locales/client.en.yml
@@ -31,6 +31,22 @@ en:
description: "AI-assisted workflow authoring"
workflow_authoring: "Workflow authoring"
discourse_workflows:
+ admin_assistant:
+ preview:
+ label: "Workflow preview"
+ exact_configuration: "Exact configuration"
+ read_only: "Read-only preview"
+ script_validation_warning: "Some Code nodes failed syntax or mode checks. Review the errors in Exact configuration before approving."
+ connects_to: "Connects to %{nodes}"
+ branch: "Branch %{number}"
+ node_count:
+ one: "%{count} node"
+ other: "%{count} nodes"
+ connection_count:
+ one: "%{count} connection"
+ other: "%{count} connections"
+ cycle: "Includes a cycle"
+ unavailable: "This workflow is too complex to draw safely here. Review the exact configuration before approving."
actor:
system: "System user"
anonymous: "Anonymous user"
diff --git a/plugins/discourse-workflows/config/locales/server.en.yml b/plugins/discourse-workflows/config/locales/server.en.yml
index 64ceb2159e1..dd3e709db9b 100644
--- a/plugins/discourse-workflows/config/locales/server.en.yml
+++ b/plugins/discourse-workflows/config/locales/server.en.yml
@@ -11,6 +11,26 @@ en:
type_options:
enum_choices_required: "must include at least one choice for an enum field"
discourse_workflows:
+ admin_assistant:
+ generating: "Generating and validating an unpublished workflow draft"
+ create_summary: "Save this workflow as an unpublished draft?"
+ not_allowed: "Only administrators who can manage workflows can create workflows."
+ invalid_request: "The workflow request is empty, contains a secret, or is too long. Please provide a shorter description without secrets."
+ invalid_draft: "This workflow draft reference is invalid, unavailable, or expired. Please generate a new draft."
+ incomplete_draft: "The generated workflow draft is incomplete. Please generate a new draft."
+ invalid_graph: "The generated workflow graph is no longer valid. Please generate a new draft."
+ secret_draft: "Workflow drafts cannot contain raw secrets or embedded credentials. Store credentials separately and generate a new draft that references them safely."
+ requester_not_admin: "The administrator who requested this workflow no longer has permission to manage workflows. Please request a new draft from an authorized administrator."
+ approval_required: "Saving this workflow requires human approval."
+ draft_used: "This workflow draft has already been used or is being saved. Please generate a new draft."
+ generation_failed: "The workflow could not be generated and validated. Please try again or refine your request."
+ clarification_required: "More information is needed before the workflow can be generated."
+ creation_failed: "The workflow could not be saved. No workflow was created."
+ availability:
+ available: "Workflow creation is available. Saving requires explicit approval."
+ restricted: "Workflow creation is unavailable on this site."
+ disabled: "Workflow authoring or Discourse AI is disabled. An administrator needs to enable the required features before creating workflows."
+ unconfigured: "The workflow-authoring AI model is not configured or usable."
ai:
default_code_node_name: "Code"
error_agent_not_configured: "The workflow authoring agent is not configured."
diff --git a/plugins/discourse-workflows/lib/discourse_workflows/admin_assistant/capability.rb b/plugins/discourse-workflows/lib/discourse_workflows/admin_assistant/capability.rb
new file mode 100644
index 00000000000..de5d6ceba2d
--- /dev/null
+++ b/plugins/discourse-workflows/lib/discourse_workflows/admin_assistant/capability.rb
@@ -0,0 +1,56 @@
+# frozen_string_literal: true
+
+module DiscourseWorkflows
+ module AdminAssistant
+ class Capability
+ FEATURE = :workflow_authoring
+
+ def self.status(user:, phase:)
+ access =
+ DiscourseAi::Agents::AdminAssistantAccess.check(
+ feature: FEATURE,
+ user: user,
+ phase: phase,
+ )
+ return :restricted if !access.allowed
+ public_status
+ end
+
+ def self.public_status
+ return :disabled unless SiteSetting.discourse_ai_enabled && AiAuthoringEnqueuer.enabled?
+
+ agent = authoring_agent
+ return :unconfigured if !agent&.enabled?
+
+ model_id = agent.default_llm_id || SiteSetting.ai_default_llm_model.presence
+ model = LlmModel.find_by(id: model_id)
+ return :unconfigured if !model&.valid?
+
+ :available
+ end
+ private_class_method :public_status
+
+ def self.message(user:, phase:)
+ access =
+ DiscourseAi::Agents::AdminAssistantAccess.check(
+ feature: FEATURE,
+ user: user,
+ phase: phase,
+ )
+ return access.message if !access.allowed && access.message.present?
+
+ I18n.t(
+ "discourse_workflows.admin_assistant.availability.#{status(user: user, phase: phase)}",
+ )
+ end
+
+ def self.authoring_agent
+ configured_id = SiteSetting.discourse_workflows_workflow_authoring_agent.to_i
+ default_id =
+ DiscourseAi::Agents::Agent.external_agent_id(DiscourseWorkflows::AiWorkflowAuthor)
+ AiAgent.find_by(id: configured_id) || AiAgent.find_by(id: default_id)
+ end
+ private_class_method :authoring_agent
+ end
+ end
+end
diff --git a/plugins/discourse-workflows/lib/discourse_workflows/admin_assistant/create_workflow.rb b/plugins/discourse-workflows/lib/discourse_workflows/admin_assistant/create_workflow.rb
new file mode 100644
index 00000000000..763cbf5a9d6
--- /dev/null
+++ b/plugins/discourse-workflows/lib/discourse_workflows/admin_assistant/create_workflow.rb
@@ -0,0 +1,207 @@
+# frozen_string_literal: true
+
+module DiscourseWorkflows
+ module AdminAssistant
+ class CreateWorkflow < DiscourseAi::Agents::Tools::Tool
+ PREVIEW_KIND = "discourse_admin_assistant_workflow_preview_v1"
+
+ def self.name
+ "create_workflow"
+ end
+
+ def self.signature
+ {
+ name: name,
+ description:
+ "Request human approval to save an exact validated workflow draft as unpublished. Never invent, alter, or reuse the draft token.",
+ parameters: [
+ {
+ name: "draft_token",
+ type: "string",
+ required: true,
+ description: "The draft token returned by generate_workflow",
+ },
+ ],
+ }
+ end
+
+ def self.requires_approval?
+ true
+ end
+
+ def self.mandatory_approval?
+ true
+ end
+
+ def self.attribute_to_approver?
+ true
+ end
+
+ def self.help
+ I18n.t("discourse_workflows.admin_assistant.create_summary")
+ end
+
+ def self.available_for_context?(context)
+ context&.user&.admin? && context.user.guardian.can_manage_workflows? &&
+ Capability.status(user: context.user, phase: :visibility) == :available
+ end
+
+ def summary
+ self.class.help
+ end
+
+ def approval_parameters
+ []
+ end
+
+ def details
+ return I18n.t("discourse_workflows.admin_assistant.invalid_draft") unless draft
+ if WorkflowDraft.contains_secret?(draft.slice(:name, :operations, :script_validations))
+ return I18n.t("discourse_workflows.admin_assistant.secret_draft")
+ end
+
+ preview =
+ JSON.pretty_generate(
+ kind: PREVIEW_KIND,
+ configuration: draft.slice(:name, :operations, :script_validations),
+ )
+ longest_run = preview.scan(/`+/).map(&:length).max.to_i
+ fence = "`" * [3, longest_run + 1].max
+ "#{fence}admin-assistant-workflow\n#{preview}\n#{fence}\n"
+ end
+
+ def validation_error
+ if !authorized?
+ return error_response(I18n.t("discourse_workflows.admin_assistant.not_allowed"))
+ end
+ if Capability.status(user: context.user, phase: execution_phase) != :available
+ return error_response(Capability.message(user: context.user, phase: execution_phase))
+ end
+ return error_response(I18n.t("discourse_workflows.admin_assistant.invalid_draft")) if !draft
+ if draft[:name].blank? || !draft[:operations].is_a?(Array) || draft[:operations].blank?
+ return error_response(I18n.t("discourse_workflows.admin_assistant.incomplete_draft"))
+ end
+ if WorkflowDraft.contains_secret?(draft.slice(:name, :operations, :script_validations))
+ return error_response(I18n.t("discourse_workflows.admin_assistant.secret_draft"))
+ end
+
+ requester = User.find_by(id: draft[:user_id], admin: true)
+ if !requester || !requester.guardian.can_manage_workflows?
+ return error_response(I18n.t("discourse_workflows.admin_assistant.requester_not_admin"))
+ end
+ if context.reviewable_id.blank? && draft[:user_id] != context.user.id
+ return error_response(I18n.t("discourse_workflows.admin_assistant.not_allowed"))
+ end
+ parameters[:requester_id] = draft[:user_id] if context.reviewable_id.blank?
+
+ validation = validate_draft
+ if !validation[:valid]
+ return error_response(I18n.t("discourse_workflows.admin_assistant.invalid_graph"))
+ end
+
+ nil
+ end
+
+ def invoke
+ validation_failure = validation_error
+ return validation_failure if validation_failure
+ return approval_required if context.reviewable_id.blank?
+
+ reviewable = matching_reviewable
+ return approval_required if reviewable.blank?
+
+ reviewable.with_lock do
+ return approval_required if !reviewable.pending?
+ unless WorkflowDraft.claim(parameters[:draft_token], reviewable_id: reviewable.id)
+ return error_response(I18n.t("discourse_workflows.admin_assistant.draft_used"))
+ end
+
+ begin
+ workflow = create_unpublished_workflow!
+ WorkflowDraft.complete_after_transaction(
+ parameters[:draft_token],
+ reviewable_id: reviewable.id,
+ resource_id: workflow.id,
+ )
+ { status: "success", workflow_id: workflow.id, url: workflow_url(workflow) }
+ rescue => error
+ WorkflowDraft.release(parameters[:draft_token], reviewable_id: reviewable.id)
+ raise error
+ end
+ end
+ rescue ActiveRecord::ActiveRecordError, Discourse::InvalidParameters
+ error_response(I18n.t("discourse_workflows.admin_assistant.creation_failed"))
+ end
+
+ private
+
+ def approval_required
+ error_response(I18n.t("discourse_workflows.admin_assistant.approval_required"))
+ end
+
+ def authorized?
+ context.user&.admin? && context.user.guardian.can_manage_workflows?
+ end
+
+ def create_unpublished_workflow!
+ workflow = nil
+ DiscourseWorkflows::Workflow.transaction do
+ result =
+ DiscourseWorkflows::Workflow::Create.call(
+ params: {
+ name: draft[:name],
+ nodes: [],
+ connections: {
+ },
+ },
+ guardian: context.user.guardian,
+ )
+ raise Discourse::InvalidParameters if !result.success?
+
+ workflow = result[:workflow]
+ patch =
+ DiscourseWorkflows::Workflow::Action::ApplyPatch.call(
+ workflow: workflow,
+ operations: draft[:operations],
+ persist: true,
+ user: context.user,
+ )
+ raise Discourse::InvalidParameters if !patch[:valid] || workflow.reload.published?
+ end
+ raise Discourse::InvalidParameters if !workflow&.persisted?
+
+ workflow
+ end
+
+ def draft
+ WorkflowDraft.read_with_compatibility(parameters[:draft_token])
+ end
+
+ def execution_phase
+ context.reviewable_id.present? ? :approval : :request
+ end
+
+ def matching_reviewable
+ item = ReviewableAiToolAction.find_by(id: context.reviewable_id)
+ return if !item || item.target&.tool_name != self.class.name
+ return if item.target.tool_parameters["draft_token"] != parameters[:draft_token]
+ return if item.target.tool_parameters["requester_id"].to_i != draft[:user_id]
+
+ item
+ end
+
+ def validate_draft
+ DiscourseWorkflows::Ai::Tools::WorkflowValidatePatch.new(
+ { workflow_name: draft[:name], operations: draft[:operations] },
+ bot_user: Discourse.system_user,
+ llm: nil,
+ context: DiscourseAi::Agents::BotContext.new(messages: [], user: context.user),
+ ).invoke
+ end
+
+ def workflow_url(workflow)
+ "#{Discourse.base_url}/admin/plugins/discourse-workflows/workflows/#{workflow.id}"
+ end
+ end
+ end
+end
diff --git a/plugins/discourse-workflows/lib/discourse_workflows/admin_assistant/generate_workflow.rb b/plugins/discourse-workflows/lib/discourse_workflows/admin_assistant/generate_workflow.rb
new file mode 100644
index 00000000000..d8f1781623c
--- /dev/null
+++ b/plugins/discourse-workflows/lib/discourse_workflows/admin_assistant/generate_workflow.rb
@@ -0,0 +1,165 @@
+# frozen_string_literal: true
+
+module DiscourseWorkflows
+ module AdminAssistant
+ class GenerateWorkflow < DiscourseAi::Agents::Tools::Tool
+ def self.name
+ "generate_workflow"
+ end
+
+ def self.signature
+ {
+ name: name,
+ description:
+ "Generate and validate an unpublished workflow draft without saving it. Do not include passwords, tokens, API keys, credentials, or other secrets. If clarification is needed, ask the administrator the returned questions and retry with their answers included. Use create_workflow with the returned draft token to request approval to save the exact draft.",
+ parameters: [
+ {
+ name: "description",
+ type: "string",
+ required: true,
+ description: "The complete workflow requested by the administrator, without secrets",
+ },
+ ],
+ }
+ end
+
+ def self.help
+ I18n.t("discourse_workflows.admin_assistant.generating")
+ end
+
+ def self.custom_system_message
+ <<~TEXT
+ When an administrator asks to create a workflow, first call generate_workflow with the complete request and no secrets. If it returns needs_clarification, ask the returned questions and call generate_workflow again with the original request and answers. If generation succeeds, call create_workflow with the exact returned draft token. Saving always requires explicit human approval. Never claim that a workflow is active or execute it; newly saved workflows are unpublished.
+ TEXT
+ end
+
+ def self.available_for_context?(context)
+ context&.user&.admin? && context.user.guardian.can_manage_workflows? &&
+ Capability.status(user: context.user, phase: :visibility) == :available
+ end
+
+ def summary
+ self.class.help
+ end
+
+ def details
+ summary
+ end
+
+ def invoke
+ if !authorized?
+ return error_response(I18n.t("discourse_workflows.admin_assistant.not_allowed"))
+ end
+ if Capability.status(user: context.user, phase: :generation) != :available
+ return error_response(Capability.message(user: context.user, phase: :generation))
+ end
+
+ description = parameters[:description].to_s.strip
+ if description.blank? || WorkflowDraft.contains_secret_text?(description) ||
+ description.length > SiteSetting.discourse_workflows_ai_authoring_max_prompt_length
+ return error_response(I18n.t("discourse_workflows.admin_assistant.invalid_request"))
+ end
+
+ session = create_session(description)
+ Jobs::DiscourseWorkflows::AuthorWithAi.new.execute(
+ session_id: session.id,
+ user_id: context.user.id,
+ generation_id: SecureRandom.hex,
+ )
+ session.reload
+ return clarification_response(session) if session.status == "needs_clarification"
+ return generation_error unless session.status == "proposal_ready"
+
+ proposal = session.proposed_patch.symbolize_keys
+ operations = Array.wrap(proposal[:operations])
+ public_text = [proposal[:title], proposal[:workflow_name], proposal[:summary]].compact.join(
+ "\n",
+ )
+ if WorkflowDraft.contains_secret?(operations) ||
+ WorkflowDraft.contains_secret?(proposal[:script_validations]) ||
+ WorkflowDraft.contains_secret_text?(public_text)
+ return generation_error
+ end
+
+ name =
+ (proposal[:workflow_name].presence || proposal[:title].presence || description).truncate(
+ 100,
+ )
+ validation = validate_draft(name, operations)
+ return generation_error unless validation[:valid]
+
+ draft_attributes = {
+ name: name,
+ operations: operations,
+ script_validations: proposal[:script_validations],
+ }.compact
+ draft_token = WorkflowDraft.sign(draft_attributes, user: context.user)
+ {
+ status: "success",
+ name: name,
+ summary: proposal[:summary].to_s,
+ script_validations: proposal[:script_validations],
+ draft_token: draft_token,
+ }.compact
+ rescue ActiveRecord::ActiveRecordError, Discourse::InvalidParameters
+ generation_error
+ ensure
+ session&.destroy!
+ end
+
+ private
+
+ def authorized?
+ context.user&.admin? && context.user.guardian.can_manage_workflows?
+ end
+
+ def clarification_response(session)
+ response = session.latest_response.symbolize_keys
+ questions = Array.wrap(response[:questions])
+ return generation_error if questions.blank? || WorkflowDraft.contains_secret?(questions)
+
+ message = response[:message].to_s
+ if message.blank? || WorkflowDraft.contains_secret_text?(message)
+ message = I18n.t("discourse_workflows.admin_assistant.clarification_required")
+ end
+ { status: "needs_clarification", message: message, questions: questions }
+ end
+
+ def create_session(description)
+ DiscourseWorkflows::AiAuthoringSession.create!(
+ user: context.user,
+ status: "drafting",
+ latest_request: description,
+ latest_response: {
+ },
+ proposed_patch: {
+ },
+ messages: [
+ {
+ "type" => "user",
+ "content" =>
+ JSON.generate(
+ mode: "create",
+ message: description,
+ secret_handling: "never include secrets",
+ ),
+ },
+ ],
+ )
+ end
+
+ def generation_error
+ error_response(I18n.t("discourse_workflows.admin_assistant.generation_failed"))
+ end
+
+ def validate_draft(name, operations)
+ DiscourseWorkflows::Ai::Tools::WorkflowValidatePatch.new(
+ { workflow_name: name, operations: operations },
+ bot_user: Discourse.system_user,
+ llm: nil,
+ context: DiscourseAi::Agents::BotContext.new(messages: [], user: context.user),
+ ).invoke
+ end
+ end
+ end
+end
diff --git a/plugins/discourse-workflows/lib/discourse_workflows/admin_assistant/workflow_draft.rb b/plugins/discourse-workflows/lib/discourse_workflows/admin_assistant/workflow_draft.rb
new file mode 100644
index 00000000000..6c09cc4d05d
--- /dev/null
+++ b/plugins/discourse-workflows/lib/discourse_workflows/admin_assistant/workflow_draft.rb
@@ -0,0 +1,74 @@
+# frozen_string_literal: true
+
+module DiscourseWorkflows
+ module AdminAssistant
+ class WorkflowDraft < DiscourseAi::Agents::Tools::DraftReference
+ SENSITIVE_KEYS = %w[
+ password
+ secret
+ secret_key
+ token
+ auth_token
+ bearer_token
+ credential
+ credentials
+ api_key
+ authorization
+ private_key
+ client_secret
+ access_token
+ refresh_token
+ ].freeze
+ SENSITIVE_TEXT =
+ %r{
+ (?:
+ \b(?:password|secret|token|credential|api[ _-]?key|authorization|
+ private[ _-]?key|client[ _-]?secret|access[ _-]?token|refresh[ _-]?token)\b
+ \s*(?:is|:|=)\s*["']?\S{4,}
+ |
+ \bbearer\s+[a-z0-9._~+\/-]{8,}
+ )
+ }ix
+ PRIVATE_KEY_TEXT = /-----BEGIN (?:[A-Z]+ )?PRIVATE KEY-----/
+ JWT_TEXT = /\beyJ[a-z0-9_-]{8,}\.eyJ[a-z0-9_-]{8,}\.[a-z0-9_-]{8,}\b/i
+ PROVIDER_KEY_TEXT = /\b(?:AKIA|ASIA)[A-Z0-9]{16}\b|\b(?:gh[pousr]_|sk-)[a-z0-9_-]{20,}\b/i
+ URL_CREDENTIALS_TEXT = %r{\b[a-z][a-z0-9+.-]*://[^/\s:@]+:[^/\s@]+@}i
+
+ def self.contains_secret?(value, key: nil)
+ return true if key.to_s == "credentials" && value.present?
+ return true if SENSITIVE_KEYS.include?(key.to_s.underscore) && value.present?
+
+ case value
+ when Hash
+ value.any? { |nested_key, nested_value| contains_secret?(nested_value, key: nested_key) }
+ when Array
+ value.any? { |nested_value| contains_secret?(nested_value) }
+ else
+ value.is_a?(String) && contains_secret_text?(value)
+ end
+ end
+
+ def self.contains_secret_text?(value)
+ [
+ SENSITIVE_TEXT,
+ PRIVATE_KEY_TEXT,
+ JWT_TEXT,
+ PROVIDER_KEY_TEXT,
+ URL_CREDENTIALS_TEXT,
+ ].any? { |pattern| pattern.match?(value.to_s) }
+ end
+
+ class << self
+ private
+
+ def draft_kind
+ "workflow"
+ end
+
+ def reference_prefix
+ "workflow_authoring_draft_"
+ end
+ end
+ end
+ end
+end
diff --git a/plugins/discourse-workflows/plugin.rb b/plugins/discourse-workflows/plugin.rb
index 26ae611c974..46c08ccb9b5 100644
--- a/plugins/discourse-workflows/plugin.rb
+++ b/plugins/discourse-workflows/plugin.rb
@@ -63,6 +63,8 @@ require_relative "lib/discourse_workflows/plugin_node_registration"
register_asset "stylesheets/common/index.scss"
register_svg_icon "bolt"
+register_svg_icon "code-branch"
+register_svg_icon "gear"
register_svg_icon "arrows-split-up-and-left"
register_svg_icon "list"
register_svg_icon "arrow-rotate-right"
@@ -225,6 +227,17 @@ after_initialize do
require_relative "lib/discourse_workflows/ai/tools/data_table_query"
require_relative "lib/discourse_workflows/ai/tools/data_table_write"
require_relative "lib/discourse_workflows/ai_workflow_author"
+ require_relative "lib/discourse_workflows/admin_assistant/capability"
+ require_relative "lib/discourse_workflows/admin_assistant/workflow_draft"
+ require_relative "lib/discourse_workflows/admin_assistant/generate_workflow"
+ require_relative "lib/discourse_workflows/admin_assistant/create_workflow"
+
+ admin_assistant_tools = [
+ DiscourseWorkflows::AdminAssistant::GenerateWorkflow,
+ DiscourseWorkflows::AdminAssistant::CreateWorkflow,
+ ]
+ register_modifier(:ai_agent_available_tools) { |tools| tools + admin_assistant_tools }
+ register_modifier(:admin_assistant_tools) { |tools, _agent| tools + admin_assistant_tools }
DiscourseAi.register_feature(
module_name: :discourse_workflows,
diff --git a/plugins/discourse-workflows/spec/lib/discourse_workflows/admin_assistant/capability_spec.rb b/plugins/discourse-workflows/spec/lib/discourse_workflows/admin_assistant/capability_spec.rb
new file mode 100644
index 00000000000..896a75bb859
--- /dev/null
+++ b/plugins/discourse-workflows/spec/lib/discourse_workflows/admin_assistant/capability_spec.rb
@@ -0,0 +1,31 @@
+# frozen_string_literal: true
+
+RSpec.describe DiscourseWorkflows::AdminAssistant::Capability do
+ fab!(:admin)
+
+ before do
+ SiteSetting.discourse_ai_enabled = true
+ SiteSetting.enable_discourse_workflows = true
+ SiteSetting.discourse_workflows_ai_authoring_enabled = true
+ end
+
+ it "reports disabled public settings" do
+ SiteSetting.discourse_workflows_ai_authoring_enabled = false
+ expect(described_class.status(user: admin, phase: :visibility)).to eq(:disabled)
+ end
+
+ it "reports an unusable model configuration" do
+ AiAgent.stubs(:find_by).returns(nil)
+ expect(described_class.status(user: admin, phase: :visibility)).to eq(:unconfigured)
+ end
+
+ it "stops before model lookup when a generic policy denies access" do
+ DiscourseAi::Agents::AdminAssistantAccess.stubs(:check).returns(
+ DiscourseAi::Agents::AdminAssistantAccess::Result.new(allowed: false, message: "No"),
+ )
+ AiAgent.expects(:find_by).never
+
+ expect(described_class.status(user: admin, phase: :approval)).to eq(:restricted)
+ expect(described_class.message(user: admin, phase: :approval)).to eq("No")
+ end
+end
diff --git a/plugins/discourse-workflows/spec/lib/discourse_workflows/admin_assistant/completion_spec.rb b/plugins/discourse-workflows/spec/lib/discourse_workflows/admin_assistant/completion_spec.rb
new file mode 100644
index 00000000000..7d3101006cf
--- /dev/null
+++ b/plugins/discourse-workflows/spec/lib/discourse_workflows/admin_assistant/completion_spec.rb
@@ -0,0 +1,86 @@
+# frozen_string_literal: true
+
+RSpec.describe DiscourseWorkflows::AdminAssistant::CreateWorkflow do
+ fab!(:admin)
+ fab!(:llm_model) { Fabricate(:llm_model, name: "gpt-3.5-turbo") }
+ fab!(:ai_agent) do
+ Fabricate(
+ :ai_agent,
+ allowed_group_ids: [Group::AUTO_GROUPS[:admins]],
+ allow_chat_direct_messages: true,
+ require_approval: true,
+ ).tap(&:create_user!)
+ end
+
+ before do
+ prepare_ai_bot_fixtures(bots: [llm_model])
+ SiteSetting.chat_enabled = true
+ DiscourseWorkflows::AdminAssistant::Capability.stubs(:status).returns(:available)
+ end
+
+ it "approves in chat and presents the saved workflow URL through generic continuation" do
+ channel = Fabricate(:direct_message_channel, users: [admin, ai_agent.user])
+ source_message = Fabricate(:chat_message, chat_channel: channel, user: admin)
+ operations = [
+ {
+ "op" => "add_node",
+ "client_id" => "manual",
+ "node" => {
+ "type" => "trigger:manual",
+ "name" => "Manual",
+ "parameters" => {
+ },
+ },
+ },
+ ]
+ token =
+ DiscourseWorkflows::AdminAssistant::WorkflowDraft.sign(
+ { name: "Manual workflow", operations: operations },
+ user: admin,
+ )
+ action =
+ AiToolAction.create!(
+ tool_name: DiscourseWorkflows::AdminAssistant::CreateWorkflow.name,
+ tool_parameters: {
+ draft_token: token,
+ requester_id: admin.id,
+ },
+ ai_agent: ai_agent,
+ bot_user_id: ai_agent.user_id,
+ )
+ reviewable =
+ ReviewableAiToolAction.needs_review!(
+ target: action,
+ created_by: ai_agent.user,
+ reviewable_by_moderator: true,
+ payload: {
+ chat_message_id: source_message.id,
+ llm_model_id: llm_model.id,
+ },
+ )
+ approval_message =
+ Fabricate(
+ :chat_message,
+ chat_channel: channel,
+ user: ai_agent.user,
+ blocks: DiscourseAi::AiBot::ChatToolApproval.pending_blocks(reviewable.id),
+ )
+
+ reviewable.perform(admin, :approve, chat_message_id: approval_message.id)
+ workflow = DiscourseWorkflows::Workflow.order(:id).last
+ url = "#{Discourse.base_url}/admin/plugins/discourse-workflows/workflows/#{workflow.id}"
+ prompts = nil
+
+ DiscourseAi::Completions::Llm.with_prepared_responses(
+ ["[Open the workflow](#{url})."],
+ ) do |_, _, captured_prompts|
+ Jobs::ResumeAiToolApproval.new.execute(reviewable_id: reviewable.id)
+ prompts = captured_prompts
+ end
+
+ result = JSON.parse(prompts.first.messages.last[:content]).fetch("result")
+ expect(result).to eq("status" => "success", "url" => url, "workflow_id" => workflow.id)
+ expect(channel.chat_messages.order(:id).last.message).to eq("[Open the workflow](#{url}).")
+ expect(workflow).not_to be_published
+ end
+end
diff --git a/plugins/discourse-workflows/spec/lib/discourse_workflows/admin_assistant/workflow_tools_spec.rb b/plugins/discourse-workflows/spec/lib/discourse_workflows/admin_assistant/workflow_tools_spec.rb
new file mode 100644
index 00000000000..4ddfaecc978
--- /dev/null
+++ b/plugins/discourse-workflows/spec/lib/discourse_workflows/admin_assistant/workflow_tools_spec.rb
@@ -0,0 +1,632 @@
+# frozen_string_literal: true
+
+RSpec.describe DiscourseWorkflows::AdminAssistant::CreateWorkflow do
+ fab!(:admin)
+ fab!(:other_admin, :admin)
+ fab!(:user)
+ fab!(:ai_agent)
+
+ let(:operations) do
+ [
+ {
+ "op" => "add_node",
+ "client_id" => "manual",
+ "node" => {
+ "type" => "trigger:manual",
+ "name" => "Manual",
+ "parameters" => {
+ },
+ },
+ },
+ {
+ "op" => "add_node",
+ "client_id" => "log",
+ "node" => {
+ "type" => "action:log",
+ "name" => "Log",
+ "parameters" => {
+ "message" => "Hello",
+ },
+ },
+ },
+ { "op" => "add_connection", "from" => "manual", "to" => "log" },
+ ]
+ end
+ let(:draft_attributes) { { name: "Manual log", operations: operations } }
+ let(:agent_operations) do
+ [
+ {
+ "op" => "create_ai_agent",
+ "client_id" => "review-agent",
+ "agent" => {
+ "name" => "Workflow review agent",
+ "description" => "Reviews content for this workflow.",
+ "system_prompt" => "Review the supplied content and return a short result.",
+ },
+ },
+ {
+ "op" => "add_node",
+ "client_id" => "manual",
+ "node" => {
+ "type" => "trigger:manual",
+ "name" => "Manual",
+ "parameters" => {
+ },
+ },
+ },
+ {
+ "op" => "add_node",
+ "client_id" => "review",
+ "node" => {
+ "type" => "action:ai_agent",
+ "name" => "Review",
+ "parameters" => {
+ "agent_id" => {
+ "$ref" => "review-agent",
+ },
+ "prompt" => "Review this workflow run.",
+ },
+ },
+ },
+ { "op" => "add_connection", "from" => "manual", "to" => "review" },
+ ]
+ end
+ let(:token) do
+ DiscourseWorkflows::AdminAssistant::WorkflowDraft.sign(draft_attributes, user: admin)
+ end
+ let(:context) { DiscourseAi::Agents::BotContext.new(user: admin, messages: []) }
+ let(:tool) do
+ described_class.new(
+ { draft_token: token },
+ bot_user: Discourse.system_user,
+ llm: nil,
+ context: context,
+ )
+ end
+
+ before do
+ SiteSetting.discourse_ai_enabled = true
+ SiteSetting.enable_discourse_workflows = true
+ SiteSetting.discourse_workflows_ai_authoring_enabled = true
+ DiscourseWorkflows::AdminAssistant::Capability.stubs(:status).returns(:available)
+ end
+
+ def build_reviewable(draft_token = token)
+ action =
+ AiToolAction.create!(
+ tool_name: described_class.name,
+ tool_parameters: {
+ draft_token: draft_token,
+ requester_id: admin.id,
+ },
+ ai_agent: ai_agent,
+ bot_user_id: Discourse.system_user.id,
+ )
+ item =
+ ReviewableAiToolAction.needs_review!(
+ target: action,
+ created_by: Discourse.system_user,
+ reviewable_by_moderator: true,
+ )
+ item.add_score(
+ Discourse.system_user,
+ ReviewableScore.types[:needs_approval],
+ force_review: true,
+ )
+ item
+ end
+
+ it "requires mandatory approval and exposes the exact draft without its token" do
+ expect(described_class.mandatory_approval?).to eq(true)
+ expect(tool.approval_show_description?).to eq(true)
+ details = tool.details
+ expect(details).to include(
+ "```admin-assistant-workflow",
+ draft_attributes[:name],
+ "trigger:manual",
+ "action:log",
+ )
+ expect(details).not_to include(token)
+ expect(PrettyText.cook(details)).to include('<code class="lang-admin-assistant-workflow">')
+ expect(tool.approval_parameters).to be_empty
+ expect { tool.invoke }.not_to change { DiscourseWorkflows::Workflow.count }
+ end
+
+ it "rejects secret-bearing script validation metadata in signed drafts" do
+ tool.parameters[:draft_token] = DiscourseWorkflows::AdminAssistant::WorkflowDraft.sign(
+ draft_attributes.merge(
+ script_validations: [{ "valid" => false, "errors" => ["api_key: sensitive-value"] }],
+ ),
+ user: admin,
+ )
+
+ expect(tool.details).to eq(I18n.t("discourse_workflows.admin_assistant.secret_draft"))
+ expect(tool.validation_error[:status]).to eq("error")
+ expect { tool.invoke }.not_to change { DiscourseWorkflows::Workflow.count }
+ end
+
+ it "keeps malicious node text inert while preserving the exact configuration" do
+ unsafe_attributes = {
+ name: "Unsafe </code><script>alert(1)</script> ``` name",
+ operations: [
+ operations.first.deep_merge("node" => { "name" => "<img src=x onerror=alert(1)>" }),
+ ],
+ }
+ unsafe_token =
+ DiscourseWorkflows::AdminAssistant::WorkflowDraft.sign(unsafe_attributes, user: admin)
+ unsafe_tool =
+ described_class.new(
+ { draft_token: unsafe_token },
+ bot_user: Discourse.system_user,
+ llm: nil,
+ context: context,
+ )
+
+ cooked = Nokogiri::HTML5.fragment(PrettyText.cook(unsafe_tool.details))
+ code = cooked.at_css("code.lang-admin-assistant-workflow")
+
+ expect(cooked.at_css("script, img")).to be_nil
+ expect(JSON.parse(code.text).fetch("configuration")).to eq(
+ unsafe_attributes.deep_stringify_keys,
+ )
+ expect(unsafe_tool.details).not_to include(unsafe_token)
+ end
+
+ it "creates the exact workflow as unpublished, credits the approver, and returns its URL" do
+ item = build_reviewable
+
+ expect { item.perform(other_admin, :approve) }.to change {
+ DiscourseWorkflows::Workflow.count
+ }.by(1)
+ workflow = DiscourseWorkflows::Workflow.order(:id).last
+ expect(workflow).to have_attributes(name: "Manual log", created_by_id: other_admin.id)
+ expect(workflow).not_to be_published
+ expect(workflow.nodes.map { |node| node["type"] }).to contain_exactly(
+ "trigger:manual",
+ "action:log",
+ )
+ end
+
+ it "does not save rejected drafts" do
+ item = build_reviewable
+ expect { item.perform(admin, :reject) }.not_to change { DiscourseWorkflows::Workflow.count }
+ end
+
+ it "only creates a proposed AI agent after the workflow draft is approved" do
+ agent_token =
+ DiscourseWorkflows::AdminAssistant::WorkflowDraft.sign(
+ { name: "AI review", operations: agent_operations },
+ user: admin,
+ )
+ initial_tool =
+ described_class.new(
+ { draft_token: agent_token },
+ bot_user: Discourse.system_user,
+ llm: nil,
+ context: context,
+ )
+
+ expect { initial_tool.validation_error }.not_to change { AiAgent.count }
+ item = build_reviewable(agent_token)
+ expect { item.perform(other_admin, :approve) }.to change { AiAgent.count }.by(1)
+ expect(AiAgent.find_by(name: "Workflow review agent")).to have_attributes(
+ created_by_id: other_admin.id,
+ system_prompt: "Review the supplied content and return a short result.",
+ )
+ end
+
+ it "rejects non-admin requesters and approvers" do
+ context.user = user
+ expect(tool.validation_error[:status]).to eq("error")
+
+ item = build_reviewable
+ expect { item.perform(user, :approve) }.to raise_error(Reviewable::InvalidAction)
+ expect(DiscourseWorkflows::Workflow.count).to eq(0)
+ end
+
+ it "rejects a draft requested by another admin before approval" do
+ context.user = other_admin
+ expect(tool.validation_error[:status]).to eq("error")
+ end
+
+ it "rejects a reviewable that is not bound to the signed requester" do
+ item = build_reviewable
+ item.target.tool_parameters["requester_id"] = other_admin.id
+ item.target.save!
+
+ expect { item.perform(other_admin, :approve) }.to raise_error(Discourse::InvalidAccess)
+ expect(DiscourseWorkflows::Workflow.count).to eq(0)
+ end
+
+ it "requires the Core workflow management permission" do
+ guardian = admin.guardian
+ guardian.stubs(:can_manage_workflows?).returns(false)
+ admin.stubs(:guardian).returns(guardian)
+
+ expect(tool.validation_error[:status]).to eq("error")
+ end
+
+ it "rejects invalid, expired, and malformed graph drafts" do
+ tool.parameters[:draft_token] = token + "tampered"
+ expect(tool.validation_error[:status]).to eq("error")
+
+ expired = token
+ tool.parameters[:draft_token] = expired
+ tool.instance_variable_set(:@draft, nil)
+ freeze_time 2.days.from_now
+ expect(tool.validation_error[:status]).to eq("error")
+
+ freeze_time 2.days.ago
+ malformed =
+ DiscourseWorkflows::AdminAssistant::WorkflowDraft.sign(
+ { name: "Broken", operations: [{ op: "add_node", node: { type: "missing", name: "X" } }] },
+ user: admin,
+ )
+ broken_tool =
+ described_class.new(
+ { draft_token: malformed },
+ bot_user: Discourse.system_user,
+ llm: nil,
+ context: context.tap { |value| value.user = admin },
+ )
+ expect(broken_tool.validation_error[:error]).to eq(
+ I18n.t("discourse_workflows.admin_assistant.invalid_graph"),
+ )
+ end
+
+ it "rejects drafts containing raw secrets" do
+ unsafe =
+ DiscourseWorkflows::AdminAssistant::WorkflowDraft.sign(
+ {
+ name: "Unsafe",
+ operations: [
+ {
+ op: "add_node",
+ node: {
+ type: "action:log",
+ name: "Log",
+ parameters: {
+ api_key: "raw-secret",
+ },
+ },
+ },
+ ],
+ },
+ user: admin,
+ )
+ unsafe_tool =
+ described_class.new(
+ { draft_token: unsafe },
+ bot_user: Discourse.system_user,
+ llm: nil,
+ context: context,
+ )
+
+ expect(unsafe_tool.validation_error[:error]).to eq(
+ I18n.t("discourse_workflows.admin_assistant.secret_draft"),
+ )
+ end
+
+ it "rechecks capability and the requester's admin status at approval time" do
+ item = build_reviewable
+ DiscourseWorkflows::AdminAssistant::Capability.stubs(:status).returns(:disabled)
+ expect { item.perform(admin, :approve) }.to raise_error(Discourse::InvalidAccess)
+ expect(item.reload).to be_pending
+
+ DiscourseWorkflows::AdminAssistant::Capability.stubs(:status).returns(:available)
+ admin.update!(admin: false)
+ expect { item.perform(other_admin, :approve) }.to raise_error(Discourse::InvalidAccess)
+ expect(item.reload).to be_pending
+ end
+
+ it "prevents replay through a second approval" do
+ first = build_reviewable
+ second = build_reviewable
+
+ first.perform(admin, :approve)
+ expect { second.perform(other_admin, :approve) }.to raise_error(Discourse::InvalidAccess)
+ expect(DiscourseWorkflows::Workflow.count).to eq(1)
+ end
+
+ it "rolls back AI-agent side effects and releases the claim with the approval transaction" do
+ agent_token =
+ DiscourseWorkflows::AdminAssistant::WorkflowDraft.sign(
+ { name: "AI review", operations: agent_operations },
+ user: admin,
+ )
+ item = build_reviewable(agent_token)
+ replay_context = DiscourseAi::Agents::BotContext.new(user: other_admin, messages: [])
+ replay_context.reviewable_id = item.id
+ replay_tool =
+ described_class.new(
+ { draft_token: agent_token, requester_id: admin.id },
+ bot_user: Discourse.system_user,
+ llm: nil,
+ context: replay_context,
+ )
+
+ expect do
+ expect do
+ DiscourseWorkflows::Workflow.transaction(requires_new: true) do
+ expect(replay_tool.invoke[:status]).to eq("success")
+ expect(AiAgent.find_by(name: "Workflow review agent")).to be_present
+ raise ActiveRecord::Rollback
+ end
+ end.not_to change { DiscourseWorkflows::Workflow.count }
+ end.not_to change { AiAgent.count }
+ expect(
+ DiscourseWorkflows::AdminAssistant::WorkflowDraft.claim(agent_token, reviewable_id: item.id),
+ ).to eq(true)
+ DiscourseWorkflows::AdminAssistant::WorkflowDraft.release(agent_token, reviewable_id: item.id)
+ end
+
+ it "hides tools and authoring instructions when public capability is unavailable" do
+ DiscourseWorkflows::AdminAssistant::Capability.stubs(:status).returns(:unconfigured)
+ context = DiscourseAi::Agents::BotContext.new(user: admin, messages: [])
+ assistant = DiscourseAi::Agents::DiscourseAdminAssistant.new
+
+ expect(assistant.runtime_tools(context: context)).not_to include(
+ DiscourseWorkflows::AdminAssistant::GenerateWorkflow,
+ described_class,
+ )
+ expect(assistant.craft_prompt(context).system_message_text).not_to include(
+ "call generate_workflow",
+ )
+ end
+
+ it "registers both workflow tools for the admin assistant and pending replay" do
+ tools = DiscourseAi::Agents::DiscourseAdminAssistant.new.tools
+ expect(tools).to include(DiscourseWorkflows::AdminAssistant::GenerateWorkflow, described_class)
+ expect(DiscourseAi::Agents::Agent.all_available_tools).to include(described_class)
+ prompt =
+ DiscourseAi::Agents::DiscourseAdminAssistant.new.craft_prompt(
+ DiscourseAi::Agents::BotContext.new(user: admin, messages: []),
+ )
+ expect(prompt.system_message_text).to include(
+ "explicit human approval",
+ "needs_clarification",
+ "unpublished",
+ )
+ end
+end
+
+RSpec.describe DiscourseWorkflows::AdminAssistant::GenerateWorkflow do
+ fab!(:admin)
+
+ let(:context) { DiscourseAi::Agents::BotContext.new(user: admin, messages: []) }
+ let(:tool) do
+ described_class.new(
+ { description: "Create a manual workflow that logs Hello" },
+ bot_user: Discourse.system_user,
+ llm: nil,
+ context: context,
+ )
+ end
+ let(:proposal) do
+ {
+ "title" => "Manual log",
+ "summary" => "Logs a message when run manually",
+ "operations" => [
+ {
+ "op" => "add_node",
+ "client_id" => "manual",
+ "node" => {
+ "type" => "trigger:manual",
+ "name" => "Manual",
+ "parameters" => {
+ },
+ },
+ },
+ ],
+ }
+ end
+
+ before do
+ SiteSetting.enable_discourse_workflows = true
+ DiscourseWorkflows::AdminAssistant::Capability.stubs(:status).returns(:available)
+ allow_any_instance_of(Jobs::DiscourseWorkflows::AuthorWithAi).to receive(
+ :execute,
+ ) do |_job, args|
+ DiscourseWorkflows::AiAuthoringSession.find(args[:session_id]).update!(
+ status: "proposal_ready",
+ proposed_patch: proposal,
+ )
+ end
+ end
+
+ it "generates and validates a signed draft without saving a workflow" do
+ result = nil
+ expect { result = tool.invoke }.not_to change { DiscourseWorkflows::Workflow.count }
+
+ expect(result[:status]).to eq("success")
+ expect(result[:draft_token]).to match(/\Aworkflow_authoring_draft_[0-9a-f]{32}\z/)
+ expect(DiscourseWorkflows::AdminAssistant::WorkflowDraft.read(result[:draft_token])).to include(
+ name: "Manual log",
+ operations: proposal["operations"],
+ user_id: admin.id,
+ )
+ expect(DiscourseWorkflows::AiAuthoringSession.count).to eq(0)
+ end
+
+ it "preserves passed and failed script checks in the signed draft and approval preview" do
+ proposal["operations"] += [
+ {
+ "op" => "add_node",
+ "client_id" => "code",
+ "node" => {
+ "type" => "action:code",
+ "name" => "Process items",
+ "parameters" => {
+ "mode" => "runOnceForEachItem",
+ "code" => "var items = $input.all(); return items;",
+ },
+ },
+ },
+ { "op" => "add_connection", "from" => "manual", "to" => "code" },
+ ]
+ [true, false].each do |valid|
+ validations = [
+ {
+ "operation_index" => 1,
+ "node_name" => "Process items",
+ "mode" => "runOnceForEachItem",
+ "valid" => valid,
+ "errors" => valid ? [] : ["$input.all is only available in runOnceForAllItems mode"],
+ },
+ ]
+ proposal["script_validations"] = validations
+ result = nil
+ expect { result = tool.invoke }.not_to change { DiscourseWorkflows::Workflow.count }
+ expect(result[:status]).to eq("success")
+ expect(result[:script_validations]).to eq(validations)
+ expect(
+ DiscourseWorkflows::AdminAssistant::WorkflowDraft.read(result[:draft_token])[
+ :script_validations
+ ],
+ ).to eq(validations)
+
+ creator =
+ DiscourseWorkflows::AdminAssistant::CreateWorkflow.new(
+ { draft_token: result[:draft_token] },
+ bot_user: Discourse.system_user,
+ llm: nil,
+ context: context,
+ )
+ code = Nokogiri::HTML5.fragment(PrettyText.cook(creator.details)).at_css("pre code")
+ expect(JSON.parse(code.text).dig("configuration", "script_validations")).to eq(validations)
+ expect(creator.validation_error).to be_nil
+ end
+ end
+
+ it "does not return secret-bearing script validation metadata" do
+ proposal["script_validations"] = [
+ { "valid" => false, "errors" => ["api_key: sensitive-value"] },
+ ]
+
+ result = tool.invoke
+ expect(result[:status]).to eq("error")
+ expect(result[:draft_token]).to be_nil
+ expect(result[:script_validations]).to be_nil
+ expect(DiscourseWorkflows::AiAuthoringSession.count).to eq(0)
+ end
+
+ it "rejects non-admin users and unavailable capability" do
+ context.user = Fabricate(:user)
+ expect(tool.invoke[:status]).to eq("error")
+
+ context.user = admin
+ DiscourseWorkflows::AdminAssistant::Capability.stubs(:status).returns(:unconfigured)
+ expect(tool.invoke[:status]).to eq("error")
+ end
+
+ it "does not forward secret-bearing requests to workflow authoring" do
+ expect_any_instance_of(Jobs::DiscourseWorkflows::AuthorWithAi).not_to receive(:execute)
+
+ [
+ "Use API key: raw-secret-value",
+ "POST to https://admin:[email protected]/hook",
+ "Use -----BEGIN PRIVATE KEY----- raw-private-key",
+ "Use eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiIxMjM0NTY3ODkwIn0.signature123",
+ ].each do |description|
+ tool.parameters[:description] = description
+ expect(tool.invoke[:status]).to eq("error")
+ end
+ end
+
+ it "returns Core clarification questions without losing them" do
+ questions = [
+ {
+ "id" => "scope",
+ "question" => "Which topics should run this workflow?",
+ "multi_select" => false,
+ "custom_allowed" => true,
+ "options" => [
+ { "label" => "All topics", "description" => "Run everywhere." },
+ { "label" => "Support", "description" => "Run in support categories." },
+ ],
+ },
+ ]
+ allow_any_instance_of(Jobs::DiscourseWorkflows::AuthorWithAi).to receive(
+ :execute,
+ ) do |_job, args|
+ DiscourseWorkflows::AiAuthoringSession.find(args[:session_id]).update!(
+ status: "needs_clarification",
+ latest_response: {
+ "status" => "needs_clarification",
+ "message" => "I need the topic scope.",
+ "questions" => questions,
+ },
+ )
+ end
+
+ result = tool.invoke
+
+ expect(result).to eq(
+ status: "needs_clarification",
+ message: "I need the topic scope.",
+ questions: questions,
+ )
+ expect(DiscourseWorkflows::AiAuthoringSession.count).to eq(0)
+ end
+
+ it "does not create proposed AI agents while authoring or validating a draft" do
+ proposal["operations"] = [
+ {
+ "op" => "create_ai_agent",
+ "client_id" => "draft-agent",
+ "agent" => {
+ "name" => "Workflow draft agent",
+ "description" => "Reviews workflow input.",
+ "system_prompt" => "Review the input and return a short result.",
+ },
+ },
+ {
+ "op" => "add_node",
+ "client_id" => "manual",
+ "node" => {
+ "type" => "trigger:manual",
+ "name" => "Manual",
+ "parameters" => {
+ },
+ },
+ },
+ {
+ "op" => "add_node",
+ "client_id" => "review",
+ "node" => {
+ "type" => "action:ai_agent",
+ "name" => "Review",
+ "parameters" => {
+ "agent_id" => {
+ "$ref" => "draft-agent",
+ },
+ "prompt" => "Review this run.",
+ },
+ },
+ },
+ { "op" => "add_connection", "from" => "manual", "to" => "review" },
+ ]
+
+ expect { expect(tool.invoke[:status]).to eq("success") }.not_to change { AiAgent.count }
+ expect(AiAgent.find_by(name: "Workflow draft agent")).to be_nil
+ end
+
+ it "rejects malformed or secret-bearing generated proposals" do
+ proposal["operations"] = [{ "op" => "unknown" }]
+ expect(tool.invoke[:status]).to eq("error")
+
+ proposal["operations"] = [
+ {
+ "op" => "add_node",
+ "node" => {
+ "type" => "action:log",
+ "name" => "Log",
+ "parameters" => {
+ "password" => "raw-secret",
+ },
+ },
+ },
+ ]
+ expect(tool.invoke[:status]).to eq("error")
+ end
+end
diff --git a/plugins/discourse-workflows/spec/system/admin_assistant_workflow_spec.rb b/plugins/discourse-workflows/spec/system/admin_assistant_workflow_spec.rb
new file mode 100644
index 00000000000..617877e251b
--- /dev/null
+++ b/plugins/discourse-workflows/spec/system/admin_assistant_workflow_spec.rb
@@ -0,0 +1,138 @@
+# frozen_string_literal: true
+
+RSpec.describe "Admin Assistant workflow approval preview" do
+ fab!(:admin) { Fabricate(:admin, refresh_auto_groups: true) }
+ fab!(:ai_agent) do
+ Fabricate(
+ :ai_agent,
+ allowed_group_ids: [Group::AUTO_GROUPS[:admins]],
+ allow_chat_direct_messages: true,
+ require_approval: true,
+ ).tap(&:create_user!)
+ end
+
+ let(:chat_page) { PageObjects::Pages::Chat.new }
+ let(:operations) do
+ [
+ {
+ "op" => "add_node",
+ "client_id" => "manual",
+ "node" => {
+ "type" => "trigger:manual",
+ "name" => "Manual trigger",
+ "parameters" => {
+ },
+ },
+ },
+ {
+ "op" => "add_node",
+ "client_id" => "accepted",
+ "node" => {
+ "type" => "action:log",
+ "name" => "Record accepted topic",
+ "parameters" => {
+ "message" => "Accepted",
+ },
+ },
+ },
+ { "op" => "add_connection", "from" => "manual", "to" => "accepted" },
+ ]
+ end
+
+ before do
+ SiteSetting.discourse_ai_enabled = true
+ SiteSetting.ai_bot_enabled = true
+ SiteSetting.enable_discourse_workflows = true
+ SiteSetting.chat_enabled = true
+ SiteSetting.chat_allowed_groups = Group::AUTO_GROUPS[:everyone]
+ DiscourseWorkflows::AdminAssistant::Capability.stubs(:status).returns(:available)
+ sign_in(admin)
+ end
+
+ it "shows the exact graph before controls and saves only after approval" do
+ channel = Fabricate(:direct_message_channel, users: [admin, ai_agent.user])
+ source_message = Fabricate(:chat_message, chat_channel: channel, user: admin)
+ token =
+ DiscourseWorkflows::AdminAssistant::WorkflowDraft.sign(
+ { name: "Topic triage", operations: operations },
+ user: admin,
+ )
+ context = DiscourseAi::Agents::BotContext.new(user: admin, messages: [])
+ tool =
+ DiscourseWorkflows::AdminAssistant::CreateWorkflow.new(
+ { draft_token: token, requester_id: admin.id },
+ bot_user: ai_agent.user,
+ llm: nil,
+ context: context,
+ )
+ action =
+ AiToolAction.create!(
+ tool_name: tool.name,
+ tool_parameters: tool.parameters,
+ ai_agent: ai_agent,
+ bot_user_id: ai_agent.user_id,
+ )
+ reviewable =
+ ReviewableAiToolAction.needs_review!(
+ target: action,
+ created_by: ai_agent.user,
+ reviewable_by_moderator: true,
+ payload: {
+ chat_message_id: source_message.id,
+ },
+ )
+ reviewable.add_score(
+ Discourse.system_user,
+ ReviewableScore.types[:needs_approval],
+ force_review: true,
+ )
+ approval_message =
+ Fabricate(
+ :chat_message,
+ chat_channel: channel,
+ user: ai_agent.user,
+ message: tool.details,
+ blocks:
+ DiscourseAi::AiBot::ChatToolApproval.pending_blocks(
+ reviewable.id,
+ info: {
+ summary: tool.summary,
+ details: tool.details,
+ question: tool.approval_question,
+ parameters: [],
+ },
+ ),
+ )
+
+ expect { chat_page.visit_channel(channel) }.not_to change { DiscourseWorkflows::Workflow.count }
+ expect(page).to have_css(
+ ".chat-confirmation__description .assistant-workflow-preview",
+ text: "Topic triage",
+ )
+ expect(page).to have_css(".assistant-workflow-preview__node", count: 2)
+ expect(page).to have_css(".assistant-workflow-preview__connection", count: 1)
+ expect(page).to have_css(".assistant-workflow-preview details:not([open])")
+ expect(page.html).not_to include(token)
+ expect(page.evaluate_script(<<~JS)).to eq(true)
+ document.querySelector(".assistant-workflow-preview").compareDocumentPosition(
+ document.querySelector(".chat-confirmation__footer")
+ ) === Node.DOCUMENT_POSITION_FOLLOWING
+ JS
+
+ click_button(I18n.t("discourse_ai.ai_bot.chat_tool_approval.approve_label"))
+
+ expect(page).to have_text("Approved by @#{admin.username}")
+ workflow = DiscourseWorkflows::Workflow.order(:id).last
+ expect(workflow).to have_attributes(name: "Topic triage", created_by_id: admin.id)
+ expect(workflow).not_to be_published
+ url = "#{Discourse.base_url}/admin/plugins/discourse-workflows/workflows/#{workflow.id}"
+ expect(reviewable.reload.payload["continuation"]).to eq(
+ "chat_message_id" => approval_message.id,
+ "tool_result" => {
+ "status" => "success",
+ "workflow_id" => workflow.id,
+ "url" => url,
+ },
+ )
+ end
+end
diff --git a/plugins/discourse-workflows/test/javascripts/components/admin-assistant/workflow-preview-test.gjs b/plugins/discourse-workflows/test/javascripts/components/admin-assistant/workflow-preview-test.gjs
new file mode 100644
index 00000000000..7f920d54723
--- /dev/null
+++ b/plugins/discourse-workflows/test/javascripts/components/admin-assistant/workflow-preview-test.gjs
@@ -0,0 +1,457 @@
+import { trustHTML } from "@ember/template";
+import { click, render, settled } from "@ember/test-helpers";
+import { module, test } from "qunit";
+import { setupRenderingTest } from "discourse/tests/helpers/component-test";
+import DDecoratedHtml from "discourse/ui-kit/d-decorated-html";
+import AdminAssistantWorkflowPreview from "discourse/plugins/discourse-workflows/discourse/components/admin-assistant/workflow-preview";
+import { decorateWorkflowPreview } from "discourse/plugins/discourse-workflows/discourse/initializers/assistant-workflow-preview";
+import {
+ extractWorkflowPreview,
+ layoutWorkflowPreview,
+} from "discourse/plugins/discourse-workflows/discourse/lib/admin-assistant/workflow-preview";
+
+const APPROVAL_TITLE = "Save this workflow as an unpublished draft?";
+const PREVIEW_KIND = "discourse_admin_assistant_workflow_preview_v1";
+
+function escapeHtml(value) {
+ return value
+ .replaceAll("&", "&amp;")
+ .replaceAll("<", "&lt;")
+ .replaceAll(">", "&gt;");
+}
+
+function cookedPreview(configuration, kind = PREVIEW_KIND) {
+ return `<pre><code class="lang-admin-assistant-workflow">${escapeHtml(JSON.stringify({ kind, configuration }))}</code></pre>`;
+}
+
+function addNode(clientId, name, type = "action:log") {
+ return {
+ op: "add_node",
+ client_id: clientId,
+ node: { name, parameters: {}, type },
+ };
+}
+
+function approvalMessage(
+ id,
+ configuration,
+ title = APPROVAL_TITLE,
+ kind = PREVIEW_KIND
+) {
+ return {
+ id,
+ blocks: [{ type: "confirmation", title }],
+ cooked: cookedPreview(configuration, kind),
+ };
+}
+
+module(
+ "Discourse Workflows | Admin Assistant | Workflow preview",
+ function (hooks) {
+ setupRenderingTest(hooks);
+
+ test("renders escaped nodes and directed branches from the exact configuration", async function (assert) {
+ const maliciousName = '<img src=x onerror="alert(1)">';
+ this.message = approvalMessage(42, {
+ name: '<script>alert("workflow")</script>',
+ operations: [
+ addNode("start", maliciousName, "trigger:manual"),
+ addNode("condition", "Check trust", "logic:condition"),
+ addNode("accepted", "Send welcome"),
+ addNode("rejected", "Record rejection"),
+ { op: "add_connection", from: "start", to: "condition" },
+ {
+ op: "add_connection",
+ from: "condition",
+ to: "accepted",
+ output_index: 0,
+ },
+ {
+ op: "add_connection",
+ from: "condition",
+ to: "rejected",
+ output_index: 1,
+ },
+ ],
+ });
+ const layout = layoutWorkflowPreview(
+ extractWorkflowPreview(this.message.cooked)
+ );
+
+ assert.deepEqual(
+ layout.nodes.map(({ id, x, y }) => ({ id, x, y })),
+ [
+ { id: "node-0", x: 20, y: 20 },
+ { id: "node-1", x: 228, y: 20 },
+ { id: "node-2", x: 436, y: 20 },
+ { id: "node-3", x: 436, y: 144 },
+ ],
+ "places both branch targets in a stable lane"
+ );
+ assert.deepEqual(
+ layout.connections.map(({ from, outputIndex, to }) => ({
+ from,
+ outputIndex,
+ to,
+ })),
+ [
+ { from: "node-0", outputIndex: 0, to: "node-1" },
+ { from: "node-1", outputIndex: 0, to: "node-2" },
+ { from: "node-1", outputIndex: 1, to: "node-3" },
+ ],
+ "connects the expected nodes"
+ );
+
+ await render(
+ <template>
+ <AdminAssistantWorkflowPreview @message={{this.message}} />
+ </template>
+ );
+
+ assert
+ .dom(".assistant-workflow-preview__heading")
+ .hasText('<script>alert("workflow")</script>');
+ assert.dom(".assistant-workflow-preview__node").exists({ count: 4 });
+ assert
+ .dom(".assistant-workflow-preview__connection")
+ .exists({ count: 3 });
+ assert
+ .dom('[data-node-type="trigger:manual"] strong')
+ .hasText(maliciousName);
+ assert.dom(".assistant-workflow-preview img").doesNotExist();
+ assert.dom(".assistant-workflow-preview script").doesNotExist();
+ assert
+ .dom('[data-output-index="1"]')
+ .hasText("Branch 2", "labels the second output branch");
+ assert
+ .dom(".assistant-workflow-preview__node .sr-only")
+ .includesText("Connects to Check trust");
+ assert
+ .dom('[data-node-type="logic:condition"] .sr-only')
+ .includesText("Branch 2: Record rejection");
+ assert
+ .dom(".assistant-workflow-preview__badge")
+ .hasText("Read-only preview");
+ });
+
+ test("keeps nodes and SVG connections aligned in RTL", async function (assert) {
+ this.message = approvalMessage(110, {
+ name: "RTL workflow",
+ operations: [
+ addNode("start", "Start", "trigger:manual"),
+ addNode("end", "End"),
+ { op: "add_connection", from: "start", to: "end" },
+ ],
+ });
+ await render(
+ <template>
+ <div dir="rtl">
+ <AdminAssistantWorkflowPreview @message={{this.message}} />
+ </div>
+ </template>
+ );
+ const nodes = this.element.querySelectorAll(
+ ".assistant-workflow-preview__node"
+ );
+ const connection = this.element.querySelector(
+ ".assistant-workflow-preview__connection"
+ );
+ const start = connection
+ .getPointAtLength(0)
+ .matrixTransform(connection.getScreenCTM());
+ const end = connection
+ .getPointAtLength(connection.getTotalLength())
+ .matrixTransform(connection.getScreenCTM());
+ assert.true(
+ Math.abs(start.x - nodes[0].getBoundingClientRect().right) < 1,
+ "connection starts at the source node"
+ );
+ assert.true(
+ Math.abs(end.x - nodes[1].getBoundingClientRect().left) < 1,
+ "connection ends at the target node"
+ );
+ assert.strictEqual(
+ getComputedStyle(nodes[0]).direction,
+ "rtl",
+ "node text keeps the page direction"
+ );
+ });
+
+ test("shows script-check warnings and preserves errors in exact configuration", async function (assert) {
+ this.message = approvalMessage(111, {
+ name: "Code workflow",
+ operations: [addNode("code", "Process items", "action:code")],
+ script_validations: [
+ {
+ operation_index: 0,
+ node_name: "Process items",
+ valid: false,
+ errors: ["<img src=x onerror=alert(1)> invalid script"],
+ },
+ ],
+ });
+ await render(
+ <template>
+ <AdminAssistantWorkflowPreview @message={{this.message}} />
+ </template>
+ );
+ assert.dom(".assistant-workflow-preview__warning").exists();
+ assert
+ .dom(".assistant-workflow-preview__details code")
+ .includesText("invalid script");
+ assert.dom(".assistant-workflow-preview img").doesNotExist();
+ });
+
+ test("does not warn for successful script checks", async function (assert) {
+ this.message = approvalMessage(112, {
+ name: "Code workflow",
+ operations: [addNode("code", "Process items", "action:code")],
+ script_validations: [{ valid: true, errors: [] }],
+ });
+ await render(
+ <template>
+ <AdminAssistantWorkflowPreview @message={{this.message}} />
+ </template>
+ );
+ assert.dom(".assistant-workflow-preview__warning").doesNotExist();
+ });
+
+ test("lays out cycles deterministically and labels them", async function (assert) {
+ const configuration = {
+ name: "Retry loop",
+ operations: [
+ addNode("start", "Start", "trigger:manual"),
+ addNode("retry", "Retry"),
+ { op: "add_connection", from: "start", to: "retry" },
+ { op: "add_connection", from: "retry", to: "start" },
+ ],
+ };
+ const preview = extractWorkflowPreview(cookedPreview(configuration));
+ const layout = layoutWorkflowPreview(preview);
+
+ assert.deepEqual(
+ layout.nodes.map(({ id, x, y }) => ({ id, x, y })),
+ [
+ { id: "node-0", x: 20, y: 20 },
+ { id: "node-1", x: 20, y: 144 },
+ ],
+ "keeps a strongly connected component together"
+ );
+ assert.true(layout.hasCycle);
+ assert.true(
+ layout.connections.every((connection) =>
+ connection.path.includes(" C ")
+ ),
+ "draws both directed cycle connections"
+ );
+
+ this.message = approvalMessage(43, configuration);
+ await render(
+ <template>
+ <AdminAssistantWorkflowPreview @message={{this.message}} />
+ </template>
+ );
+
+ assert
+ .dom(".assistant-workflow-preview__connection")
+ .exists({ count: 2 });
+ assert
+ .dom(".assistant-workflow-preview__footer")
+ .includesText("Includes a cycle");
+ });
+
+ test("simulates rename, removal, reconnection, and self-loops", function (assert) {
+ const preview = extractWorkflowPreview(
+ cookedPreview({
+ name: "Mutated graph",
+ operations: [
+ addNode("start", "Start", "trigger:manual"),
+ addNode("temporary", "Temporary"),
+ addNode("kept", "Original"),
+ { op: "add_connection", from: "start", to: "temporary" },
+ { op: "remove_node", client_id: "temporary" },
+ { op: "rename_node", client_id: "kept", name: "Renamed" },
+ addNode("after", "After removal"),
+ { op: "add_connection", from: "start", to: "after" },
+ { op: "remove_connection", from: "start", to: "after" },
+ { op: "add_connection", from: "start", to: "kept" },
+ { op: "add_connection", from: "kept", to: "kept" },
+ { op: "add_connection", from: "kept", to: "after" },
+ ],
+ })
+ );
+ const layout = layoutWorkflowPreview(preview);
+
+ assert.deepEqual(
+ preview.nodes.map(({ id, name }) => ({ id, name })),
+ [
+ { id: "node-0", name: "Start" },
+ { id: "node-2", name: "Renamed" },
+ { id: "node-3", name: "After removal" },
+ ]
+ );
+ assert.deepEqual(
+ preview.connections.map(({ from, to }) => ({ from, to })),
+ [
+ { from: "node-0", to: "node-2" },
+ { from: "node-2", to: "node-2" },
+ { from: "node-2", to: "node-3" },
+ ]
+ );
+ assert.true(layout.hasCycle, "recognizes a self-loop as a cycle");
+ });
+
+ test("falls back honestly for unsupported or oversized exact drafts", async function (assert) {
+ this.message = approvalMessage(44, {
+ name: "Unsupported graph",
+ operations: [{ op: "future_operation" }],
+ });
+
+ await render(
+ <template>
+ <AdminAssistantWorkflowPreview @message={{this.message}} />
+ </template>
+ );
+
+ assert.dom(".assistant-workflow-preview__node").doesNotExist();
+ assert
+ .dom(".assistant-workflow-preview__fallback")
+ .includesText("Review the exact configuration before approving");
+
+ this.set(
+ "message",
+ approvalMessage(45, {
+ name: "Large graph",
+ operations: Array.from({ length: 25 }, (_, index) =>
+ addNode(`node-${index}`, `Node ${index}`)
+ ),
+ })
+ );
+
+ await settled();
+ assert.dom(".assistant-workflow-preview__node").doesNotExist();
+ assert.dom(".assistant-workflow-preview__fallback").exists();
+ });
+
+ test("does not render for non-workflow confirmation cards", async function (assert) {
+ this.message = approvalMessage(
+ 46,
+ { name: "Spoof", operations: [addNode("start", "Start")] },
+ "Another approval",
+ "another_tool_preview_v1"
+ );
+
+ await render(
+ <template>
+ <AdminAssistantWorkflowPreview @message={{this.message}} />
+ </template>
+ );
+
+ assert.dom(".assistant-workflow-preview").doesNotExist();
+ });
+
+ test("renders the preview in the confirmation body before the controls", async function (assert) {
+ this.message = approvalMessage(99, {
+ name: "Manual workflow",
+ operations: [addNode("manual", "Manual trigger", "trigger:manual")],
+ });
+ this.cooked = trustHTML(this.message.cooked);
+ this.decorate = (element, helper) =>
+ decorateWorkflowPreview(element, helper, this.message);
+
+ await render(
+ <template>
+ <section class="chat-confirmation">
+ <div class="chat-confirmation__description">
+ <DDecoratedHtml
+ @decorate={{this.decorate}}
+ @html={{this.cooked}}
+ />
+ </div>
+ <div class="chat-confirmation__footer">Approve or reject</div>
+ </section>
+ </template>
+ );
+
+ assert.dom(".assistant-workflow-preview").exists({ count: 1 });
+ const preview = this.element.querySelector(".assistant-workflow-preview");
+ const controls = this.element.querySelector(".chat-confirmation__footer");
+ assert.strictEqual(
+ preview.compareDocumentPosition(controls),
+ Node.DOCUMENT_POSITION_FOLLOWING
+ );
+ assert
+ .dom(".assistant-workflow-preview__footer")
+ .includesText("1 node · 0 connections");
+ assert
+ .dom(".assistant-workflow-preview__footer")
+ .includesText("Exact configuration");
+ assert
+ .dom(".assistant-workflow-preview__details")
+ .doesNotHaveAttribute("open");
+ await click(".assistant-workflow-preview__footer");
+ assert.dom(".assistant-workflow-preview__details").hasAttribute("open");
+ assert
+ .dom(".assistant-workflow-preview__details code")
+ .includesText('"Manual workflow"');
+ });
+
+ test("leaves ordinary code and non-confirmation messages unchanged", function (assert) {
+ const element = document.createElement("div");
+ element.innerHTML = cookedPreview({ name: "Manual", operations: [] });
+ const original = element.innerHTML;
+ const helper = {
+ renderGlimmer() {
+ assert.true(false, "must not mount outside a confirmation");
+ },
+ };
+ decorateWorkflowPreview(element, helper, {
+ blocks: [],
+ cooked: original,
+ });
+ assert.strictEqual(element.innerHTML, original);
+
+ element.innerHTML = "<pre><code>ordinary code</code></pre>";
+ const ordinary = element.innerHTML;
+ decorateWorkflowPreview(element, helper, {
+ blocks: [{ type: "confirmation" }],
+ });
+ assert.strictEqual(element.innerHTML, ordinary);
+
+ element.innerHTML = original;
+ decorateWorkflowPreview(
+ element,
+ {},
+ { blocks: [{ type: "confirmation" }] }
+ );
+ assert.strictEqual(
+ element.innerHTML,
+ original,
+ "preserves readable configuration without mounting support"
+ );
+ });
+
+ test("does not replace another payload in a confirmation title or error", function (assert) {
+ const message = approvalMessage(101, {
+ name: "Approved configuration",
+ operations: [addNode("manual", "Manual", "trigger:manual")],
+ });
+ const element = document.createElement("div");
+ element.innerHTML = cookedPreview({
+ name: "Different configuration",
+ operations: [],
+ });
+ const original = element.innerHTML;
+ decorateWorkflowPreview(
+ element,
+ {
+ renderGlimmer() {
+ assert.true(false, "must not mount a different payload");
+ },
+ },
+ message
+ );
+ assert.strictEqual(element.innerHTML, original);
+ });
+ }
+);