Skip to content

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

FEATURE: chat approval node v2, custom buttons (#42587)

Joffrey JAFFEUXa5e9a50c75e1
diff --git a/plugins/chat/app/jobs/regular/chat/resume_workflow_approval_interaction.rb b/plugins/chat/app/jobs/regular/chat/resume_workflow_approval_interaction.rb
new file mode 100644
index 00000000000..273e9cbb44a
--- /dev/null
+++ b/plugins/chat/app/jobs/regular/chat/resume_workflow_approval_interaction.rb
@@ -0,0 +1,15 @@
+# frozen_string_literal: true
+
+module Jobs
+ module Chat
+ class ResumeWorkflowApprovalInteraction < ::Jobs::Base
+ def execute(args)
+ ::Chat::Workflows::Approval::ResumeInteraction.call(
+ params: {
+ interaction_id: args[:interaction_id],
+ },
+ )
+ end
+ end
+ end
+end
diff --git a/plugins/chat/app/serializers/chat/workflow_channel_serializer.rb b/plugins/chat/app/serializers/chat/workflow_channel_serializer.rb
new file mode 100644
index 00000000000..1ab1ff135d0
--- /dev/null
+++ b/plugins/chat/app/serializers/chat/workflow_channel_serializer.rb
@@ -0,0 +1,29 @@
+# frozen_string_literal: true
+
+module Chat
+ class WorkflowChannelSerializer < ApplicationSerializer
+ PROPERTIES = {
+ "id" => {
+ "type" => "integer",
+ },
+ "title" => {
+ "type" => "string",
+ },
+ "slug" => {
+ "type" => "string",
+ },
+ "chatable_type" => {
+ "type" => "string",
+ },
+ "chatable_id" => {
+ "type" => "integer",
+ },
+ }.freeze
+
+ attributes(*PROPERTIES.keys.map(&:to_sym))
+
+ def title
+ object.title(scope.user)
+ end
+ end
+end
diff --git a/plugins/chat/app/services/chat/workflows/approval/resume.rb b/plugins/chat/app/services/chat/workflows/approval/resume.rb
index 63cc795852a..c5485c1f857 100644
--- a/plugins/chat/app/services/chat/workflows/approval/resume.rb
+++ b/plugins/chat/app/services/chat/workflows/approval/resume.rb
@@ -30,7 +30,7 @@ module Chat
::DiscourseWorkflows::InteractiveResume.from_action_id(
params.action_id,
expected_node_type: "action:chat_approval",
- allowed_actions: %w[approve deny],
+ allowed_actions: ::DiscourseWorkflows::Nodes::ChatApproval::V1::ACTION_IDS,
)
end
diff --git a/plugins/chat/app/services/chat/workflows/approval/resume_interaction.rb b/plugins/chat/app/services/chat/workflows/approval/resume_interaction.rb
new file mode 100644
index 00000000000..1b9b3a8bfb0
--- /dev/null
+++ b/plugins/chat/app/services/chat/workflows/approval/resume_interaction.rb
@@ -0,0 +1,51 @@
+# frozen_string_literal: true
+
+module Chat
+ module Workflows
+ module Approval
+ class ResumeInteraction
+ include Service::Base
+
+ params do
+ attribute :interaction_id, :integer
+
+ validates :interaction_id, presence: true
+ end
+
+ policy :workflows_enabled
+
+ model :interaction
+ model :resolved_interaction
+ model :claimed_resume_request
+ step :resume_execution
+
+ private
+
+ def workflows_enabled
+ SiteSetting.enable_discourse_workflows
+ end
+
+ def fetch_interaction(params:)
+ Chat::MessageInteraction.includes(:user, message: :chat_channel).find_by(
+ id: params.interaction_id,
+ )
+ end
+
+ def fetch_resolved_interaction(interaction:)
+ Chat::Workflows::Approval::InteractionResolver.call(interaction)
+ end
+
+ def fetch_claimed_resume_request(resolved_interaction:)
+ resolved_interaction.resume_request.claim
+ end
+
+ def resume_execution(claimed_resume_request:, resolved_interaction:)
+ claimed_resume_request.resume!(
+ resolved_interaction.response_items,
+ user: resolved_interaction.user,
+ )
+ end
+ end
+ end
+ end
+end
diff --git a/plugins/chat/config/locales/client.en.yml b/plugins/chat/config/locales/client.en.yml
index 12ae2c6d2e7..d3b2e4430af 100644
--- a/plugins/chat/config/locales/client.en.yml
+++ b/plugins/chat/config/locales/client.en.yml
@@ -907,6 +907,15 @@ en:
message: "Message"
chat_approval:
message: "Message"
+ buttons: "Buttons"
+ buttons_description: "Add between one and ten response buttons."
+ add_button: "Add button"
+ label: "Label"
+ label_description: "The text shown on the button."
+ label_placeholder: "Button label"
+ value: "Value"
+ value_description: "The value returned by the workflow when this button is clicked."
+ value_placeholder: "Returned value"
approve_label: "Approve button label"
approve_label_description: "Defaults to \"Approve\" if left blank."
deny_label: "Deny button label"
@@ -917,5 +926,6 @@ en:
timeout_minutes_description: "Leave blank for no timeout."
timeout_action: "On timeout"
timeout_action_description: "What happens when the approval times out."
+ timeout_action_continue: "Continue the workflow"
timeout_action_deny: "Resume as denied"
timeout_action_fail: "Fail the workflow"
diff --git a/plugins/chat/config/locales/server.en.yml b/plugins/chat/config/locales/server.en.yml
index 35b37fca969..dfabf42f4c3 100644
--- a/plugins/chat/config/locales/server.en.yml
+++ b/plugins/chat/config/locales/server.en.yml
@@ -262,6 +262,13 @@ en:
invalid_params: "Chat message failed: %{errors}"
failed: "Chat message failed: %{steps}"
timeout_must_be_positive: "Timeout minutes must be greater than 0."
+ invalid_timeout_action: "Invalid timeout action: %{action}."
+ buttons_required: "At least one chat approval button is required."
+ too_many_buttons: "Chat approval supports at most %{max} buttons."
+ button_label_required: "Chat approval button %{position} requires a label."
+ button_label_too_long: "Chat approval button %{position} label must be %{max} characters or fewer."
+ button_value_required: "Chat approval button %{position} requires a value."
+ button_value_too_long: "Chat approval button %{position} value must be %{max} characters or fewer."
reviewable_score_types:
needs_review:
diff --git a/plugins/chat/lib/chat/workflows/approval/interaction_resolver.rb b/plugins/chat/lib/chat/workflows/approval/interaction_resolver.rb
new file mode 100644
index 00000000000..7c1760f9753
--- /dev/null
+++ b/plugins/chat/lib/chat/workflows/approval/interaction_resolver.rb
@@ -0,0 +1,60 @@
+# frozen_string_literal: true
+
+module Chat
+ module Workflows
+ module Approval
+ class InteractionResolver
+ Result = Data.define(:resume_request, :response_items, :user)
+
+ NODE_TYPE = "action:chat_approval"
+ SUPPORTED_VERSION = "2.0"
+
+ def self.call(interaction)
+ return unless interaction.action.is_a?(Hash)
+ return if interaction.user.blank? || interaction.message.blank?
+ return if interaction.message.chat_channel.blank?
+
+ action_id = interaction.action["action_id"].to_s
+ payload = DiscourseWorkflows::InteractiveResume.action_payload(action_id)
+ return if payload.blank?
+
+ execution =
+ DiscourseWorkflows::Execution.find_by(id: payload["execution_id"], status: :waiting)
+ return if execution.blank?
+
+ waiting_node = execution.find_waiting_node
+ return if waiting_node.blank?
+ return if DiscourseWorkflows::NodeData.read(waiting_node, "type") != NODE_TYPE
+
+ type_version = DiscourseWorkflows::NodeData.type_version(waiting_node)
+ return unless type_version == SUPPORTED_VERSION
+
+ node_class = DiscourseWorkflows::Registry.find_node_type(NODE_TYPE, version: type_version)
+ return if node_class.blank?
+
+ parameters = DiscourseWorkflows::NodeData.parameters(waiting_node).deep_stringify_keys
+ resume_request =
+ DiscourseWorkflows::InteractiveResume.from_action_id(
+ action_id,
+ expected_node_type: NODE_TYPE,
+ allowed_actions: node_class.allowed_actions(parameters),
+ )
+ return if resume_request.blank?
+ unless node_class.valid_interaction?(
+ interaction,
+ action: resume_request.action,
+ parameters:,
+ )
+ return
+ end
+
+ Result.new(
+ resume_request,
+ node_class.response_items(action: resume_request.action, interaction:),
+ node_class.resume_user(interaction),
+ )
+ end
+ end
+ end
+ end
+end
diff --git a/plugins/chat/lib/discourse_workflows/nodes/chat_approval/v1.rb b/plugins/chat/lib/discourse_workflows/nodes/chat_approval/v1.rb
index c0576976182..5e384dcbfe3 100644
--- a/plugins/chat/lib/discourse_workflows/nodes/chat_approval/v1.rb
+++ b/plugins/chat/lib/discourse_workflows/nodes/chat_approval/v1.rb
@@ -7,6 +7,8 @@ if defined?(DiscourseWorkflows)
class V1 < DiscourseWorkflows::NodeType
include ChatChannelSelection
+ ACTION_IDS = %w[approve deny].freeze
+
APPROVAL_OUTPUT_SCHEMA = {
"$schema" => DiscourseWorkflows::Schema::DRAFT_URI,
"type" => "object",
diff --git a/plugins/chat/lib/discourse_workflows/nodes/chat_approval/v2.rb b/plugins/chat/lib/discourse_workflows/nodes/chat_approval/v2.rb
new file mode 100644
index 00000000000..46a6c1fd9ff
--- /dev/null
+++ b/plugins/chat/lib/discourse_workflows/nodes/chat_approval/v2.rb
@@ -0,0 +1,343 @@
+# frozen_string_literal: true
+
+if defined?(DiscourseWorkflows)
+ module DiscourseWorkflows
+ module Nodes
+ module ChatApproval
+ class V2 < V1
+ MAX_BUTTONS = 10
+ MAX_LABEL_LENGTH = 75
+ MAX_VALUE_LENGTH = 2000
+ TIMEOUT_ACTIONS = %w[continue fail].freeze
+ ACTION_IDS = Array.new(MAX_BUTTONS) { |index| "button_#{index}" }.freeze
+
+ CLICK_OUTPUT_SCHEMA = {
+ "$schema" => DiscourseWorkflows::Schema::DRAFT_URI,
+ "type" => "object",
+ "properties" => {
+ "value" => {
+ "type" => "string",
+ },
+ "channel" => {
+ "type" => "object",
+ "properties" => Chat::WorkflowChannelSerializer::PROPERTIES,
+ },
+ "user" => {
+ "type" => "object",
+ "properties" => DiscourseWorkflows::Schema::BASIC_USER_PROPERTIES,
+ },
+ },
+ }.freeze
+
+ description(
+ name: "action:chat_approval",
+ version: "2.0",
+ defaults: {
+ icon: "comments",
+ color: "cyan",
+ },
+ group: "human_review",
+ available: -> { SiteSetting.chat_enabled },
+ unavailable_reason_key: "discourse_workflows.node_unavailable.requires_chat",
+ capabilities: {
+ waits_for_resume: true,
+ },
+ output_contracts: [
+ {
+ schema: CLICK_OUTPUT_SCHEMA,
+ variants: [
+ {
+ schema: CLICK_OUTPUT_SCHEMA,
+ mode: :union,
+ display_options: {
+ show: {
+ timeout_minutes: [{ condition: { exists: true } }],
+ },
+ hide: {
+ timeout_action: ["fail"],
+ },
+ },
+ },
+ ],
+ },
+ ],
+ properties: -> do
+ {
+ channel_id: {
+ type: :integer,
+ required: true,
+ type_options: {
+ load_options_method: "chat_channels",
+ },
+ no_data_expression: true,
+ ui: {
+ control: :combo_box,
+ },
+ control_options: {
+ 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,
+ ui: {
+ control: :textarea,
+ },
+ },
+ buttons: {
+ type: :fixed_collection,
+ required: true,
+ default: default_buttons,
+ max_items: MAX_BUTTONS,
+ type_options: {
+ multiple_values: true,
+ sortable: true,
+ },
+ ui: {
+ singular_name: "button",
+ },
+ options: [
+ {
+ name: "values",
+ values: {
+ label: {
+ type: :string,
+ required: true,
+ no_data_expression: true,
+ },
+ value: {
+ type: :string,
+ required: true,
+ no_data_expression: true,
+ },
+ },
+ },
+ ],
+ },
+ timeout_minutes: {
+ type: :integer,
+ required: false,
+ min: 1,
+ },
+ timeout_action: {
+ type: :options,
+ required: false,
+ options: TIMEOUT_ACTIONS,
+ default: "continue",
+ no_data_expression: true,
+ },
+ }
+ end,
+ )
+
+ def self.default_button_rows
+ [
+ {
+ "label" => I18n.t("discourse_workflows.chat_approval.default_approve_label"),
+ "value" => "approve",
+ },
+ {
+ "label" => I18n.t("discourse_workflows.chat_approval.default_deny_label"),
+ "value" => "deny",
+ },
+ ]
+ end
+
+ def self.default_buttons
+ { "values" => default_button_rows }
+ end
+
+ def self.button_rows(parameters)
+ value = DiscourseWorkflows::CollectionParameters.fetch_value(parameters, :buttons)
+ value = default_buttons if value.nil?
+ DiscourseWorkflows::CollectionParameters
+ .rows_from_value(value)
+ .map { |row| row.respond_to?(:deep_stringify_keys) ? row.deep_stringify_keys : row }
+ end
+
+ def self.allowed_actions(parameters)
+ ACTION_IDS.first(button_rows(parameters).size)
+ end
+
+ def self.button_value(parameters, action)
+ index = ACTION_IDS.index(action.to_s)
+ return if index.nil?
+
+ row = button_rows(parameters)[index]
+ row["value"].to_s if row.is_a?(Hash)
+ end
+
+ def self.valid_interaction?(interaction, action:, parameters:)
+ configured_channel_id =
+ Integer(
+ DiscourseWorkflows::CollectionParameters.fetch_value(parameters, :channel_id),
+ exception: false,
+ )
+ return false if configured_channel_id.nil?
+
+ configured_value = button_value(parameters, action)
+ action_id = interaction.action["action_id"].to_s
+ message_action =
+ interaction
+ .message
+ .blocks
+ &.filter_map { |block| block["elements"] }
+ .to_a
+ .flatten
+ .find { |element| element["action_id"].to_s == action_id }
+
+ configured_value.present? &&
+ interaction.message.chat_channel_id == configured_channel_id &&
+ interaction.action["value"].to_s == configured_value &&
+ message_action == interaction.action
+ end
+
+ def self.resume_user(interaction)
+ interaction.user
+ end
+
+ def self.response_items(action:, interaction:)
+ if ACTION_IDS.exclude?(action.to_s)
+ raise ArgumentError, "Unsupported chat approval action: #{action}"
+ end
+
+ user = interaction.user
+ channel = interaction.message.chat_channel
+ scope = user.guardian
+ channel_data =
+ Chat::WorkflowChannelSerializer.new(channel, scope: scope, root: false).as_json
+ user_data = BasicUserSerializer.new(user, scope: scope, root: false).as_json
+
+ [
+ DiscourseWorkflows::Item.wrap(
+ { value: interaction.action["value"].to_s, channel: channel_data, user: user_data },
+ paired_item: 0,
+ ),
+ ]
+ end
+
+ def self.validate_configuration(configuration, errors)
+ button_validation_errors(button_rows(configuration)).each do |message|
+ errors.add(:base, message)
+ end
+ end
+
+ def self.button_validation_errors(rows)
+ errors = []
+
+ if rows.empty?
+ errors << I18n.t("discourse_workflows.errors.chat_approval.buttons_required")
+ return errors
+ end
+
+ if rows.length > MAX_BUTTONS
+ errors << I18n.t(
+ "discourse_workflows.errors.chat_approval.too_many_buttons",
+ max: MAX_BUTTONS,
+ )
+ end
+
+ rows.each_with_index do |row, index|
+ label = row.is_a?(Hash) ? row["label"].to_s : ""
+ value = row.is_a?(Hash) ? row["value"].to_s : ""
+ position = index + 1
+
+ if label.blank?
+ errors << I18n.t(
+ "discourse_workflows.errors.chat_approval.button_label_required",
+ position: position,
+ )
+ elsif label.length > MAX_LABEL_LENGTH
+ errors << I18n.t(
+ "discourse_workflows.errors.chat_approval.button_label_too_long",
+ position: position,
+ max: MAX_LABEL_LENGTH,
+ )
+ end
+
+ if value.blank?
+ errors << I18n.t(
+ "discourse_workflows.errors.chat_approval.button_value_required",
+ position: position,
+ )
+ elsif value.length > MAX_VALUE_LENGTH
+ errors << I18n.t(
+ "discourse_workflows.errors.chat_approval.button_value_too_long",
+ position: position,
+ max: MAX_VALUE_LENGTH,
+ )
+ end
+ end
+
+ errors
+ end
+
+ def execute(exec_ctx)
+ message_text = exec_ctx.get_node_parameter("message", 0)
+ buttons_value = exec_ctx.get_node_parameter("buttons", 0)
+ buttons = self.class.button_rows("buttons" => buttons_value)
+ validate_buttons!(buttons)
+
+ channel_id = exec_ctx.get_node_parameter("channel_id", 0).to_i
+ timeout_minutes = exec_ctx.get_node_parameter("timeout_minutes", 0).presence&.to_i
+ if timeout_minutes && timeout_minutes < 1
+ raise_node_error!(
+ I18n.t("discourse_workflows.errors.chat_approval.timeout_must_be_positive"),
+ )
+ end
+
+ timeout_action =
+ exec_ctx.get_node_parameter("timeout_action", 0, default: "continue").to_s
+ if TIMEOUT_ACTIONS.exclude?(timeout_action)
+ raise_node_error!(
+ I18n.t(
+ "discourse_workflows.errors.chat_approval.invalid_timeout_action",
+ action: timeout_action,
+ ),
+ )
+ end
+
+ blocks = [
+ {
+ "type" => "actions",
+ "elements" =>
+ buttons.map.with_index do |button, index|
+ button_block(
+ button["label"].to_s,
+ exec_ctx.resume_action_id(ACTION_IDS[index]),
+ button["value"].to_s,
+ )
+ end,
+ },
+ ]
+ send_chat_message(channel_id, message_text, blocks)
+
+ exec_ctx.put_execution_to_wait(
+ timeout_minutes&.minutes&.from_now,
+ timeout_action: timeout_minutes ? timeout_action : nil,
+ )
+ [exec_ctx.input_items]
+ end
+
+ private
+
+ def validate_buttons!(buttons)
+ error = self.class.button_validation_errors(buttons).first
+ raise_node_error!(error) if error
+ end
+ end
+ end
+ end
+ end
+end
diff --git a/plugins/chat/lib/discourse_workflows/nodes/chat_message_created/v1.rb b/plugins/chat/lib/discourse_workflows/nodes/chat_message_created/v1.rb
index ead32834c32..ca1cd0ea76e 100644
--- a/plugins/chat/lib/discourse_workflows/nodes/chat_message_created/v1.rb
+++ b/plugins/chat/lib/discourse_workflows/nodes/chat_message_created/v1.rb
@@ -52,23 +52,7 @@ if defined?(DiscourseWorkflows)
},
"channel" => {
"type" => "object",
- "properties" => {
- "id" => {
- "type" => "integer",
- },
- "title" => {
- "type" => "string",
- },
- "slug" => {
- "type" => "string",
- },
- "chatable_type" => {
- "type" => "string",
- },
- "chatable_id" => {
- "type" => "integer",
- },
- },
+ "properties" => Chat::WorkflowChannelSerializer::PROPERTIES,
},
"user" => {
"type" => "object",
@@ -143,13 +127,7 @@ if defined?(DiscourseWorkflows)
thread_id: @message.thread_id,
chat_channel_id: @message.chat_channel_id,
},
- channel: {
- id: @channel.id,
- title: @channel.title(@user),
- slug: @channel.slug,
- chatable_type: @channel.chatable_type,
- chatable_id: @channel.chatable_id,
- },
+ channel: channel_data,
user: user_data,
}
end
@@ -161,6 +139,11 @@ if defined?(DiscourseWorkflows)
serialize_record(@user, BasicUserSerializer)
end
+
+ def channel_data
+ scope = @user&.guardian || Discourse.system_user.guardian
+ serialize_record(@channel, Chat::WorkflowChannelSerializer, scope:)
+ end
end
end
end
diff --git a/plugins/chat/plugin.rb b/plugins/chat/plugin.rb
index a9ae6cfedf1..c4005a78ac0 100644
--- a/plugins/chat/plugin.rb
+++ b/plugins/chat/plugin.rb
@@ -114,8 +114,13 @@ after_initialize do
require_relative "lib/discourse_workflows/nodes/chat_channel_selection"
require_relative "lib/discourse_workflows/nodes/send_chat_message/v1"
require_relative "lib/discourse_workflows/nodes/chat_approval/v1"
+ require_relative "lib/discourse_workflows/nodes/chat_approval/v2"
- [DiscourseWorkflows::Nodes::SendChatMessage::V1, DiscourseWorkflows::Nodes::ChatApproval::V1]
+ [
+ DiscourseWorkflows::Nodes::SendChatMessage::V1,
+ DiscourseWorkflows::Nodes::ChatApproval::V1,
+ DiscourseWorkflows::Nodes::ChatApproval::V2,
+ ]
end
require_relative "lib/discourse_workflows/nodes/chat_message_created/v1"
@@ -136,21 +141,29 @@ after_initialize do
on(:chat_message_interaction) do |interaction|
next unless SiteSetting.enable_discourse_workflows
- action_id = interaction.action&.dig("action_id").to_s
+ action_id = interaction.action.is_a?(Hash) ? interaction.action["action_id"].to_s : ""
next if action_id.blank?
- unless DiscourseWorkflows::InteractiveResume.action_id?(
- action_id,
- expected_node_type: "action:chat_approval",
- allowed_actions: %w[approve deny],
- )
- next
- end
+ resume_request =
+ DiscourseWorkflows::InteractiveResume.from_action_id(
+ action_id,
+ expected_node_type: "action:chat_approval",
+ allowed_actions:
+ DiscourseWorkflows::Nodes::ChatApproval::V1::ACTION_IDS +
+ DiscourseWorkflows::Nodes::ChatApproval::V2::ACTION_IDS,
+ )
+ next if resume_request.blank?
- Jobs.enqueue(
- Jobs::Chat::ResumeWorkflowApproval,
- action_id: action_id,
- channel_id: interaction.message.chat_channel_id,
- )
+ if DiscourseWorkflows::Nodes::ChatApproval::V1::ACTION_IDS.include?(resume_request.action)
+ Jobs.enqueue(
+ Jobs::Chat::ResumeWorkflowApproval,
+ action_id: action_id,
+ channel_id: interaction.message.chat_channel_id,
+ )
+ else
+ next if interaction.id.blank?
+
+ Jobs.enqueue(Jobs::Chat::ResumeWorkflowApprovalInteraction, interaction_id: interaction.id)
+ end
end
end
diff --git a/plugins/chat/spec/integration/workflows_chat_approval_spec.rb b/plugins/chat/spec/integration/workflows_chat_approval_spec.rb
index 1c2bf709895..c0fb5117315 100644
--- a/plugins/chat/spec/integration/workflows_chat_approval_spec.rb
+++ b/plugins/chat/spec/integration/workflows_chat_approval_spec.rb
@@ -1,7 +1,7 @@
# frozen_string_literal: true
-RSpec.describe "Wait for Approval end-to-end" do
- fab!(:user)
+RSpec.describe "Chat approval workflows end-to-end" do
+ fab!(:workflow_owner, :user)
fab!(:approver, :user)
fab!(:channel, :chat_channel)
@@ -10,119 +10,212 @@ RSpec.describe "Wait for Approval end-to-end" do
SiteSetting.enable_discourse_workflows = true
end
- def run_pending_approval_job
- job_args = Jobs::Chat::ResumeWorkflowApproval.jobs.last&.dig("args", 0)
- Jobs::Chat::ResumeWorkflowApproval.new.execute(job_args.symbolize_keys) if job_args
+ def create_approval_workflow(version:, configuration:)
+ graph =
+ build_workflow_graph do |builder|
+ builder.node "trigger-1", "trigger:manual"
+ builder.node(
+ "wait-1",
+ "action:chat_approval",
+ name: "Approval",
+ configuration: configuration,
+ )
+ builder.node(
+ "final-1",
+ "action:set_fields",
+ name: "Final",
+ configuration: {
+ "mode" => "raw",
+ "include_other_fields" => true,
+ "json_output" => '{"completed": true}',
+ },
+ )
+ builder.chain "trigger-1", "wait-1", "final-1"
+ end
+ graph[:nodes].find { |node| node["id"] == "wait-1" }["typeVersion"] = version
+
+ Fabricate(:discourse_workflows_workflow, created_by: workflow_owner, **graph).tap do |workflow|
+ publish_workflow!(workflow)
+ end
end
- def trigger_approval_interaction(user:, message:, action_id:, value: "approve")
+ def click_approval_button(user:, message:, button:)
interaction =
- Chat::MessageInteraction.new(
- user: user,
- message: message,
- action: {
- "action_id" => action_id,
- "value" => value,
- },
- )
+ Fabricate(:chat_message_interaction, user: user, message: message, action: button.deep_dup)
DiscourseEvent.trigger(:chat_message_interaction, interaction)
- end
- it "pauses, receives approval via chat interaction, and completes the workflow" do
- graph =
- build_workflow_graph do |g|
- g.node "trigger-1", "trigger:manual"
- g.node "wait-1",
- "action:chat_approval",
- name: "Approval",
- configuration: {
- "message" => "Please review",
- "approve_label" => "LGTM",
- "deny_label" => "Reject",
- "channel_id" => channel.id.to_s,
- "timeout_minutes" => "30",
- }
- g.node "final-1",
- "action:set_fields",
- name: "Final",
- configuration: {
- "mode" => "raw",
- "include_other_fields" => true,
- "json_output" => '{"completed": "true"}',
- }
- g.chain "trigger-1", "wait-1", "final-1"
+ action = DiscourseWorkflows::InteractiveResume.action_payload(button["action_id"])["action"]
+ job_class =
+ if %w[approve deny].include?(action)
+ Jobs::Chat::ResumeWorkflowApproval
+ else
+ Jobs::Chat::ResumeWorkflowApprovalInteraction
end
+ job_args = job_class.jobs.last.fetch("args").first
+ job_class.new.execute(job_args.symbolize_keys)
+ interaction
+ end
- workflow = Fabricate(:discourse_workflows_workflow, created_by: user, **graph)
- publish_workflow!(workflow)
+ it "uses the default V2 buttons and returns the clicked default value" do
+ workflow =
+ create_approval_workflow(
+ version: "2.0",
+ configuration: {
+ "message" => "Please review",
+ "channel_id" => channel.id.to_s,
+ },
+ )
- execution = nil
- freeze_time do
- execution = DiscourseWorkflows::Executor.new(workflow, "trigger-1", { "topic_id" => 1 }).run
- expect(execution.status).to eq("waiting")
- expect(execution.waiting_until).to eq_time(30.minutes.from_now)
- end
+ execution = DiscourseWorkflows::Executor.new(workflow, "trigger-1", {}).run
+ message = Chat::Message.where(chat_channel_id: channel.id).last
+ buttons = message.blocks.first["elements"]
- chat_message = Chat::Message.where(chat_channel_id: channel.id).last
- buttons = chat_message.blocks.first["elements"]
- expect(chat_message.message).to eq("Please review")
- expect(buttons.first["text"]["text"]).to eq("LGTM")
- expect(buttons.last["text"]["text"]).to eq("Reject")
+ expect(buttons.map { |button| button.dig("text", "text") }).to eq(%w[Approve Deny])
- trigger_approval_interaction(
- user: approver,
- message: chat_message,
- action_id: buttons.first["action_id"],
- )
- run_pending_approval_job
+ click_approval_button(user: approver, message: message, button: buttons.first)
execution.reload
expect(execution.status).to eq("success")
- expect(execution.execution_data.context_data["Final"].first["json"]).to include(
- "completed" => "true",
- "approved" => true,
+ expect(execution.execution_data.context_data.dig("Final", 0, "json")).to include(
+ "value" => "approve",
+ "user" => hash_including("id" => approver.id, "username" => approver.username),
+ "completed" => true,
)
end
- it "rejects a stale approval button when the execution revisits the same approval node" do
- graph =
- build_workflow_graph do |g|
- g.node "trigger-1", "trigger:manual"
- g.node "wait-1",
- "action:chat_approval",
- name: "Approval",
- configuration: {
- "message" => "Please review",
- "channel_id" => channel.id.to_s,
- }
- g.chain "trigger-1", "wait-1"
- end
+ it "returns the selected custom V2 value" do
+ workflow =
+ create_approval_workflow(
+ version: "2.0",
+ configuration: {
+ "message" => "Choose an outcome",
+ "buttons" => {
+ "values" => [
+ { "label" => "Ship it", "value" => "release:now" },
+ { "label" => "Revise", "value" => "needs:changes" },
+ ],
+ },
+ "channel_id" => channel.id.to_s,
+ },
+ )
+
+ execution = DiscourseWorkflows::Executor.new(workflow, "trigger-1", {}).run
+ message = Chat::Message.where(chat_channel_id: channel.id).last
+ selected_button = message.blocks.first["elements"].last
- workflow = Fabricate(:discourse_workflows_workflow, created_by: user, **graph)
- publish_workflow!(workflow)
+ click_approval_button(user: approver, message: message, button: selected_button)
+
+ expect(execution.reload.execution_data.context_data.dig("Final", 0, "json")).to include(
+ "value" => "needs:changes",
+ "channel" => hash_including("id" => channel.id),
+ )
+ end
+
+ it "supports a V2 workflow with one button" do
+ workflow =
+ create_approval_workflow(
+ version: "2.0",
+ configuration: {
+ "message" => "Acknowledge",
+ "buttons" => {
+ "values" => [{ "label" => "Got it", "value" => "acknowledged" }],
+ },
+ "channel_id" => channel.id.to_s,
+ },
+ )
execution = DiscourseWorkflows::Executor.new(workflow, "trigger-1", {}).run
- expect(execution.status).to eq("waiting")
+ message = Chat::Message.where(chat_channel_id: channel.id).last
+ buttons = message.blocks.first["elements"]
- first_message = Chat::Message.where(chat_channel_id: channel.id).last
- original_action_id = first_message.blocks.first["elements"].first["action_id"]
+ expect(buttons.one?).to eq(true)
+ click_approval_button(user: approver, message: message, button: buttons.first)
- trigger_approval_interaction(
- user: approver,
- message: first_message,
- action_id: original_action_id,
+ expect(execution.reload.execution_data.context_data.dig("Final", 0, "json")).to include(
+ "value" => "acknowledged",
)
- run_pending_approval_job
- expect(execution.reload.status).to eq("success")
+ end
+
+ it "continues a timed-out V2 workflow with its original input and no click fields" do
+ workflow =
+ create_approval_workflow(
+ version: "2.0",
+ configuration: {
+ "message" => "Please review",
+ "channel_id" => channel.id.to_s,
+ "timeout_minutes" => "1",
+ "timeout_action" => "continue",
+ },
+ )
+
+ freeze_time
+ execution = DiscourseWorkflows::Executor.new(workflow, "trigger-1", { "request_id" => 42 }).run
+ expect(execution).to have_attributes(
+ status: "waiting",
+ waiting_until: be_within(1.second).of(1.minute.from_now),
+ timeout_action: "continue",
+ )
+
+ freeze_time(2.minutes.from_now)
+ DiscourseWorkflows::Execution::ExpireWaiting.call
+
+ final_output = execution.reload.execution_data.context_data.dig("Final", 0, "json")
+ expect(execution.status).to eq("success")
+ expect(final_output).to include("request_id" => 42, "completed" => true)
+ expect(final_output.keys).not_to include("value", "channel", "user")
+ end
+
+ it "fails a timed-out V2 workflow with the approval timeout error" do
+ workflow =
+ create_approval_workflow(
+ version: "2.0",
+ configuration: {
+ "message" => "Please review",
+ "channel_id" => channel.id.to_s,
+ "timeout_minutes" => "1",
+ "timeout_action" => "fail",
+ },
+ )
- execution.update!(status: :waiting, waiting_node_id: "wait-1", resume_token: SecureRandom.uuid)
+ freeze_time
+ execution = DiscourseWorkflows::Executor.new(workflow, "trigger-1", {}).run
+ expect(execution.timeout_action).to eq("fail")
+
+ freeze_time(2.minutes.from_now)
+ DiscourseWorkflows::Execution::ExpireWaiting.call
- trigger_approval_interaction(
- user: approver,
- message: first_message,
- action_id: original_action_id,
+ expect(execution.reload).to have_attributes(
+ status: "error",
+ error: I18n.t("discourse_workflows.errors.approval_timed_out"),
+ timeout_action: nil,
+ )
+ end
+
+ it "keeps explicit V1 workflows on the legacy output contract" do
+ workflow =
+ create_approval_workflow(
+ version: "1.0",
+ configuration: {
+ "message" => "Please review",
+ "approve_label" => "LGTM",
+ "deny_label" => "Reject",
+ "channel_id" => channel.id.to_s,
+ },
+ )
+
+ execution = DiscourseWorkflows::Executor.new(workflow, "trigger-1", {}).run
+ message = Chat::Message.where(chat_channel_id: channel.id).last
+ approve_button = message.blocks.first["elements"].first
+
+ click_approval_button(user: approver, message: message, button: approve_button)
+
+ expect(execution.reload.execution_data.context_data["Approval"]).to eq(
+ [{ "json" => { "approved" => true, "channel_id" => channel.id } }],
+ )
+ expect(execution.execution_data.context_data.dig("Final", 0, "json")).to eq(
+ "approved" => true,
+ "channel_id" => channel.id,
+ "completed" => true,
)
- run_pending_approval_job
- expect(execution.reload.status).to eq("waiting")
end
end
diff --git a/plugins/chat/spec/integration/workflows_chat_interaction_spec.rb b/plugins/chat/spec/integration/workflows_chat_interaction_spec.rb
index c04b9bce876..0b9ee9f53ba 100644
--- a/plugins/chat/spec/integration/workflows_chat_interaction_spec.rb
+++ b/plugins/chat/spec/integration/workflows_chat_interaction_spec.rb
@@ -10,7 +10,7 @@ RSpec.describe "Chat interaction listener for workflow approvals" do
SiteSetting.enable_discourse_workflows = true
end
- it "enqueues ResumeWorkflowApproval when an approve button is clicked" do
+ it "enqueues the persisted interaction id when a V2 button is clicked" do
graph =
build_workflow_graph do |g|
g.node "trigger-1", "trigger:manual"
@@ -22,6 +22,7 @@ RSpec.describe "Chat interaction listener for workflow approvals" do
}
g.chain "trigger-1", "wait-1"
end
+ graph[:nodes].find { |node| node["id"] == "wait-1" }["typeVersion"] = "2.0"
workflow = Fabricate(:discourse_workflows_workflow, created_by: user, **graph)
publish_workflow!(workflow)
@@ -31,7 +32,8 @@ RSpec.describe "Chat interaction listener for workflow approvals" do
approve_action_id = Chat::Message.last.blocks.first["elements"].first["action_id"]
interaction =
- Chat::MessageInteraction.new(
+ Fabricate(
+ :chat_message_interaction,
user: user,
message: Chat::Message.last,
action: {
@@ -40,6 +42,42 @@ RSpec.describe "Chat interaction listener for workflow approvals" do
},
)
+ expect_enqueued_with(
+ job: Jobs::Chat::ResumeWorkflowApprovalInteraction,
+ args: {
+ interaction_id: interaction.id,
+ },
+ ) { DiscourseEvent.trigger(:chat_message_interaction, interaction) }
+ end
+
+ it "preserves the legacy job payload when a V1 button is clicked" do
+ graph =
+ build_workflow_graph do |g|
+ g.node "trigger-1", "trigger:manual"
+ g.node "wait-1",
+ "action:chat_approval",
+ configuration: {
+ "message" => "Approve?",
+ "channel_id" => channel.id.to_s,
+ }
+ g.chain "trigger-1", "wait-1"
+ end
+ workflow = Fabricate(:discourse_workflows_workflow, created_by: user, **graph)
+ publish_workflow!(workflow)
+
+ DiscourseWorkflows::Executor.new(workflow, "trigger-1", {}).run
+ message = Chat::Message.last
+ approve_action_id = message.blocks.first["elements"].first["action_id"]
+ interaction =
+ Chat::MessageInteraction.new(
+ user: user,
+ message: message,
+ action: {
+ "action_id" => approve_action_id,
+ "value" => "approve",
+ },
+ )
+
expect_enqueued_with(
job: Jobs::Chat::ResumeWorkflowApproval,
args: {
@@ -51,7 +89,8 @@ RSpec.describe "Chat interaction listener for workflow approvals" do
it "ignores interactions whose action_id does not match any waiting execution" do
interaction =
- Chat::MessageInteraction.new(
+ Fabricate(
+ :chat_message_interaction,
user: user,
message: chat_message,
action: {
@@ -59,10 +98,12 @@ RSpec.describe "Chat interaction listener for workflow approvals" do
},
)
- expect { DiscourseEvent.trigger(:chat_message_interaction, interaction) }.not_to change(
- Jobs::Chat::ResumeWorkflowApproval.jobs,
- :size,
- )
+ expect { DiscourseEvent.trigger(:chat_message_interaction, interaction) }.not_to change {
+ [
+ Jobs::Chat::ResumeWorkflowApproval.jobs.size,
+ Jobs::Chat::ResumeWorkflowApprovalInteraction.jobs.size,
+ ]
+ }
end
it "ignores interactions with an unrecognized action type" do
@@ -74,7 +115,8 @@ RSpec.describe "Chat interaction listener for workflow approvals" do
)
interaction =
- Chat::MessageInteraction.new(
+ Fabricate(
+ :chat_message_interaction,
user: user,
message: chat_message,
action: {
@@ -82,9 +124,11 @@ RSpec.describe "Chat interaction listener for workflow approvals" do
},
)
- expect { DiscourseEvent.trigger(:chat_message_interaction, interaction) }.not_to change(
- Jobs::Chat::ResumeWorkflowApproval.jobs,
- :size,
- )
+ expect { DiscourseEvent.trigger(:chat_message_interaction, interaction) }.not_to change {
+ [
+ Jobs::Chat::ResumeWorkflowApproval.jobs.size,
+ Jobs::Chat::ResumeWorkflowApprovalInteraction.jobs.size,
+ ]
+ }
end
end
diff --git a/plugins/chat/spec/jobs/regular/chat/resume_workflow_approval_interaction_spec.rb b/plugins/chat/spec/jobs/regular/chat/resume_workflow_approval_interaction_spec.rb
new file mode 100644
index 00000000000..45d0579d3ba
--- /dev/null
+++ b/plugins/chat/spec/jobs/regular/chat/resume_workflow_approval_interaction_spec.rb
@@ -0,0 +1,55 @@
+# frozen_string_literal: true
+
+RSpec.describe Jobs::Chat::ResumeWorkflowApprovalInteraction do
+ fab!(:workflow_owner, :user)
+ fab!(:clicking_user, :user)
+ fab!(:channel, :chat_channel)
+
+ before do
+ SiteSetting.chat_enabled = true
+ SiteSetting.enable_discourse_workflows = true
+ end
+
+ it "resumes the waiting V2 execution from the persisted interaction" do
+ graph =
+ build_workflow_graph do |builder|
+ builder.node "trigger-1", "trigger:manual"
+ builder.node(
+ "wait-1",
+ "action:chat_approval",
+ name: "Approval",
+ configuration: {
+ "message" => "Choose",
+ "channel_id" => channel.id.to_s,
+ },
+ )
+ builder.chain "trigger-1", "wait-1"
+ end
+ graph[:nodes].find { |node| node["id"] == "wait-1" }["typeVersion"] = "2.0"
+ workflow =
+ Fabricate(:discourse_workflows_workflow, created_by: workflow_owner, **graph).tap do |record|
+ publish_workflow!(record)
+ end
+ execution = DiscourseWorkflows::Executor.new(workflow, "trigger-1", {}).run
+ message = Chat::Message.where(chat_channel_id: channel.id).last
+ interaction =
+ Fabricate(
+ :chat_message_interaction,
+ user: clicking_user,
+ message: message,
+ action: message.blocks.first["elements"].first.deep_dup,
+ )
+
+ described_class.new.execute(interaction_id: interaction.id)
+
+ expect(execution.reload).to have_attributes(status: "success")
+ expect(execution.execution_data.context_data.dig("Approval", 0, "json")).to include(
+ "value" => "approve",
+ "user" => hash_including("id" => clicking_user.id),
+ )
+ end
+
+ it "does nothing when the persisted interaction does not exist" do
+ expect { described_class.new.execute(interaction_id: -1) }.not_to raise_error
+ end
+end
diff --git a/plugins/chat/spec/jobs/regular/chat/resume_workflow_approval_spec.rb b/plugins/chat/spec/jobs/regular/chat/resume_workflow_approval_spec.rb
new file mode 100644
index 00000000000..e84c8371646
--- /dev/null
+++ b/plugins/chat/spec/jobs/regular/chat/resume_workflow_approval_spec.rb
@@ -0,0 +1,41 @@
+# frozen_string_literal: true
+
+RSpec.describe Jobs::Chat::ResumeWorkflowApproval do
+ fab!(:workflow_owner, :user)
+ fab!(:channel, :chat_channel)
+
+ before do
+ SiteSetting.chat_enabled = true
+ SiteSetting.enable_discourse_workflows = true
+ end
+
+ it "preserves the legacy queued action and channel payload contract" do
+ graph =
+ build_workflow_graph do |builder|
+ builder.node "trigger-1", "trigger:manual"
+ builder.node(
+ "wait-1",
+ "action:chat_approval",
+ name: "Approval",
+ configuration: {
+ "message" => "Approve?",
+ "channel_id" => channel.id.to_s,
+ },
+ )
+ builder.chain "trigger-1", "wait-1"
+ end
+ workflow =
+ Fabricate(:discourse_workflows_workflow, created_by: workflow_owner, **graph).tap do |record|
+ publish_workflow!(record)
+ end
+ execution = DiscourseWorkflows::Executor.new(workflow, "trigger-1", {}).run
+ action_id = Chat::Message.last.blocks.first["elements"].first["action_id"]
+
+ described_class.new.execute(action_id: action_id, channel_id: channel.id)
+
+ expect(execution.reload).to have_attributes(status: "success")
+ expect(execution.execution_data.context_data["Approval"]).to eq(
+ [{ "json" => { "approved" => true, "channel_id" => channel.id } }],
+ )
+ end
+end
diff --git a/plugins/chat/spec/lib/discourse_workflows/nodes/chat_approval_spec.rb b/plugins/chat/spec/lib/discourse_workflows/nodes/chat_approval/v1_spec.rb
similarity index 100%
rename from plugins/chat/spec/lib/discourse_workflows/nodes/chat_approval_spec.rb
rename to plugins/chat/spec/lib/discourse_workflows/nodes/chat_approval/v1_spec.rb
diff --git a/plugins/chat/spec/lib/discourse_workflows/nodes/chat_approval/v2_spec.rb b/plugins/chat/spec/lib/discourse_workflows/nodes/chat_approval/v2_spec.rb
new file mode 100644
index 00000000000..d162bb52cf1
--- /dev/null
+++ b/plugins/chat/spec/lib/discourse_workflows/nodes/chat_approval/v2_spec.rb
@@ -0,0 +1,282 @@
+# frozen_string_literal: true
+
+RSpec.describe DiscourseWorkflows::Nodes::ChatApproval::V2 do
+ fab!(:channel, :chat_channel)
+ fab!(:execution, :discourse_workflows_execution)
+
+ before { SiteSetting.chat_enabled = true }
+
+ describe "node contract" do
+ it "registers as the latest version while retaining V1 as the versionless default" do
+ expect(described_class.identifier).to eq("action:chat_approval")
+ expect(described_class.version).to eq("2.0")
+ expect(DiscourseWorkflows::Registry.latest_version(described_class.identifier)).to eq("2.0")
+ expect(DiscourseWorkflows::Registry.find_node_type(described_class.identifier)).to eq(
+ DiscourseWorkflows::Nodes::ChatApproval::V1,
+ )
+ expect(
+ DiscourseWorkflows::Registry.find_node_type(described_class.identifier, version: "2.0"),
+ ).to eq(described_class)
+ end
+
+ it "declares editable label and value rows with Chat's collection limits" do
+ buttons = described_class.property_schema.fetch(:buttons)
+
+ expect(buttons).to include(
+ type: :fixed_collection,
+ required: true,
+ max_items: 10,
+ default: described_class.default_buttons,
+ )
+ expect(buttons.dig(:type_options, :sortable)).to eq(true)
+ expect(buttons.dig(:options, 0, :values, :label)).to include(
+ type: :string,
+ required: true,
+ no_data_expression: true,
+ )
+ expect(buttons.dig(:options, 0, :values, :value)).to include(
+ type: :string,
+ required: true,
+ no_data_expression: true,
+ )
+ expect(described_class.property_schema.fetch(:timeout_action)).to include(
+ options: %w[continue fail],
+ default: "continue",
+ )
+ end
+
+ it "uses localized Approve and Deny defaults" do
+ expect(described_class.default_button_rows).to eq(
+ [
+ {
+ "label" => I18n.t("discourse_workflows.chat_approval.default_approve_label"),
+ "value" => "approve",
+ },
+ {
+ "label" => I18n.t("discourse_workflows.chat_approval.default_deny_label"),
+ "value" => "deny",
+ },
+ ],
+ )
+ end
+
+ it "exposes the exact click output and timeout continuation contracts" do
+ input_schema = DiscourseWorkflows::Schema::POST_SCHEMA
+ expected_properties = {
+ "value" => {
+ "type" => "string",
+ },
+ "channel" => {
+ "type" => "object",
+ "properties" => Chat::WorkflowChannelSerializer::PROPERTIES,
+ },
+ "user" => {
+ "type" => "object",
+ "properties" => DiscourseWorkflows::Schema::BASIC_USER_PROPERTIES,
+ },
+ }
+
+ expect(described_class::CLICK_OUTPUT_SCHEMA.fetch("properties")).to eq(expected_properties)
+ expect(described_class.output_schemas({})).to eq([described_class::CLICK_OUTPUT_SCHEMA])
+ expect(
+ described_class.output_schemas(
+ { "timeout_minutes" => "30" },
+ input_schemas: [input_schema],
+ ),
+ ).to eq(
+ [DiscourseWorkflows::Schema.union(input_schema, described_class::CLICK_OUTPUT_SCHEMA)],
+ )
+ expect(
+ described_class.output_schemas(
+ { "timeout_minutes" => "30", "timeout_action" => "fail" },
+ input_schemas: [input_schema],
+ ),
+ ).to eq([described_class::CLICK_OUTPUT_SCHEMA])
+ end
+ end
+
+ describe ".validate_configuration" do
+ def errors_for(button_rows)
+ errors = ActiveModel::Errors.new(Object.new)
+ described_class.validate_configuration({ "buttons" => { "values" => button_rows } }, errors)
+ errors
+ end
+
+ it "accepts one through ten buttons at the label and value length boundaries" do
+ one_button = [{ "label" => "L" * 75, "value" => "v" * 2000 }]
+ ten_buttons =
+ Array.new(10) { |index| { "label" => "Button #{index}", "value" => index.to_s } }
+
+ expect(errors_for(one_button)).to be_empty
+ expect(errors_for(ten_buttons)).to be_empty
+ end
+
+ it "accepts duplicate and punctuation-rich values" do
+ rows = [
+ { "label" => "First", "value" => "review:later" },
+ { "label" => "Second", "value" => "review:later" },
+ ]
+
+ expect(errors_for(rows)).to be_empty
+ end
+
+ it "rejects empty, excessive, and oversized button collections", :aggregate_failures do
+ valid_row = { "label" => "Choose", "value" => "choice" }
+
+ expect(errors_for([])[:base]).to include(
+ I18n.t("discourse_workflows.errors.chat_approval.buttons_required"),
+ )
+ expect(errors_for(Array.new(11) { valid_row })[:base]).to include(
+ I18n.t("discourse_workflows.errors.chat_approval.too_many_buttons", max: 10),
+ )
+ expect(errors_for([{ "label" => "L" * 76, "value" => "choice" }])[:base]).to include(
+ I18n.t(
+ "discourse_workflows.errors.chat_approval.button_label_too_long",
+ position: 1,
+ max: 75,
+ ),
+ )
+ expect(errors_for([{ "label" => "Choose", "value" => "v" * 2001 }])[:base]).to include(
+ I18n.t(
+ "discourse_workflows.errors.chat_approval.button_value_too_long",
+ position: 1,
+ max: 2000,
+ ),
+ )
+ expect(errors_for([{ "label" => "", "value" => "choice" }])[:base]).to include(
+ I18n.t("discourse_workflows.errors.chat_approval.button_label_required", position: 1),
+ )
+ expect(errors_for([{ "label" => "Choose", "value" => "" }])[:base]).to include(
+ I18n.t("discourse_workflows.errors.chat_approval.button_value_required", position: 1),
+ )
+ end
+ end
+
+ describe ".valid_interaction?" do
+ it "rejects absent and malformed channel identifiers", :aggregate_failures do
+ interaction = Fabricate(:chat_message_interaction, action: {})
+ parameters = { "buttons" => described_class.default_buttons }
+
+ expect(
+ described_class.valid_interaction?(interaction, action: "button_0", parameters:),
+ ).to eq(false)
+ expect(
+ described_class.valid_interaction?(
+ interaction,
+ action: "button_0",
+ parameters: parameters.merge("channel_id" => "not-a-channel"),
+ ),
+ ).to eq(false)
+ end
+ end
+
+ describe "#execute" do
+ let(:resume_token) { SecureRandom.uuid }
+ let(:sandbox) { DiscourseWorkflows::JsSandbox.new({}) }
+
+ after { sandbox.dispose }
+
+ def build_v2_exec_ctx(
+ config,
+ runtime_state: DiscourseWorkflows::Executor::NodeExecutionContext::RuntimeState.new
+ )
+ resolver = DiscourseWorkflows::ExpressionResolver.new({ "$json" => {} }, sandbox: sandbox)
+ DiscourseWorkflows::Executor::NodeExecutionContext.new(
+ input_items: [{ "json" => { "request_id" => 42 } }],
+ resolver: resolver,
+ parameters: config,
+ property_schema: described_class.property_schema,
+ execution_id: execution.id,
+ node_id: "node_abc",
+ resume_token: resume_token,
+ runtime_state: runtime_state,
+ )
+ end
+
+ it "renders the default buttons when the buttons parameter is missing" do
+ config = { "message" => "Choose", "channel_id" => channel.id.to_s }
+ instance = described_class.new(parameters: config)
+
+ instance.execute(build_v2_exec_ctx(config))
+
+ buttons = Chat::Message.last.blocks.first["elements"]
+ expect(buttons.map { |button| [button.dig("text", "text"), button["value"]] }).to eq(
+ [%w[Approve approve], %w[Deny deny]],
+ )
+ end
+
+ it "creates indexed signed actions for custom, duplicate, punctuation, and long values" do
+ long_value = "v" * 2000
+ rows = [
+ { "label" => "Review later", "value" => "review:later" },
+ { "label" => "Same outcome", "value" => "review:later" },
+ { "label" => "Long outcome", "value" => long_value },
+ ]
+ config = {
+ "message" => "Choose",
+ "buttons" => {
+ "values" => rows,
+ },
+ "channel_id" => channel.id.to_s,
+ }
+ instance = described_class.new(parameters: config)
+
+ instance.execute(build_v2_exec_ctx(config))
+
+ buttons = Chat::Message.last.blocks.first["elements"]
+ payloads =
+ buttons.map do |button|
+ DiscourseWorkflows::InteractiveResume.action_payload(button["action_id"])
+ end
+ expect(buttons.map { |button| button["value"] }).to eq(
+ ["review:later", "review:later", long_value],
+ )
+ expect(payloads.map { |payload| payload["action"] }).to eq(%w[button_0 button_1 button_2])
+ expect(buttons.map { |button| button["action_id"] }).to all(
+ satisfy { |action_id| action_id.length <= 255 && !action_id.include?(long_value) },
+ )
+ end
+
+ it "treats an explicitly empty button collection as invalid" do
+ config = {
+ "message" => "Choose",
+ "buttons" => {
+ "values" => [],
+ },
+ "channel_id" => channel.id.to_s,
+ }
+ instance = described_class.new(parameters: config)
+
+ expect { instance.execute(build_v2_exec_ctx(config)) }.to raise_error(
+ DiscourseWorkflows::NodeError,
+ I18n.t("discourse_workflows.errors.chat_approval.buttons_required"),
+ )
+ expect(channel.chat_messages).to be_empty
+ end
+
+ it "passes timeout action only when an explicit timeout is configured" do
+ without_timeout = {
+ "message" => "Choose",
+ "channel_id" => channel.id.to_s,
+ "timeout_action" => "fail",
+ }
+ without_timeout_state = DiscourseWorkflows::Executor::NodeExecutionContext::RuntimeState.new
+ described_class.new(parameters: without_timeout).execute(
+ build_v2_exec_ctx(without_timeout, runtime_state: without_timeout_state),
+ )
+
+ with_timeout = without_timeout.merge("timeout_minutes" => "12")
+ with_timeout_state = DiscourseWorkflows::Executor::NodeExecutionContext::RuntimeState.new
+ freeze_time do
+ described_class.new(parameters: with_timeout).execute(
+ build_v2_exec_ctx(with_timeout, runtime_state: with_timeout_state),
+ )
+
+ expect(with_timeout_state.wait_request.waiting_until).to eq_time(12.minutes.from_now)
+ end
+
+ expect(without_timeout_state.wait_request.timeout_action).to be_nil
+ expect(with_timeout_state.wait_request.timeout_action).to eq("fail")
+ end
+ end
+end
diff --git a/plugins/chat/spec/services/chat/workflows/approval/resume_interaction_spec.rb b/plugins/chat/spec/services/chat/workflows/approval/resume_interaction_spec.rb
new file mode 100644
index 00000000000..a16cb0d86c9
--- /dev/null
+++ b/plugins/chat/spec/services/chat/workflows/approval/resume_interaction_spec.rb
@@ -0,0 +1,302 @@
+# frozen_string_literal: true
+
+RSpec.describe Chat::Workflows::Approval::ResumeInteraction do
+ describe described_class::Contract, type: :model do
+ it { is_expected.to validate_presence_of(:interaction_id) }
+ end
+
+ describe ".call" do
+ subject(:result) { described_class.call(params:) }
+
+ fab!(:workflow_owner, :user)
+ fab!(:clicking_user, :user)
+ fab!(:channel, :chat_channel)
+
+ let(:node_version) { "2.0" }
+ let(:button_rows) do
+ [
+ { "label" => "Approve", "value" => "approve" },
+ { "label" => "Needs changes", "value" => "needs:changes" },
+ ]
+ end
+ let(:approval_configuration) do
+ {
+ "message" => "Approve?",
+ "buttons" => {
+ "values" => button_rows,
+ },
+ "channel_id" => channel.id.to_s,
+ }
+ end
+ let(:workflow) do
+ graph =
+ build_workflow_graph do |builder|
+ builder.node "trigger-1", "trigger:manual", name: "Manual"
+ builder.node(
+ "wait-1",
+ "action:chat_approval",
+ name: "Wait",
+ configuration: approval_configuration,
+ )
+ builder.node("after-1", "action:code", name: "After", configuration: { "code" => <<~JS })
+ var items = $input.all();
+ items.forEach(function(item) {
+ item.json.current_user_id = $current_user.id || null;
+ });
+ return items;
+ JS
+
+ builder.chain "trigger-1", "wait-1", "after-1"
+ end
+ if node_version
+ graph[:nodes].find { |node| node["id"] == "wait-1" }["typeVersion"] = node_version
+ end
+
+ Fabricate(:discourse_workflows_workflow, created_by: workflow_owner, **graph).tap do |record|
+ publish_workflow!(record)
+ end
+ end
+ let(:execution) { DiscourseWorkflows::Executor.new(workflow, "trigger-1", {}).run }
+ let(:message) do
+ execution
+ Chat::Message.where(chat_channel_id: channel.id).last
+ end
+ let(:button_index) { 0 }
+ let(:button) { message.blocks.first["elements"][button_index] }
+ let(:interaction) do
+ Fabricate(
+ :chat_message_interaction,
+ user: clicking_user,
+ message: message,
+ action: button.deep_dup,
+ )
+ end
+ let(:params) { { interaction_id: interaction.id } }
+
+ before do
+ SiteSetting.chat_enabled = true
+ SiteSetting.enable_discourse_workflows = true
+ SiteSetting.enable_names = true
+ end
+
+ context "when the plugin is disabled" do
+ before { SiteSetting.enable_discourse_workflows = false }
+
+ it { is_expected.to fail_a_policy(:workflows_enabled) }
+ end
+
+ context "when the contract is invalid" do
+ let(:params) { {} }
+
+ it { is_expected.to fail_a_contract }
+ end
+
+ context "when the persisted interaction does not exist" do
+ let(:params) { { interaction_id: -1 } }
+
+ it { is_expected.to fail_to_find_a_model(:interaction) }
+ end
+
+ context "when the signed action points to a missing execution" do
+ let(:missing_action_id) do
+ DiscourseWorkflows::InteractiveResume.action_id(
+ execution_id: 999_999,
+ resume_token: "missing",
+ action: "button_0",
+ )
+ end
+ let(:interaction) do
+ Fabricate(
+ :chat_message_interaction,
+ user: clicking_user,
+ message: Fabricate(:chat_message, chat_channel: channel),
+ action: {
+ "action_id" => missing_action_id,
+ "value" => "approve",
+ },
+ )
+ end
+
+ it { is_expected.to fail_to_find_a_model(:resolved_interaction) }
+ end
+
+ context "when the action token is stale" do
+ let(:stale_action_id) do
+ DiscourseWorkflows::InteractiveResume.action_id(
+ execution_id: execution.id,
+ resume_token: "stale-token",
+ action: "button_0",
+ )
+ end
+ let(:interaction) do
+ Fabricate(
+ :chat_message_interaction,
+ user: clicking_user,
+ message: message,
+ action: button.merge("action_id" => stale_action_id),
+ )
+ end
+
+ it { is_expected.to fail_to_find_a_model(:resolved_interaction) }
+ end
+
+ context "when the signed index is not configured" do
+ let(:invalid_action_id) do
+ DiscourseWorkflows::InteractiveResume.action_id(
+ execution_id: execution.id,
+ resume_token: execution.resume_token,
+ action: "button_9",
+ )
+ end
+ let(:interaction) do
+ Fabricate(
+ :chat_message_interaction,
+ user: clicking_user,
+ message: message,
+ action: button.merge("action_id" => invalid_action_id),
+ )
+ end
+
+ it { is_expected.to fail_to_find_a_model(:resolved_interaction) }
+ end
+
+ context "when the interaction message belongs to another channel" do
+ fab!(:other_channel, :chat_channel)
+
+ let(:interaction) do
+ Fabricate(
+ :chat_message_interaction,
+ user: clicking_user,
+ message:
+ Fabricate(
+ :chat_message,
+ chat_channel: other_channel,
+ user: Discourse.system_user,
+ blocks: message.blocks,
+ ),
+ action: button.deep_dup,
+ )
+ end
+
+ it { is_expected.to fail_to_find_a_model(:resolved_interaction) }
+ end
+
+ context "when the persisted action value was tampered with" do
+ let(:interaction) do
+ Fabricate(
+ :chat_message_interaction,
+ user: clicking_user,
+ message: message,
+ action: button.merge("value" => "tampered"),
+ )
+ end
+
+ it { is_expected.to fail_to_find_a_model(:resolved_interaction) }
+ end
+
+ context "when the message was trashed after the interaction was persisted" do
+ before do
+ interaction
+ message.trash!(clicking_user)
+ end
+
+ it { is_expected.to fail_to_find_a_model(:resolved_interaction) }
+ end
+
+ context "when the channel was trashed after the interaction was persisted" do
+ before do
+ interaction
+ channel.trash!(clicking_user)
+ end
+
+ it { is_expected.to fail_to_find_a_model(:resolved_interaction) }
+ end
+
+ context "when given an interaction for a versionless V1 waiting node" do
+ let(:node_version) { nil }
+ let(:approval_configuration) do
+ {
+ "message" => "Approve?",
+ "approve_label" => "Yes",
+ "deny_label" => "No",
+ "channel_id" => channel.id.to_s,
+ }
+ end
+ it { is_expected.to fail_to_find_a_model(:resolved_interaction) }
+ end
+
+ context "with a V2 waiting node" do
+ let(:button_index) { 1 }
+
+ it "returns the configured value, channel, and clicking user as one paired item" do
+ expect(result).to run_successfully
+
+ expected_user = {
+ "id" => clicking_user.id,
+ "username" => clicking_user.username,
+ "name" => clicking_user.name,
+ "avatar_template" => clicking_user.avatar_template,
+ }
+ expected_channel = {
+ "id" => channel.id,
+ "title" => channel.title(clicking_user),
+ "slug" => channel.slug,
+ "chatable_type" => channel.chatable_type,
+ "chatable_id" => channel.chatable_id,
+ }
+
+ execution.reload
+ expect(execution.execution_data.context_data["Wait"]).to eq(
+ [
+ {
+ "json" => {
+ "value" => "needs:changes",
+ "channel" => expected_channel,
+ "user" => expected_user,
+ },
+ "pairedItem" => {
+ "item" => 0,
+ },
+ },
+ ],
+ )
+ expect(execution.execution_data.context_data.dig("After", 0, "json")).to include(
+ "value" => "needs:changes",
+ "current_user_id" => clicking_user.id,
+ )
+ end
+ end
+
+ it "allows only one concurrent persisted interaction to claim the execution" do
+ second_user = Fabricate(:user)
+ second_interaction =
+ Fabricate(
+ :chat_message_interaction,
+ user: second_user,
+ message: message,
+ action: button.deep_dup,
+ )
+
+ ready = Queue.new
+ start = Queue.new
+ interaction_ids = [interaction.id, second_interaction.id]
+ threads =
+ interaction_ids.map do |interaction_id|
+ Thread.new do
+ ready << true
+ start.pop
+ described_class.call(params: { interaction_id: interaction_id })
+ end
+ end
+ interaction_ids.length.times { ready.pop }
+ interaction_ids.length.times { start << true }
+ results = threads.map(&:value)
+
+ expect(results.count(&:success?)).to eq(1)
+ expect(results.count(&:failure?)).to eq(1)
+ expect(execution.reload.execution_data.context_data.dig("After", 0, "json")).to include(
+ "current_user_id" => satisfy { |id| [clicking_user.id, second_user.id].include?(id) },
+ )
+ end
+ end
+end
diff --git a/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/configurators/fixed-collection.gjs b/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/configurators/fixed-collection.gjs
index 30341f95575..a2767ff4048 100644
--- a/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/configurators/fixed-collection.gjs
+++ b/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/configurators/fixed-collection.gjs
@@ -97,6 +97,10 @@ export default class FixedCollection extends Component {
return this.args.schema?.ui?.flat === true;
}
+ get isSortable() {
+ return this.args.schema?.type_options?.sortable === true;
+ }
+
get hide_optional_fields() {
const type_options = this.args.schema.type_options || {};
return type_options.hide_optional_fields;
@@ -263,6 +267,56 @@ export default class FixedCollection extends Component {
this.args.onChange?.();
}
+ @action
+ isFirstItem(index) {
+ return index === 0;
+ }
+
+ @action
+ isLastItem(group, index) {
+ return index === this.itemCount(group) - 1;
+ }
+
+ @action
+ moveItemLabel(direction, index) {
+ return i18n(`discourse_workflows.property_engine.move_item_${direction}`, {
+ position: index + 1,
+ });
+ }
+
+ @action
+ async moveItem(group, index, offset) {
+ const path = this.groupPath(group);
+ const items = this.args.formApi?.get(path);
+ const newIndex = index + offset;
+
+ if (!Array.isArray(items) || newIndex < 0 || newIndex >= items.length) {
+ return;
+ }
+
+ const reorderedItems = [...items];
+ const [movedItem] = reorderedItems.splice(index, 1);
+ reorderedItems.splice(newIndex, 0, movedItem);
+
+ const currentKey = this.activeAttrKey(group, index);
+ const newKey = this.activeAttrKey(group, newIndex);
+ const reorderedAttrs = new Map(this.activeAttrs);
+ const currentAttrs = reorderedAttrs.get(currentKey);
+ const newAttrs = reorderedAttrs.get(newKey);
+ reorderedAttrs.delete(currentKey);
+ reorderedAttrs.delete(newKey);
+ if (currentAttrs) {
+ reorderedAttrs.set(newKey, currentAttrs);
+ }
+ if (newAttrs) {
+ reorderedAttrs.set(currentKey, newAttrs);
+ }
+ this.activeAttrs = reorderedAttrs;
+
+ await this.args.formApi.set(path, reorderedItems);
+ this.args.onChange?.();
+ }
+
@action
isAttrActive(group, index, field, item) {
return isExtraFieldShown(
@@ -351,6 +405,29 @@ export default class FixedCollection extends Component {
>
<div class="workflows-property-engine__collection-row">
+ {{#if this.isSortable}}
+ <div
+ class="workflows-property-engine__collection-order-controls"
+ >
+ <DButton
+ @action={{fn this.moveItem group index -1}}
+ @icon="arrow-up"
+ @disabled={{this.isFirstItem index}}
+ @translatedAriaLabel={{this.moveItemLabel "up" index}}
+ @translatedTitle={{this.moveItemLabel "up" index}}
+ class="workflows-property-engine__collection-move"
+ />
+ <DButton
+ @action={{fn this.moveItem group index 1}}
+ @icon="arrow-down"
+ @disabled={{this.isLastItem group index}}
+ @translatedAriaLabel={{this.moveItemLabel "down" index}}
+ @translatedTitle={{this.moveItemLabel "down" index}}
+ class="workflows-property-engine__collection-move"
+ />
+ </div>
+ {{/if}}
+
<DButton
@action={{fn this.removeItem group collection.remove index}}
@icon="xmark"
diff --git a/plugins/discourse-workflows/assets/stylesheets/common/configurator/configurator.scss b/plugins/discourse-workflows/assets/stylesheets/common/configurator/configurator.scss
index 74d38e76555..960d3e148c5 100644
--- a/plugins/discourse-workflows/assets/stylesheets/common/configurator/configurator.scss
+++ b/plugins/discourse-workflows/assets/stylesheets/common/configurator/configurator.scss
@@ -201,6 +201,23 @@
}
}
+ &__collection-order-controls {
+ position: absolute;
+ inset-block-start: 0;
+ inset-inline-start: var(--space-2);
+ transform: translateY(-50%);
+ display: flex;
+ gap: var(--space-half);
+ }
+
+ &__collection-move {
+ padding: var(--space-half);
+ border-radius: 6px;
+ font-size: var(--font-down-1-rem);
+ background: var(--secondary);
+ border: 1px solid var(--primary-low-mid);
+ }
+
&__collection-fields {
flex: 1;
min-width: 0;
diff --git a/plugins/discourse-workflows/config/locales/client.en.yml b/plugins/discourse-workflows/config/locales/client.en.yml
index ed843de01ac..e1f0de7e0fd 100644
--- a/plugins/discourse-workflows/config/locales/client.en.yml
+++ b/plugins/discourse-workflows/config/locales/client.en.yml
@@ -705,6 +705,8 @@ en:
add_field: "Add field"
remove_assignment: "Remove %{name}"
remove_item: "Remove item"
+ move_item_up: "Move item %{position} up"
+ move_item_down: "Move item %{position} down"
dynamic_hint: "Must resolve to %{value}."
assignment_types:
string: "String"
diff --git a/plugins/discourse-workflows/lib/discourse_workflows/executor.rb b/plugins/discourse-workflows/lib/discourse_workflows/executor.rb
index 1964a75940d..87431f0d07d 100644
--- a/plugins/discourse-workflows/lib/discourse_workflows/executor.rb
+++ b/plugins/discourse-workflows/lib/discourse_workflows/executor.rb
@@ -927,7 +927,7 @@ module DiscourseWorkflows
if wait_request.workflow_call?
begin_workflow_call_wait!(wait_request)
else
- begin_timed_wait!(wait_request.waiting_until)
+ begin_timed_wait!(wait_request.waiting_until, timeout_action: wait_request.timeout_action)
end
rescue => e
@store.fail!(error: e, steps: @steps)
@@ -942,13 +942,18 @@ module DiscourseWorkflows
@context.store_pending_queue(@queue.drop(@queue_index || 0))
end
- def begin_timed_wait!(waiting_until)
+ def begin_timed_wait!(waiting_until, timeout_action: nil)
now = Time.current
ceiling = now + MAX_WAIT_DURATION_SECONDS
resolved = waiting_until.blank? ? ceiling : [waiting_until, ceiling].min
execution =
- @store.pause_waiting_execution!(node: @waiting_node, waiting_until: resolved, steps: @steps)
+ @store.pause_waiting_execution!(
+ node: @waiting_node,
+ waiting_until: resolved,
+ timeout_action: timeout_action,
+ steps: @steps,
+ )
Jobs.enqueue_in(
[resolved - now, 0].max,
diff --git a/plugins/discourse-workflows/lib/discourse_workflows/executor/execution_store.rb b/plugins/discourse-workflows/lib/discourse_workflows/executor/execution_store.rb
index 8471024f1f9..ada16c2582f 100644
--- a/plugins/discourse-workflows/lib/discourse_workflows/executor/execution_store.rb
+++ b/plugins/discourse-workflows/lib/discourse_workflows/executor/execution_store.rb
@@ -97,12 +97,13 @@ module DiscourseWorkflows
create_execution_with_status(:rate_limited, trigger_data: { "rate_limited" => true })
end
- def pause_waiting_execution!(node:, waiting_until: nil, steps: [])
+ def pause_waiting_execution!(node:, waiting_until: nil, timeout_action: nil, steps: [])
execution.update!(
status: :waiting,
waiting_node_id: node.id,
waiting_until: waiting_until,
resume_token: @execution_context.resume_token,
+ timeout_action: timeout_action,
)
save!(steps)
publish_waiting_form_notification(node)
diff --git a/plugins/discourse-workflows/lib/discourse_workflows/executor/node_execution_context.rb b/plugins/discourse-workflows/lib/discourse_workflows/executor/node_execution_context.rb
index cb4d61225af..79ee11371f6 100644
--- a/plugins/discourse-workflows/lib/discourse_workflows/executor/node_execution_context.rb
+++ b/plugins/discourse-workflows/lib/discourse_workflows/executor/node_execution_context.rb
@@ -15,7 +15,7 @@ module DiscourseWorkflows
JAVASCRIPT_UNDEFINED = CodeRunner::JAVASCRIPT_UNDEFINED
JobResult = Data.define(:ok, :result, :error)
WaitRequest =
- Data.define(:waiting_until, :kind, :payload) do
+ Data.define(:waiting_until, :kind, :payload, :timeout_action) do
def workflow_call?
kind == "workflow_call"
end
@@ -72,8 +72,9 @@ module DiscourseWorkflows
@wait_request = nil
end
- def request_wait(waiting_until, kind: "default", payload: {})
- @wait_request = WaitRequest.new(waiting_until, kind.to_s, payload.deep_stringify_keys)
+ def request_wait(waiting_until, kind: "default", payload: {}, timeout_action: nil)
+ @wait_request =
+ WaitRequest.new(waiting_until, kind.to_s, payload.deep_stringify_keys, timeout_action)
end
def add_condition_details(details)
@@ -406,8 +407,18 @@ module DiscourseWorkflows
self.class.serialize_topic(topic, guardian:, custom_field_names:)
end
- def put_execution_to_wait(waiting_until = nil, kind: "default", payload: {})
- @runtime_state.request_wait(waiting_until, kind: kind, payload: payload)
+ def put_execution_to_wait(
+ waiting_until = nil,
+ kind: "default",
+ payload: {},
+ timeout_action: nil
+ )
+ @runtime_state.request_wait(
+ waiting_until,
+ kind: kind,
+ payload: payload,
+ timeout_action: timeout_action,
+ )
end
def resume_action_id(action, target_user_id: nil)
diff --git a/plugins/discourse-workflows/lib/discourse_workflows/workflow_graph_validator.rb b/plugins/discourse-workflows/lib/discourse_workflows/workflow_graph_validator.rb
index e8aa6e90303..e95389d4590 100644
--- a/plugins/discourse-workflows/lib/discourse_workflows/workflow_graph_validator.rb
+++ b/plugins/discourse-workflows/lib/discourse_workflows/workflow_graph_validator.rb
@@ -328,9 +328,16 @@ module DiscourseWorkflows
end
def resolve_type_version(node_data, existing)
- existing&.dig("typeVersion") || node_data[:typeVersion] ||
- DiscourseWorkflows::Registry.latest_version(node_data[:type]) ||
+ existing&.dig("typeVersion").presence || node_data[:typeVersion].presence ||
+ implicit_type_version(node_data, existing) || DiscourseWorkflows::Registry::DEFAULT_VERSION
+ end
+
+ def implicit_type_version(node_data, existing)
+ if existing && existing["type"] == node_data[:type]
DiscourseWorkflows::Registry::DEFAULT_VERSION
+ else
+ DiscourseWorkflows::Registry.latest_version(node_data[:type])
+ end
end
def normalized_nodes_data
diff --git a/plugins/discourse-workflows/spec/jobs/regular/discourse_workflows/resume_waiting_execution_spec.rb b/plugins/discourse-workflows/spec/jobs/regular/discourse_workflows/resume_waiting_execution_spec.rb
index 2aecc7f9f21..636823e1efe 100644
--- a/plugins/discourse-workflows/spec/jobs/regular/discourse_workflows/resume_waiting_execution_spec.rb
+++ b/plugins/discourse-workflows/spec/jobs/regular/discourse_workflows/resume_waiting_execution_spec.rb
@@ -43,4 +43,21 @@ RSpec.describe Jobs::DiscourseWorkflows::ResumeWaitingExecution do
expect(execution.status).to eq("running")
expect(execution.updated_at).to eq_time(before_updated_at)
end
+
+ context "when the timeout action is fail" do
+ before { execution.update!(timeout_action: "fail") }
+
+ it "fails the execution with the existing timeout error and clears its wait state" do
+ described_class.new.execute(execution_id: execution.id)
+
+ expect(execution.reload).to have_attributes(
+ status: "error",
+ error: I18n.t("discourse_workflows.errors.approval_timed_out"),
+ waiting_node_id: nil,
+ waiting_until: nil,
+ resume_token: nil,
+ timeout_action: nil,
+ )
+ end
+ end
end
diff --git a/plugins/discourse-workflows/spec/lib/discourse_workflows/executor/execution_store_spec.rb b/plugins/discourse-workflows/spec/lib/discourse_workflows/executor/execution_store_spec.rb
index 15dc22ecac2..3283e6ad899 100644
--- a/plugins/discourse-workflows/spec/lib/discourse_workflows/executor/execution_store_spec.rb
+++ b/plugins/discourse-workflows/spec/lib/discourse_workflows/executor/execution_store_spec.rb
@@ -201,6 +201,37 @@ RSpec.describe DiscourseWorkflows::Executor::ExecutionStore do
end
end
+ describe "#pause_waiting_execution!" do
+ let(:node) do
+ OpenStruct.new(id: "wait-1", name: "Wait", type: "action:test", typeVersion: "1.0")
+ end
+
+ before { store.start! }
+
+ it "persists the requested timeout action" do
+ waiting_until = 15.minutes.from_now
+
+ store.pause_waiting_execution!(
+ node: node,
+ waiting_until: waiting_until,
+ timeout_action: "fail",
+ )
+
+ expect(store.execution.reload).to have_attributes(
+ status: "waiting",
+ waiting_node_id: "wait-1",
+ waiting_until: be_within(1.second).of(waiting_until),
+ timeout_action: "fail",
+ )
+ end
+
+ it "keeps timeout action nil when existing callers omit it" do
+ store.pause_waiting_execution!(node: node)
+
+ expect(store.execution.reload.timeout_action).to be_nil
+ end
+ end
+
describe "wait-state cleanup" do
let(:waiting_step) do
DiscourseWorkflows::Executor::Step.build(
diff --git a/plugins/discourse-workflows/spec/lib/discourse_workflows/executor/node_execution_context_spec.rb b/plugins/discourse-workflows/spec/lib/discourse_workflows/executor/node_execution_context_spec.rb
index 4bb803a9914..1fdcfb9caef 100644
--- a/plugins/discourse-workflows/spec/lib/discourse_workflows/executor/node_execution_context_spec.rb
+++ b/plugins/discourse-workflows/spec/lib/discourse_workflows/executor/node_execution_context_spec.rb
@@ -256,6 +256,45 @@ RSpec.describe DiscourseWorkflows::Executor::NodeExecutionContext do
end
end
+ describe "#put_execution_to_wait" do
+ let(:runtime_state) { described_class::RuntimeState.new }
+ let(:ctx) { described_class.new(input_items: [], resolver: nil, runtime_state: runtime_state) }
+
+ it "includes an explicit timeout action in the wait request" do
+ waiting_until = 10.minutes.from_now
+
+ ctx.put_execution_to_wait(
+ waiting_until,
+ kind: :approval,
+ payload: {
+ source: "chat",
+ },
+ timeout_action: "fail",
+ )
+
+ expect(runtime_state.wait_request).to have_attributes(
+ waiting_until: waiting_until,
+ kind: "approval",
+ payload: {
+ "source" => "chat",
+ },
+ timeout_action: "fail",
+ )
+ end
+
+ it "keeps timeout action nil for existing callers that omit it" do
+ ctx.put_execution_to_wait
+
+ expect(runtime_state.wait_request).to have_attributes(
+ waiting_until: nil,
+ kind: "default",
+ payload: {
+ },
+ timeout_action: nil,
+ )
+ end
+ end
+
describe "#set_metadata" do
it "merges execution metadata with string keys" do
ctx = described_class.new(input_items: [], resolver: nil)
diff --git a/plugins/discourse-workflows/spec/lib/discourse_workflows/executor_wait_spec.rb b/plugins/discourse-workflows/spec/lib/discourse_workflows/executor_wait_spec.rb
index 5fe75bb0aba..ddab1bb4d52 100644
--- a/plugins/discourse-workflows/spec/lib/discourse_workflows/executor_wait_spec.rb
+++ b/plugins/discourse-workflows/spec/lib/discourse_workflows/executor_wait_spec.rb
@@ -29,6 +29,7 @@ RSpec.describe DiscourseWorkflows::Executor do
status: "waiting",
waiting_node_id: "wait-1",
finished_at: nil,
+ timeout_action: nil,
)
expect(execution.waiting_until).to eq_time(
described_class::MAX_WAIT_DURATION_SECONDS.seconds.from_now,
@@ -169,6 +170,54 @@ RSpec.describe DiscourseWorkflows::Executor do
expect(execution.waiting_until).to eq_time(3.hours.from_now)
end
end
+
+ context "when a node supplies a timeout action" do
+ let(:timeout_wait_node_class) do
+ Class.new(DiscourseWorkflows::NodeType) do
+ description(
+ name: "action:timeout_wait_test",
+ version: "1.0",
+ capabilities: {
+ waits_for_resume: true,
+ },
+ )
+
+ def execute(exec_ctx)
+ exec_ctx.put_execution_to_wait(5.minutes.from_now, timeout_action: "fail")
+ [exec_ctx.input_items]
+ end
+ end
+ end
+
+ before do
+ plugin = Plugin::Instance.new
+ DiscoursePluginRegistry.register_discourse_workflows_node(timeout_wait_node_class, plugin)
+ DiscourseWorkflows::Registry.reset_indexes!
+ end
+
+ after { unregister_workflow_nodes(timeout_wait_node_class) }
+
+ it "carries the timeout action through the executor into the execution" do
+ graph =
+ build_workflow_graph do |g|
+ g.node "trigger-1", "trigger:manual"
+ g.node "wait-1", "action:timeout_wait_test"
+ g.chain "trigger-1", "wait-1"
+ end
+ workflow =
+ Fabricate(:discourse_workflows_workflow, created_by: user, published: true, **graph)
+
+ freeze_time do
+ execution = described_class.new(workflow, "trigger-1", {}).run
+
+ expect(execution).to have_attributes(
+ status: "waiting",
+ waiting_until: be_within(1.second).of(5.minutes.from_now),
+ timeout_action: "fail",
+ )
+ end
+ end
+ end
end
describe ".resume" do
diff --git a/plugins/discourse-workflows/spec/services/discourse_workflows/execution/expire_waiting_spec.rb b/plugins/discourse-workflows/spec/services/discourse_workflows/execution/expire_waiting_spec.rb
index f916175bc7b..314df3168fd 100644
--- a/plugins/discourse-workflows/spec/services/discourse_workflows/execution/expire_waiting_spec.rb
+++ b/plugins/discourse-workflows/spec/services/discourse_workflows/execution/expire_waiting_spec.rb
@@ -55,6 +55,7 @@ RSpec.describe DiscourseWorkflows::Execution::ExpireWaiting do
waiting_execution.reload
expect(waiting_execution.status).to eq("error")
expect(waiting_execution.error).to eq("Approval timed out")
+ expect(waiting_execution.timeout_action).to be_nil
end
end
@@ -109,7 +110,7 @@ RSpec.describe DiscourseWorkflows::Execution::ExpireWaiting do
)
result
- expect(waiting_execution.reload.status).to eq("success")
+ expect(waiting_execution.reload).to have_attributes(status: "success", timeout_action: nil)
end
end
end
diff --git a/plugins/discourse-workflows/spec/services/discourse_workflows/workflow/action/populate_graph_spec.rb b/plugins/discourse-workflows/spec/services/discourse_workflows/workflow/action/populate_graph_spec.rb
index da478d05970..45f4eb4833b 100644
--- a/plugins/discourse-workflows/spec/services/discourse_workflows/workflow/action/populate_graph_spec.rb
+++ b/plugins/discourse-workflows/spec/services/discourse_workflows/workflow/action/populate_graph_spec.rb
@@ -310,6 +310,49 @@ RSpec.describe DiscourseWorkflows::Workflow::Action::PopulateGraph do
ensure
unregister_workflow_nodes(v1, v2)
end
+
+ it "keeps an existing versionless node on the default version" do
+ v1 =
+ Class.new(DiscourseWorkflows::NodeType) do
+ description(name: "action:populate_versionless_test", version: "1.0")
+ end
+ v2 =
+ Class.new(DiscourseWorkflows::NodeType) do
+ description(name: "action:populate_versionless_test", version: "2.0")
+ end
+ plugin = Plugin::Instance.new
+ DiscoursePluginRegistry.register_discourse_workflows_node(v1, plugin)
+ DiscoursePluginRegistry.register_discourse_workflows_node(v2, plugin)
+ DiscourseWorkflows::Registry.reset_indexes!
+ workflow.update!(
+ nodes: [
+ {
+ "id" => "node-1",
+ "type" => "action:populate_versionless_test",
+ "name" => "Versionless",
+ "parameters" => {
+ },
+ },
+ ],
+ connections: {
+ },
+ )
+
+ result =
+ described_class.call(
+ workflow: workflow,
+ nodes_data: [
+ { id: "node-1", type: "action:populate_versionless_test", name: "Updated" },
+ ],
+ connections_data: {
+ },
+ )
+
+ expect(result).to eq(true)
+ expect(workflow.reload.nodes.first["typeVersion"]).to eq("1.0")
+ ensure
+ unregister_workflow_nodes(v1, v2)
+ end
end
context "with nodes and connections" do
diff --git a/plugins/discourse-workflows/test/javascripts/integration/components/workflows/property-engine-test.gjs b/plugins/discourse-workflows/test/javascripts/integration/components/workflows/property-engine-test.gjs
index 006f74440f1..9d4fa2f3670 100644
--- a/plugins/discourse-workflows/test/javascripts/integration/components/workflows/property-engine-test.gjs
+++ b/plugins/discourse-workflows/test/javascripts/integration/components/workflows/property-engine-test.gjs
@@ -1,6 +1,7 @@
import {
click,
fillIn,
+ find,
findAll,
render,
select,
@@ -1022,6 +1023,174 @@ module("Integration | Component | workflows property engine", function (hooks) {
assert.strictEqual(this.formApi.get("entries.values").length, 1);
});
+ test("reorders sortable fixed collection items", async function (assert) {
+ this.setProperties({
+ configuration: {
+ buttons: {
+ values: [
+ { label: "Approve", value: "approve" },
+ { label: "Deny", value: "deny" },
+ ],
+ },
+ },
+ formApi: null,
+ nodeType: "action:chat_approval",
+ onChange: sinon.spy(),
+ schema: {
+ buttons: {
+ type: "fixed_collection",
+ type_options: {
+ multiple_values: true,
+ sortable: true,
+ },
+ options: [
+ {
+ name: "values",
+ values: {
+ label: {
+ type: "string",
+ required: true,
+ no_data_expression: true,
+ },
+ value: {
+ type: "string",
+ required: true,
+ no_data_expression: true,
+ },
+ },
+ },
+ ],
+ },
+ },
+ registerApi: (api) => {
+ this.set("formApi", api);
+ },
+ });
+
+ await render(
+ <template>
+ <Form
+ @data={{this.configuration}}
+ @onRegisterApi={{this.registerApi}}
+ as |form transientData|
+ >
+ <PropertyEngineConfigurator
+ @form={{form}}
+ @formApi={{this.formApi}}
+ @configuration={{transientData}}
+ @nodeType={{this.nodeType}}
+ @schema={{this.schema}}
+ @session={{this.session}}
+ @onChange={{this.onChange}}
+ />
+ </Form>
+ </template>
+ );
+
+ const moveItemSelector = (direction, position) =>
+ `[aria-label="${i18n(
+ `discourse_workflows.property_engine.move_item_${direction}`,
+ { position }
+ )}"]`;
+ const moveButtons = (direction) => [
+ find(moveItemSelector(direction, 1)),
+ find(moveItemSelector(direction, 2)),
+ ];
+ let moveUpButtons = moveButtons("up");
+ let moveDownButtons = moveButtons("down");
+
+ assert
+ .dom(".workflows-property-engine__collection-move")
+ .exists({ count: 4 }, "each item has reorder controls");
+ assert.dom(moveUpButtons[0]).isDisabled("the first item cannot move up");
+ assert.dom(moveDownButtons[1]).isDisabled("the last item cannot move down");
+
+ await click(moveUpButtons[1]);
+
+ assert.deepEqual(
+ this.formApi.get("buttons.values"),
+ [
+ { label: "Deny", value: "deny" },
+ { label: "Approve", value: "approve" },
+ ],
+ "moving up updates the collection value"
+ );
+ assert
+ .dom(findAll(".workflows-property-engine__collection-row input")[0])
+ .hasValue("Deny", "the reordered value renders in the first row");
+ assert.true(this.onChange.calledOnce, "the editor observes the reorder");
+
+ moveDownButtons = moveButtons("down");
+ await click(moveDownButtons[0]);
+
+ assert.deepEqual(
+ this.formApi.get("buttons.values"),
+ [
+ { label: "Approve", value: "approve" },
+ { label: "Deny", value: "deny" },
+ ],
+ "moving down updates the collection value"
+ );
+ assert.true(this.onChange.calledTwice, "the editor observes each reorder");
+
+ moveUpButtons = moveButtons("up");
+ moveDownButtons = moveButtons("down");
+ assert.dom(moveUpButtons[0]).isDisabled("the first boundary is restored");
+ assert.dom(moveDownButtons[1]).isDisabled("the last boundary is restored");
+ });
+
+ test("does not add reorder controls to non-sortable fixed collections", async function (assert) {
+ this.setProperties({
+ configuration: {
+ entries: {
+ values: [{ key: "first" }, { key: "second" }],
+ },
+ },
+ nodeType: "action:log",
+ schema: {
+ entries: {
+ type: "fixed_collection",
+ type_options: {
+ multiple_values: true,
+ },
+ options: [
+ {
+ name: "values",
+ values: {
+ key: {
+ type: "string",
+ required: true,
+ no_data_expression: true,
+ },
+ },
+ },
+ ],
+ },
+ },
+ });
+
+ await render(
+ <template>
+ <Form @data={{this.configuration}} as |form transientData|>
+ <PropertyEngineConfigurator
+ @form={{form}}
+ @configuration={{transientData}}
+ @nodeType={{this.nodeType}}
+ @schema={{this.schema}}
+ @session={{this.session}}
+ />
+ </Form>
+ </template>
+ );
+
+ assert
+ .dom(".workflows-property-engine__collection-order-controls")
+ .doesNotExist("reordering remains opt-in");
+ assert
+ .dom(".workflows-property-engine__collection-delete")
+ .exists({ count: 2 }, "existing collection controls remain unchanged");
+ });
+
test("labels fixed collection remove buttons for items without a name", async function (assert) {
this.setProperties({
configuration: { entries: { values: [{ aggregation: "count" }] } },