A platform for community discussion. Free, open, simple.
FEATURE: Let workflows choose the sender of chat channel messages (#44927)
Rafael dos Santos Silva3e5b9f59fb7f
diff --git a/plugins/chat/config/locales/client.en.yml b/plugins/chat/config/locales/client.en.ymlindex 5f06fca930a..ffe1963cce3 100644--- a/plugins/chat/config/locales/client.en.yml+++ b/plugins/chat/config/locales/client.en.yml@@ -956,7 +956,7 @@ en:target_usernames_description: "Users to message. Use an expression such as $trigger.user.username to pick them from each item."message: "Message"actor_username: "Sender"- actor_username_description: "Direct messages are sent as this user, and recipients see them as written by them."+ actor_username_description: "Messages are sent as this user, and everyone sees them as written by them. When posting to a channel, the user must be a member of it."chat_approval:message: "Message"buttons: "Buttons"diff --git a/plugins/chat/config/locales/server.en.yml b/plugins/chat/config/locales/server.en.ymlindex 3c40ed27bea..e9ac6b54099 100644--- a/plugins/chat/config/locales/server.en.yml+++ b/plugins/chat/config/locales/server.en.yml@@ -286,11 +286,13 @@ en:recipient_inactive: "'%{username}' hasn't activated their account yet."recipient_chat_disabled: "'%{username}' has disabled chat in their preferences."recipient_cannot_chat: "'%{username}' can't use chat because they aren't in a group allowed by the 'chat allowed groups' setting."- sender_anonymous: "Direct messages can't be sent anonymously. Choose a user as the sender."+ sender_anonymous: "Chat messages can't be sent anonymously. Choose a user as the sender."sender_chat_disabled: "Sender '%{sender}' has disabled chat in their preferences."sender_cannot_chat: "Sender '%{sender}' can't use chat because they aren't in a group allowed by the 'chat allowed groups' setting."sender_cannot_create_dm: "Sender '%{sender}' isn't allowed to send direct messages (see the 'direct message enabled groups' setting)."sender_dms_disabled: "Sender '%{sender}' has disabled personal messages in their preferences."+ sender_cannot_post: "Sender '%{sender}' isn't allowed to post in channel %{channel_id}."+ sender_not_member: "Sender '%{sender}' isn't a member of channel %{channel_id}. Join the channel as that user first."user_blocked: "'%{sender}' can't send a direct message to '%{username}': %{reason}"group_blocked: "'%{sender}' can't send a group direct message to %{usernames}: %{reason}"chat_approval:@@ -314,7 +316,7 @@ en:preferences_bypassed: "'%{username}' doesn't accept direct messages from '%{sender}', but the message was delivered because the sender is staff."logs:send_chat_message:- sent_to_channel: "Item %{item_index}: sent message %{message_id} to channel %{channel_id}."+ sent_to_channel: "Item %{item_index}: '%{sender}' sent message %{message_id} to channel %{channel_id}."sent_to_user: "Item %{item_index}: '%{sender}' sent message %{message_id} to '%{username}'."sent_to_group: "Item %{item_index}: '%{sender}' sent message %{message_id} to the group direct message with %{usernames}."diff --git a/plugins/chat/lib/discourse_workflows/nodes/send_chat_message/v1.rb b/plugins/chat/lib/discourse_workflows/nodes/send_chat_message/v1.rbindex 70738306197..6dd8eb9f103 100644--- a/plugins/chat/lib/discourse_workflows/nodes/send_chat_message/v1.rb+++ b/plugins/chat/lib/discourse_workflows/nodes/send_chat_message/v1.rb@@ -117,14 +117,7 @@ if defined?(DiscourseWorkflows)control: :textarea,},},- **actor_property(- allow_anonymous: false,- display_options: {- show: {- target: DM_TARGETS,- },- },- ),+ **actor_property(allow_anonymous: false),},)@@ -146,10 +139,11 @@ if defined?(DiscourseWorkflows)message: exec_ctx.get_node_parameter("message", item_index),)target = run.parameter("target", default: "channel")+ sender = resolve_sender!(run)if DM_TARGETS.include?(target)- send_direct_messages(run, group: target == "group")+ send_direct_messages(run, sender, group: target == "group")else- send_to_channel(run)+ send_to_channel(run, sender)endend[items]@@ -157,28 +151,33 @@ if defined?(DiscourseWorkflows)private- def send_to_channel(run)+ def resolve_sender!(run)+ sender = run.exec_ctx.actor_from_parameter("actor_username", run.item_index)+ # `allow_anonymous: false` only hides the option in the UI.+ node_error!(run, :sender_anonymous) if sender.is_a?(DiscourseWorkflows::AnonymousActor)+ sender+ end++ def send_to_channel(run, sender)channel_id = run.parameter("channel_id")channel = selectable_chat_channel(channel_id)node_error!(run, :channel_not_found, channel_id:) if channel.blank?+ ensure_sender_can_chat!(run, sender)wrap(create_message(run,:channel,- Discourse.system_user.guardian,+ sender.guardian,channel,+ sender: sender.username,channel_id: channel.id,),)end- def send_direct_messages(run, group:)- sender = run.exec_ctx.actor_from_parameter("actor_username", run.item_index)- # `allow_anonymous: false` only hides the option in the UI.- node_error!(run, :sender_anonymous) if sender.is_a?(DiscourseWorkflows::AnonymousActor)-+ def send_direct_messages(run, sender, group:)# Account states are checked for every recipient before anything is sent.recipients = resolve_recipients!(run)ensure_sender_can_chat!(run, sender)@@ -360,6 +359,23 @@ if defined?(DiscourseWorkflows)}endon_failed_contract { |contract| invalid_params!(run, contract) }+ on_failed_policy(:can_post_in_channel) do+ node_error!(+ run,+ :sender_cannot_post,+ sender: guardian.user.username,+ channel_id: channel.id,+ )+ end+ # Bots are added to the channel by the service, people have to join it themselves.+ on_model_not_found(:membership) do+ node_error!(+ run,+ :sender_not_member,+ sender: guardian.user.username,+ channel_id: channel.id,+ )+ endon_model_errors(:message_instance) do |message_instance|invalid_params!(run, message_instance)enddiff --git a/plugins/chat/spec/lib/discourse_workflows/nodes/send_chat_message_spec.rb b/plugins/chat/spec/lib/discourse_workflows/nodes/send_chat_message_spec.rbindex 3cbacf8e44a..4a386bea56f 100644--- a/plugins/chat/spec/lib/discourse_workflows/nodes/send_chat_message_spec.rb+++ b/plugins/chat/spec/lib/discourse_workflows/nodes/send_chat_message_spec.rb@@ -104,10 +104,17 @@ RSpec.describe DiscourseWorkflows::Nodes::SendChatMessage::V1 do],)expect([first, second].map(&:message)).to eq(["First message", "Second message"])+ expect([first, second].map(&:user_id)).to all(eq(Discourse.system_user.id))expect(log).to eq([- sent_log(:channel, first, channel_id: channel.id),- sent_log(:channel, second, item_index: 1, channel_id: channel.id),+ sent_log(:channel, first, sender: Discourse.system_user.username, channel_id: channel.id),+ sent_log(+ :channel,+ second,+ item_index: 1,+ sender: Discourse.system_user.username,+ channel_id: channel.id,+ ),],)end@@ -170,6 +177,78 @@ RSpec.describe DiscourseWorkflows::Nodes::SendChatMessage::V1 doendend+ describe "#execute with a channel sender" do+ fab!(:sender) { Fabricate(:user, username: "alice", refresh_auto_groups: true) }++ def send_to_channel(**parameters, &block)+ execute_node_output(+ configuration: {+ "channel_id" => channel.id.to_s,+ "message" => "Hello channel",+ "actor_username" => sender.username,+ }.merge(parameters.stringify_keys),+ &block+ )+ end++ it "posts the message as the sender when they are a member of the channel" do+ channel.add(sender)+ log = nil++ output = send_to_channel { |ctx| log = log_messages(ctx) }++ message = channel.chat_messages.sole+ expect(output.first.sole["json"]).to eq(+ "channel_id" => channel.id,+ "message_id" => message.id,+ "message" => "Hello channel",+ )+ expect(message.user_id).to eq(sender.id)+ expect(log).to eq(+ [sent_log(:channel, message, sender: sender.username, channel_id: channel.id)],+ )+ end++ it "fails without joining the channel when the sender is not a member" do+ expect {+ expect { send_to_channel }.to raise_error(+ DiscourseWorkflows::NodeError,+ node_error(:sender_not_member, sender: sender.username, channel_id: channel.id),+ )+ }.not_to change { channel.user_chat_channel_memberships.count }+ expect(channel.chat_messages).to be_empty+ end++ it "fails when the sender can't post in the channel's category" do+ group = Fabricate(:group)+ channel.chatable.set_permissions(group => :full)+ channel.chatable.save!+ channel.add(sender)++ expect { send_to_channel }.to raise_error(+ DiscourseWorkflows::NodeError,+ node_error(:sender_cannot_post, sender: sender.username, channel_id: channel.id),+ )+ expect(channel.chat_messages).to be_empty+ end++ it "fails when the sender disabled chat" do+ channel.add(sender)+ sender.user_option.update!(chat_enabled: false)++ expect { send_to_channel }.to raise_error(+ DiscourseWorkflows::NodeError,+ node_error(:sender_chat_disabled, sender: sender.username),+ )+ end++ it "fails when the sender is anonymous" do+ expect {+ send_to_channel(actor_username: DiscourseWorkflows::AnonymousActor::USERNAME)+ }.to raise_error(DiscourseWorkflows::NodeError, node_error(:sender_anonymous))+ end+ end+describe "#execute with a failing item" dolet(:configuration) do{ "channel_id" => "={{ $json.channel_id }}", "message" => "={{ $json.text }}" }diff --git a/plugins/discourse-workflows/lib/discourse_workflows/ai_workflow_author.rb b/plugins/discourse-workflows/lib/discourse_workflows/ai_workflow_author.rbindex cd62a23f40a..f8f5deebcd1 100644--- a/plugins/discourse-workflows/lib/discourse_workflows/ai_workflow_author.rb+++ b/plugins/discourse-workflows/lib/discourse_workflows/ai_workflow_author.rb@@ -57,8 +57,9 @@ 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.- action:send_chat_message posts to a chat channel (target "channel", the default), sends each listed user their own chat direct message (target "user"), or sends one group chat direct message to all of them (target "group"). Use target "user" or "group" only when the admin asks for a chat DM; a plain DM or personal message to a user means action:send_personal_message.- - With action:send_chat_message target "user" or "group", set target_usernames to an array of usernames or an expression such as ={{ $json.user.username }}, and actor_username to the sender (defaults to system). Do not call search_chat_channels or set channel_id in this mode. The recipient must already be able to chat: users from trigger:user_created are usually still inactive and at trust level 0, so welcome new signups with action:send_personal_message instead.+ - With action:send_chat_message target "user" or "group", set target_usernames to an array of usernames or an expression such as ={{ $json.user.username }}. Do not call search_chat_channels or set channel_id in this mode. The recipient must already be able to chat: users from trigger:user_created are usually still inactive and at trust level 0, so welcome new signups with action:send_personal_message instead.- With action:send_chat_message target "channel", use search_chat_channels before asking the admin to choose a chat channel or before setting 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.+ - With action:send_chat_message, set actor_username to the sender for any target (defaults to system). A channel sender other than system must already be a member of the channel.- 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, look up the 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.