A platform for community discussion. Free, open, simple.
Feature: Add chat integration workflows send action (#40663)
Gabriel Grubba606bdbfb0f2b
diff --git a/plugins/discourse-chat-integration/config/locales/client.en.yml b/plugins/discourse-chat-integration/config/locales/client.en.ymlindex adc986a2fb4..d3c5abde93b 100644--- a/plugins/discourse-chat-integration/config/locales/client.en.yml+++ b/plugins/discourse-chat-integration/config/locales/client.en.yml@@ -321,3 +321,15 @@ en:description: "You can find the channel name in the Chat Integration settings"provider:label: Provider++ discourse_workflows:+ node_unavailable:+ requires_chat_integration: "Requires the Chat Integration plugin to be enabled"+ nodes:+ "action:send_chat_integration_message": "Send chat-integration message"+ node_descriptions:+ "action:send_chat_integration_message": "Send a notification to a chat-integration channel (Slack, Discord, Telegram, etc.)"+ send_chat_integration_message:+ channel_id: "Channel"+ configure: "Configure"+ message: "Message"diff --git a/plugins/discourse-chat-integration/config/locales/server.en.yml b/plugins/discourse-chat-integration/config/locales/server.en.ymlindex 1989839ac7b..f9f24f9ba27 100644--- a/plugins/discourse-chat-integration/config/locales/server.en.yml+++ b/plugins/discourse-chat-integration/config/locales/server.en.yml@@ -124,6 +124,15 @@ en:send_chat_integration_message:title: Send Chat-Integration message+ discourse_workflows:+ errors:+ send_chat_integration_message:+ channel_not_found: "Channel not found: %{channel_id}"+ provider_disabled: "Chat integration provider is disabled or missing: %{provider}"+ provider_failed: "The %{provider} provider could not send the message"+ provider_failed_with_details: "The %{provider} provider could not send the message: %{details}"+ message_required: "A message is required"+chat_integration:all_categories: "(all categories)"deleted_category: "(deleted category)"@@ -148,6 +157,10 @@ en:########## SLACK STRINGS #####################################################slack:+ errors:+ auth_error: "The provided authentication token is invalid"+ action_prohibited: "The bot does not have permission to post to that channel"+ channel_not_found: "The specified channel does not exist on Slack"status:header: |*Rules for this channel*diff --git a/plugins/discourse-chat-integration/lib/discourse_chat_integration/chat_integration_reference_post.rb b/plugins/discourse-chat-integration/lib/discourse_chat_integration/chat_integration_reference_post.rbindex 7aca38d70ce..c8740fc98c8 100644--- a/plugins/discourse-chat-integration/lib/discourse_chat_integration/chat_integration_reference_post.rb+++ b/plugins/discourse-chat-integration/lib/discourse_chat_integration/chat_integration_reference_post.rb@@ -2,9 +2,43 @@module DiscourseChatIntegrationclass ChatIntegrationReferencePost- def initialize(user:, topic:, kind:, raw: nil, context: {})+ class StandaloneTopic+ def id+ nil+ end++ def title+ SiteSetting.title+ end++ def category+ nil+ end++ def tags+ []+ end++ def posts+ []+ end++ def url+ Discourse.base_url+ end++ def highest_post_number+ 0+ end++ def custom_fields+ {}+ end+ end++ def initialize(user:, topic: nil, kind:, raw: nil, context: {})@user = user- @topic = topic+ @topic = topic || StandaloneTopic.new@kind = kind@raw = raw if raw.present?@context = contextdiff --git a/plugins/discourse-chat-integration/lib/discourse_chat_integration/provider/gitter/gitter_provider.rb b/plugins/discourse-chat-integration/lib/discourse_chat_integration/provider/gitter/gitter_provider.rbindex 4ba08c6251a..f896e306cd7 100644--- a/plugins/discourse-chat-integration/lib/discourse_chat_integration/provider/gitter/gitter_provider.rb+++ b/plugins/discourse-chat-integration/lib/discourse_chat_integration/provider/gitter/gitter_provider.rb@@ -38,8 +38,10 @@ module DiscourseChatIntegration(if parent_category"[#{parent_category.name}/#{topic.category.name}]"- else+ elsif topic.category"[#{topic.category.name}]"+ else+ ""end)diff --git a/plugins/discourse-chat-integration/lib/discourse_chat_integration/provider/slack/slack_provider.rb b/plugins/discourse-chat-integration/lib/discourse_chat_integration/provider/slack/slack_provider.rbindex 1e4a4ec2f46..b1562aa7df0 100644--- a/plugins/discourse-chat-integration/lib/discourse_chat_integration/provider/slack/slack_provider.rb+++ b/plugins/discourse-chat-integration/lib/discourse_chat_integration/provider/slack/slack_provider.rb@@ -287,7 +287,7 @@ module DiscourseChatIntegration::Provider::SlackProviderdata[:thread_ts] = message[:thread_ts]elsif (match = slack_thread_regex.match(post.raw)) && match.captures[0] == channeldata[:thread_ts] = match.captures[1]- set_slack_thread_ts(post.topic, channel, match.captures[1])+ set_slack_thread_ts(post.topic, channel, match.captures[1]) if post.topic.id.present?endend@@ -313,6 +313,8 @@ module DiscourseChatIntegration::Provider::SlackProvidererror_key = "chat_integration.provider.slack.errors.channel_not_found"elsif json["error"] == "invalid_auth"error_key = "chat_integration.provider.slack.errors.auth_error"+ elsif %w[not_in_channel no_permission restricted_action].include?(json["error"])+ error_key = "chat_integration.provider.slack.errors.action_prohibited"elseerror_key = nilend@@ -326,7 +328,7 @@ module DiscourseChatIntegration::Provider::SlackProviderendts = json.dig("message", "thread_ts") || json["ts"]- set_slack_thread_ts(post.topic, channel, ts) if !ts.nil? && !post.nil?+ set_slack_thread_ts(post.topic, channel, ts) if ts.present? && post&.topic&.id.present?responseenddiff --git a/plugins/discourse-chat-integration/lib/discourse_workflows/nodes/channel_selection.rb b/plugins/discourse-chat-integration/lib/discourse_workflows/nodes/channel_selection.rbnew file mode 100644index 00000000000..85e8b2ce5b3--- /dev/null+++ b/plugins/discourse-chat-integration/lib/discourse_workflows/nodes/channel_selection.rb@@ -0,0 +1,47 @@+# frozen_string_literal: true++if defined?(DiscourseWorkflows)+ module DiscourseWorkflows+ module Nodes+ module ChatIntegrationChannelSelection+ MAX_LOAD_OPTIONS = 200++ def self.channel_label(channel)+ provider = DiscourseChatIntegration::Provider.get_by_name(channel.provider)++ "#{channel.provider}: #{channel_identifier(channel, provider)}"+ end++ def self.channel_identifier(channel, provider = nil)+ provider ||= DiscourseChatIntegration::Provider.get_by_name(channel.provider)++ if provider&.const_defined?(:CHANNEL_IDENTIFIER_KEY)+ channel.data[provider::CHANNEL_IDENTIFIER_KEY]+ else+ channel.data.values.first+ end+ end++ def self.selectable_channels+ provider_names = DiscourseChatIntegration::Provider.enabled_provider_names+ return DiscourseChatIntegration::Channel.none if provider_names.empty?++ DiscourseChatIntegration::Channel.where("value::json->>'provider' IN (?)", provider_names)+ end++ def self.load_options(context)+ options =+ selectable_channels.map { |channel| { id: channel.id, name: channel_label(channel) } }++ options.select! { |option| context.matches_filter?(option[:name]) }++ options.sort_by { |option| option[:name].downcase }.first(MAX_LOAD_OPTIONS)+ end++ def selectable_channel(channel_id)+ DiscourseChatIntegration::Channel.find_by(id: channel_id)+ end+ end+ end+ end+enddiff --git a/plugins/discourse-chat-integration/lib/discourse_workflows/nodes/send_chat_integration_message/v1.rb b/plugins/discourse-chat-integration/lib/discourse_workflows/nodes/send_chat_integration_message/v1.rbnew file mode 100644index 00000000000..f1f72c9ed20--- /dev/null+++ b/plugins/discourse-chat-integration/lib/discourse_workflows/nodes/send_chat_integration_message/v1.rb@@ -0,0 +1,196 @@+# frozen_string_literal: true++if defined?(DiscourseWorkflows)+ module DiscourseWorkflows+ module Nodes+ module SendChatIntegrationMessage+ class V1 < DiscourseWorkflows::NodeType+ include ChatIntegrationChannelSelection++ description(+ name: "action:send_chat_integration_message",+ version: "1.0",+ defaults: {+ icon: "paper-plane",+ color: "green",+ },+ group: "discourse_actions",+ available: -> { SiteSetting.chat_integration_enabled },+ unavailable_reason_key:+ "discourse_workflows.node_unavailable.requires_chat_integration",+ capabilities: {+ run_scope: "per_item",+ },+ output_contracts: [+ {+ schema: {+ "$schema" => DiscourseWorkflows::Schema::DRAFT_URI,+ "type" => "object",+ "properties" => {+ "channel_id" => {+ "type" => "integer",+ },+ "provider" => {+ "type" => "string",+ },+ },+ },+ },+ ],+ properties: {+ channel_id: {+ type: :integer,+ required: true,+ type_options: {+ load_options_method: "chat_integration_channels",+ },+ ui: {+ control: :combo_box,+ dynamic_value: :chat_channel_id,+ },+ control_options: {+ action_icon: "wrench",+ action_label: "discourse_workflows.send_chat_integration_message.configure",+ action_route: "adminPlugins.show.discourse-chat-integration-providers",+ action_route_models: ["discourse-chat-integration"],+ filterable: true,+ value_property: :id,+ name_property: :name,+ set_from_option: {+ channel_name: "name",+ },+ },+ },+ channel_name: {+ type: :string,+ ui: {+ hidden: true,+ },+ },+ message: {+ type: :string,+ required: true,+ default: "={{ $trigger.post.excerpt }}",+ ui: {+ control: :textarea,+ },+ },+ },+ )++ def self.load_options_context(context)+ case context.method_name+ when "chat_integration_channels"+ ChatIntegrationChannelSelection.load_options(context)+ end+ end++ def execute(exec_ctx)+ items =+ exec_ctx.input_items.map.with_index do |_item, item_index|+ config = {+ "channel_id" => exec_ctx.get_node_parameter("channel_id", item_index),+ "message" => exec_ctx.get_node_parameter("message", item_index),+ }+ wrap(process(config, item_index))+ end+ [items]+ end++ private++ def process(config, item_index)+ channel = selectable_channel(config["channel_id"])+ if channel.blank?+ raise_node_error!(+ I18n.t(+ "discourse_workflows.errors.send_chat_integration_message.channel_not_found",+ channel_id: config["channel_id"],+ ),+ item_index: item_index,+ )+ end++ provider = DiscourseChatIntegration::Provider.get_by_name(channel.provider)+ if provider.blank? || !DiscourseChatIntegration::Provider.is_enabled(provider)+ raise_node_error!(+ I18n.t(+ "discourse_workflows.errors.send_chat_integration_message.provider_disabled",+ provider: channel.provider,+ ),+ item_index: item_index,+ )+ end++ if config["message"].blank?+ raise_node_error!(+ I18n.t("discourse_workflows.errors.send_chat_integration_message.message_required"),+ item_index: item_index,+ )+ end++ target = build_target(config["message"])+ begin+ provider.trigger_notification(target, channel, nil)+ rescue DiscourseChatIntegration::ProviderError => error+ raise_node_error!(+ provider_error_message(error, channel.provider),+ item_index: item_index,+ )+ end++ { "channel_id" => channel.id, "provider" => channel.provider }+ end++ def build_target(message)+ DiscourseChatIntegration::ChatIntegrationReferencePost.new(+ user: Discourse.system_user,+ kind: :workflow,+ raw: message,+ )+ end++ def provider_error_message(error, provider)+ details = provider_error_details(error)+ translation_key = details.present? ? "provider_failed_with_details" : "provider_failed"++ I18n.t(+ "discourse_workflows.errors.send_chat_integration_message.#{translation_key}",+ provider: provider.humanize,+ details: details,+ )+ end++ def provider_error_details(error)+ info = error.info || {}+ error_key = info[:error_key] || info["error_key"]+ return I18n.t(error_key) if error_key.present? && I18n.exists?(error_key)++ response_error = provider_response_error(info[:response_body] || info["response_body"])+ return response_error.humanize if response_error.present?+ return error_key.split(".").last.humanize if error_key.present?++ error.message if error.message.present? && error.message != error.class.name+ end++ def provider_response_error(response_body)+ response =+ case response_body+ when Hash+ response_body+ when String+ JSON.parse(response_body)+ else+ return+ end++ value = response["error"] || response[:error]+ value if value.is_a?(String) && value.match?(/\A[a-zA-Z0-9_.-]{1,100}\z/)+ rescue JSON::ParserError+ nil+ end+ end+ end+ end+ end+enddiff --git a/plugins/discourse-chat-integration/plugin.rb b/plugins/discourse-chat-integration/plugin.rbindex 9151b3bc0dd..3340dcb9e68 100644--- a/plugins/discourse-chat-integration/plugin.rb+++ b/plugins/discourse-chat-integration/plugin.rb@@ -13,6 +13,7 @@ register_asset "stylesheets/chat-integration.scss"register_svg_icon "rocket"register_svg_icon "arrow-circle-o-right"+register_svg_icon "paper-plane"module ::DiscourseChatIntegrationPLUGIN_NAME = "discourse-chat-integration"@@ -43,6 +44,15 @@ after_initialize do"discourse-chat-integration",use_new_show_route: true+ if respond_to?(:register_discourse_workflows_node)+ register_discourse_workflows_node do+ require_relative "lib/discourse_workflows/nodes/channel_selection"+ require_relative "lib/discourse_workflows/nodes/send_chat_integration_message/v1"++ [DiscourseWorkflows::Nodes::SendChatIntegrationMessage::V1]+ end+ end+DiscourseChatIntegration::Provider.mount_enginesif defined?(DiscourseAutomation)diff --git a/plugins/discourse-chat-integration/spec/integration/workflows_send_chat_integration_message_spec.rb b/plugins/discourse-chat-integration/spec/integration/workflows_send_chat_integration_message_spec.rbnew file mode 100644index 00000000000..07ef4f29132--- /dev/null+++ b/plugins/discourse-chat-integration/spec/integration/workflows_send_chat_integration_message_spec.rb@@ -0,0 +1,98 @@+# frozen_string_literal: true++require_relative "../dummy_provider"++RSpec.describe "Workflow: post created -> if author in group -> send to chat-integration channel" do+ include_context "with dummy provider"++ fab!(:admin)+ fab!(:category)+ fab!(:vips, :group)+ fab!(:member) { Fabricate(:user, refresh_auto_groups: true) }+ fab!(:outsider) { Fabricate(:user, refresh_auto_groups: true) }++ let(:channel) { DiscourseChatIntegration::Channel.create!(provider: "dummy") }++ before do+ SiteSetting.chat_integration_enabled = true+ SiteSetting.dummy_provider_enabled = true+ SiteSetting.enable_discourse_workflows = true+ vips.add(member)+ Jobs::DiscourseWorkflows::ExecuteWorkflow.jobs.clear++ graph =+ build_workflow_graph do |g|+ g.node "trigger-1",+ "trigger:post_created",+ configuration: {+ "category_ids" => [category.id],+ }+ g.node "group-1",+ "action:group",+ name: "Check author group",+ configuration: {+ "operation" => "check_membership",+ "username" => "={{ $json.user.username }}",+ "group_id" => vips.id,+ "actor_username" => "system",+ }+ g.node "condition-1",+ "condition:if",+ name: "Author in group",+ configuration: {+ "combinator" => "and",+ "conditions" => [+ {+ "id" => "1",+ "leftValue" => "={{ $json.group_membership.in_group }}",+ "rightValue" => true,+ "operator" => {+ "type" => "boolean",+ "operation" => "equals",+ },+ },+ ],+ }+ g.node "action-1",+ "action:send_chat_integration_message",+ name: "Notify channel",+ configuration: {+ "channel_id" => channel.id,+ "message" => "={{ $trigger.post.excerpt }}",+ }+ g.chain "trigger-1", "group-1", "condition-1"+ g.connect "condition-1", "action-1", output: "true"+ end++ workflow =+ Fabricate(:discourse_workflows_workflow, created_by: admin, name: "Notify VIPs", **graph)+ publish_workflow!(workflow)+ end++ def run_enqueued_workflows+ jobs = Jobs::DiscourseWorkflows::ExecuteWorkflow.jobs.dup+ Jobs::DiscourseWorkflows::ExecuteWorkflow.jobs.clear+ jobs.each do |job|+ Jobs::DiscourseWorkflows::ExecuteWorkflow.new.execute(job["args"].first.symbolize_keys)+ end+ end++ it "notifies the channel only for posts authored by a group member" do+ PostCreator.create!(+ member,+ title: "Member topic in category",+ raw: "Hello from a VIP",+ category: category.id,+ )+ PostCreator.create!(+ outsider,+ title: "Outsider topic in category",+ raw: "Hello from outside",+ category: category.id,+ )++ run_enqueued_workflows++ expect(provider.sent_to_channel_ids).to contain_exactly(channel.id)+ end+enddiff --git a/plugins/discourse-chat-integration/spec/lib/discourse_chat_integration/chat_integration_reference_post_spec.rb b/plugins/discourse-chat-integration/spec/lib/discourse_chat_integration/chat_integration_reference_post_spec.rbindex 8b27f583d7b..9cfbf6aad6a 100644--- a/plugins/discourse-chat-integration/spec/lib/discourse_chat_integration/chat_integration_reference_post_spec.rb+++ b/plugins/discourse-chat-integration/spec/lib/discourse_chat_integration/chat_integration_reference_post_spec.rb@@ -11,6 +11,51 @@ RSpec.describe DiscourseChatIntegration::ChatIntegrationReferencePost do}end+ describe "when no topic is provided" do+ subject(:post) do+ described_class.new(user: Discourse.system_user, kind: :workflow, raw: "A custom message")+ end++ it "provides standalone site context", :aggregate_failures do+ expect(post.id).to be_nil+ expect(post.user).to eq(Discourse.system_user)+ expect(post.topic.id).to be_nil+ expect(post.topic.title).to eq(SiteSetting.title)+ expect(post.topic.category).to be_nil+ expect(post.topic.tags).to be_empty+ expect(post.topic.posts).to be_empty+ expect(post.topic.custom_fields).to be_empty+ expect(post.full_url).to eq(Discourse.base_url)+ expect(post.excerpt).to eq("A custom message")+ expect(post).to be_is_first_post+ end++ it "can be formatted by every chat-integration provider" do+ messages = [+ DiscourseChatIntegration::Provider::SlackProvider.slack_message(post, "#alerts", ""),+ DiscourseChatIntegration::Provider::DiscordProvider.generate_discord_message(post),+ DiscourseChatIntegration::Provider::TelegramProvider.message_text(post),+ DiscourseChatIntegration::Provider::MattermostProvider.mattermost_message(post, "alerts"),+ DiscourseChatIntegration::Provider::MatrixProvider.generate_matrix_message(post),+ DiscourseChatIntegration::Provider::RocketchatProvider.rocketchat_message(post, "#alerts"),+ DiscourseChatIntegration::Provider::WebexProvider.get_message(post),+ DiscourseChatIntegration::Provider::GuildedProvider.generate_guilded_message(post),+ DiscourseChatIntegration::Provider::GroupmeProvider.generate_groupme_message(post),+ DiscourseChatIntegration::Provider::ZulipProvider.generate_zulip_message(+ post,+ "alerts",+ "subject",+ ),+ DiscourseChatIntegration::Provider::GitterProvider.gitter_message(post),+ DiscourseChatIntegration::Provider::GoogleProvider.get_message(post),+ DiscourseChatIntegration::Provider::TeamsProvider.get_message(post),+ DiscourseChatIntegration::Provider::PowerAutomateProvider.get_message(post),+ ]++ expect(messages).to all(be_present)+ end+ end+describe "when creating when topic tags change" dobefore docontext["kind"] = DiscourseAutomation::Triggers::TOPIC_TAGS_CHANGEDdiff --git a/plugins/discourse-chat-integration/spec/lib/discourse_chat_integration/provider/slack/slack_provider_spec.rb b/plugins/discourse-chat-integration/spec/lib/discourse_chat_integration/provider/slack/slack_provider_spec.rbindex c3174ac8c2d..3b01fc75d54 100644--- a/plugins/discourse-chat-integration/spec/lib/discourse_chat_integration/provider/slack/slack_provider_spec.rb+++ b/plugins/discourse-chat-integration/spec/lib/discourse_chat_integration/provider/slack/slack_provider_spec.rb@@ -187,6 +187,35 @@ RSpec.describe DiscourseChatIntegration::Provider::SlackProvider doexpect(@thread_stub).to have_been_requested.times(0)end+ it "sends a standalone message without storing topic thread metadata" do+ reference_post =+ DiscourseChatIntegration::ChatIntegrationReferencePost.new(+ user: Discourse.system_user,+ kind: :workflow,+ raw: "Custom alert",+ )++ expect { described_class.trigger_notification(reference_post, chan1, nil) }.not_to change(+ TopicCustomField,+ :count,+ )+ expect(@stub2).to have_been_requested.once+ end++ it "reports when the bot cannot post to the channel" do+ stub_request(:post, %r{https://slack.com/api/chat.postMessage}).to_return(+ body: { ok: false, error: "not_in_channel" }.to_json,+ )++ expect { described_class.trigger_notification(post, chan1, nil) }.to raise_error(+ DiscourseChatIntegration::ProviderError,+ ) do |error|+ expect(error.info[:error_key]).to eq(+ "chat_integration.provider.slack.errors.action_prohibited",+ )+ end+ end+it "sends thread id for thread" doexpect(@thread_stub).to have_been_requested.times(0)diff --git a/plugins/discourse-chat-integration/spec/lib/discourse_workflows/ai/tools/search_chat_integration_channels_spec.rb b/plugins/discourse-chat-integration/spec/lib/discourse_workflows/ai/tools/search_chat_integration_channels_spec.rbnew file mode 100644index 00000000000..ba312b497ad--- /dev/null+++ b/plugins/discourse-chat-integration/spec/lib/discourse_workflows/ai/tools/search_chat_integration_channels_spec.rb@@ -0,0 +1,47 @@+# frozen_string_literal: true++require_relative "../../../../dummy_provider"++RSpec.describe DiscourseWorkflows::Ai::Tools::SearchChatIntegrationChannels do+ include_context "with validated dummy provider"++ fab!(:admin)++ let(:channel) do+ DiscourseChatIntegration::Channel.create!(provider: "dummy2", data: { "val" => "#alerts" })+ end++ before do+ SiteSetting.enable_discourse_workflows = true+ SiteSetting.chat_integration_enabled = true+ SiteSetting.other_dummy_provider_enabled = true+ end++ def invoke_tool(query:)+ context = DiscourseAi::Agents::BotContext.new(messages: [], user: admin)+ described_class.new(+ { query: query },+ bot_user: Discourse.system_user,+ llm: nil,+ context: context,+ ).invoke+ end++ it "searches enabled external channels by provider or channel label" do+ channel # force creation before searching++ result = invoke_tool(query: "#aler")++ expect(result).to include(status: "success", query: "aler")+ expect(result[:matches]).to contain_exactly(+ { id: channel.id, name: "dummy2: #alerts", provider: "dummy2" },+ )+ end++ it "excludes channels for disabled providers" do+ channel # force creation before disabling the provider+ SiteSetting.other_dummy_provider_enabled = false++ expect(invoke_tool(query: "dummy2")[:matches]).to be_empty+ end+enddiff --git a/plugins/discourse-chat-integration/spec/lib/discourse_workflows/nodes/send_chat_integration_message_spec.rb b/plugins/discourse-chat-integration/spec/lib/discourse_workflows/nodes/send_chat_integration_message_spec.rbnew file mode 100644index 00000000000..f37b21b5aa9--- /dev/null+++ b/plugins/discourse-chat-integration/spec/lib/discourse_workflows/nodes/send_chat_integration_message_spec.rb@@ -0,0 +1,166 @@+# frozen_string_literal: true++require_relative "../../../dummy_provider"++RSpec.describe DiscourseWorkflows::Nodes::SendChatIntegrationMessage::V1 do+ include_context "with dummy provider"++ let(:channel) { DiscourseChatIntegration::Channel.create!(provider: "dummy") }++ before do+ SiteSetting.chat_integration_enabled = true+ SiteSetting.dummy_provider_enabled = true+ end++ def load_options(filter: nil)+ context =+ DiscourseWorkflows::LoadOptionsContext.new(+ method_name: "chat_integration_channels",+ filter: filter,+ node_class: described_class,+ )++ described_class.load_options_context(context)+ end++ describe ".load_options_context" do+ it "returns each channel labelled by its provider" do+ channel # force creation before loading options++ expect(load_options).to contain_exactly({ id: channel.id, name: "dummy: " })+ expect(load_options(filter: "missing")).to be_empty+ end++ it "excludes channels for disabled providers" do+ channel # force creation before disabling the provider+ SiteSetting.dummy_provider_enabled = false++ expect(load_options).to be_empty+ end+ end++ describe ".property_schema" do+ it "preserves the selected channel label for dynamic values", :aggregate_failures do+ schema = described_class.property_schema++ expect(schema.dig(:channel_id, :ui, :dynamic_value)).to eq(:chat_channel_id)+ expect(schema.dig(:channel_id, :control_options, :set_from_option)).to eq(+ channel_name: "name",+ )+ expect(schema.dig(:channel_id, :control_options)).to include(+ action_icon: "wrench",+ action_label: "discourse_workflows.send_chat_integration_message.configure",+ action_route: "adminPlugins.show.discourse-chat-integration-providers",+ action_route_models: ["discourse-chat-integration"],+ )+ expect(schema.dig(:channel_name, :ui, :hidden)).to eq(true)+ expect(schema).not_to have_key(:post_id)+ expect(schema.dig(:message, :required)).to eq(true)+ expect(+ described_class.output_contracts.first.dig(:schema, "properties").keys,+ ).to contain_exactly("channel_id", "provider")+ end+ end++ describe "#execute" do+ def execute_node(channel_id:, message: nil)+ parameters = { "channel_id" => channel_id.to_s }+ parameters["message"] = message if message+ resolver_context = { "$json" => {} }+ sandbox = DiscourseWorkflows::JsSandbox.new(resolver_context)+ resolver = DiscourseWorkflows::ExpressionResolver.new(resolver_context, sandbox: sandbox)+ exec_ctx =+ DiscourseWorkflows::Executor::NodeExecutionContext.new(+ input_items: [{ "json" => {} }],+ resolver: resolver,+ parameters: parameters,+ property_schema: described_class.property_schema,+ node_identifier: described_class.identifier,+ resolver_context: resolver_context,+ )++ described_class.new(parameters: parameters).execute(exec_ctx)+ ensure+ resolver&.dispose+ sandbox&.dispose+ end++ it "sends a standalone message", :aggregate_failures do+ target = nil+ allow(provider).to receive(:trigger_notification) do |post, sent_channel, rule|+ target = post+ expect(sent_channel).to eq(channel)+ expect(rule).to be_nil+ end++ output = execute_node(channel_id: channel.id, message: "Custom alert")+ result = output.first.first.fetch("json")++ expect(target).to be_an_instance_of(DiscourseChatIntegration::ChatIntegrationReferencePost)+ expect(target.user).to eq(Discourse.system_user)+ expect(target.topic.title).to eq(SiteSetting.title)+ expect(target.full_url).to eq(Discourse.base_url)+ expect(target.excerpt).to eq("Custom alert")+ expect(result).to eq("channel_id" => channel.id, "provider" => "dummy")+ expect(result).to match_node_output_schema(described_class)+ end++ it "raises when the message is not set" do+ expect { execute_node(channel_id: channel.id) }.to raise_error(+ DiscourseWorkflows::NodeError,+ include("A message is required"),+ )+ expect(provider.sent_messages).to be_empty+ end++ it "raises when the channel does not exist" do+ missing_id = channel.id + 1++ expect { execute_node(channel_id: missing_id, message: "Custom alert") }.to raise_error(+ include(missing_id.to_s),+ )+ expect(provider.sent_messages).to be_empty+ end++ it "raises when the provider is disabled" do+ SiteSetting.dummy_provider_enabled = false++ expect { execute_node(channel_id: channel.id, message: "Custom alert") }.to raise_error(+ include("dummy"),+ )+ expect(provider.sent_messages).to be_empty+ end++ it "reports translated provider errors" do+ provider.set_raise_exception(+ DiscourseChatIntegration::ProviderError.new(+ info: {+ error_key: "chat_integration.provider.slack.errors.action_prohibited",+ },+ ),+ )++ expect { execute_node(channel_id: channel.id, message: "Custom alert") }.to raise_error(+ DiscourseWorkflows::NodeError,+ include("The bot does not have permission to post to that channel"),+ )+ end++ it "reports safe API error codes when no translation is available" do+ provider.set_raise_exception(+ DiscourseChatIntegration::ProviderError.new(+ info: {+ response_body: {+ error: "account_inactive",+ },+ },+ ),+ )++ expect { execute_node(channel_id: channel.id, message: "Custom alert") }.to raise_error(+ DiscourseWorkflows::NodeError,+ include("Account inactive"),+ )+ end+ end+enddiff --git a/plugins/discourse-workflows/app/jobs/regular/discourse_workflows/author_with_ai.rb b/plugins/discourse-workflows/app/jobs/regular/discourse_workflows/author_with_ai.rbindex 074d689bae0..c5ef468eaff 100644--- a/plugins/discourse-workflows/app/jobs/regular/discourse_workflows/author_with_ai.rb+++ b/plugins/discourse-workflows/app/jobs/regular/discourse_workflows/author_with_ai.rb@@ -129,6 +129,11 @@ module Jobs:search_chat_channels] = "Call this before asking the admin to choose a chat channel or before setting action:send_chat_message channel_id. Use returned matches; never invent channel names or IDs."end+ if ::DiscourseWorkflows::Ai::Tools::SearchChatIntegrationChannels.available?+ context_tools[+ :search_chat_integration_channels+ ] = "Call this before asking the admin to choose an external chat integration channel or before setting action:send_chat_integration_message channel_id. Use returned matches; never invent provider names, channel labels, or IDs."+ endpayload = {workflow: workflow_summary,diff --git a/plugins/discourse-workflows/config/locales/server.en.yml b/plugins/discourse-workflows/config/locales/server.en.ymlindex 0c4f928a4e8..c8421f8fe88 100644--- a/plugins/discourse-workflows/config/locales/server.en.yml+++ b/plugins/discourse-workflows/config/locales/server.en.yml@@ -192,6 +192,7 @@ en:workflow_authoring_result: "Returns the final workflow authoring result"workflow_resolve_entity: "Resolves Discourse names to workflow parameter values"search_chat_channels: "Searches chat channel names and IDs for workflow parameters"+ search_chat_integration_channels: "Searches external chat integration channel labels and IDs for workflow parameters"workflow_script_context: "Returns context for writing workflow Code node JavaScript"workflow_validate_script: "Validates workflow Code node JavaScript"tool_summary:@@ -203,6 +204,7 @@ en:workflow_authoring_result: "Returning workflow authoring result"workflow_resolve_entity: "Resolving Discourse entities"search_chat_channels: "Searching chat channels"+ search_chat_integration_channels: "Searching external chat integration channels"workflow_script_context: "Loading script context"workflow_validate_script: "Validating script"tool_description:@@ -214,5 +216,6 @@ en:workflow_authoring_result: "Returned workflow authoring result"workflow_resolve_entity: "Resolved Discourse entities"search_chat_channels: "Searched chat channels"+ search_chat_integration_channels: "Searched external chat integration channels"workflow_script_context: "Loaded script context"workflow_validate_script: "Validated script"diff --git a/plugins/discourse-workflows/lib/discourse_workflows/ai/tools/search_chat_integration_channels.rb b/plugins/discourse-workflows/lib/discourse_workflows/ai/tools/search_chat_integration_channels.rbnew file mode 100644index 00000000000..a4a86e4e6f8--- /dev/null+++ b/plugins/discourse-workflows/lib/discourse_workflows/ai/tools/search_chat_integration_channels.rb@@ -0,0 +1,67 @@+# frozen_string_literal: true++module DiscourseWorkflows+ module Ai+ module Tools+ class SearchChatIntegrationChannels < Base+ MAX_RESULTS = 20++ def self.signature+ {+ name: name,+ description:+ "Searches configured external chat integration channels and returns provider names, channel labels, and IDs for workflow parameters.",+ parameters: [+ {+ name: "query",+ description: "Partial provider or channel name to search for",+ type: "string",+ required: false,+ },+ ],+ }+ end++ def self.name+ "search_chat_integration_channels"+ end++ def self.available?+ defined?(DiscourseWorkflows::Nodes::ChatIntegrationChannelSelection) &&+ defined?(SiteSetting.chat_integration_enabled) && SiteSetting.chat_integration_enabled+ end++ def invoke+ return not_allowed_response if !ensure_can_manage_workflows!+ return error_response("Chat integration is not enabled") if !self.class.available?++ query = normalize_query(parameters[:query])++ { status: "success", query: query, matches: channels_matching(query) }+ end++ private++ def channels_matching(query)+ selection = DiscourseWorkflows::Nodes::ChatIntegrationChannelSelection+ matches =+ selection.selectable_channels.map do |channel|+ { id: channel.id, name: selection.channel_label(channel), provider: channel.provider }+ end++ if query.present?+ matches.select! do |match|+ [match[:name], match[:provider]].any? { |value| value.downcase.include?(query) }+ end+ end++ matches.sort_by { |match| match[:name].downcase }.first(MAX_RESULTS)+ end++ def normalize_query(query)+ query.to_s.strip.delete_prefix("#").strip.downcase+ end+ end+ end+ end+enddiff --git a/plugins/discourse-workflows/lib/discourse_workflows/ai/tools/workflow_node_catalog.rb b/plugins/discourse-workflows/lib/discourse_workflows/ai/tools/workflow_node_catalog.rbindex de65f16039c..d1ccd74f58f 100644--- a/plugins/discourse-workflows/lib/discourse_workflows/ai/tools/workflow_node_catalog.rb+++ b/plugins/discourse-workflows/lib/discourse_workflows/ai/tools/workflow_node_catalog.rb@@ -151,6 +151,16 @@ module DiscourseWorkflows},},],+ "action:send_chat_integration_message" => [+ {+ name: "Send a message to an external chat integration channel",+ parameters: {+ channel_id: 123,+ channel_name: "Slack: #general",+ message: "={{ $json.post.excerpt }}",+ },+ },+ ],"action:ai_agent" => [{name: "Classify the trigger post with an existing agent",@@ -200,6 +210,8 @@ module DiscourseWorkflowsSEARCH_ALIASES = {"action:send_personal_message" => "dm direct message pm personal private message",+ "action:send_chat_integration_message" =>+ "external chat integration notification slack discord telegram mattermost matrix zulip rocket chat gitter groupme teams power automate webex google chat guilded","action:ai_agent" =>"ai agent bot llm classify summarize generate sentiment triage runner run as permissions uploads attachments","action:group" => "group membership member belongs friend friends",diff --git a/plugins/discourse-workflows/lib/discourse_workflows/ai_workflow_author.rb b/plugins/discourse-workflows/lib/discourse_workflows/ai_workflow_author.rbindex 6bb879f7d5f..ea00f43e20d 100644--- a/plugins/discourse-workflows/lib/discourse_workflows/ai_workflow_author.rb+++ b/plugins/discourse-workflows/lib/discourse_workflows/ai_workflow_author.rb@@ -26,6 +26,7 @@ module DiscourseWorkflowsDiscourseWorkflows::Ai::Tools::WorkflowValidateScript,*discovery_tools,*chat_tools,+ *chat_integration_tools,]end@@ -58,6 +59,7 @@ module DiscourseWorkflows- When proposing a new AI agent, include a create_ai_agent operation before the action:ai_agent node that uses it. Reference the proposed agent with agent_id: { "$ref": "agent-client-id" } and set agent_name to the proposed agent name.- Include created AI agents in proposal assumptions or risks so admins know the draft creates a reusable agent record.- Use search_chat_channels before asking the admin to choose a chat channel or before setting action:send_chat_message channel_id. Never invent chat channel names, IDs, or clarification options. If search_chat_channels returns matches, ask using those exact channel names/IDs or use the named match. If it returns no matches, ask for a custom channel name/ID instead of suggesting made-up channels.+ - Use search_chat_integration_channels before asking the admin to choose an external chat integration channel or before setting action:send_chat_integration_message channel_id. Never invent provider names, channel labels, IDs, or clarification options. If search_chat_integration_channels returns matches, set channel_id and channel_name from the exact match or ask using those exact values. If it returns no matches, explain that a matching channel must be configured instead of suggesting made-up channels.- Use workflow_validate_patch as a dry-run planning tool when drafting workflow changes. It does not save anything. For non-trivial workflows, query relevant node types with workflow_node_catalog, then call workflow_validate_patch after adding or connecting candidate nodes to inspect node_fields for exact input/output paths, then continue from those fields.- If workflow_validate_patch returns expression_errors or schema-path errors, repair the operations and call workflow_validate_patch again before returning a final proposal.- Action nodes may replace the current item JSON. Always use the downstream node's input_fields from workflow_validate_patch rather than assuming trigger fields are still available after an action node.@@ -119,5 +121,13 @@ module DiscourseWorkflows[]endend++ def chat_integration_tools+ if DiscourseWorkflows::Ai::Tools::SearchChatIntegrationChannels.available?+ [DiscourseWorkflows::Ai::Tools::SearchChatIntegrationChannels]+ else+ []+ end+ endendenddiff --git a/plugins/discourse-workflows/plugin.rb b/plugins/discourse-workflows/plugin.rbindex dbc8c5cdc8e..69524404f7a 100644--- a/plugins/discourse-workflows/plugin.rb+++ b/plugins/discourse-workflows/plugin.rb@@ -105,6 +105,7 @@ after_initialize dorequire_relative "lib/discourse_workflows/ai/tools/workflow_ask_questions"require_relative "lib/discourse_workflows/ai/tools/workflow_resolve_entity"require_relative "lib/discourse_workflows/ai/tools/search_chat_channels"+ require_relative "lib/discourse_workflows/ai/tools/search_chat_integration_channels"require_relative "lib/discourse_workflows/ai/tools/workflow_script_context"require_relative "lib/discourse_workflows/ai/tools/workflow_validate_script"require_relative "lib/discourse_workflows/ai_workflow_author"diff --git a/plugins/discourse-workflows/spec/jobs/regular/discourse_workflows/author_with_ai_spec.rb b/plugins/discourse-workflows/spec/jobs/regular/discourse_workflows/author_with_ai_spec.rbindex 033804c5ec0..7afd8ad69e5 100644--- a/plugins/discourse-workflows/spec/jobs/regular/discourse_workflows/author_with_ai_spec.rb+++ b/plugins/discourse-workflows/spec/jobs/regular/discourse_workflows/author_with_ai_spec.rb@@ -133,6 +133,9 @@ RSpec.describe Jobs::DiscourseWorkflows::AuthorWithAi doallow(DiscourseWorkflows::Ai::Tools::SearchChatChannels).to receive(:available?).and_return(true,)+ allow(DiscourseWorkflows::Ai::Tools::SearchChatIntegrationChannels).to receive(+ :available?,+ ).and_return(true)described_class.new.execute(session_id: session.id,@@ -154,6 +157,9 @@ RSpec.describe Jobs::DiscourseWorkflows::AuthorWithAi doexpect(payload.dig("context_tools", "workflow_node_catalog")).to include("node parameters")expect(payload.dig("context_tools", "workflow_graph_context")).to include("current graph")expect(payload.dig("context_tools", "search_chat_channels")).to include("never invent")+ expect(payload.dig("context_tools", "search_chat_integration_channels")).to include(+ "never invent",+ )expect(payload.dig("context_tools", "workflow_validate_script")).to include("exact Code node")expect(payload.dig("context_tools", "workflow_authoring_result")).to include("final response")expect(payload["trigger_author_field_facts"]).to include(diff --git a/plugins/discourse-workflows/spec/lib/discourse_workflows/ai/tools/workflow_node_catalog_spec.rb b/plugins/discourse-workflows/spec/lib/discourse_workflows/ai/tools/workflow_node_catalog_spec.rbindex 9aff4996df4..07ea3051e34 100644--- a/plugins/discourse-workflows/spec/lib/discourse_workflows/ai/tools/workflow_node_catalog_spec.rb+++ b/plugins/discourse-workflows/spec/lib/discourse_workflows/ai/tools/workflow_node_catalog_spec.rb@@ -23,6 +23,32 @@ RSpec.describe DiscourseWorkflows::Ai::Tools::WorkflowNodeCatalog dooutput_contract(nodes_by_type, type, output_index).fetch(:fields)end+ it "finds the external chat integration action by provider keywords" do+ SiteSetting.chat_integration_enabled = true++ result = invoke_tool(query: "slack", include_examples: true)+ node =+ result[:nodes].find { |candidate| candidate[:type] == "action:send_chat_integration_message" }++ expect(node).to include(+ available: true,+ examples: [+ a_hash_including(+ parameters:+ a_hash_including(+ channel_id: 123,+ channel_name: "Slack: #general",+ message: "={{ $json.post.excerpt }}",+ ),+ ),+ ],+ )+ expect(node.dig(:output_contracts, 0, :fields)).to eq(+ "channel_id" => "integer",+ "provider" => "string",+ )+ end+it "exposes post author, topic link, and action output fields", :aggregate_failures doresult = invoke_toolnodes_by_type = result[:nodes].index_by { |node| node[:type] }diff --git a/plugins/discourse-workflows/spec/lib/discourse_workflows/ai_workflow_author_spec.rb b/plugins/discourse-workflows/spec/lib/discourse_workflows/ai_workflow_author_spec.rbindex d2165735211..ae3e25e5bcf 100644--- a/plugins/discourse-workflows/spec/lib/discourse_workflows/ai_workflow_author_spec.rb+++ b/plugins/discourse-workflows/spec/lib/discourse_workflows/ai_workflow_author_spec.rb@@ -31,6 +31,7 @@ RSpec.describe DiscourseWorkflows::AiWorkflowAuthor do"parameters.runner_username","parameters.upload_ids","Use search_chat_channels before asking the admin to choose a chat channel",+ "Use search_chat_integration_channels before asking the admin to choose an external chat integration channel","call workflow_validate_script with the exact mode and code","Do not add a Code node only to copy trigger fields forward","create_ai_agent",@@ -48,4 +49,18 @@ RSpec.describe DiscourseWorkflows::AiWorkflowAuthor doSiteSetting.chat_enabled = trueexpect(described_class.new.tools).to include(DiscourseWorkflows::Ai::Tools::SearchChatChannels)end++ it "includes external chat integration channel search only when the integration is enabled" do+ skip "Chat Integration plugin is not available" if !defined?(DiscourseChatIntegration::Channel)++ SiteSetting.chat_integration_enabled = false+ expect(described_class.new.tools).not_to include(+ DiscourseWorkflows::Ai::Tools::SearchChatIntegrationChannels,+ )++ SiteSetting.chat_integration_enabled = true+ expect(described_class.new.tools).to include(+ DiscourseWorkflows::Ai::Tools::SearchChatIntegrationChannels,+ )+ endend