Skip to content

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

FIX: Close workflow modals in every tab once handled (#42651)

Régis Hanola8e449a1345c
diff --git a/plugins/discourse-workflows/app/controllers/discourse_workflows/modal_dismissals_controller.rb b/plugins/discourse-workflows/app/controllers/discourse_workflows/modal_dismissals_controller.rb
new file mode 100644
index 00000000000..42608810c48
--- /dev/null
+++ b/plugins/discourse-workflows/app/controllers/discourse_workflows/modal_dismissals_controller.rb
@@ -0,0 +1,33 @@
+# frozen_string_literal: true
+
+module DiscourseWorkflows
+ class ModalDismissalsController < ::ApplicationController
+ requires_plugin DiscourseWorkflows::PLUGIN_NAME
+
+ before_action :ensure_logged_in
+ before_action :check_rate_limit
+
+ def create
+ DiscourseWorkflows::Modal::Dismiss.call(service_params) do
+ on_success { head :no_content }
+ on_failed_contract do |contract|
+ render(
+ json: failed_json.merge(errors: contract.errors.full_messages),
+ status: :bad_request,
+ )
+ end
+ end
+ end
+
+ private
+
+ def check_rate_limit
+ RateLimiter.new(
+ current_user,
+ "workflow_modal_dismiss:#{request.remote_ip}",
+ 10,
+ 60,
+ ).performed!
+ end
+ end
+end
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
index 6a1c7753cc7..c85b4a0891c 100644
--- a/plugins/discourse-workflows/app/controllers/discourse_workflows/modal_responses_controller.rb
+++ b/plugins/discourse-workflows/app/controllers/discourse_workflows/modal_responses_controller.rb
@@ -5,19 +5,31 @@ module DiscourseWorkflows
requires_plugin DiscourseWorkflows::PLUGIN_NAME
before_action :ensure_logged_in
+ before_action :check_rate_limit
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 }
+ on_model_not_found(:payload) { raise Discourse::NotFound }
+ on_failed_policy(:targets_current_user) { raise Discourse::NotFound }
end
end
+
+ private
+
+ def check_rate_limit
+ RateLimiter.new(
+ current_user,
+ "workflow_modal_respond:#{request.remote_ip}",
+ 10,
+ 60,
+ ).performed!
+ end
end
end
diff --git a/plugins/discourse-workflows/app/services/discourse_workflows/modal/dismiss.rb b/plugins/discourse-workflows/app/services/discourse_workflows/modal/dismiss.rb
new file mode 100644
index 00000000000..a5fe59c5b9a
--- /dev/null
+++ b/plugins/discourse-workflows/app/services/discourse_workflows/modal/dismiss.rb
@@ -0,0 +1,25 @@
+# frozen_string_literal: true
+
+module DiscourseWorkflows
+ class Modal::Dismiss
+ include Service::Base
+
+ params do
+ attribute :modal_id, :string
+
+ validates :modal_id,
+ presence: true,
+ length: {
+ maximum: DiscourseWorkflows::Nodes::Modal::V1::MODAL_ID_MAX_LENGTH,
+ }
+ end
+
+ step :close_modal_in_all_tabs
+
+ private
+
+ def close_modal_in_all_tabs(params:, guardian:)
+ DiscourseWorkflows::Nodes::Modal::V1.publish_close(guardian.user.id, params.modal_id)
+ end
+ end
+end
diff --git a/plugins/discourse-workflows/app/services/discourse_workflows/modal/respond.rb b/plugins/discourse-workflows/app/services/discourse_workflows/modal/respond.rb
index 34acf970a17..828a8e0ca28 100644
--- a/plugins/discourse-workflows/app/services/discourse_workflows/modal/respond.rb
+++ b/plugins/discourse-workflows/app/services/discourse_workflows/modal/respond.rb
@@ -8,43 +8,76 @@ module DiscourseWorkflows
params do
attribute :action_id, :string
+ attribute :modal_id, :string
validates :action_id, presence: true
+ validates :modal_id,
+ length: {
+ maximum: DiscourseWorkflows::Nodes::Modal::V1::MODAL_ID_MAX_LENGTH,
+ }
end
- model :resume_request
- step :resume
+ model :payload
+ policy :targets_current_user
+ # The token is bound to the resume token consumed on resume, so a click on
+ # a leftover copy of an already-handled modal matches nothing — treat that
+ # as success (clean up the copies) rather than a misleading 404.
+ model :resume_request, optional: true
+ only_if(:resume_request_present?) { step :resume }
+ # After the resume, so an error raised while resuming leaves the other
+ # tabs' copies open — they are the only remaining way to answer.
+ only_if(:modal_id_present?) { step :close_modal_in_all_tabs }
private
- def fetch_resume_request(params:, guardian:)
- payload = DiscourseWorkflows::InteractiveResume.action_payload(params.action_id)
- return if payload.blank?
+ def fetch_payload(params:)
+ DiscourseWorkflows::InteractiveResume.action_payload(params.action_id)
+ end
+
+ def targets_current_user(payload:, guardian:)
+ payload["target_user_id"].present? && payload["target_user_id"] == guardian.user&.id
+ end
+ def fetch_resume_request(params:, payload:)
+ # Node checks inlined: find_waiting_node re-parses the snapshot per call.
execution =
- DiscourseWorkflows::Execution.find_by(id: payload["execution_id"], status: :waiting)
+ DiscourseWorkflows::WaitingExecution.find_by_action_token(
+ params.action_id,
+ expected_node_type: nil,
+ )
return if execution.blank?
waiting_node = execution.find_waiting_node
return unless waiting_node && waiting_node["type"] == NODE_TYPE
- resume_request =
- DiscourseWorkflows::InteractiveResume.from_action_id(
- params.action_id,
- expected_node_type: NODE_TYPE,
- allowed_actions:
- DiscourseWorkflows::Nodes::Modal::V1.button_values(waiting_node["parameters"]),
- )
- return if resume_request.blank?
- return if resume_request.target_user_id.blank?
- return if resume_request.target_user_id != guardian.user&.id
+ action = payload["action"]
+ allowed_actions =
+ DiscourseWorkflows::Nodes::Modal::V1.button_values(waiting_node["parameters"])
+ return if allowed_actions.exclude?(action)
+
+ DiscourseWorkflows::InteractiveResume::Request.new(
+ execution:,
+ action:,
+ target_user_id: payload["target_user_id"],
+ )
+ end
+
+ def resume_request_present?(resume_request:)
+ resume_request.present?
+ end
+
+ def modal_id_present?(params:)
+ params.modal_id.present?
+ end
- resume_request
+ def close_modal_in_all_tabs(params:, guardian:)
+ DiscourseWorkflows::Nodes::Modal::V1.publish_close(guardian.user.id, params.modal_id)
end
def resume(resume_request:, guardian:)
claimed = resume_request.claim
- fail!(I18n.t("discourse_workflows.errors.already_resumed")) if claimed.blank?
+ # Another tab or device answered first; the modal was handled either way.
+ return if claimed.blank?
claimed.resume!(
DiscourseWorkflows::Nodes::Modal::V1.response_items(action: resume_request.action),
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
index e09c9cef60e..fc97baac6ee 100644
--- a/plugins/discourse-workflows/assets/javascripts/discourse/components/workflows-user-modal.gjs
+++ b/plugins/discourse-workflows/assets/javascripts/discourse/components/workflows-user-modal.gjs
@@ -34,12 +34,35 @@ export default class WorkflowsUserModal extends Component {
try {
await ajax("/discourse-workflows/modal-responses", {
type: "POST",
- data: { action_id: button.action_id },
+ data: {
+ action_id: button.action_id,
+ modal_id: this.args.model.modal_id,
+ },
});
- this.args.closeModal();
} catch (e) {
+ // Deliberately unguarded: the dialog is global, unlike closeModal below.
popupAjaxError(e);
this.submitting = false;
+ return;
+ }
+
+ // While awaiting, the server's close_modal broadcast may have already
+ // closed this modal — and the workflow may have shown the next one.
+ // Closing again here would close that new modal instead.
+ if (!this.isDestroying && !this.isDestroyed) {
+ this.args.closeModal();
+ }
+ }
+
+ @action
+ propagateDismissal() {
+ // Not while a response is in flight: if it fails, the copies in the
+ // other tabs are the only place the modal can still be answered.
+ if (this.args.model.modal_id && !this.submitting) {
+ ajax("/discourse-workflows/modal-dismissals", {
+ type: "POST",
+ data: { modal_id: this.args.model.modal_id },
+ }).catch(() => {});
}
}
@@ -47,6 +70,7 @@ export default class WorkflowsUserModal extends Component {
<DModal
@title={{@model.title}}
@closeModal={{@closeModal}}
+ @beforeClose={{this.propagateDismissal}}
class="workflows-user-modal"
>
<:body>
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
index 6ef7ba70b82..c8140a22ef7 100644
--- a/plugins/discourse-workflows/assets/javascripts/discourse/initializers/workflows-user-modal.js
+++ b/plugins/discourse-workflows/assets/javascripts/discourse/initializers/workflows-user-modal.js
@@ -1,5 +1,13 @@
+import { next } from "@ember/runloop";
+import discourseLater from "discourse/lib/later";
import WorkflowsUserModal from "../components/workflows-user-modal";
+// modal.show() only activates a modal once core's keyboard-close wait is
+// over (capped at 1s in discourse/lib/wait-for-keyboard), so a close landing
+// in that window finds nothing to close and is retried once after the cap.
+// Must stay above it.
+const CLOSE_RECHECK_MS = 1500;
+
export default {
name: "discourse-workflows-user-modal",
@@ -20,11 +28,44 @@ export default {
const modal = container.lookup("service:modal");
const channel = `/discourse-workflows/user-modal/${currentUser.id}`;
+ let pendingShow = null;
+
+ const closeIfActive = (modalId) => {
+ const active = modal.activeModal;
+ if (
+ active?.component === WorkflowsUserModal &&
+ active.opts?.model?.modal_id === modalId
+ ) {
+ modal.close();
+ return true;
+ }
+ return false;
+ };
+
messageBus.subscribe(
channel,
(data) => {
if (data?.type === "show_modal") {
- modal.show(WorkflowsUserModal, { model: data });
+ pendingShow = data;
+ // Deferred so that a close_modal delivered in the same poll batch
+ // (a tab reconnecting after the modal was handled elsewhere) can
+ // cancel the show instead of leaving a stale modal behind.
+ next(() => {
+ if (pendingShow === data) {
+ pendingShow = null;
+ modal.show(WorkflowsUserModal, { model: data });
+ }
+ });
+ } else if (data?.type === "close_modal" && data.modal_id) {
+ if (pendingShow?.modal_id === data.modal_id) {
+ pendingShow = null;
+ } else if (!closeIfActive(data.modal_id)) {
+ // Safe to fire late — ids are unique per show.
+ discourseLater(
+ () => closeIfActive(data.modal_id),
+ CLOSE_RECHECK_MS
+ );
+ }
}
},
lastId
diff --git a/plugins/discourse-workflows/config/routes.rb b/plugins/discourse-workflows/config/routes.rb
index e800311021a..d41021ead30 100644
--- a/plugins/discourse-workflows/config/routes.rb
+++ b/plugins/discourse-workflows/config/routes.rb
@@ -94,6 +94,7 @@ DiscourseWorkflows::Engine.routes.draw do
post "/trigger-topic-admin-button" => "topic_admin_button#create"
post "/trigger-post-button" => "post_button#create"
post "/modal-responses" => "modal_responses#create"
+ post "/modal-dismissals" => "modal_dismissals#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
index 498bffa547c..05d56dfda08 100644
--- a/plugins/discourse-workflows/lib/discourse_workflows/nodes/modal/v1.rb
+++ b/plugins/discourse-workflows/lib/discourse_workflows/nodes/modal/v1.rb
@@ -7,6 +7,7 @@ module DiscourseWorkflows
USER_CHANNEL_PREFIX = "/discourse-workflows/user-modal"
BUTTON_STYLES = %w[default primary danger].freeze
DEFAULT_BUTTON_STYLE = "default"
+ MODAL_ID_MAX_LENGTH = 100
description(
name: "action:modal",
@@ -76,6 +77,14 @@ module DiscourseWorkflows
"#{USER_CHANNEL_PREFIX}/#{user_id}"
end
+ def self.publish_close(user_id, modal_id)
+ MessageBus.publish(
+ user_channel(user_id),
+ { type: "close_modal", modal_id: modal_id },
+ user_ids: [user_id],
+ )
+ end
+
def self.button_rows(parameters)
DiscourseWorkflows::CollectionParameters.rows_from_value(
DiscourseWorkflows::CollectionParameters.fetch_value(parameters, :buttons),
@@ -98,6 +107,8 @@ module DiscourseWorkflows
self.class.user_channel(target_user.id),
{
type: "show_modal",
+ # Unique per show: close_modal must only dismiss this exact prompt.
+ modal_id: SecureRandom.hex(8),
title: exec_ctx.get_node_parameter("title", 0).to_s,
body: exec_ctx.get_node_parameter("body", 0).to_s,
buttons: buttons,
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
index f9c3491e1ff..abcfb72baaa 100644
--- a/plugins/discourse-workflows/spec/lib/discourse_workflows/nodes/modal_spec.rb
+++ b/plugins/discourse-workflows/spec/lib/discourse_workflows/nodes/modal_spec.rb
@@ -51,6 +51,7 @@ RSpec.describe DiscourseWorkflows::Nodes::Modal::V1 do
message = messages.first
expect(message.user_ids).to eq([user.id])
expect(message.data[:type]).to eq("show_modal")
+ expect(message.data[:modal_id]).to match(/\A\h{16}\z/)
expect(message.data[:title]).to eq("Approve topic?")
expect(message.data[:body]).to eq("Please choose an option")
@@ -140,6 +141,20 @@ RSpec.describe DiscourseWorkflows::Nodes::Modal::V1 do
end
end
+ describe ".publish_close" do
+ it "tells every tab of the target user to close the modal" do
+ messages =
+ MessageBus.track_publish(described_class.user_channel(user.id)) do
+ described_class.publish_close(user.id, "abcd1234abcd1234")
+ end
+
+ expect(messages.size).to eq(1)
+ message = messages.first
+ expect(message.user_ids).to eq([user.id])
+ expect(message.data).to eq(type: "close_modal", modal_id: "abcd1234abcd1234")
+ 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])
diff --git a/plugins/discourse-workflows/spec/requests/discourse_workflows/modal_dismissals_controller_spec.rb b/plugins/discourse-workflows/spec/requests/discourse_workflows/modal_dismissals_controller_spec.rb
new file mode 100644
index 00000000000..b71707ec34c
--- /dev/null
+++ b/plugins/discourse-workflows/spec/requests/discourse_workflows/modal_dismissals_controller_spec.rb
@@ -0,0 +1,43 @@
+# frozen_string_literal: true
+
+RSpec.describe DiscourseWorkflows::ModalDismissalsController do
+ fab!(:user)
+
+ let(:modal_id) { "abcd1234abcd1234" }
+
+ describe "POST /discourse-workflows/modal-dismissals" do
+ it "requires authentication" do
+ post "/discourse-workflows/modal-dismissals.json", params: { modal_id: }
+
+ expect(response).to have_http_status(:forbidden)
+ end
+
+ context "when signed in" do
+ before { sign_in(user) }
+
+ it "returns 204 and closes the user's copies of the modal" do
+ messages =
+ MessageBus.track_publish(DiscourseWorkflows::Nodes::Modal::V1.user_channel(user.id)) do
+ post "/discourse-workflows/modal-dismissals.json", params: { modal_id: }
+ end
+
+ expect(response).to have_http_status(:no_content)
+ expect(messages.size).to eq(1)
+ end
+
+ it "returns 400 for a blank modal id" do
+ post "/discourse-workflows/modal-dismissals.json", params: { modal_id: "" }
+
+ expect(response).to have_http_status(:bad_request)
+ end
+
+ it "is rate limited" do
+ RateLimiter.any_instance.expects(:performed!).raises(RateLimiter::LimitExceeded.new(60))
+
+ post "/discourse-workflows/modal-dismissals.json", params: { modal_id: }
+
+ expect(response).to have_http_status(:too_many_requests)
+ end
+ end
+ end
+end
diff --git a/plugins/discourse-workflows/spec/requests/discourse_workflows/modal_responses_controller_spec.rb b/plugins/discourse-workflows/spec/requests/discourse_workflows/modal_responses_controller_spec.rb
new file mode 100644
index 00000000000..c6010103b74
--- /dev/null
+++ b/plugins/discourse-workflows/spec/requests/discourse_workflows/modal_responses_controller_spec.rb
@@ -0,0 +1,128 @@
+# frozen_string_literal: true
+
+RSpec.describe DiscourseWorkflows::ModalResponsesController do
+ fab!(:user)
+ fab!(:other_user, :user)
+
+ 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?",
+ "target_user" => user.username,
+ "buttons" => {
+ "values" => [
+ { "label" => "Approve", "value" => "approve", "style" => "primary" },
+ ],
+ },
+ }
+ g.chain "trigger-1", "modal-1"
+ end
+ Fabricate(:discourse_workflows_workflow, name: "Published", published: true, **graph)
+ end
+
+ let(:execution) do
+ DiscourseWorkflows::Executor.new(
+ workflow,
+ "trigger-1",
+ {},
+ DiscourseWorkflows::Executor::ExecutionOptions.new(user: user),
+ ).run
+ end
+
+ let(:action_id) do
+ DiscourseWorkflows::InteractiveResume.action_id(
+ execution_id: execution.id,
+ resume_token: execution.resume_token,
+ action: "approve",
+ target_user_id: user.id,
+ )
+ end
+ let(:modal_id) { "abcd1234abcd1234" }
+
+ describe "POST /discourse-workflows/modal-responses" do
+ it "requires authentication" do
+ post "/discourse-workflows/modal-responses.json", params: { action_id:, modal_id: }
+
+ expect(response).to have_http_status(:forbidden)
+ end
+
+ context "when signed in as the modal's target user" do
+ before { sign_in(user) }
+
+ it "returns 204 and resumes the execution" do
+ post "/discourse-workflows/modal-responses.json", params: { action_id:, modal_id: }
+
+ expect(response).to have_http_status(:no_content)
+ expect(execution.reload.status).to eq("success")
+ end
+
+ it "returns 204 when the modal was already handled" do
+ post "/discourse-workflows/modal-responses.json", params: { action_id:, modal_id: }
+ expect(response).to have_http_status(:no_content)
+
+ post "/discourse-workflows/modal-responses.json", params: { action_id:, modal_id: }
+ expect(response).to have_http_status(:no_content)
+ end
+
+ it "acknowledges a token with a forged signature without resuming anything" do
+ post "/discourse-workflows/modal-responses.json",
+ params: {
+ action_id: "#{execution.id}:#{user.id}:approve:forged-signature",
+ modal_id:,
+ }
+
+ # Indistinguishable from a stale token by design (uniform response, no
+ # oracle); the crucial guarantee is that the execution is untouched.
+ expect(response).to have_http_status(:no_content)
+ expect(execution.reload.status).to eq("waiting")
+ end
+
+ it "returns 404 for a token that does not parse" do
+ post "/discourse-workflows/modal-responses.json",
+ params: {
+ action_id: "not-a-token",
+ modal_id:,
+ }
+
+ expect(response).to have_http_status(:not_found)
+ end
+
+ it "returns 400 for a blank action id" do
+ post "/discourse-workflows/modal-responses.json", params: { action_id: "", modal_id: }
+
+ expect(response).to have_http_status(:bad_request)
+ end
+
+ it "is rate limited" do
+ RateLimiter.any_instance.expects(:performed!).raises(RateLimiter::LimitExceeded.new(60))
+
+ # A static token: the rate limit check runs before the token is even
+ # parsed, and building a real one would run the executor's own
+ # rate-limited code under the mock above.
+ post "/discourse-workflows/modal-responses.json",
+ params: {
+ action_id: "1:1:approve:sig",
+ modal_id:,
+ }
+
+ expect(response).to have_http_status(:too_many_requests)
+ end
+ end
+
+ context "when signed in as another user" do
+ before { sign_in(other_user) }
+
+ it "returns 404 and leaves the execution waiting" do
+ post "/discourse-workflows/modal-responses.json", params: { action_id:, modal_id: }
+
+ expect(response).to have_http_status(:not_found)
+ expect(execution.reload.status).to eq("waiting")
+ end
+ end
+ end
+end
diff --git a/plugins/discourse-workflows/spec/services/discourse_workflows/modal/dismiss_spec.rb b/plugins/discourse-workflows/spec/services/discourse_workflows/modal/dismiss_spec.rb
new file mode 100644
index 00000000000..8c51a938e0c
--- /dev/null
+++ b/plugins/discourse-workflows/spec/services/discourse_workflows/modal/dismiss_spec.rb
@@ -0,0 +1,45 @@
+# frozen_string_literal: true
+
+RSpec.describe DiscourseWorkflows::Modal::Dismiss do
+ describe described_class::Contract, type: :model do
+ it { is_expected.to validate_presence_of(:modal_id) }
+
+ it do
+ is_expected.to validate_length_of(:modal_id).is_at_most(
+ DiscourseWorkflows::Nodes::Modal::V1::MODAL_ID_MAX_LENGTH,
+ )
+ end
+ end
+
+ describe ".call" do
+ subject(:result) { described_class.call(params:, **dependencies) }
+
+ fab!(:user)
+
+ let(:dependencies) { { guardian: user.guardian } }
+ let(:modal_id) { "abcd1234abcd1234" }
+ let(:params) { { modal_id: } }
+
+ context "when the modal id is valid" do
+ it { is_expected.to run_successfully }
+
+ it "tells every tab of the user to close their copies of the modal" do
+ messages =
+ MessageBus.track_publish(DiscourseWorkflows::Nodes::Modal::V1.user_channel(user.id)) do
+ result
+ end
+
+ expect(messages.size).to eq(1)
+ message = messages.first
+ expect(message.user_ids).to eq([user.id])
+ expect(message.data).to eq(type: "close_modal", modal_id: modal_id)
+ end
+ end
+
+ context "when the modal id is blank" do
+ let(:modal_id) { "" }
+
+ it { is_expected.to fail_a_contract }
+ 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
index 9ad13f76d3c..2e630aa6872 100644
--- a/plugins/discourse-workflows/spec/services/discourse_workflows/modal/respond_spec.rb
+++ b/plugins/discourse-workflows/spec/services/discourse_workflows/modal/respond_spec.rb
@@ -3,6 +3,12 @@
RSpec.describe DiscourseWorkflows::Modal::Respond do
describe described_class::Contract, type: :model do
it { is_expected.to validate_presence_of(:action_id) }
+
+ it do
+ is_expected.to validate_length_of(:modal_id).is_at_most(
+ DiscourseWorkflows::Nodes::Modal::V1::MODAL_ID_MAX_LENGTH,
+ )
+ end
end
describe ".call" do
@@ -21,7 +27,8 @@ RSpec.describe DiscourseWorkflows::Modal::Respond do
target_user_id:,
)
end
- let(:params) { { action_id: } }
+ let(:modal_id) { "abcd1234abcd1234" }
+ let(:params) { { action_id:, modal_id: } }
fab!(:workflow) do
graph =
@@ -46,8 +53,6 @@ RSpec.describe DiscourseWorkflows::Modal::Respond do
Fabricate(:discourse_workflows_workflow, name: "Published", published: true, **graph)
end
- before { allow(MessageBus).to receive(:publish) }
-
let!(:execution) do
DiscourseWorkflows::Executor.new(
workflow,
@@ -71,6 +76,51 @@ RSpec.describe DiscourseWorkflows::Modal::Respond do
output = execution.execution_data.entries.dig("modal-1", 0, "output", 0, "json")
expect(output).to eq("button" => "approve")
end
+
+ it "tells the user's other tabs to close their copies of the modal" do
+ messages =
+ MessageBus.track_publish(DiscourseWorkflows::Nodes::Modal::V1.user_channel(user.id)) do
+ result
+ end
+ close_messages = messages.select { |message| message.data[:type] == "close_modal" }
+
+ expect(close_messages.size).to eq(1)
+ expect(close_messages.first.user_ids).to eq([user.id])
+ expect(close_messages.first.data[:modal_id]).to eq(modal_id)
+ end
+ end
+
+ context "when no modal id is provided" do
+ let(:modal_id) { nil }
+
+ it { is_expected.to run_successfully }
+
+ it "resumes the execution without broadcasting a close" do
+ messages =
+ MessageBus.track_publish(DiscourseWorkflows::Nodes::Modal::V1.user_channel(user.id)) do
+ result
+ end
+
+ expect(messages).to be_empty
+ expect(execution.reload.status).to eq("success")
+ end
+ end
+
+ context "when another tab claims the resume first" do
+ before { allow(DiscourseWorkflows::Execution).to receive(:claim_for_resume).and_return(nil) }
+
+ it { is_expected.to run_successfully }
+
+ it "leaves the execution alone but still closes the modal copies" do
+ messages =
+ MessageBus.track_publish(DiscourseWorkflows::Nodes::Modal::V1.user_channel(user.id)) do
+ result
+ end
+ close_messages = messages.select { |message| message.data[:type] == "close_modal" }
+
+ expect(close_messages.size).to eq(1)
+ expect(execution.reload.status).to eq("waiting")
+ end
end
context "when the action id is blank" do
@@ -79,16 +129,26 @@ RSpec.describe DiscourseWorkflows::Modal::Respond do
it { is_expected.to fail_a_contract }
end
- context "when the action id is unknown" do
+ context "when the action id does not parse" do
let(:params) { { action_id: "999:approve:deadbeef" } }
- it { is_expected.to fail_to_find_a_model(:resume_request) }
+ it { is_expected.to fail_to_find_a_model(:payload) }
end
context "when the action is not one of the configured buttons" do
let(:action) { "delete" }
- it { is_expected.to fail_to_find_a_model(:resume_request) }
+ it { is_expected.to run_successfully }
+
+ it "acknowledges the response but leaves the execution waiting" do
+ messages =
+ MessageBus.track_publish(DiscourseWorkflows::Nodes::Modal::V1.user_channel(user.id)) do
+ result
+ end
+
+ expect(messages.map { |message| message.data[:type] }).to eq(["close_modal"])
+ expect(execution.reload.status).to eq("waiting")
+ end
end
context "when a user other than the modal target holds the token" do
@@ -96,7 +156,7 @@ RSpec.describe DiscourseWorkflows::Modal::Respond do
let(:dependencies) { { guardian: other_user.guardian } }
- it { is_expected.to fail_to_find_a_model(:resume_request) }
+ it { is_expected.to fail_a_policy(:targets_current_user) }
it "leaves the execution waiting instead of resuming it" do
described_class.call(params:, **dependencies)
@@ -108,9 +168,16 @@ RSpec.describe DiscourseWorkflows::Modal::Respond do
context "when the execution was already resumed" do
before { described_class.call(params:, **dependencies) }
- it "no longer finds a waiting execution to resume" do
+ it { is_expected.to run_successfully }
+
+ it "closes the leftover copies without touching the finished execution" do
+ messages =
+ MessageBus.track_publish(DiscourseWorkflows::Nodes::Modal::V1.user_channel(user.id)) do
+ result
+ end
+
+ expect(messages.map { |message| message.data[:type] }).to eq(["close_modal"])
expect(execution.reload.status).to eq("success")
- is_expected.to fail_to_find_a_model(:resume_request)
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
index fb5012a7fff..c646ace9a20 100644
--- a/plugins/discourse-workflows/test/javascripts/acceptance/workflows-user-modal-test.js
+++ b/plugins/discourse-workflows/test/javascripts/acceptance/workflows-user-modal-test.js
@@ -12,15 +12,23 @@ acceptance("Discourse Workflows | User modal", function (needs) {
needs.user({ discourse_workflows_user_modal_last_id: 0 });
let lastRequestBody = null;
+ let lastDismissalBody = null;
needs.pretender((server, helper) => {
server.post("/discourse-workflows/modal-responses", (request) => {
lastRequestBody = request.requestBody;
return helper.response({});
});
+ server.post("/discourse-workflows/modal-dismissals", (request) => {
+ lastDismissalBody = request.requestBody;
+ return helper.response({});
+ });
});
- needs.hooks.beforeEach(() => (lastRequestBody = null));
+ needs.hooks.beforeEach(() => {
+ lastRequestBody = null;
+ lastDismissalBody = null;
+ });
function channel() {
return `/discourse-workflows/user-modal/${loggedInUser().id}`;
@@ -28,6 +36,7 @@ acceptance("Discourse Workflows | User modal", function (needs) {
const payload = {
type: "show_modal",
+ modal_id: "abcd1234abcd1234",
title: "Approve topic?",
body: "Please choose an option",
buttons: [
@@ -70,12 +79,93 @@ acceptance("Discourse Workflows | User modal", function (needs) {
await click(".d-modal__footer .btn-primary");
+ const requestParams = new URLSearchParams(lastRequestBody);
assert.strictEqual(
- new URLSearchParams(lastRequestBody).get("action_id"),
+ requestParams.get("action_id"),
"1:approve:sig-approve",
"submits the action id of the clicked button"
);
+ assert.strictEqual(
+ requestParams.get("modal_id"),
+ "abcd1234abcd1234",
+ "submits the id of the modal instance"
+ );
assert.dom(".workflows-user-modal").doesNotExist("the modal closes");
+ assert.strictEqual(
+ lastDismissalBody,
+ null,
+ "responding does not also post a dismissal"
+ );
+ });
+
+ test("closes the modal when it is handled in another tab", async function (assert) {
+ await visit("/");
+ await publishToMessageBus(channel(), payload);
+ await settled();
+ assert.dom(".workflows-user-modal").exists("the modal opens");
+
+ await publishToMessageBus(channel(), {
+ type: "close_modal",
+ modal_id: payload.modal_id,
+ });
+ await settled();
+
+ assert
+ .dom(".workflows-user-modal")
+ .doesNotExist("the modal closes without user interaction");
+ });
+
+ test("never shows a modal whose close arrives in the same poll batch", async function (assert) {
+ await visit("/");
+
+ // No await between the two publishes: both message bus callbacks run in
+ // the same runloop, like a reconnecting tab replaying missed messages.
+ const show = publishToMessageBus(channel(), payload);
+ const close = publishToMessageBus(channel(), {
+ type: "close_modal",
+ modal_id: payload.modal_id,
+ });
+ await show;
+ await close;
+ await settled();
+
+ assert
+ .dom(".workflows-user-modal")
+ .doesNotExist("the batched close cancels the pending show");
+ });
+
+ test("ignores close_modal messages for other modal instances", async function (assert) {
+ await visit("/");
+ await publishToMessageBus(channel(), payload);
+ await settled();
+
+ await publishToMessageBus(channel(), {
+ type: "close_modal",
+ modal_id: "another-modal-id",
+ });
+ await settled();
+
+ assert.dom(".workflows-user-modal").exists("the modal stays open");
+ });
+
+ test("propagates a manual close to the user's other tabs", async function (assert) {
+ await visit("/");
+ await publishToMessageBus(channel(), payload);
+ await settled();
+
+ await click(".workflows-user-modal .modal-close");
+
+ assert.dom(".workflows-user-modal").doesNotExist("the modal closes");
+ assert.strictEqual(
+ new URLSearchParams(lastDismissalBody).get("modal_id"),
+ "abcd1234abcd1234",
+ "posts a dismissal for the modal instance"
+ );
+ assert.strictEqual(
+ lastRequestBody,
+ null,
+ "dismissing does not submit a button response"
+ );
});
test("ignores message bus payloads of other types", async function (assert) {