Skip to content

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

FEATURE: adds a modal node to discourse workflows (#40978)

Joffrey JAFFEUX90c5ba36fa0b
diff --git a/plugins/discourse-workflows/app/controllers/discourse_workflows/modal_responses_controller.rb b/plugins/discourse-workflows/app/controllers/discourse_workflows/modal_responses_controller.rb
new file mode 100644
index 00000000000..6a1c7753cc7
--- /dev/null
+++ b/plugins/discourse-workflows/app/controllers/discourse_workflows/modal_responses_controller.rb
@@ -0,0 +1,23 @@
+# frozen_string_literal: true
+
+module DiscourseWorkflows
+ class ModalResponsesController < ::ApplicationController
+ requires_plugin DiscourseWorkflows::PLUGIN_NAME
+
+ before_action :ensure_logged_in
+
+ def create
+ DiscourseWorkflows::Modal::Respond.call(service_params) do
+ on_success { head :no_content }
+ on_failure { render(json: failed_json, status: :unprocessable_entity) }
+ on_failed_contract do |contract|
+ render(
+ json: failed_json.merge(errors: contract.errors.full_messages),
+ status: :bad_request,
+ )
+ end
+ on_model_not_found(:resume_request) { raise Discourse::NotFound }
+ end
+ end
+ end
+end
diff --git a/plugins/discourse-workflows/app/models/discourse_workflows/workflow_dependency.rb b/plugins/discourse-workflows/app/models/discourse_workflows/workflow_dependency.rb
index 4eff582f791..9b05e0d3f67 100644
--- a/plugins/discourse-workflows/app/models/discourse_workflows/workflow_dependency.rb
+++ b/plugins/discourse-workflows/app/models/discourse_workflows/workflow_dependency.rb
@@ -5,6 +5,7 @@ module DiscourseWorkflows
self.table_name = "discourse_workflows_workflow_dependencies"
TOPIC_ADMIN_BUTTON_CACHE_KEY = "topic_admin_buttons"
+ USER_MODAL_CACHE_KEY = "has_user_modals"
belongs_to :workflow, class_name: "DiscourseWorkflows::Workflow"
belongs_to :workflow_version,
@@ -42,6 +43,12 @@ module DiscourseWorkflows
end
end
+ def self.cached_user_modals?
+ cache.defer_get_set(USER_MODAL_CACHE_KEY) do
+ workflows_referencing("node_type", DiscourseWorkflows::Nodes::Modal::V1.identifier).exists?
+ end
+ end
+
def self.workflows_referencing(type, key)
joins(:workflow)
.where(dependency_type: type, dependency_key: key.to_s)
diff --git a/plugins/discourse-workflows/app/services/discourse_workflows/modal/respond.rb b/plugins/discourse-workflows/app/services/discourse_workflows/modal/respond.rb
new file mode 100644
index 00000000000..b9b5a08f594
--- /dev/null
+++ b/plugins/discourse-workflows/app/services/discourse_workflows/modal/respond.rb
@@ -0,0 +1,49 @@
+# frozen_string_literal: true
+
+module DiscourseWorkflows
+ class Modal::Respond
+ include Service::Base
+
+ NODE_TYPE = DiscourseWorkflows::Nodes::Modal::V1.identifier
+
+ params do
+ attribute :action_id, :string
+
+ validates :action_id, presence: true
+ end
+
+ model :resume_request
+ step :resume
+
+ private
+
+ def fetch_resume_request(params:)
+ payload = DiscourseWorkflows::InteractiveResume.action_payload(params.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 unless waiting_node && waiting_node["type"] == NODE_TYPE
+
+ DiscourseWorkflows::InteractiveResume.from_action_id(
+ params.action_id,
+ expected_node_type: NODE_TYPE,
+ allowed_actions:
+ DiscourseWorkflows::Nodes::Modal::V1.button_values(waiting_node["parameters"]),
+ )
+ end
+
+ def resume(resume_request:, guardian:)
+ claimed = resume_request.claim
+ fail!(I18n.t("discourse_workflows.errors.already_resumed")) if claimed.blank?
+
+ claimed.resume!(
+ DiscourseWorkflows::Nodes::Modal::V1.response_items(action: resume_request.action),
+ user: guardian.user,
+ )
+ end
+ end
+end
diff --git a/plugins/discourse-workflows/assets/javascripts/discourse/components/workflows-user-modal.gjs b/plugins/discourse-workflows/assets/javascripts/discourse/components/workflows-user-modal.gjs
new file mode 100644
index 00000000000..e09c9cef60e
--- /dev/null
+++ b/plugins/discourse-workflows/assets/javascripts/discourse/components/workflows-user-modal.gjs
@@ -0,0 +1,69 @@
+import Component from "@glimmer/component";
+import { tracked } from "@glimmer/tracking";
+import { fn } from "@ember/helper";
+import { action } from "@ember/object";
+import { ajax } from "discourse/lib/ajax";
+import { popupAjaxError } from "discourse/lib/ajax-error";
+import DButton from "discourse/ui-kit/d-button";
+import DModal from "discourse/ui-kit/d-modal";
+
+const STYLE_CLASSES = {
+ primary: "btn-primary",
+ danger: "btn-danger",
+ default: "btn-default",
+};
+
+export default class WorkflowsUserModal extends Component {
+ @tracked submitting = false;
+
+ get buttons() {
+ return (this.args.model.buttons || []).map((button) => ({
+ ...button,
+ styleClass: STYLE_CLASSES[button.style] || STYLE_CLASSES.default,
+ }));
+ }
+
+ @action
+ async respond(button) {
+ if (this.submitting) {
+ return;
+ }
+
+ this.submitting = true;
+
+ try {
+ await ajax("/discourse-workflows/modal-responses", {
+ type: "POST",
+ data: { action_id: button.action_id },
+ });
+ this.args.closeModal();
+ } catch (e) {
+ popupAjaxError(e);
+ this.submitting = false;
+ }
+ }
+
+ <template>
+ <DModal
+ @title={{@model.title}}
+ @closeModal={{@closeModal}}
+ class="workflows-user-modal"
+ >
+ <:body>
+ {{#if @model.body}}
+ <p class="workflows-user-modal__body">{{@model.body}}</p>
+ {{/if}}
+ </:body>
+ <:footer>
+ {{#each this.buttons as |button|}}
+ <DButton
+ class={{button.styleClass}}
+ @translatedLabel={{button.label}}
+ @action={{fn this.respond button}}
+ @disabled={{this.submitting}}
+ />
+ {{/each}}
+ </:footer>
+ </DModal>
+ </template>
+}
diff --git a/plugins/discourse-workflows/assets/javascripts/discourse/initializers/workflows-user-modal.js b/plugins/discourse-workflows/assets/javascripts/discourse/initializers/workflows-user-modal.js
new file mode 100644
index 00000000000..6ef7ba70b82
--- /dev/null
+++ b/plugins/discourse-workflows/assets/javascripts/discourse/initializers/workflows-user-modal.js
@@ -0,0 +1,33 @@
+import WorkflowsUserModal from "../components/workflows-user-modal";
+
+export default {
+ name: "discourse-workflows-user-modal",
+
+ initialize(container) {
+ const currentUser = container.lookup("service:current-user");
+
+ if (!currentUser) {
+ return;
+ }
+
+ const lastId = currentUser.discourse_workflows_user_modal_last_id;
+
+ if (lastId === undefined || lastId === null) {
+ return;
+ }
+
+ const messageBus = container.lookup("service:message-bus");
+ const modal = container.lookup("service:modal");
+ const channel = `/discourse-workflows/user-modal/${currentUser.id}`;
+
+ messageBus.subscribe(
+ channel,
+ (data) => {
+ if (data?.type === "show_modal") {
+ modal.show(WorkflowsUserModal, { model: data });
+ }
+ },
+ lastId
+ );
+ },
+};
diff --git a/plugins/discourse-workflows/config/locales/client.en.yml b/plugins/discourse-workflows/config/locales/client.en.yml
index f618f5456f8..610ad9b779b 100644
--- a/plugins/discourse-workflows/config/locales/client.en.yml
+++ b/plugins/discourse-workflows/config/locales/client.en.yml
@@ -170,6 +170,7 @@ en:
"trigger:topic_admin_button": "Topic admin button"
"trigger:error": "Error trigger"
"flow:wait": "Wait"
+ "action:modal": "Modal"
node_descriptions:
"trigger:topic_closed": "Fires when a topic is closed by a user or auto-close timer"
"trigger:post_created": "Fires when a new post or reply is created"
@@ -208,10 +209,28 @@ en:
"trigger:topic_admin_button": "Adds a button to the topic admin menu that triggers this workflow"
"trigger:error": "Fires when another workflow fails"
"flow:wait": "Pause workflow execution and resume after a delay or webhook callback"
+ "action:modal": "Shows a modal to a user and waits for them to choose an option"
topic_admin_button:
label: "Button label"
label_placeholder: "Run workflow"
icon: "Button icon"
+ modal:
+ target_user: "Target user"
+ target_user_placeholder: "Defaults to the user who triggered the workflow"
+ title: "Title"
+ title_placeholder: "Title shown at the top of the modal"
+ body: "Body"
+ body_placeholder: "Message shown to the user..."
+ buttons: "Buttons"
+ add_button: "Add button"
+ label: "Label"
+ label_placeholder: "Approve"
+ value: "Value"
+ value_placeholder: "approve"
+ style: "Style"
+ style_default: "Default"
+ style_primary: "Primary"
+ style_danger: "Danger"
if:
no_conditions_body: "Conditions are used to filter items based on their values"
add_condition: "Add condition"
diff --git a/plugins/discourse-workflows/config/locales/server.en.yml b/plugins/discourse-workflows/config/locales/server.en.yml
index 404012b59a2..fe487b7820c 100644
--- a/plugins/discourse-workflows/config/locales/server.en.yml
+++ b/plugins/discourse-workflows/config/locales/server.en.yml
@@ -54,6 +54,9 @@ en:
invalid_unit: "Invalid wait unit: %{unit}."
invalid_timeout_unit: "Invalid timeout unit: %{unit}."
timeout_amount_must_be_positive: "Timeout amount must be greater than 0."
+ modal:
+ no_target_user: "No target user is available for the modal."
+ user_not_found: "User '%{username}' not found."
topic_tags:
no_tag_names: "No tag names provided."
operation_failed: "Tag operation failed: %{errors}"
diff --git a/plugins/discourse-workflows/config/routes.rb b/plugins/discourse-workflows/config/routes.rb
index b3790c582cb..f2e97f7ca1d 100644
--- a/plugins/discourse-workflows/config/routes.rb
+++ b/plugins/discourse-workflows/config/routes.rb
@@ -75,6 +75,7 @@ DiscourseWorkflows::Engine.routes.draw do
scope "/discourse-workflows", defaults: { format: :json } do
post "/trigger-topic-admin-button" => "topic_admin_button#create"
+ post "/modal-responses" => "modal_responses#create"
end
scope "/workflows", defaults: { format: :json } do
diff --git a/plugins/discourse-workflows/lib/discourse_workflows/nodes/modal/v1.rb b/plugins/discourse-workflows/lib/discourse_workflows/nodes/modal/v1.rb
new file mode 100644
index 00000000000..4a51e6d2bad
--- /dev/null
+++ b/plugins/discourse-workflows/lib/discourse_workflows/nodes/modal/v1.rb
@@ -0,0 +1,160 @@
+# frozen_string_literal: true
+
+module DiscourseWorkflows
+ module Nodes
+ module Modal
+ class V1 < NodeType
+ USER_CHANNEL_PREFIX = "/discourse-workflows/user-modal"
+ BUTTON_STYLES = %w[default primary danger].freeze
+ DEFAULT_BUTTON_STYLE = "default"
+
+ description(
+ name: "action:modal",
+ version: "1.0",
+ defaults: {
+ icon: "window-maximize",
+ color: "blue",
+ },
+ group: "human_review",
+ properties: {
+ target_user: {
+ type: :string,
+ required: false,
+ },
+ title: {
+ type: :string,
+ required: true,
+ },
+ body: {
+ type: :string,
+ ui: {
+ control: :textarea,
+ },
+ },
+ buttons: {
+ type: :fixed_collection,
+ type_options: {
+ multiple_values: true,
+ },
+ options: [
+ {
+ name: "values",
+ values: {
+ label: {
+ type: :string,
+ required: true,
+ ui: {
+ expression: false,
+ },
+ },
+ value: {
+ type: :string,
+ required: true,
+ ui: {
+ expression: false,
+ },
+ },
+ style: {
+ type: :options,
+ default: DEFAULT_BUTTON_STYLE,
+ options: BUTTON_STYLES,
+ ui: {
+ expression: false,
+ },
+ },
+ },
+ },
+ ],
+ },
+ },
+ capabilities: {
+ waits_for_resume: true,
+ },
+ )
+
+ def self.user_channel(user_id)
+ "#{USER_CHANNEL_PREFIX}/#{user_id}"
+ end
+
+ def self.button_rows(parameters)
+ DiscourseWorkflows::CollectionParameters.rows_from_value(
+ DiscourseWorkflows::CollectionParameters.fetch_value(parameters, :buttons),
+ )
+ end
+
+ def self.button_values(parameters)
+ button_rows(parameters).filter_map { |row| row["value"].to_s.presence }
+ end
+
+ def self.response_items(action:)
+ [{ "json" => { "button" => action.to_s }, "pairedItem" => { "item" => 0 } }]
+ end
+
+ def execute(exec_ctx)
+ target_user = resolve_target_user(exec_ctx)
+ buttons = build_buttons(exec_ctx)
+
+ MessageBus.publish(
+ self.class.user_channel(target_user.id),
+ {
+ type: "show_modal",
+ title: exec_ctx.get_node_parameter("title", 0).to_s,
+ body: exec_ctx.get_node_parameter("body", 0).to_s,
+ buttons: buttons,
+ },
+ user_ids: [target_user.id],
+ )
+
+ # With buttons we pause until the user picks one. With no buttons there
+ # is nothing to respond to, so the modal is informational: show it and
+ # let the flow continue (the user just closes it).
+ exec_ctx.put_execution_to_wait(nil) if buttons.any?
+ [exec_ctx.input_items]
+ end
+
+ private
+
+ def resolve_target_user(exec_ctx)
+ username = exec_ctx.get_node_parameter("target_user", 0).presence
+
+ if username
+ user = User.find_by(username: username)
+ if user.nil?
+ raise_node_error!(
+ I18n.t("discourse_workflows.errors.modal.user_not_found", username: username),
+ )
+ end
+ return user
+ end
+
+ user = exec_ctx.user
+ raise_node_error!(I18n.t("discourse_workflows.errors.modal.no_target_user")) if user.nil?
+ user
+ end
+
+ def build_buttons(exec_ctx)
+ rows =
+ DiscourseWorkflows::CollectionParameters.rows_from_value(
+ exec_ctx.get_node_parameter("buttons", 0, default: []),
+ )
+
+ rows.filter_map do |row|
+ value = row["value"].to_s
+ next if value.blank?
+
+ {
+ "label" => row["label"].to_s.presence || value,
+ "value" => value,
+ "style" => normalize_style(row["style"]),
+ "action_id" => exec_ctx.resume_action_id(value),
+ }
+ end
+ end
+
+ def normalize_style(style)
+ BUTTON_STYLES.include?(style.to_s) ? style.to_s : DEFAULT_BUTTON_STYLE
+ end
+ end
+ end
+ end
+end
diff --git a/plugins/discourse-workflows/plugin.rb b/plugins/discourse-workflows/plugin.rb
index c94f875a4b6..848867d815b 100644
--- a/plugins/discourse-workflows/plugin.rb
+++ b/plugins/discourse-workflows/plugin.rb
@@ -42,6 +42,7 @@ register_svg_icon "triangle-exclamation"
register_svg_icon "clock"
register_svg_icon "comments"
register_svg_icon "pause"
+register_svg_icon "window-maximize"
register_svg_icon "user-plus"
register_svg_icon "grip-vertical"
register_svg_icon "arrow-down-a-z"
@@ -91,6 +92,14 @@ after_initialize do
DiscourseWorkflows::WorkflowDependency.cached_topic_admin_buttons
end
+ add_to_serializer :current_user,
+ :discourse_workflows_user_modal_last_id,
+ include_condition: -> do
+ DiscourseWorkflows::WorkflowDependency.cached_user_modals?
+ end do
+ MessageBus.last_id(DiscourseWorkflows::Nodes::Modal::V1.user_channel(object.id))
+ end
+
on(:site_setting_changed) do |name, old_value, new_value|
next if name != :discourse_workflows_enabled
next unless new_value && !old_value
diff --git a/plugins/discourse-workflows/spec/lib/discourse_workflows/nodes/modal_spec.rb b/plugins/discourse-workflows/spec/lib/discourse_workflows/nodes/modal_spec.rb
new file mode 100644
index 00000000000..556fb035452
--- /dev/null
+++ b/plugins/discourse-workflows/spec/lib/discourse_workflows/nodes/modal_spec.rb
@@ -0,0 +1,135 @@
+# frozen_string_literal: true
+
+RSpec.describe DiscourseWorkflows::Nodes::Modal::V1 do
+ fab!(:user)
+ fab!(:other_user, :user)
+
+ let(:sandbox) { DiscourseWorkflows::JsSandbox.new({ "$json" => {} }) }
+ after { sandbox.dispose }
+
+ let(:config) do
+ {
+ "title" => "Approve topic?",
+ "body" => "Please choose an option",
+ "buttons" => {
+ "values" => [
+ { "label" => "Approve", "value" => "approve", "style" => "primary" },
+ { "label" => "Reject", "value" => "reject", "style" => "danger" },
+ ],
+ },
+ }
+ end
+
+ def build_exec_ctx(configuration, ctx_user: nil, execution_id: 7, resume_token: "tok-7")
+ DiscourseWorkflows::Executor::NodeExecutionContext.new(
+ input_items: [{ "json" => {} }],
+ parameters: configuration,
+ property_schema: described_class.property_schema,
+ node_context: {
+ },
+ resolver: DiscourseWorkflows::ExpressionResolver.new({ "$json" => {} }, sandbox: sandbox),
+ user: ctx_user,
+ execution_id: execution_id,
+ resume_token: resume_token,
+ )
+ end
+
+ describe "#execute" do
+ it "publishes the modal to the triggering user and pauses the execution" do
+ exec_ctx = build_exec_ctx(config, ctx_user: user)
+ allow(exec_ctx).to receive(:put_execution_to_wait).and_call_original
+
+ messages =
+ MessageBus.track_publish(described_class.user_channel(user.id)) do
+ result = described_class.new(parameters: config).execute(exec_ctx)
+ expect(result).to eq([exec_ctx.input_items])
+ end
+
+ expect(exec_ctx).to have_received(:put_execution_to_wait).with(nil)
+ expect(messages.size).to eq(1)
+ message = messages.first
+ expect(message.user_ids).to eq([user.id])
+ expect(message.data[:type]).to eq("show_modal")
+ expect(message.data[:title]).to eq("Approve topic?")
+ expect(message.data[:body]).to eq("Please choose an option")
+
+ buttons = message.data[:buttons]
+ expect(buttons.map { |button| button["value"] }).to eq(%w[approve reject])
+ expect(buttons.map { |button| button["label"] }).to eq(%w[Approve Reject])
+ expect(buttons.map { |button| button["style"] }).to eq(%w[primary danger])
+ expect(buttons.first["action_id"]).to eq(
+ DiscourseWorkflows::InteractiveResume.action_id(
+ execution_id: 7,
+ resume_token: "tok-7",
+ action: "approve",
+ ),
+ )
+ end
+
+ it "sends the modal to a configured target user instead of the triggering user" do
+ configuration = config.merge("target_user" => other_user.username)
+ exec_ctx = build_exec_ctx(configuration, ctx_user: user)
+
+ messages =
+ MessageBus.track_publish(described_class.user_channel(other_user.id)) do
+ described_class.new(parameters: configuration).execute(exec_ctx)
+ end
+
+ expect(messages.size).to eq(1)
+ expect(messages.first.user_ids).to eq([other_user.id])
+ end
+
+ it "raises when no target user can be resolved" do
+ exec_ctx = build_exec_ctx(config, ctx_user: nil)
+
+ expect { described_class.new(parameters: config).execute(exec_ctx) }.to raise_error(
+ DiscourseWorkflows::NodeError,
+ I18n.t("discourse_workflows.errors.modal.no_target_user"),
+ )
+ end
+
+ it "raises when the configured target user does not exist" do
+ configuration = config.merge("target_user" => "ghost")
+ exec_ctx = build_exec_ctx(configuration, ctx_user: user)
+
+ expect { described_class.new(parameters: configuration).execute(exec_ctx) }.to raise_error(
+ DiscourseWorkflows::NodeError,
+ I18n.t("discourse_workflows.errors.modal.user_not_found", username: "ghost"),
+ )
+ end
+
+ it "shows an informational modal without waiting when there are no buttons" do
+ configuration = config.merge("buttons" => { "values" => [] })
+ exec_ctx = build_exec_ctx(configuration, ctx_user: user)
+ allow(exec_ctx).to receive(:put_execution_to_wait)
+
+ messages =
+ MessageBus.track_publish(described_class.user_channel(user.id)) do
+ result = described_class.new(parameters: configuration).execute(exec_ctx)
+ expect(result).to eq([exec_ctx.input_items])
+ end
+
+ expect(exec_ctx).not_to have_received(:put_execution_to_wait)
+ expect(messages.size).to eq(1)
+ expect(messages.first.data[:buttons]).to eq([])
+ end
+ end
+
+ describe ".button_values" do
+ it "returns the configured button output values" do
+ expect(described_class.button_values(config)).to eq(%w[approve reject])
+ end
+
+ it "returns an empty array when there are no buttons" do
+ expect(described_class.button_values({})).to eq([])
+ end
+ end
+
+ describe ".response_items" do
+ it "wraps the chosen action as the node output" do
+ expect(described_class.response_items(action: "approve")).to eq(
+ [{ "json" => { "button" => "approve" }, "pairedItem" => { "item" => 0 } }],
+ )
+ end
+ end
+end
diff --git a/plugins/discourse-workflows/spec/models/discourse_workflows/workflow_dependency_spec.rb b/plugins/discourse-workflows/spec/models/discourse_workflows/workflow_dependency_spec.rb
new file mode 100644
index 00000000000..364c0fde7b1
--- /dev/null
+++ b/plugins/discourse-workflows/spec/models/discourse_workflows/workflow_dependency_spec.rb
@@ -0,0 +1,47 @@
+# frozen_string_literal: true
+
+RSpec.describe DiscourseWorkflows::WorkflowDependency do
+ fab!(:admin)
+
+ before { described_class.clear_cache! }
+
+ def index(workflow)
+ version = workflow.workflow_versions.find_by(version_id: workflow.version_id)
+ DiscourseWorkflows::WorkflowDependencyIndexer.call(workflow, version: version)
+ end
+
+ describe ".cached_user_modals?" do
+ it "is true when a workflow uses the modal node" do
+ graph =
+ build_workflow_graph do |g|
+ g.node "t1", "trigger:manual"
+ g.node "m1",
+ "action:modal",
+ configuration: {
+ "title" => "Approve?",
+ "buttons" => {
+ "values" => [{ "label" => "Approve", "value" => "approve" }],
+ },
+ }
+ g.chain "t1", "m1"
+ end
+ workflow = Fabricate(:discourse_workflows_workflow, created_by: admin, **graph)
+ index(workflow)
+
+ expect(described_class.cached_user_modals?).to eq(true)
+ end
+
+ it "is false when no workflow uses the modal node" do
+ graph =
+ build_workflow_graph do |g|
+ g.node "t1", "trigger:manual"
+ g.node "a1", "action:topic"
+ g.chain "t1", "a1"
+ end
+ workflow = Fabricate(:discourse_workflows_workflow, created_by: admin, **graph)
+ index(workflow)
+
+ expect(described_class.cached_user_modals?).to eq(false)
+ end
+ end
+end
diff --git a/plugins/discourse-workflows/spec/serializers/current_user_modal_spec.rb b/plugins/discourse-workflows/spec/serializers/current_user_modal_spec.rb
new file mode 100644
index 00000000000..39374396718
--- /dev/null
+++ b/plugins/discourse-workflows/spec/serializers/current_user_modal_spec.rb
@@ -0,0 +1,47 @@
+# frozen_string_literal: true
+
+RSpec.describe CurrentUserSerializer do
+ fab!(:admin)
+ fab!(:user)
+
+ before { DiscourseWorkflows::WorkflowDependency.clear_cache! }
+
+ def serialized(target)
+ JSON.parse(described_class.new(target, scope: Guardian.new(target), root: false).to_json)
+ end
+
+ def index_modal_workflow
+ graph =
+ build_workflow_graph do |g|
+ g.node "t1", "trigger:manual"
+ g.node "m1",
+ "action:modal",
+ configuration: {
+ "title" => "Approve?",
+ "buttons" => {
+ "values" => [{ "label" => "Approve", "value" => "approve" }],
+ },
+ }
+ g.chain "t1", "m1"
+ end
+ workflow = Fabricate(:discourse_workflows_workflow, created_by: admin, **graph)
+ version = workflow.workflow_versions.find_by(version_id: workflow.version_id)
+ DiscourseWorkflows::WorkflowDependencyIndexer.call(workflow, version: version)
+ end
+
+ describe "discourse_workflows_user_modal_last_id" do
+ it "is omitted when no workflow uses a modal node" do
+ expect(serialized(user)).not_to have_key("discourse_workflows_user_modal_last_id")
+ end
+
+ it "is the channel's last id when a workflow uses a modal node" do
+ index_modal_workflow
+ channel = DiscourseWorkflows::Nodes::Modal::V1.user_channel(user.id)
+ MessageBus.publish(channel, { type: "show_modal" }, user_ids: [user.id])
+
+ payload = serialized(user)
+
+ expect(payload["discourse_workflows_user_modal_last_id"]).to eq(MessageBus.last_id(channel))
+ end
+ end
+end
diff --git a/plugins/discourse-workflows/spec/services/discourse_workflows/modal/respond_spec.rb b/plugins/discourse-workflows/spec/services/discourse_workflows/modal/respond_spec.rb
new file mode 100644
index 00000000000..e9bab7b5ce0
--- /dev/null
+++ b/plugins/discourse-workflows/spec/services/discourse_workflows/modal/respond_spec.rb
@@ -0,0 +1,101 @@
+# frozen_string_literal: true
+
+RSpec.describe DiscourseWorkflows::Modal::Respond do
+ describe described_class::Contract, type: :model do
+ it { is_expected.to validate_presence_of(:action_id) }
+ end
+
+ describe ".call" do
+ subject(:result) { described_class.call(params:, **dependencies) }
+
+ fab!(:user)
+
+ let(:dependencies) { { guardian: user.guardian } }
+ let(:params) { { action_id: action_id("approve") } }
+
+ fab!(:workflow) do
+ graph =
+ build_workflow_graph do |g|
+ g.node "trigger-1", "trigger:manual", name: "Manual"
+ g.node "modal-1",
+ "action:modal",
+ name: "Modal",
+ configuration: {
+ "title" => "Approve topic?",
+ "body" => "Please choose",
+ "target_user" => user.username,
+ "buttons" => {
+ "values" => [
+ { "label" => "Approve", "value" => "approve", "style" => "primary" },
+ { "label" => "Reject", "value" => "reject", "style" => "danger" },
+ ],
+ },
+ }
+ g.chain "trigger-1", "modal-1"
+ end
+ Fabricate(:discourse_workflows_workflow, name: "Published", published: true, **graph)
+ end
+
+ before { allow(MessageBus).to receive(:publish) }
+
+ let!(:execution) do
+ DiscourseWorkflows::Executor.new(
+ workflow,
+ "trigger-1",
+ {},
+ DiscourseWorkflows::Executor::ExecutionOptions.new(user: user),
+ ).run
+ end
+
+ def action_id(action)
+ DiscourseWorkflows::InteractiveResume.action_id(
+ execution_id: execution.id,
+ resume_token: execution.resume_token,
+ action: action,
+ )
+ end
+
+ it "pauses at the modal node before being resumed" do
+ expect(execution.status).to eq("waiting")
+ end
+
+ context "when the action id is valid" do
+ it { is_expected.to run_successfully }
+
+ it "resumes the execution with the chosen button value" do
+ result
+
+ expect(execution.reload.status).to eq("success")
+ output = execution.execution_data.entries.dig("modal-1", 0, "output", 0, "json")
+ expect(output).to eq("button" => "approve")
+ end
+ end
+
+ context "when the action id is blank" do
+ let(:params) { { action_id: "" } }
+
+ it { is_expected.to fail_a_contract }
+ end
+
+ context "when the action id is unknown" do
+ let(:params) { { action_id: "999:approve:deadbeef" } }
+
+ it { is_expected.to fail_to_find_a_model(:resume_request) }
+ end
+
+ context "when the action is not one of the configured buttons" do
+ let(:params) { { action_id: action_id("delete") } }
+
+ it { is_expected.to fail_to_find_a_model(:resume_request) }
+ end
+
+ context "when the execution was already resumed" do
+ before { described_class.call(params:, **dependencies) }
+
+ it "no longer finds a waiting execution to resume" do
+ expect(execution.reload.status).to eq("success")
+ is_expected.to fail_to_find_a_model(:resume_request)
+ end
+ end
+ end
+end
diff --git a/plugins/discourse-workflows/test/javascripts/acceptance/workflows-user-modal-test.js b/plugins/discourse-workflows/test/javascripts/acceptance/workflows-user-modal-test.js
new file mode 100644
index 00000000000..fb5012a7fff
--- /dev/null
+++ b/plugins/discourse-workflows/test/javascripts/acceptance/workflows-user-modal-test.js
@@ -0,0 +1,112 @@
+import { click, settled, visit } from "@ember/test-helpers";
+import { test } from "qunit";
+import {
+ acceptance,
+ loggedInUser,
+ publishToMessageBus,
+} from "discourse/tests/helpers/qunit-helpers";
+
+acceptance("Discourse Workflows | User modal", function (needs) {
+ // Present only when a published workflow uses a modal node; gates the
+ // subscription and provides the channel's starting message-bus id.
+ needs.user({ discourse_workflows_user_modal_last_id: 0 });
+
+ let lastRequestBody = null;
+
+ needs.pretender((server, helper) => {
+ server.post("/discourse-workflows/modal-responses", (request) => {
+ lastRequestBody = request.requestBody;
+ return helper.response({});
+ });
+ });
+
+ needs.hooks.beforeEach(() => (lastRequestBody = null));
+
+ function channel() {
+ return `/discourse-workflows/user-modal/${loggedInUser().id}`;
+ }
+
+ const payload = {
+ type: "show_modal",
+ title: "Approve topic?",
+ body: "Please choose an option",
+ buttons: [
+ {
+ label: "Approve",
+ value: "approve",
+ style: "primary",
+ action_id: "1:approve:sig-approve",
+ },
+ {
+ label: "Reject",
+ value: "reject",
+ style: "danger",
+ action_id: "1:reject:sig-reject",
+ },
+ ],
+ };
+
+ test("opens a modal with the configured title, body, and buttons", async function (assert) {
+ await visit("/");
+ await publishToMessageBus(channel(), payload);
+ await settled();
+
+ assert.dom(".workflows-user-modal").exists("the modal opens");
+ assert.dom(".d-modal__title-text").hasText("Approve topic?");
+ assert
+ .dom(".workflows-user-modal__body")
+ .hasText("Please choose an option");
+ assert
+ .dom(".d-modal__footer .btn")
+ .exists({ count: 2 }, "renders one button per configured option");
+ assert.dom(".d-modal__footer .btn-primary").hasText("Approve");
+ assert.dom(".d-modal__footer .btn-danger").hasText("Reject");
+ });
+
+ test("posts the chosen button's action id and closes the modal", async function (assert) {
+ await visit("/");
+ await publishToMessageBus(channel(), payload);
+ await settled();
+
+ await click(".d-modal__footer .btn-primary");
+
+ assert.strictEqual(
+ new URLSearchParams(lastRequestBody).get("action_id"),
+ "1:approve:sig-approve",
+ "submits the action id of the clicked button"
+ );
+ assert.dom(".workflows-user-modal").doesNotExist("the modal closes");
+ });
+
+ test("ignores message bus payloads of other types", async function (assert) {
+ await visit("/");
+ await publishToMessageBus(channel(), { type: "something_else" });
+ await settled();
+
+ assert.dom(".workflows-user-modal").doesNotExist("no modal is opened");
+ });
+});
+
+acceptance(
+ "Discourse Workflows | User modal (feature unused)",
+ function (needs) {
+ // No `discourse_workflows_user_modal_last_id` on the user: no published
+ // workflow uses a modal node, so the initializer must not subscribe.
+ needs.user();
+
+ test("does not subscribe when no workflow uses a modal node", async function (assert) {
+ await visit("/");
+ await publishToMessageBus(
+ `/discourse-workflows/user-modal/${loggedInUser().id}`,
+ {
+ type: "show_modal",
+ title: "Should not appear",
+ buttons: [],
+ }
+ );
+ await settled();
+
+ assert.dom(".workflows-user-modal").doesNotExist("no modal is opened");
+ });
+ }
+);