Skip to content

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

FEATURE: Add composer paused workflow trigger and composer message node (#45157)

Gabriel Grubba7936f7af6009
diff --git a/app/controllers/drafts_controller.rb b/app/controllers/drafts_controller.rb
index 90bccaa1b19..0b471fc6221 100644
--- a/app/controllers/drafts_controller.rb
+++ b/app/controllers/drafts_controller.rb
@@ -97,6 +97,8 @@ class DraftsController < ApplicationController
json = success_json.merge(draft_sequence: sequence)
+ DiscourseEvent.trigger(:draft_saved, current_user, params[:draft_key], data)
+
# check for conflicts when editing a post
if data.present? && data["postId"].present? && data["action"].to_s.start_with?("edit")
original_text = data["original_text"] || data["originalText"]
diff --git a/frontend/discourse/app/components/composer-body.js b/frontend/discourse/app/components/composer-body.js
index 017dd418d52..be0c6005c1b 100644
--- a/frontend/discourse/app/components/composer-body.js
+++ b/frontend/discourse/app/components/composer-body.js
@@ -10,6 +10,9 @@ import discourseDebounce from "discourse/lib/debounce";
import discourseLater from "discourse/lib/later";
import Composer from "discourse/models/composer";
+// A space or new line typed after the end of a sentence counts as a pause.
+const SENTENCE_END_REGEXP = /(?:[.!?]\s|\n)$/;
+
@classNameBindings(
"composer.creatingPrivateMessage:private-message",
"composeState",
@@ -29,6 +32,11 @@ export default class ComposerBody extends Component {
elementId = "reply-control";
+ #pausedComposer = null;
+ #pausedContent = null;
+ #typedComposer = null;
+ #typedReply = "";
+
@computed("composer.action")
get prefixedComposerAction() {
return this.composer?.action
@@ -55,6 +63,11 @@ export default class ComposerBody extends Component {
const lastKeyUp = new Date();
this._lastKeyUp = lastKeyUp;
+ const composer = this.composer;
+ if (this.#appendedSentenceEnd(composer)) {
+ this.#typingPaused(composer);
+ }
+
// One second from now, check to see if the last key was hit when
// we recorded it. If it was, the user paused typing.
cancel(this._lastKeyTimeout);
@@ -63,6 +76,10 @@ export default class ComposerBody extends Component {
return;
}
this.appEvents.trigger("composer:find-similar");
+
+ if (this.composer === composer) {
+ this.#typingPaused(composer);
+ }
}, 1000);
}
@@ -116,6 +133,36 @@ export default class ComposerBody extends Component {
}
}
+ // Only an edit at the end counts, so editing earlier text in a reply that
+ // already ends a sentence doesn't fire on every key.
+ #appendedSentenceEnd(composer) {
+ const reply = composer?.reply || "";
+ const previous = composer === this.#typedComposer ? this.#typedReply : "";
+
+ this.#typedComposer = composer;
+ this.#typedReply = reply;
+
+ return (
+ reply.length > previous.length &&
+ reply.startsWith(previous) &&
+ SENTENCE_END_REGEXP.test(reply)
+ );
+ }
+
+ #typingPaused(composer) {
+ const content = `${composer?.title}\n${composer?.reply}`;
+
+ // Only pauses after an edit count, so a sentence end and the idle timer
+ // that follows it fire once.
+ if (composer === this.#pausedComposer && content === this.#pausedContent) {
+ return;
+ }
+
+ this.#pausedComposer = composer;
+ this.#pausedContent = content;
+ this.appEvents.trigger("composer:typing-paused", composer);
+ }
+
@observes("composeState", "composer.{action,canEditTopicFeaturedLink}")
_triggerComposerResized() {
schedule("afterRender", () => {
diff --git a/frontend/discourse/tests/acceptance/composer-test.js b/frontend/discourse/tests/acceptance/composer-test.js
index c5c180a3118..59a8fc31a00 100644
--- a/frontend/discourse/tests/acceptance/composer-test.js
+++ b/frontend/discourse/tests/acceptance/composer-test.js
@@ -2280,3 +2280,78 @@ acceptance(`composer buttons API`, function (needs) {
);
});
});
+
+acceptance("Composer - Typing paused", function (needs) {
+ needs.user();
+ needs.settings({ allow_uncategorized_topics: true });
+
+ function trackPauses(owner) {
+ const paused = [];
+ owner
+ .lookup("service:app-events")
+ .on("composer:typing-paused", (composer) => paused.push(composer.reply));
+ return paused;
+ }
+
+ test("fires once the user pauses after an edit", async function (assert) {
+ await visit("/");
+ const paused = trackPauses(this.owner);
+ await click("#create-topic");
+ await fillIn(".d-editor-input", "Magic words");
+ await triggerKeyEvent(".d-editor-input", "keyup", "S");
+
+ assert.deepEqual(paused, ["Magic words"], "fires after the pause");
+
+ await triggerKeyEvent(".d-editor-input", "keyup", "ArrowLeft");
+ assert.deepEqual(paused, ["Magic words"], "ignores keys without edits");
+
+ await fillIn(".d-editor-input", "Magic words and more");
+ await triggerKeyEvent(".d-editor-input", "keyup", "E");
+ assert.deepEqual(
+ paused,
+ ["Magic words", "Magic words and more"],
+ "fires again after the next edit"
+ );
+ });
+
+ test("fires right away at the end of a sentence", async function (assert) {
+ await visit("/");
+ const paused = trackPauses(this.owner);
+ await click("#create-topic");
+ await fillIn(".d-editor-input", "Food stand. ");
+
+ // Dispatched directly so the assertion runs before the pause timer.
+ document
+ .querySelector(".d-editor-input")
+ .dispatchEvent(new KeyboardEvent("keyup", { key: " ", bubbles: true }));
+ assert.deepEqual(paused, ["Food stand. "], "fires immediately");
+
+ await settled();
+ assert.deepEqual(
+ paused,
+ ["Food stand. "],
+ "the pause that follows doesn't fire again"
+ );
+ });
+
+ test("editing earlier text waits for the pause", async function (assert) {
+ await visit("/");
+ const paused = trackPauses(this.owner);
+ await click("#create-topic");
+ await fillIn(".d-editor-input", "Hello world.\n");
+ await triggerKeyEvent(".d-editor-input", "keyup", "Enter");
+
+ await fillIn(".d-editor-input", "Hey, hello world.\n");
+ document
+ .querySelector(".d-editor-input")
+ .dispatchEvent(new KeyboardEvent("keyup", { key: "y", bubbles: true }));
+ assert.deepEqual(paused, ["Hello world.\n"], "doesn't fire right away");
+
+ await settled();
+ assert.deepEqual(
+ paused,
+ ["Hello world.\n", "Hey, hello world.\n"],
+ "fires after the pause"
+ );
+ });
+});
diff --git a/plugins/discourse-workflows/USE_CASES.md b/plugins/discourse-workflows/USE_CASES.md
index 50d0c68046d..97be48c2bd0 100644
--- a/plugins/discourse-workflows/USE_CASES.md
+++ b/plugins/discourse-workflows/USE_CASES.md
@@ -38,6 +38,7 @@ For each run, record:
| --- | --- | --- | --- |
| `post-staff-exclusion` | `when a non-staff user posts in General and the post contains urgent, send a message to General chat with a link to the post` | `trigger:post_created -> condition:filter -> action:send_chat_message` | Uses boolean filter on `$json.user.staff` plus string contains on `$json.post.raw`; no Code node. |
| `topic-created-category-chat` | `when a new topic is created in Support by a TL0 user, message General chat with the topic title and post link` | `trigger:topic_created -> condition:filter -> action:send_chat_message` | Uses `$json.user.trust_level == 0`, `$json.topic.title`, `$json.post.post_url`. |
+| `composer-phrase-nudge` | `while someone writes a new topic or reply mentioning food stand, show them a tip above the composer linking to the Food category` | `trigger:composer_paused -> action:composer_message` | Puts the phrase in the trigger's `phrases` (watched word syntax) instead of a filter on `$json.composer.raw`; keeps `fire_on: pause`; the message body links the category in markdown. `action:composer_message` only works after `trigger:composer_paused`. |
| `closed-topic-no-author-filter` | `when any topic in General is closed, message General chat with a link to the topic` | `trigger:topic_closed -> action:send_chat_message` or `trigger:topic_closed -> action:topic (get) -> action:send_chat_message` | If only topic link is needed, no author lookup is required; if post link is requested, use `action:topic` get. |
| `wait-chat-reminder` | `when a topic in Support is closed, wait 7 days and message General chat with the topic title` | `trigger:topic_closed -> flow:wait -> action:send_chat_message` | Wait parameters are `wait_amount: 7`, `wait_unit: days`; dynamic chat template starts with `=`. |
| `tag-only` | `when a new topic is created in Support, add the needs-review tag` | `trigger:topic_created -> action:topic_tags` | Resolves category/tag; no reply; no Code node. |
diff --git a/plugins/discourse-workflows/app/controllers/discourse_workflows/composer_paused_controller.rb b/plugins/discourse-workflows/app/controllers/discourse_workflows/composer_paused_controller.rb
new file mode 100644
index 00000000000..430aa395cee
--- /dev/null
+++ b/plugins/discourse-workflows/app/controllers/discourse_workflows/composer_paused_controller.rb
@@ -0,0 +1,37 @@
+# frozen_string_literal: true
+
+module DiscourseWorkflows
+ class ComposerPausedController < ::ApplicationController
+ requires_plugin DiscourseWorkflows::PLUGIN_NAME
+
+ before_action :ensure_logged_in
+ before_action :check_rate_limit
+
+ def create
+ DiscourseWorkflows::Workflow::TriggerComposerPaused.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
+ on_failed_step(:fire_triggers) { rate_limited! }
+ end
+ end
+
+ private
+
+ # The run limit only counts fired workflows, so this just turns away users who have none left.
+ def check_rate_limit
+ ComposerPausedClaims.attempt_rate_limiter(current_user).performed!
+ rate_limited! if !ComposerPausedClaims.rate_limiter(current_user).can_perform?
+ end
+
+ def rate_limited!
+ raise RateLimiter::LimitExceeded.new(
+ ComposerPausedClaims.rate_limiter(current_user).seconds_to_wait,
+ )
+ 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 da059ba82c9..3d7f822f4ca 100644
--- a/plugins/discourse-workflows/app/models/discourse_workflows/workflow_dependency.rb
+++ b/plugins/discourse-workflows/app/models/discourse_workflows/workflow_dependency.rb
@@ -73,6 +73,40 @@ module DiscourseWorkflows
end
end
+ # Serialized for every logged-in page load, so the compiled patterns are cached. Patterns
+ # depend on the watched words regex mode, which is part of the key.
+ def self.cached_composer_paused_triggers
+ trigger_class = DiscourseWorkflows::Nodes::ComposerPaused::V1
+ key = "composer_paused_triggers:#{SiteSetting.watched_words_regular_expressions}"
+
+ cache.defer_get_set(key) do
+ cached_published_triggers(trigger_class.identifier).filter_map do |published_trigger|
+ parameters = NodeData.parameters(published_trigger.trigger_node)
+ next if !trigger_class.fires_on?(parameters, trigger_class::PAUSE)
+
+ {
+ trigger_node_id: published_trigger.trigger_node_id,
+ workflow_id: published_trigger.workflow_id,
+ patterns: trigger_class.patterns(parameters),
+ composer_actions: trigger_class.composer_actions(parameters),
+ category_ids: trigger_class.normalize_ids(parameters["category_ids"]),
+ include_subcategories: parameters["include_subcategories"] != false,
+ group_ids: trigger_class.normalized_group_ids(parameters),
+ }
+ end
+ end
+ end
+
+ def self.composer_paused_triggers_for(user)
+ return [] if user.blank?
+
+ cached_composer_paused_triggers.filter_map do |trigger|
+ next if trigger[:group_ids].present? && !user.in_any_groups?(trigger[:group_ids])
+
+ trigger.except(:group_ids)
+ end
+ end
+
def self.active_node_types
cached_dependency_index[:active_node_types].to_set
end
@@ -86,9 +120,11 @@ module DiscourseWorkflows
end
def self.cached_user_modals?
- cached_dependency_index[:referenced_node_types].include?(
- DiscourseWorkflows::Nodes::Modal::V1.identifier,
- )
+ references_node_type?(DiscourseWorkflows::Nodes::Modal::V1.identifier)
+ end
+
+ def self.references_node_type?(identifier)
+ cached_dependency_index[:referenced_node_types].include?(identifier)
end
def self.workflows_referencing(type, key)
diff --git a/plugins/discourse-workflows/app/services/discourse_workflows/workflow/trigger_composer_paused.rb b/plugins/discourse-workflows/app/services/discourse_workflows/workflow/trigger_composer_paused.rb
new file mode 100644
index 00000000000..d82a9d41d28
--- /dev/null
+++ b/plugins/discourse-workflows/app/services/discourse_workflows/workflow/trigger_composer_paused.rb
@@ -0,0 +1,75 @@
+# frozen_string_literal: true
+
+module DiscourseWorkflows
+ # Fires every composer paused trigger the draft matches, so the browser sends one request per
+ # pause however many workflows it matched.
+ class Workflow::TriggerComposerPaused
+ include Service::Base
+
+ MAX_DRAFT_KEY_LENGTH = 100
+
+ params do
+ attribute :draft_key, :string
+ attribute :session_id, :string
+ attribute :composer_action, :string
+ attribute :title, :string
+ attribute :raw, :string
+ attribute :category_id, :integer
+ attribute :topic_id, :integer
+ attribute :reply_to_post_number, :integer
+
+ validates :draft_key, presence: true, length: { maximum: MAX_DRAFT_KEY_LENGTH }
+ validates :session_id,
+ presence: true,
+ length: {
+ maximum: ComposerSnapshot::MAX_SESSION_ID_LENGTH,
+ }
+ validates :composer_action, inclusion: { in: ComposerSnapshot::ACTIONS }
+ validates :topic_id, presence: true, if: -> { composer_action == ComposerSnapshot::REPLY }
+ validate :text_within_limits
+
+ def text_within_limits
+ errors.add(:title, :too_long) if title.to_s.length > SiteSetting.max_topic_title_length
+ errors.add(:raw, :too_long) if raw.to_s.length > SiteSetting.max_post_length
+ end
+ end
+
+ model :topic, optional: true
+ model :snapshot
+ step :fire_triggers
+
+ private
+
+ def fetch_topic(params:)
+ ::Topic.find_by(id: params.topic_id) if params.composer_action == ComposerSnapshot::REPLY
+ end
+
+ def fetch_snapshot(params:, topic:, guardian:)
+ ComposerSnapshot.new(
+ user: guardian.user,
+ action: params.composer_action,
+ draft_key: params.draft_key,
+ session_id: params.session_id,
+ title: params.title,
+ raw: params.raw,
+ category_id: params.category_id,
+ topic:,
+ reply_to_post_number: params.reply_to_post_number,
+ )
+ end
+
+ # The browser only asks after a match, but it is never trusted to have matched. Reopening the
+ # composer starts a new session, so its phrases can fire again.
+ def fire_triggers(params:, snapshot:, guardian:)
+ fired_all =
+ ComposerPausedDispatch.call(
+ ComposerPausedDispatch.published_triggers(Nodes::ComposerPaused::V1::PAUSE),
+ snapshot,
+ "session:#{guardian.user.id}:#{params.draft_key}:#{params.session_id}",
+ )
+
+ # The browser asks again later for what didn't fire, and claims keep the rest from firing twice.
+ fail!("rate limited") if !fired_all
+ end
+ end
+end
diff --git a/plugins/discourse-workflows/assets/javascripts/discourse/initializers/workflows-composer-message.js b/plugins/discourse-workflows/assets/javascripts/discourse/initializers/workflows-composer-message.js
new file mode 100644
index 00000000000..e18c39f7c53
--- /dev/null
+++ b/plugins/discourse-workflows/assets/javascripts/discourse/initializers/workflows-composer-message.js
@@ -0,0 +1,54 @@
+import { withPluginApi } from "discourse/lib/plugin-api";
+import { SESSION_ID_FIELD } from "../services/workflows-composer-session.js";
+
+export default {
+ name: "discourse-workflows-composer-message",
+
+ initialize(container) {
+ const currentUser = container.lookup("service:current-user");
+ const lastId = currentUser?.discourse_workflows_composer_message_last_id;
+
+ if (lastId === undefined || lastId === null) {
+ return;
+ }
+
+ const composer = container.lookup("service:composer");
+ const appEvents = container.lookup("service:app-events");
+ const session = container.lookup("service:workflows-composer-session");
+
+ withPluginApi((api) => api.serializeToDraft(SESSION_ID_FIELD));
+
+ // Before the first autosave, which carries the session to the server.
+ appEvents.on("composer:open", ({ model }) => {
+ if (model) {
+ session.idFor(model);
+ }
+ });
+
+ container.lookup("service:message-bus").subscribe(
+ `/discourse-workflows/composer-message/${currentUser.id}`,
+ (data) => {
+ const model = composer.model;
+
+ // The user may have posted, closed or switched drafts since pausing,
+ // or this may be another tab with the same draft.
+ if (
+ data?.type !== "show_composer_message" ||
+ !model?.viewOpenOrFullscreen ||
+ model.draftKey !== data.draft_key ||
+ session.idFor(model) !== data.session_id
+ ) {
+ return;
+ }
+
+ appEvents.trigger("composer-messages:create", {
+ extraClass: "workflows-composer-message",
+ templateName: "education",
+ title: data.title,
+ body: data.body,
+ });
+ },
+ lastId
+ );
+ },
+};
diff --git a/plugins/discourse-workflows/assets/javascripts/discourse/initializers/workflows-composer-paused.js b/plugins/discourse-workflows/assets/javascripts/discourse/initializers/workflows-composer-paused.js
new file mode 100644
index 00000000000..64af28b6824
--- /dev/null
+++ b/plugins/discourse-workflows/assets/javascripts/discourse/initializers/workflows-composer-paused.js
@@ -0,0 +1,23 @@
+export default {
+ name: "discourse-workflows-composer-paused",
+
+ initialize(container) {
+ const site = container.lookup("service:site");
+
+ if (!site.composer_paused_workflows?.length) {
+ return;
+ }
+
+ const composerPaused = container.lookup(
+ "service:workflows-composer-paused"
+ );
+
+ container
+ .lookup("service:app-events")
+ .on(
+ "composer:typing-paused",
+ composerPaused,
+ composerPaused.typingPaused
+ );
+ },
+};
diff --git a/plugins/discourse-workflows/assets/javascripts/discourse/lib/phrase-matcher.js b/plugins/discourse-workflows/assets/javascripts/discourse/lib/phrase-matcher.js
new file mode 100644
index 00000000000..d0f686595b9
--- /dev/null
+++ b/plugins/discourse-workflows/assets/javascripts/discourse/lib/phrase-matcher.js
@@ -0,0 +1,150 @@
+import { waitForPromise } from "@ember/test-waiters";
+
+const PATTERN_TIMEOUT_MS = 1000;
+// A busy device can stall a fast pattern once, so only a repeat offender is skipped.
+const TIMEOUTS_BEFORE_SKIPPING = 2;
+
+// Regular expression phrases may use syntax only the server supports, so those never match.
+const WORKER_SOURCE = `
+const regexps = new Map();
+
+onmessage = ({ data: { id, text, sources } }) => {
+ sources.forEach((source, index) => {
+ if (!regexps.has(source)) {
+ try {
+ regexps.set(source, new RegExp(source, "iu"));
+ } catch {
+ regexps.set(source, null);
+ }
+ }
+
+ postMessage({ id, index, matched: !!regexps.get(source)?.test(text) });
+ });
+};
+`;
+
+function createWorker() {
+ const url = URL.createObjectURL(
+ new Blob([WORKER_SOURCE], { type: "text/javascript" })
+ );
+
+ try {
+ return new Worker(url);
+ } finally {
+ URL.revokeObjectURL(url);
+ }
+}
+
+// Matches phrase patterns off the main thread, because a pattern that backtracks can run for
+// minutes. A pattern that keeps running past the timeout is skipped from then on.
+export default class PhraseMatcher {
+ #destroyed = false;
+ #lastId = 0;
+ #queue = Promise.resolve();
+ #timeouts = new Map();
+ #timeoutMs;
+ #worker = null;
+
+ constructor({ timeoutMs = PATTERN_TIMEOUT_MS } = {}) {
+ this.#timeoutMs = timeoutMs;
+ }
+
+ // Resolves to the set of sources that match the text.
+ match(text, sources) {
+ // Matches share one worker, so each waits for the one before it.
+ const result = this.#queue.then(() =>
+ this.#match(
+ text,
+ sources.filter((source) => !this.#isSkipped(source))
+ )
+ );
+ this.#queue = result.catch(() => {});
+ return waitForPromise(result);
+ }
+
+ destroy() {
+ this.#destroyed = true;
+ this.#stopWorker();
+ }
+
+ #isSkipped(source) {
+ return (this.#timeouts.get(source) ?? 0) >= TIMEOUTS_BEFORE_SKIPPING;
+ }
+
+ async #match(text, sources) {
+ if (!sources.length || this.#destroyed) {
+ return new Set();
+ }
+
+ const { matched, slowIndex } = await this.#run(text, sources);
+ if (slowIndex === null) {
+ return matched;
+ }
+
+ const slow = sources[slowIndex];
+ this.#timeouts.set(slow, (this.#timeouts.get(slow) ?? 0) + 1);
+ this.#stopWorker();
+
+ const rest = await this.#match(text, sources.slice(slowIndex + 1));
+ return new Set([...matched, ...rest]);
+ }
+
+ #stopWorker() {
+ this.#worker?.terminate();
+ this.#worker = null;
+ }
+
+ // The worker answers for each pattern in order, so the first missing answer is the slow one.
+ #run(text, sources) {
+ try {
+ this.#worker ??= createWorker();
+ } catch {
+ return Promise.resolve({ matched: new Set(), slowIndex: null });
+ }
+
+ const worker = this.#worker;
+ const id = ++this.#lastId;
+ const matched = new Set();
+ let answered = 0;
+ let timer;
+
+ return new Promise((resolve) => {
+ const finish = (slowIndex) => {
+ clearTimeout(timer);
+ worker.removeEventListener("message", onMessage);
+ worker.removeEventListener("error", onError);
+ resolve({ matched, slowIndex });
+ };
+ const waitForAnswer = () => {
+ clearTimeout(timer);
+ timer = setTimeout(() => finish(answered), this.#timeoutMs);
+ };
+ const onMessage = ({ data }) => {
+ if (data.id !== id) {
+ return;
+ }
+
+ if (data.matched) {
+ matched.add(sources[data.index]);
+ }
+ answered = data.index + 1;
+
+ if (answered === sources.length) {
+ finish(null);
+ } else {
+ waitForAnswer();
+ }
+ };
+ // A worker that can't start matches nothing rather than marking every pattern slow.
+ const onError = () => {
+ this.#stopWorker();
+ finish(null);
+ };
+
+ worker.addEventListener("message", onMessage);
+ worker.addEventListener("error", onError);
+ waitForAnswer();
+ worker.postMessage({ id, text, sources });
+ });
+ }
+}
diff --git a/plugins/discourse-workflows/assets/javascripts/discourse/services/workflows-composer-paused.js b/plugins/discourse-workflows/assets/javascripts/discourse/services/workflows-composer-paused.js
new file mode 100644
index 00000000000..b98fdf51d97
--- /dev/null
+++ b/plugins/discourse-workflows/assets/javascripts/discourse/services/workflows-composer-paused.js
@@ -0,0 +1,281 @@
+import Service, { service } from "@ember/service";
+import { ajax } from "discourse/lib/ajax";
+import Category from "discourse/models/category";
+import { CREATE_TOPIC, REPLY } from "discourse/models/composer";
+import PhraseMatcher from "../lib/phrase-matcher.js";
+
+// Without phrases, a trigger fires on pauses at most this often.
+const NO_PHRASES_INTERVAL_MS = 15000;
+// Attributes are capped so that a tag without its closing bracket can't make
+// scanning quadratic.
+const QUOTE_TAG_REGEXP = /\[quote(?:=[^\]]{0,300})?\]|\[\/quote\]/gi;
+const BLOCKQUOTE_LINE_REGEXP = /^[ \t]*>.*$/gm;
+const HTML_COMMENT_START = "<!--";
+const HTML_COMMENT_END = "-->";
+const COMPOSER_ACTIONS = { [CREATE_TOPIC]: "create_topic", [REPLY]: "reply" };
+// For failed requests that don't say how long to wait.
+const RETRY_AFTER_ERROR_MS = 15000;
+
+function stripHtmlComments(text) {
+ const parts = [];
+ let position = 0;
+ let start;
+
+ while ((start = text.indexOf(HTML_COMMENT_START, position)) !== -1) {
+ const end = text.indexOf(
+ HTML_COMMENT_END,
+ start + HTML_COMMENT_START.length
+ );
+ if (end === -1) {
+ break;
+ }
+
+ parts.push(text.slice(position, start));
+ position = end + HTML_COMMENT_END.length;
+ }
+
+ parts.push(text.slice(position));
+ return parts.join("");
+}
+
+// Removes balanced quote blocks, nested ones included, in one pass. An
+// unclosed quote is kept as text.
+function stripQuoteBlocks(text) {
+ const parts = [];
+ const openQuotes = [];
+ let position = 0;
+
+ for (const match of text.matchAll(QUOTE_TAG_REGEXP)) {
+ const tag = match[0];
+ parts.push(text.slice(position, match.index));
+ position = match.index + tag.length;
+
+ if (tag.startsWith("[/")) {
+ if (openQuotes.length) {
+ parts.length = openQuotes.pop();
+ } else {
+ parts.push(tag);
+ }
+ } else {
+ openQuotes.push(parts.length);
+ parts.push(tag);
+ }
+ }
+
+ parts.push(text.slice(position));
+ return parts.join("");
+}
+
+// Must match `ComposerSnapshot.own_text` on the server.
+export function ownText({ title, reply }) {
+ const body = stripQuoteBlocks(stripHtmlComments(reply || "")).replace(
+ BLOCKQUOTE_LINE_REGEXP,
+ ""
+ );
+
+ return [title, body].filter(Boolean).join("\n");
+}
+
+function composerAction(composer) {
+ const action = COMPOSER_ACTIONS[composer?.action];
+
+ // A restored reply loads its target post after opening.
+ if (
+ action &&
+ composer.viewOpenOrFullscreen &&
+ !composer.privateMessage &&
+ !composer.loading
+ ) {
+ return action;
+ }
+}
+
+function retryDelayMs(error) {
+ const waitSeconds = error?.jqXHR?.responseJSON?.extras?.wait_seconds;
+ return waitSeconds ? waitSeconds * 1000 : RETRY_AFTER_ERROR_MS;
+}
+
+function matchesCategory(trigger, categoryId) {
+ if (!trigger.category_ids.length) {
+ return true;
+ }
+
+ let category = Category.findById(categoryId);
+ if (!category) {
+ // Not loaded in the browser, so the server decides.
+ return !!categoryId;
+ }
+
+ if (!trigger.include_subcategories) {
+ return trigger.category_ids.includes(category.id);
+ }
+
+ while (category) {
+ if (trigger.category_ids.includes(category.id)) {
+ return true;
+ }
+ category = category.parentCategory;
+ }
+
+ return false;
+}
+
+export default class WorkflowsComposerPaused extends Service {
+ @service site;
+ @service siteSettings;
+ @service workflowsComposerSession;
+
+ #checking = false;
+ #matcher = new PhraseMatcher();
+ #nextComposer = null;
+ #retryAt = 0;
+ #sessions = new WeakMap();
+ #triggers = this.site.composer_paused_workflows || [];
+
+ willDestroy() {
+ super.willDestroy(...arguments);
+ this.#matcher.destroy();
+ }
+
+ // Pauses that come in during a check are folded into one check of the latest draft, so there
+ // is at most one request in flight.
+ async typingPaused(composer) {
+ this.#nextComposer = composer;
+ if (this.#checking) {
+ return;
+ }
+
+ this.#checking = true;
+ try {
+ while (this.#nextComposer) {
+ const next = this.#nextComposer;
+ this.#nextComposer = null;
+ await this.#check(next);
+ }
+ } finally {
+ this.#checking = false;
+ }
+ }
+
+ async #check(composer) {
+ const action = composerAction(composer);
+ if (!action || Date.now() < this.#retryAt) {
+ return;
+ }
+
+ // the server never matches past what a post can hold
+ const draft = {
+ title: composer.title?.slice(0, this.siteSettings.max_topic_title_length),
+ reply: composer.reply?.slice(0, this.siteSettings.max_post_length),
+ };
+ const text = ownText(draft);
+ const categoryId = composer.topic?.category_id ?? composer.categoryId;
+ const sessionId = this.workflowsComposerSession.idFor(composer);
+ const triggers = this.#triggers
+ .filter(
+ (trigger) =>
+ trigger.composer_actions.includes(action) &&
+ matchesCategory(trigger, categoryId)
+ )
+ .map((trigger) => ({
+ trigger,
+ state: this.#stateFor(composer, trigger),
+ }));
+
+ const unmatched = new Set(
+ triggers.flatMap(({ trigger, state }) =>
+ trigger.patterns.filter((source) => !state.matched.has(source))
+ )
+ );
+ const matched = await this.#matcher.match(text, [...unmatched]);
+
+ // The composer may have closed or reopened while matching.
+ if (
+ composerAction(composer) !== action ||
+ this.workflowsComposerSession.idFor(composer) !== sessionId
+ ) {
+ return;
+ }
+
+ const now = Date.now();
+ const newMatches = [];
+ const noPhraseStates = [];
+
+ for (const { trigger, state } of triggers) {
+ if (!trigger.patterns.length) {
+ noPhraseStates.push(state);
+ continue;
+ }
+
+ const sources = trigger.patterns.filter(
+ (source) => matched.has(source) && !state.matched.has(source)
+ );
+ if (sources.length) {
+ newMatches.push({ state, sources });
+ }
+ }
+
+ const noPhrasesDue = noPhraseStates.some(
+ (state) =>
+ text !== state.text && now - state.firedAt >= NO_PHRASES_INTERVAL_MS
+ );
+ if (!newMatches.length && !noPhrasesDue) {
+ return;
+ }
+
+ // A trigger only counts as fired once the server answered, so it can fire again after an
+ // error. A nudge is best effort, so an error must never interrupt writing.
+ try {
+ await this.#post(composer, draft, action);
+ newMatches.forEach(({ state, sources }) =>
+ sources.forEach((source) => state.matched.add(source))
+ );
+ // The server checks every trigger on each request, so those without phrases restart their
+ // interval together.
+ noPhraseStates.forEach((state) => {
+ state.text = text;
+ state.firedAt = now;
+ });
+ } catch (error) {
+ this.#retryAt = Date.now() + retryDelayMs(error);
+ }
+ }
+
+ // State lives in the composer session, so reopening the composer starts over.
+ #stateFor(composer, trigger) {
+ const sessionId = this.workflowsComposerSession.idFor(composer);
+ let session = this.#sessions.get(composer);
+ if (session?.id !== sessionId) {
+ session = { id: sessionId, states: new Map() };
+ this.#sessions.set(composer, session);
+ }
+
+ const key = `${trigger.workflow_id}:${trigger.trigger_node_id}`;
+ if (!session.states.has(key)) {
+ session.states.set(key, {
+ matched: new Set(),
+ text: null,
+ firedAt: -Infinity,
+ });
+ }
+ return session.states.get(key);
+ }
+
+ #post(composer, draft, action) {
+ return ajax("/discourse-workflows/trigger-composer-paused", {
+ type: "POST",
+ data: {
+ draft_key: composer.draftKey,
+ session_id: this.workflowsComposerSession.idFor(composer),
+ composer_action: action,
+ title: draft.title,
+ raw: draft.reply,
+ category_id: composer.categoryId,
+ topic_id: composer.topic?.id,
+ // A reply targets `post`; `reply_to_post_number` only changes when a
+ // post is edited.
+ reply_to_post_number: composer.post?.post_number,
+ },
+ });
+ }
+}
diff --git a/plugins/discourse-workflows/assets/javascripts/discourse/services/workflows-composer-session.js b/plugins/discourse-workflows/assets/javascripts/discourse/services/workflows-composer-session.js
new file mode 100644
index 00000000000..78991f8ee1d
--- /dev/null
+++ b/plugins/discourse-workflows/assets/javascripts/discourse/services/workflows-composer-session.js
@@ -0,0 +1,26 @@
+import Service from "@ember/service";
+
+// Saved in the draft too, so a workflow fired by an autosave can answer the
+// composer that saved it.
+export const SESSION_ID_FIELD = "workflowsSessionId";
+
+// Identifies one opening of the composer, so a workflow only answers the
+// composer it started from: not a later reply to the same topic, nor another
+// tab with the same draft.
+export default class WorkflowsComposerSession extends Service {
+ #ids = new WeakMap();
+
+ idFor(composer) {
+ let id = this.#ids.get(composer);
+
+ // Opening the composer resets its draft fields, or restores a saved draft's,
+ // so a mismatch means a new opening.
+ if (!id || composer.get(SESSION_ID_FIELD) !== id) {
+ id = crypto.randomUUID();
+ this.#ids.set(composer, id);
+ composer.set(SESSION_ID_FIELD, id);
+ }
+
+ return id;
+ }
+}
diff --git a/plugins/discourse-workflows/config/locales/client.en.yml b/plugins/discourse-workflows/config/locales/client.en.yml
index 12d4d9d3cb3..84cef69ee06 100644
--- a/plugins/discourse-workflows/config/locales/client.en.yml
+++ b/plugins/discourse-workflows/config/locales/client.en.yml
@@ -358,9 +358,11 @@ en:
"action:respond_to_webhook": "Respond to webhook"
"trigger:topic_admin_button": "Topic admin button"
"trigger:post_button": "Post button"
+ "trigger:composer_paused": "Composer paused"
"trigger:error": "Error trigger"
"flow:wait": "Wait"
"action:modal": "Modal"
+ "action:composer_message": "Composer message"
"action:topic_category": "Topic category"
"action:topic_pin": "Topic pinning"
"action:topic_moderation": "Topic moderation"
@@ -447,9 +449,11 @@ en:
"action:respond_to_webhook": "Send a custom HTTP response to the webhook caller"
"trigger:topic_admin_button": "Adds a button to the topic admin menu that triggers this workflow"
"trigger:post_button": "Adds a button to the post actions menu that triggers this workflow"
+ "trigger:composer_paused": "Fires while a user writes a topic or reply"
"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"
+ "action:composer_message": "Shows a tip above the user's composer"
"action:topic_category": "Set or clear the category of a topic"
"action:topic_pin": "Pin or unpin a topic in its category, globally, or as a banner"
"action:topic_moderation": "Perform moderation actions on a topic"
@@ -494,6 +498,24 @@ en:
confirmation_message: "Confirmation message"
confirmation_message_placeholder: "Are you sure?"
confirmation_default_message: "Are you sure?"
+ composer_paused:
+ fire_on: "Fire on"
+ fire_on_pause: "Typing pause"
+ fire_on_draft_saved: "Draft save"
+ fire_on_description: "Typing pause shows instantly but sends the phrases to the browser. Draft save keeps them hidden but fires a few seconds later."
+ phrases: "Phrases"
+ phrases_description: "Watched word syntax, once per post each. Leave empty to fire on every pause."
+ phrases_placeholder: "Add phrases"
+ composer_actions: "Fire for"
+ composer_actions_create_topic: "New topic"
+ composer_actions_reply: "Reply"
+ composer_actions_description: "Never fires for messages or edits"
+ group_ids_description: "Leave empty for all users."
+ composer_message:
+ title: "Title"
+ title_placeholder: "Message title"
+ body: "Body"
+ body_placeholder: "Message body"
modal:
target_user: "Target user"
target_user_placeholder: "Defaults to the user who triggered the workflow"
diff --git a/plugins/discourse-workflows/config/locales/server.en.yml b/plugins/discourse-workflows/config/locales/server.en.yml
index 8af78369ed2..beedd0c0047 100644
--- a/plugins/discourse-workflows/config/locales/server.en.yml
+++ b/plugins/discourse-workflows/config/locales/server.en.yml
@@ -175,6 +175,13 @@ en:
modal:
no_target_user: "No target user is available for the modal."
user_not_found: "User '%{username}' not found."
+ composer_paused:
+ too_many_phrases: "A composer trigger can have at most %{max} phrases."
+ phrase_too_long: "The phrase '%{phrase}' is longer than %{max} characters."
+ invalid_phrase: "The phrase '%{phrase}' is invalid, matches any text, or could take too long to match."
+ composer_message:
+ no_user: "No user is available to show the composer message to."
+ no_composer: "Composer messages need a workflow started by the composer trigger."
topic_tags:
unknown_mode: "Unknown tag mode: %{mode}."
no_tag_names: "No tag names provided."
diff --git a/plugins/discourse-workflows/config/routes.rb b/plugins/discourse-workflows/config/routes.rb
index 4a8a0214b06..977b46355af 100644
--- a/plugins/discourse-workflows/config/routes.rb
+++ b/plugins/discourse-workflows/config/routes.rb
@@ -109,6 +109,7 @@ DiscourseWorkflows::Engine.routes.draw do
scope "/discourse-workflows", defaults: { format: :json } do
post "/trigger-topic-admin-button" => "topic_admin_button#create"
post "/trigger-post-button" => "post_button#create"
+ post "/trigger-composer-paused" => "composer_paused#create"
post "/modal-responses" => "modal_responses#create"
post "/modal-dismissals" => "modal_dismissals#create"
end
diff --git a/plugins/discourse-workflows/lib/discourse_workflows/composer_paused_claims.rb b/plugins/discourse-workflows/lib/discourse_workflows/composer_paused_claims.rb
new file mode 100644
index 00000000000..c177f735e7d
--- /dev/null
+++ b/plugins/discourse-workflows/lib/discourse_workflows/composer_paused_claims.rb
@@ -0,0 +1,66 @@
+# frozen_string_literal: true
+
+module DiscourseWorkflows
+ # Remembers what a composer paused trigger already fired for, so each phrase fires once per
+ # draft and triggers without phrases don't fire on every pause.
+ module ComposerPausedClaims
+ PHRASES_TTL = 1.day
+ NO_PHRASES_INTERVAL = 15.seconds
+ RATE_LIMIT = 20
+ RATE_PERIOD = 1.minute
+ ATTEMPT_LIMIT = 60
+
+ # Returns the phrases that haven't fired yet in this scope ([] for a trigger without
+ # phrases), or nil when there is nothing new to fire.
+ def self.claim(scope, published_trigger, phrases)
+ key = key(scope, published_trigger)
+
+ if phrases.empty?
+ [] if Discourse.redis.set(key, "1", ex: NO_PHRASES_INTERVAL.to_i, nx: true)
+ else
+ fresh = phrases.select { |phrase| Discourse.redis.sadd?(key, phrase) }
+ Discourse.redis.expire(key, PHRASES_TTL.to_i)
+ fresh.presence
+ end
+ end
+
+ # Gives back a claim whose workflow didn't fire, so it can fire later.
+ def self.release(scope, published_trigger, phrases)
+ key = key(scope, published_trigger)
+ phrases.empty? ? Discourse.redis.del(key) : Discourse.redis.srem(key, phrases)
+ end
+
+ # Lets callers skip matching the phrases that already fired.
+ def self.unclaimed(scope, published_trigger, phrases)
+ phrases - Discourse.redis.smembers(key(scope, published_trigger))
+ end
+
+ def self.rate_limiter(user)
+ RateLimiter.new(
+ user,
+ "workflow_composer_paused",
+ RATE_LIMIT,
+ RATE_PERIOD.to_i,
+ apply_limit_to_staff: true,
+ )
+ end
+
+ # Every request costs a scan, while the run limit only counts workflows that fired.
+ def self.attempt_rate_limiter(user)
+ RateLimiter.new(
+ user,
+ "workflow_composer_paused_attempt",
+ ATTEMPT_LIMIT,
+ RATE_PERIOD.to_i,
+ apply_limit_to_staff: true,
+ )
+ end
+
+ def self.key(scope, published_trigger)
+ "discourse_workflows:composer_paused:#{scope}:" \
+ "#{published_trigger.workflow_id}:#{published_trigger.trigger_node_id}"
+ end
+
+ private_class_method :key
+ end
+end
diff --git a/plugins/discourse-workflows/lib/discourse_workflows/composer_paused_dispatch.rb b/plugins/discourse-workflows/lib/discourse_workflows/composer_paused_dispatch.rb
new file mode 100644
index 00000000000..1f3e2cce41d
--- /dev/null
+++ b/plugins/discourse-workflows/lib/discourse_workflows/composer_paused_dispatch.rb
@@ -0,0 +1,58 @@
+# frozen_string_literal: true
+
+module DiscourseWorkflows
+ # Fires the composer paused triggers a draft matches, each phrase once per claim scope.
+ module ComposerPausedDispatch
+ def self.published_triggers(fire_on)
+ trigger_class = Nodes::ComposerPaused::V1
+
+ WorkflowDependency
+ .cached_published_triggers(trigger_class.identifier)
+ .select do |published_trigger|
+ trigger_class.fires_on?(NodeData.parameters(published_trigger.trigger_node), fire_on)
+ end
+ end
+
+ # Returns false when the rate limit ran out before every matching trigger fired. It counts
+ # workflow runs, since one pause can fire several workflows.
+ def self.call(published_triggers, snapshot, claim_scope)
+ trigger_class = Nodes::ComposerPaused::V1
+ rate_limiter = ComposerPausedClaims.rate_limiter(snapshot.user)
+
+ published_triggers.all? do |published_trigger|
+ parameters = NodeData.parameters(published_trigger.trigger_node)
+ next true if !trigger_class.matches_snapshot?(parameters, snapshot)
+
+ phrases = trigger_class.phrases(parameters)
+ if phrases.any?
+ unclaimed = ComposerPausedClaims.unclaimed(claim_scope, published_trigger, phrases)
+ phrases = trigger_class.matched_phrases(unclaimed, snapshot.own_text)
+ next true if phrases.empty?
+ end
+
+ next false if !rate_limiter.can_perform?
+
+ phrases = ComposerPausedClaims.claim(claim_scope, published_trigger, phrases)
+ next true if phrases.nil?
+
+ if !rate_limiter.performed!(raise_error: false)
+ ComposerPausedClaims.release(claim_scope, published_trigger, phrases)
+ next false
+ end
+
+ TriggerDispatcher.enqueue(
+ published_trigger,
+ trigger_data: trigger_class.new(snapshot, phrases).output,
+ user_id: snapshot.user.id,
+ )
+ true
+ rescue => e
+ Rails.logger.error(
+ "discourse-workflows: trigger:composer_paused failed " \
+ "for workflow #{published_trigger.workflow_id}: #{e.message}",
+ )
+ true
+ end
+ end
+ end
+end
diff --git a/plugins/discourse-workflows/lib/discourse_workflows/composer_paused_draft_listener.rb b/plugins/discourse-workflows/lib/discourse_workflows/composer_paused_draft_listener.rb
new file mode 100644
index 00000000000..9dfd396ba96
--- /dev/null
+++ b/plugins/discourse-workflows/lib/discourse_workflows/composer_paused_draft_listener.rb
@@ -0,0 +1,80 @@
+# frozen_string_literal: true
+
+module DiscourseWorkflows
+ # Fires composer paused triggers set to the draft autosave. Matching happens here, so their
+ # phrases never reach the browser.
+ class ComposerPausedDraftListener
+ @queued_drafts = {}
+ @queued_drafts_mutex = Mutex.new
+
+ def self.handle(user, draft_key, data)
+ return if !SiteSetting.enable_discourse_workflows
+ return if draft_saved_triggers.empty?
+ return if !ComposerPausedClaims.rate_limiter(user).can_perform?
+
+ # Autosaves are frequent, so a draft waiting for its scan only takes the newest data.
+ key = [RailsMultisite::ConnectionManagement.current_db, user.id, draft_key]
+ return if !queue_draft(key, data)
+
+ # Matching must not hold up the request. The queue is shared with unrelated work, so a
+ # scan is dropped rather than added to a full queue.
+ begin
+ Scheduler::Defer.later(
+ "discourse_workflows_composer_paused",
+ current_user: user.id,
+ force: false,
+ ) do
+ snapshot = ComposerSnapshot.from_draft(user, draft_key, take_queued_draft(key))
+ new(snapshot).dispatch if snapshot
+ end
+ rescue StandardError
+ # Nothing was queued, so the next autosave must queue a scan.
+ take_queued_draft(key)
+ raise
+ end
+ rescue WorkQueue::WorkQueueFull
+ # Scans are best effort, so a busy queue skips this one.
+ rescue => e
+ Rails.logger.error("discourse-workflows: trigger:composer_paused failed: #{e.message}")
+ end
+
+ def self.draft_saved_triggers
+ ComposerPausedDispatch.published_triggers(Nodes::ComposerPaused::V1::DRAFT_SAVED)
+ end
+
+ # Returns whether the draft needs a new scan, which it doesn't while one is queued.
+ def self.queue_draft(key, data)
+ @queued_drafts_mutex.synchronize do
+ queued = @queued_drafts.key?(key)
+ @queued_drafts[key] = data
+ !queued
+ end
+ end
+
+ def self.take_queued_draft(key)
+ @queued_drafts_mutex.synchronize { @queued_drafts.delete(key) }
+ end
+
+ private_class_method :queue_draft, :take_queued_draft
+
+ def initialize(snapshot)
+ @snapshot = snapshot
+ end
+
+ def dispatch
+ return if draft_id.nil?
+
+ ComposerPausedDispatch.call(self.class.draft_saved_triggers, @snapshot, "draft:#{draft_id}")
+ end
+
+ private
+
+ # A cleared draft is re-created with a new id, so the next post starts over.
+ def draft_id
+ return @draft_id if defined?(@draft_id)
+
+ @draft_id =
+ ::Draft.where(user_id: @snapshot.user.id, draft_key: @snapshot.draft_key).pick(:id)
+ end
+ end
+end
diff --git a/plugins/discourse-workflows/lib/discourse_workflows/composer_snapshot.rb b/plugins/discourse-workflows/lib/discourse_workflows/composer_snapshot.rb
new file mode 100644
index 00000000000..0930430342e
--- /dev/null
+++ b/plugins/discourse-workflows/lib/discourse_workflows/composer_snapshot.rb
@@ -0,0 +1,180 @@
+# frozen_string_literal: true
+
+module DiscourseWorkflows
+ # What a user is writing in the composer when they pause typing or their draft is saved.
+ class ComposerSnapshot
+ CREATE_TOPIC = "create_topic"
+ REPLY = "reply"
+ ACTIONS = [CREATE_TOPIC, REPLY].freeze
+ DRAFT_ACTIONS = { "createTopic" => CREATE_TOPIC, "reply" => REPLY }.freeze
+ # The browser keeps its composer session in the draft, so an autosave's workflow can answer
+ # the composer that saved it.
+ DRAFT_SESSION_ID_FIELD = "workflowsSessionId"
+ MAX_SESSION_ID_LENGTH = 64
+
+ # Attributes are capped so that a tag without its closing bracket can't make
+ # scanning quadratic.
+ QUOTE_TAG_REGEXP = %r{\[quote(?:=[^\]]{0,300})?\]|\[/quote\]}i
+ BLOCKQUOTE_LINE_REGEXP = /^[ \t]*>.*$/
+ HTML_COMMENT_START = "<!--"
+ HTML_COMMENT_END = "-->"
+
+ attr_reader :user,
+ :action,
+ :draft_key,
+ :session_id,
+ :title,
+ :raw,
+ :category_id,
+ :topic,
+ :reply_to_post_number
+
+ def self.from_draft(user, draft_key, data)
+ return if user.blank? || !data.is_a?(Hash)
+ return if data["archetypeId"].to_s == Archetype.private_message
+
+ action = DRAFT_ACTIONS[data["action"].to_s]
+ return if action.nil?
+
+ topic = nil
+ if action == REPLY
+ return if !draft_key.to_s.start_with?(::Draft::EXISTING_TOPIC)
+ topic = ::Topic.find_by(id: draft_key.delete_prefix(::Draft::EXISTING_TOPIC).to_i)
+ return if topic.nil?
+ end
+
+ new(
+ user:,
+ action:,
+ draft_key:,
+ session_id: data[DRAFT_SESSION_ID_FIELD],
+ title: data["title"],
+ raw: data["reply"],
+ category_id: data["categoryId"],
+ topic:,
+ reply_to_post_number: topic && reply_target_post_number(topic, data["postId"]),
+ )
+ end
+
+ # A reply targets the post it was opened from, saved as `postId`. The composer only lets an
+ # edit change `reply_to_post_number`, so a reply's draft always has it empty.
+ def self.reply_target_post_number(topic, post_id)
+ post_id = Integer(post_id, exception: false)
+ topic.posts.where(id: post_id).pick(:post_number) if post_id
+ end
+
+ # Drafts can be far longer than a post, so every step here is linear in the text length.
+ def self.own_text(raw)
+ strip_quotes(strip_html_comments(raw.to_s)).gsub(BLOCKQUOTE_LINE_REGEXP, "")
+ end
+
+ def self.strip_html_comments(text)
+ parts = []
+ position = 0
+
+ while (start = text.index(HTML_COMMENT_START, position))
+ finish = text.index(HTML_COMMENT_END, start + HTML_COMMENT_START.length)
+ break if finish.nil?
+
+ parts << text[position...start]
+ position = finish + HTML_COMMENT_END.length
+ end
+
+ parts << text[position..]
+ parts.join
+ end
+
+ # Removes balanced quote blocks, nested ones included. An unclosed quote is kept as text.
+ def self.strip_quotes(text)
+ parts = []
+ open_quotes = []
+ scanner = StringScanner.new(text)
+
+ while (scanned = scanner.scan_until(QUOTE_TAG_REGEXP))
+ tag = scanner.matched
+ parts << scanned[0, scanned.length - tag.length]
+
+ if tag.start_with?("[/")
+ if (start = open_quotes.pop)
+ parts.pop(parts.size - start)
+ else
+ parts << tag
+ end
+ else
+ open_quotes << parts.size
+ parts << tag
+ end
+ end
+
+ parts << scanner.rest
+ parts.join
+ end
+
+ def initialize(
+ user:,
+ action:,
+ draft_key:,
+ raw:,
+ session_id: nil,
+ title: nil,
+ category_id: nil,
+ topic: nil,
+ reply_to_post_number: nil
+ )
+ @user = user
+ @action = action.to_s
+ @draft_key = draft_key.to_s
+ if session_id.is_a?(String) && session_id.length <= MAX_SESSION_ID_LENGTH
+ @session_id = session_id.presence
+ end
+ # Matching never looks past what a post can hold.
+ @title = title.to_s[0, SiteSetting.max_topic_title_length].presence
+ @raw = raw.to_s[0, SiteSetting.max_post_length]
+ @category_id = category_id.presence&.to_i
+ @topic = topic
+ @reply_to_post_number = reply_to_post_number.presence&.to_i
+ end
+
+ def reply?
+ action == REPLY
+ end
+
+ # Replies are filtered by their topic's category.
+ def filter_category_id
+ reply? ? topic&.category_id : category_id
+ end
+
+ def own_text
+ @own_text ||= [title, self.class.own_text(raw)].compact_blank.join("\n")
+ end
+
+ def composable?
+ return @composable if defined?(@composable)
+
+ @composable =
+ if user.blank? || ACTIONS.exclude?(action)
+ false
+ elsif reply?
+ # Posting permission comes from the category, so it doesn't cover topics hidden
+ # inside it, like shared drafts.
+ topic.present? && !topic.private_message? && user.guardian.can_see_topic?(topic) &&
+ user.guardian.can_create_post_on_topic?(topic)
+ else
+ user.guardian.can_create_topic_on_category?(category_id)
+ end
+ end
+
+ def to_h
+ {
+ action:,
+ draft_key:,
+ session_id:,
+ title:,
+ raw:,
+ category_id: filter_category_id,
+ topic_id: topic&.id,
+ reply_to_post_number:,
+ }
+ end
+ end
+end
diff --git a/plugins/discourse-workflows/lib/discourse_workflows/composer_target.rb b/plugins/discourse-workflows/lib/discourse_workflows/composer_target.rb
new file mode 100644
index 00000000000..27a546c5448
--- /dev/null
+++ b/plugins/discourse-workflows/lib/discourse_workflows/composer_target.rb
@@ -0,0 +1,19 @@
+# frozen_string_literal: true
+
+module DiscourseWorkflows
+ # The composer a workflow started from, for nodes that show something in it.
+ module ComposerTarget
+ # Read from the trigger rather than the input items, which earlier nodes may have reshaped.
+ def self.from(exec_ctx, item_index = 0)
+ trigger_data = exec_ctx.get_context(:flow)&.fetch("$trigger", nil)
+ trigger_data = trigger_data[item_index] || trigger_data.first if trigger_data.is_a?(Array)
+ return if !trigger_data.is_a?(Hash)
+
+ draft_key = trigger_data.dig("composer", "draft_key")
+ return if !draft_key.is_a?(String) || draft_key.blank?
+
+ session_id = trigger_data.dig("composer", "session_id")
+ { draft_key:, session_id: session_id.is_a?(String) ? session_id : nil }
+ end
+ end
+end
diff --git a/plugins/discourse-workflows/lib/discourse_workflows/nodes/composer_message/v1.rb b/plugins/discourse-workflows/lib/discourse_workflows/nodes/composer_message/v1.rb
new file mode 100644
index 00000000000..1aee6ecf70a
--- /dev/null
+++ b/plugins/discourse-workflows/lib/discourse_workflows/nodes/composer_message/v1.rb
@@ -0,0 +1,65 @@
+# frozen_string_literal: true
+
+module DiscourseWorkflows
+ module Nodes
+ module ComposerMessage
+ class V1 < NodeType
+ USER_CHANNEL_PREFIX = "/discourse-workflows/composer-message"
+
+ description(
+ name: "action:composer_message",
+ version: "1.0",
+ defaults: {
+ icon: "comment",
+ color: "blue",
+ },
+ group: "discourse_actions",
+ properties: {
+ title: {
+ type: :string,
+ required: true,
+ },
+ body: {
+ type: :string,
+ required: true,
+ ui: {
+ control: :textarea,
+ },
+ },
+ },
+ output_contracts: [{ mode: :passthrough }],
+ )
+
+ def self.user_channel(user_id)
+ "#{USER_CHANNEL_PREFIX}/#{user_id}"
+ end
+
+ def execute(exec_ctx)
+ user = exec_ctx.user
+ if user.nil?
+ raise_node_error!(I18n.t("discourse_workflows.errors.composer_message.no_user"))
+ end
+
+ target = ComposerTarget.from(exec_ctx)
+ if target.nil?
+ raise_node_error!(I18n.t("discourse_workflows.errors.composer_message.no_composer"))
+ end
+
+ MessageBus.publish(
+ self.class.user_channel(user.id),
+ {
+ type: "show_composer_message",
+ draft_key: target[:draft_key],
+ session_id: target[:session_id],
+ title: exec_ctx.get_node_parameter("title", 0).to_s,
+ body: PrettyText.cook(exec_ctx.get_node_parameter("body", 0).to_s),
+ },
+ user_ids: [user.id],
+ )
+
+ [exec_ctx.input_items]
+ end
+ end
+ end
+ end
+end
diff --git a/plugins/discourse-workflows/lib/discourse_workflows/nodes/composer_paused/v1.rb b/plugins/discourse-workflows/lib/discourse_workflows/nodes/composer_paused/v1.rb
new file mode 100644
index 00000000000..67a3df44c0c
--- /dev/null
+++ b/plugins/discourse-workflows/lib/discourse_workflows/nodes/composer_paused/v1.rb
@@ -0,0 +1,264 @@
+# frozen_string_literal: true
+
+module DiscourseWorkflows
+ module Nodes
+ module ComposerPaused
+ class V1 < NodeType
+ PAUSE = "pause"
+ DRAFT_SAVED = "draft_saved"
+ FIRE_ON_OPTIONS = [PAUSE, DRAFT_SAVED].freeze
+ MAX_PHRASES = 50
+ MAX_PHRASE_LENGTH = 100
+ # A phrase that matches any of these would match nearly every draft.
+ MATCH_ANYTHING_SAMPLES = ["", " ", "zq"].freeze
+
+ COMPOSER_PROPERTIES = {
+ "action" => {
+ "type" => "string",
+ "enum" => ComposerSnapshot::ACTIONS,
+ },
+ "draft_key" => {
+ "type" => "string",
+ },
+ "session_id" => {
+ "type" => %w[string null],
+ },
+ "title" => {
+ "type" => %w[string null],
+ },
+ "raw" => {
+ "type" => "string",
+ },
+ "category_id" => {
+ "type" => %w[integer null],
+ },
+ "topic_id" => {
+ "type" => %w[integer null],
+ },
+ "reply_to_post_number" => {
+ "type" => %w[integer null],
+ },
+ "matched_phrases" => {
+ "type" => "array",
+ "items" => {
+ "type" => "string",
+ },
+ },
+ }.freeze
+
+ description(
+ name: "trigger:composer_paused",
+ version: "1.0",
+ defaults: {
+ icon: "keyboard",
+ color: "cyan",
+ },
+ group: "discourse_triggers",
+ properties: {
+ fire_on: {
+ type: :options,
+ required: true,
+ default: PAUSE,
+ options: FIRE_ON_OPTIONS,
+ },
+ phrases: {
+ type: :array,
+ required: false,
+ no_data_expression: true,
+ ui: {
+ control: :multi_input,
+ },
+ },
+ composer_actions: {
+ type: :multi_options,
+ required: false,
+ default: ComposerSnapshot::ACTIONS,
+ options: ComposerSnapshot::ACTIONS,
+ },
+ **CATEGORY_FILTER_PROPERTIES,
+ group_ids: {
+ type: :array,
+ required: false,
+ type_options: {
+ load_options_method: "groups",
+ },
+ ui: {
+ control: :group_select,
+ multiple: true,
+ },
+ control_options: {
+ value_property: "id",
+ name_property: "name",
+ filterable: true,
+ },
+ },
+ },
+ capabilities: {
+ provides_current_user: true,
+ },
+ output_contracts: [
+ {
+ schema:
+ Schema.merge(
+ Schema::USER_SCHEMA,
+ Schema::ACTOR_SCHEMA,
+ Schema.document(
+ "composer" => {
+ "type" => "object",
+ "properties" => COMPOSER_PROPERTIES,
+ },
+ "topic" => {
+ "type" => %w[object null],
+ "properties" => Schema::TOPIC_PROPERTIES,
+ },
+ ),
+ ),
+ },
+ ],
+ )
+
+ def self.load_options_context(context)
+ case context.method_name
+ when "groups"
+ ::Group
+ .order(:name)
+ .pluck(:id, :name)
+ .select { |_, name| context.matches_filter?(name) }
+ .map { |id, name| { id:, name: } }
+ end
+ end
+
+ def self.validate_configuration(configuration, errors)
+ phrases = phrases((configuration || {}).deep_stringify_keys)
+
+ if phrases.size > MAX_PHRASES
+ errors.add(
+ :base,
+ I18n.t(
+ "discourse_workflows.errors.composer_paused.too_many_phrases",
+ max: MAX_PHRASES,
+ ),
+ )
+ end
+
+ phrases.each do |phrase|
+ if phrase.length > MAX_PHRASE_LENGTH
+ errors.add(
+ :base,
+ I18n.t(
+ "discourse_workflows.errors.composer_paused.phrase_too_long",
+ phrase:,
+ max: MAX_PHRASE_LENGTH,
+ ),
+ )
+ elsif phrase_regexp(phrase).nil?
+ errors.add(
+ :base,
+ I18n.t("discourse_workflows.errors.composer_paused.invalid_phrase", phrase:),
+ )
+ end
+ end
+ end
+
+ def self.fires_on?(parameters, mode)
+ (parameters["fire_on"].presence || PAUSE) == mode
+ end
+
+ def self.phrases(parameters)
+ Array
+ .wrap(parameters["phrases"])
+ .filter_map { |phrase| phrase.to_s.strip.squeeze("*").presence }
+ .uniq
+ end
+
+ # Regexp sources in watched word syntax, for matching in the browser.
+ def self.patterns(parameters)
+ phrases(parameters).filter_map { |phrase| phrase_regexp(phrase)&.source }
+ end
+
+ def self.phrase_regexp(phrase)
+ return if phrase.length > MAX_PHRASE_LENGTH
+
+ # Pauses and autosaves are frequent, so each phrase is compiled once.
+ key = "#{SiteSetting.watched_words_regular_expressions}:#{phrase}"
+ phrase_regexps.getset(key) { compile_phrase(phrase) || false } || nil
+ end
+
+ def self.phrase_regexps
+ @phrase_regexps ||= LruRedux::ThreadSafeCache.new(1000)
+ end
+
+ def self.compile_phrase(phrase)
+ regexp = Regexp.new(WordWatcher.word_to_regexp(phrase), Regexp::IGNORECASE)
+ # Anyone can send draft text, so a phrase that may backtrack could tie up the server.
+ return if !Regexp.linear_time?(regexp)
+
+ regexp if MATCH_ANYTHING_SAMPLES.none? { |sample| regexp.match?(sample) }
+ rescue RegexpError
+ nil
+ end
+
+ def self.matched_phrases(phrases, text)
+ phrases.select { |phrase| phrase_regexp(phrase)&.match?(text) }
+ end
+
+ def self.composer_actions(parameters)
+ actions = Array.wrap(parameters["composer_actions"]).map(&:to_s).compact_blank
+ actions.empty? ? ComposerSnapshot::ACTIONS : actions & ComposerSnapshot::ACTIONS
+ end
+
+ def self.normalized_group_ids(parameters)
+ Array
+ .wrap(parameters["group_ids"])
+ .filter_map do |group_id|
+ value = group_id.to_s
+ value.to_i if value.match?(/\A\d+\z/)
+ end
+ end
+
+ def self.available_to?(user, parameters)
+ return false if user.blank?
+
+ group_ids = normalized_group_ids(parameters)
+ group_ids.empty? || user.in_any_groups?(group_ids)
+ end
+
+ # Everything but the phrases, which callers match separately to know which ones fired.
+ def self.matches_snapshot?(parameters, snapshot)
+ return false if composer_actions(parameters).exclude?(snapshot.action)
+ return false if !available_to?(snapshot.user, parameters)
+ return false if !matches_category?(parameters, snapshot.filter_category_id)
+
+ snapshot.composable?
+ end
+
+ def self.matches_category?(parameters, category_id)
+ category_ids = normalize_ids(parameters["category_ids"])
+ return true if category_ids.empty?
+
+ category_ids = expand_subcategory_ids(category_ids) if parameters[
+ "include_subcategories"
+ ] != false
+ category_ids.include?(category_id)
+ end
+
+ def initialize(snapshot, matched_phrases = [])
+ super(parameters: {})
+ @snapshot = snapshot
+ @matched_phrases = matched_phrases
+ end
+
+ def output
+ user = serialize_user(@snapshot.user)
+
+ {
+ user:,
+ actor: user,
+ composer: @snapshot.to_h.merge(matched_phrases: @matched_phrases),
+ topic: @snapshot.topic && serialize_topic_list_item(@snapshot.topic),
+ }
+ end
+ end
+ end
+ end
+end
diff --git a/plugins/discourse-workflows/plugin.rb b/plugins/discourse-workflows/plugin.rb
index e49e82bcb26..1c6664e04a8 100644
--- a/plugins/discourse-workflows/plugin.rb
+++ b/plugins/discourse-workflows/plugin.rb
@@ -275,6 +275,29 @@ after_initialize do
DiscourseWorkflows::WorkflowDependency.post_buttons_for(scope.user)
end
+ add_to_serializer :site,
+ :composer_paused_workflows,
+ include_condition: -> do
+ scope.user.present? &&
+ DiscourseWorkflows::WorkflowDependency.cached_composer_paused_triggers.present?
+ end do
+ DiscourseWorkflows::WorkflowDependency.composer_paused_triggers_for(scope.user)
+ end
+
+ add_to_serializer :current_user,
+ :discourse_workflows_composer_message_last_id,
+ include_condition: -> do
+ DiscourseWorkflows::WorkflowDependency.references_node_type?(
+ DiscourseWorkflows::Nodes::ComposerMessage::V1.identifier,
+ )
+ end do
+ MessageBus.last_id(DiscourseWorkflows::Nodes::ComposerMessage::V1.user_channel(object.id))
+ end
+
+ on(:draft_saved) do |user, draft_key, data|
+ DiscourseWorkflows::ComposerPausedDraftListener.handle(user, draft_key, data)
+ end
+
add_to_serializer :current_user,
:discourse_workflows_user_modal_last_id,
include_condition: -> do
diff --git a/plugins/discourse-workflows/spec/lib/discourse_workflows/composer_paused_draft_listener_spec.rb b/plugins/discourse-workflows/spec/lib/discourse_workflows/composer_paused_draft_listener_spec.rb
new file mode 100644
index 00000000000..215932ec8d6
--- /dev/null
+++ b/plugins/discourse-workflows/spec/lib/discourse_workflows/composer_paused_draft_listener_spec.rb
@@ -0,0 +1,264 @@
+# frozen_string_literal: true
+
+RSpec.describe DiscourseWorkflows::ComposerPausedDraftListener do
+ fab!(:admin)
+ fab!(:user) { Fabricate(:user, refresh_auto_groups: true) }
+ fab!(:topic)
+
+ let(:configuration) { { "fire_on" => "draft_saved", "phrases" => ["Magic words", "food stand"] } }
+ let!(:workflow) do
+ graph =
+ build_workflow_graph do |g|
+ g.node "trigger-1", "trigger:composer_paused", configuration: configuration
+ end
+ Fabricate(:discourse_workflows_workflow, created_by: admin, published: true, **graph)
+ end
+
+ before { DiscourseWorkflows::WorkflowDependency.clear_cache! }
+
+ def save_draft(reply, draft_key: "new_topic", action: "createTopic", **data)
+ payload = { "reply" => reply, "action" => action, **data.stringify_keys }
+ Draft.set(user, draft_key, DraftSequence.current(user, draft_key), payload.to_json)
+ described_class.handle(user, draft_key, payload)
+ end
+
+ def enqueued_trigger_data
+ Jobs::DiscourseWorkflows::ExecuteWorkflow.jobs.map { |job| job["args"].first["trigger_data"] }
+ end
+
+ describe "when a draft is saved", type: :request do
+ it "fires the trigger" do
+ sign_in(user)
+
+ post "/drafts.json",
+ params: {
+ draft_key: "new_topic",
+ sequence: 0,
+ data: { reply: "Magic words", action: "createTopic" }.to_json,
+ }
+
+ expect(response.status).to eq(200)
+ expect(enqueued_trigger_data.size).to eq(1)
+ end
+ end
+
+ it "fires once per phrase for each draft" do
+ save_draft("Some magic words", title: "Lunch review", workflowsSessionId: "session-1")
+ save_draft("Some magic words, and more magic words")
+ save_draft("Magic words. food stand")
+
+ expect(enqueued_trigger_data.map { |data| data.dig("composer", "matched_phrases") }).to eq(
+ [["Magic words"], ["food stand"]],
+ )
+ expect(enqueued_trigger_data.first).to include(
+ "user" => include("id" => user.id),
+ "composer" =>
+ include("draft_key" => "new_topic", "session_id" => "session-1", "title" => "Lunch review"),
+ )
+ expect(Jobs::DiscourseWorkflows::ExecuteWorkflow.jobs.first["args"].first["user_id"]).to eq(
+ user.id,
+ )
+ end
+
+ it "starts over once the draft is cleared" do
+ save_draft("Magic words")
+ Draft.clear(user, "new_topic", DraftSequence.current(user, "new_topic"))
+ save_draft("Magic words")
+
+ expect(enqueued_trigger_data.size).to eq(2)
+ end
+
+ it "ignores quoted text" do
+ save_draft("[quote=\"sam, post:1, topic:2\"]Magic words[/quote]\n> food stand\nMine")
+
+ expect(enqueued_trigger_data).to be_empty
+ end
+
+ it "fires for replies with the topic" do
+ save_draft("Magic words", draft_key: "topic_#{topic.id}", action: "reply")
+
+ expect(enqueued_trigger_data.first).to include(
+ "topic" => include("id" => topic.id),
+ "composer" =>
+ include("action" => "reply", "topic_id" => topic.id, "reply_to_post_number" => nil),
+ )
+ end
+
+ it "reads a reply's target from the draft's post" do
+ draft_key = "topic_#{topic.id}"
+ target = Fabricate(:post, topic:)
+
+ [target.id, Fabricate(:post).id, [target.id]].each do |post_id|
+ save_draft(
+ "Magic words",
+ draft_key:,
+ action: "reply",
+ postId: post_id,
+ reply_to_post_number: nil,
+ )
+ Draft.clear(user, draft_key, DraftSequence.current(user, draft_key))
+ end
+
+ expect(enqueued_trigger_data.map { |data| data.dig("composer", "reply_to_post_number") }).to eq(
+ [target.post_number, nil, nil],
+ )
+ end
+
+ it "never fires for personal messages or edits" do
+ pm = Fabricate(:private_message_topic, user:)
+
+ save_draft("Magic words", draft_key: "new_private_message", action: "privateMessage")
+ save_draft("Magic words", draft_key: "topic_#{pm.id}", action: "reply")
+ save_draft("Magic words", draft_key: "topic_#{topic.id}", action: "edit", postId: 1)
+
+ expect(enqueued_trigger_data).to be_empty
+ end
+
+ it "ignores triggers set to fire on pauses" do
+ configuration["fire_on"] = "pause"
+ update_workflow_node(workflow, "trigger-1") { |node| node.merge("parameters" => configuration) }
+ publish_workflow!(workflow)
+ DiscourseWorkflows::WorkflowDependency.clear_cache!
+
+ save_draft("Magic words")
+
+ expect(enqueued_trigger_data).to be_empty
+ end
+
+ context "without phrases" do
+ let(:configuration) { { "fire_on" => "draft_saved" } }
+
+ it "fires at most once per interval for each draft" do
+ save_draft("Hello")
+ save_draft("Hello there")
+ expect(enqueued_trigger_data.size).to eq(1)
+
+ key = Discourse.redis.keys("discourse_workflows:composer_paused:*").sole
+ expect(Discourse.redis.ttl(key)).to be_within(1).of(
+ DiscourseWorkflows::ComposerPausedClaims::NO_PHRASES_INTERVAL,
+ )
+
+ Discourse.redis.del(key)
+ save_draft("Hello there again")
+ expect(enqueued_trigger_data.size).to eq(2)
+ expect(enqueued_trigger_data.last.dig("composer", "matched_phrases")).to eq([])
+ end
+ end
+
+ it "is rate limited per user" do
+ RateLimiter.enable
+ stub_const(DiscourseWorkflows::ComposerPausedClaims, "RATE_LIMIT", 1) do
+ save_draft("Magic words", draft_key: "new_topic_1")
+ save_draft("Magic words", draft_key: "new_topic_2")
+ end
+
+ expect(enqueued_trigger_data.size).to eq(1)
+ end
+
+ it "doesn't queue a scan while the user is rate limited" do
+ RateLimiter.enable
+ stub_const(DiscourseWorkflows::ComposerPausedClaims, "RATE_LIMIT", 1) do
+ save_draft("Magic words", draft_key: "new_topic_1")
+ allow(Scheduler::Defer).to receive(:later)
+
+ save_draft("Magic words", draft_key: "new_topic_2")
+ end
+
+ expect(Scheduler::Defer).not_to have_received(:later)
+ end
+
+ context "when scans run in the background" do
+ let(:scans) { [] }
+
+ def stub_scans(&handler)
+ allow(Scheduler::Defer).to receive(
+ :later,
+ ).and_wrap_original do |original, desc, *args, **kwargs, &block|
+ if desc == "discourse_workflows_composer_paused"
+ handler.call(block)
+ else
+ original.call(desc, *args, **kwargs, &block)
+ end
+ end
+ end
+
+ before { stub_scans { |scan| scans << scan } }
+ after { scans.each(&:call) }
+
+ it "queues one scan per draft, which reads the newest autosave" do
+ save_draft("Hello")
+ save_draft("Magic words")
+ save_draft("Hello", draft_key: "topic_#{topic.id}", action: "reply")
+
+ expect(scans.size).to eq(2)
+ expect(Scheduler::Defer).to have_received(:later).with(
+ "discourse_workflows_composer_paused",
+ current_user: user.id,
+ force: false,
+ ).twice
+
+ scans.shift.call
+ expect(enqueued_trigger_data.map { |data| data.dig("composer", "matched_phrases") }).to eq(
+ [["Magic words"]],
+ )
+
+ save_draft("Magic words, food stand")
+ expect(scans.size).to eq(2)
+ end
+
+ it "drops the scan when the queue is full" do
+ stub_scans { raise WorkQueue::WorkQueueFull }
+ save_draft("Magic words")
+
+ stub_scans { |scan| scans << scan }
+ save_draft("Magic words")
+
+ expect(scans.size).to eq(1)
+ end
+
+ it "lets the next autosave queue a scan when queueing fails" do
+ stub_scans { raise ThreadError }
+ save_draft("Magic words")
+
+ stub_scans { |scan| scans << scan }
+ save_draft("Magic words")
+
+ expect(scans.size).to eq(1)
+ end
+ end
+
+ it "doesn't match the phrases that already fired" do
+ save_draft("Magic words")
+ allow(DiscourseWorkflows::Nodes::ComposerPaused::V1).to receive(
+ :matched_phrases,
+ ).and_call_original
+
+ save_draft("Magic words, food stand")
+
+ expect(DiscourseWorkflows::Nodes::ComposerPaused::V1).to have_received(:matched_phrases).with(
+ ["food stand"],
+ "Magic words, food stand",
+ )
+ end
+
+ it "skips users outside the trigger's groups before matching" do
+ configuration["group_ids"] = [Fabricate(:group).id]
+ update_workflow_node(workflow, "trigger-1") { |node| node.merge("parameters" => configuration) }
+ publish_workflow!(workflow)
+ DiscourseWorkflows::WorkflowDependency.clear_cache!
+
+ allow(DiscourseWorkflows::Nodes::ComposerPaused::V1).to receive(:matched_phrases)
+ save_draft("Magic words")
+
+ expect(DiscourseWorkflows::Nodes::ComposerPaused::V1).not_to have_received(:matched_phrases)
+ expect(enqueued_trigger_data).to be_empty
+ end
+
+ it "does nothing when workflows are disabled" do
+ SiteSetting.enable_discourse_workflows = false
+
+ save_draft("Magic words")
+
+ expect(enqueued_trigger_data).to be_empty
+ end
+end
diff --git a/plugins/discourse-workflows/spec/lib/discourse_workflows/composer_snapshot_spec.rb b/plugins/discourse-workflows/spec/lib/discourse_workflows/composer_snapshot_spec.rb
new file mode 100644
index 00000000000..08f3f708ca4
--- /dev/null
+++ b/plugins/discourse-workflows/spec/lib/discourse_workflows/composer_snapshot_spec.rb
@@ -0,0 +1,90 @@
+# frozen_string_literal: true
+
+RSpec.describe DiscourseWorkflows::ComposerSnapshot do
+ describe ".own_text" do
+ it "removes quotes, quoted lines and HTML comments" do
+ raw = <<~MD
+ [quote="sam, post:1, topic:2"]Magic words[/quote]
+ [quote]a [quote]b[/quote] food stand[/quote]
+ > bad food
+ <!-- Magic words -->
+ Hello world
+ MD
+
+ expect(described_class.own_text(raw).squish).to eq("Hello world")
+ end
+
+ it "keeps unclosed quotes and comments as text" do
+ expect(described_class.own_text("[quote]Magic words")).to eq("[quote]Magic words")
+ expect(described_class.own_text("<!-- Magic words")).to eq("<!-- Magic words")
+ expect(described_class.own_text("Magic words[/quote]")).to eq("Magic words[/quote]")
+ end
+
+ it "keeps text around an unclosed quote while removing the closed ones inside it" do
+ expect(described_class.own_text("[quote]a [quote]b[/quote] Magic words")).to eq(
+ "[quote]a Magic words",
+ )
+ end
+
+ it "handles deeply nested quotes in linear time" do
+ depth = 2_000
+ raw = "#{"[quote]" * depth}Magic words#{"[/quote]" * depth} Hello"
+
+ started = Process.clock_gettime(Process::CLOCK_MONOTONIC)
+ text = described_class.own_text(raw)
+ elapsed = Process.clock_gettime(Process::CLOCK_MONOTONIC) - started
+
+ expect(text).to eq(" Hello")
+ expect(elapsed).to be < 0.5
+ end
+ end
+
+ describe "#composable?" do
+ fab!(:user) { Fabricate(:user, refresh_auto_groups: true) }
+ fab!(:shared_drafts_category, :category)
+ fab!(:shared_draft_topic) { Fabricate(:topic, category: shared_drafts_category) }
+
+ before do
+ SiteSetting.shared_drafts_category = shared_drafts_category.id
+ SiteSetting.shared_drafts_allowed_groups = Group::AUTO_GROUPS[:staff]
+ Fabricate(:shared_draft, topic: shared_draft_topic, category: Fabricate(:category))
+ end
+
+ def reply_to(topic)
+ described_class.new(
+ user:,
+ action: described_class::REPLY,
+ draft_key: "topic_#{topic.id}",
+ raw: "Magic words",
+ topic:,
+ )
+ end
+
+ it "is false for a topic the user can post in but can't see" do
+ expect(user.guardian.can_create_post_on_topic?(shared_draft_topic)).to eq(true)
+ expect(reply_to(shared_draft_topic)).not_to be_composable
+ end
+
+ it "is true for a topic the user can see" do
+ expect(reply_to(Fabricate(:topic))).to be_composable
+ end
+ end
+
+ describe "#own_text" do
+ fab!(:user)
+
+ it "only looks at what a post can hold" do
+ SiteSetting.max_post_length = 20
+ snapshot =
+ described_class.new(
+ user:,
+ action: "create_topic",
+ draft_key: "new_topic",
+ raw: "#{"a" * 20} Magic words",
+ )
+
+ expect(snapshot.raw.length).to eq(20)
+ expect(snapshot.own_text).not_to include("Magic words")
+ end
+ end
+end
diff --git a/plugins/discourse-workflows/spec/lib/discourse_workflows/composer_target_spec.rb b/plugins/discourse-workflows/spec/lib/discourse_workflows/composer_target_spec.rb
new file mode 100644
index 00000000000..50da1d019a6
--- /dev/null
+++ b/plugins/discourse-workflows/spec/lib/discourse_workflows/composer_target_spec.rb
@@ -0,0 +1,38 @@
+# frozen_string_literal: true
+
+RSpec.describe DiscourseWorkflows::ComposerTarget do
+ def exec_ctx(trigger_data)
+ DiscourseWorkflows::Executor::NodeExecutionContext.new(
+ input_items: [{ "json" => {} }],
+ flow_context: {
+ "$trigger" => trigger_data,
+ },
+ )
+ end
+
+ it "reads the composer from the trigger, not the current items" do
+ trigger_data = { "composer" => { "draft_key" => "topic_12", "session_id" => "session-1" } }
+
+ expect(described_class.from(exec_ctx(trigger_data))).to eq(
+ draft_key: "topic_12",
+ session_id: "session-1",
+ )
+ end
+
+ it "reads the requested item of a multi-item trigger" do
+ trigger_data = [
+ { "composer" => { "draft_key" => "new_topic" } },
+ { "composer" => { "draft_key" => "topic_12" } },
+ ]
+
+ expect(described_class.from(exec_ctx(trigger_data), 1)).to eq(
+ draft_key: "topic_12",
+ session_id: nil,
+ )
+ end
+
+ it "returns nil when another trigger started the workflow" do
+ expect(described_class.from(exec_ctx({ "post" => { "id" => 1 } }))).to be_nil
+ expect(described_class.from(exec_ctx(nil))).to be_nil
+ end
+end
diff --git a/plugins/discourse-workflows/spec/lib/discourse_workflows/nodes/composer_message_spec.rb b/plugins/discourse-workflows/spec/lib/discourse_workflows/nodes/composer_message_spec.rb
new file mode 100644
index 00000000000..7bb3371ead1
--- /dev/null
+++ b/plugins/discourse-workflows/spec/lib/discourse_workflows/nodes/composer_message_spec.rb
@@ -0,0 +1,84 @@
+# frozen_string_literal: true
+
+RSpec.describe DiscourseWorkflows::Nodes::ComposerMessage::V1 do
+ fab!(:user)
+
+ let(:sandbox) { DiscourseWorkflows::JsSandbox.new({ "$json" => {} }) }
+ after { sandbox.dispose }
+
+ let(:config) { { "title" => "Food resources", "body" => "Visit [our guide](/t/1)" } }
+ let(:context_user) { user }
+ let(:trigger_data) do
+ { "composer" => { "draft_key" => "new_topic", "session_id" => "session-1" } }
+ end
+ let(:execution_context) do
+ DiscourseWorkflows::Executor::NodeExecutionContext.new(
+ input_items: [{ "json" => { "anything" => true } }],
+ parameters: config,
+ property_schema: described_class.property_schema,
+ resolver: DiscourseWorkflows::ExpressionResolver.new({ "$json" => {} }, sandbox: sandbox),
+ flow_context: {
+ "$trigger" => trigger_data,
+ },
+ user: context_user,
+ )
+ end
+
+ describe "#execute" do
+ it "publishes the message to the composer that triggered the workflow" do
+ result = nil
+ messages =
+ MessageBus.track_publish(described_class.user_channel(user.id)) do
+ result = described_class.new(parameters: config).execute(execution_context)
+ end
+
+ expect(result).to eq([execution_context.input_items])
+ expect(messages.size).to eq(1)
+ expect(messages.first.user_ids).to eq([user.id])
+ expect(messages.first.data).to eq(
+ type: "show_composer_message",
+ draft_key: "new_topic",
+ session_id: "session-1",
+ title: "Food resources",
+ body: PrettyText.cook("Visit [our guide](/t/1)"),
+ )
+ end
+
+ it "sanitizes the body" do
+ config["body"] = "<script>alert(1)</script>Hello"
+
+ messages =
+ MessageBus.track_publish(described_class.user_channel(user.id)) do
+ described_class.new(parameters: config).execute(execution_context)
+ end
+
+ expect(messages.first.data[:body]).not_to include("<script")
+ end
+
+ context "without a user" do
+ let(:context_user) { nil }
+
+ it "raises a node error" do
+ expect {
+ described_class.new(parameters: config).execute(execution_context)
+ }.to raise_error(
+ DiscourseWorkflows::NodeError,
+ I18n.t("discourse_workflows.errors.composer_message.no_user"),
+ )
+ end
+ end
+
+ context "when the composer trigger did not start the workflow" do
+ let(:trigger_data) { { "post" => { "id" => 1 } } }
+
+ it "raises a node error" do
+ expect {
+ described_class.new(parameters: config).execute(execution_context)
+ }.to raise_error(
+ DiscourseWorkflows::NodeError,
+ I18n.t("discourse_workflows.errors.composer_message.no_composer"),
+ )
+ end
+ end
+ end
+end
diff --git a/plugins/discourse-workflows/spec/lib/discourse_workflows/nodes/composer_paused_spec.rb b/plugins/discourse-workflows/spec/lib/discourse_workflows/nodes/composer_paused_spec.rb
new file mode 100644
index 00000000000..18c4a998313
--- /dev/null
+++ b/plugins/discourse-workflows/spec/lib/discourse_workflows/nodes/composer_paused_spec.rb
@@ -0,0 +1,187 @@
+# frozen_string_literal: true
+
+RSpec.describe DiscourseWorkflows::Nodes::ComposerPaused::V1 do
+ fab!(:user) { Fabricate(:user, refresh_auto_groups: true) }
+ fab!(:category)
+ fab!(:subcategory) { Fabricate(:category, parent_category: category) }
+ fab!(:topic) { Fabricate(:topic, category:) }
+
+ def snapshot(**attrs)
+ DiscourseWorkflows::ComposerSnapshot.new(
+ **{ user:, action: "create_topic", draft_key: "new_topic", raw: "Some text" }.merge(attrs),
+ )
+ end
+
+ describe "#output" do
+ it "matches the declared schema for a new topic" do
+ output =
+ described_class.new(
+ snapshot(title: "Lunch review", category_id: category.id),
+ ["food stand"],
+ ).output
+
+ expect(output).to match_node_output_schema(described_class)
+ expect(output[:user][:id]).to eq(user.id)
+ expect(output[:actor][:id]).to eq(user.id)
+ expect(output[:topic]).to be_nil
+ expect(output[:composer]).to eq(
+ action: "create_topic",
+ draft_key: "new_topic",
+ session_id: nil,
+ title: "Lunch review",
+ raw: "Some text",
+ category_id: category.id,
+ topic_id: nil,
+ reply_to_post_number: nil,
+ matched_phrases: ["food stand"],
+ )
+ end
+
+ it "matches the declared schema for a reply" do
+ output =
+ described_class.new(
+ snapshot(
+ action: "reply",
+ draft_key: "topic_#{topic.id}",
+ session_id: "session-1",
+ topic:,
+ reply_to_post_number: 2,
+ ),
+ ).output
+
+ expect(output).to match_node_output_schema(described_class)
+ expect(output[:topic][:id]).to eq(topic.id)
+ expect(output[:composer]).to include(
+ action: "reply",
+ session_id: "session-1",
+ topic_id: topic.id,
+ category_id: category.id,
+ reply_to_post_number: 2,
+ matched_phrases: [],
+ )
+ end
+ end
+
+ describe ".matched_phrases" do
+ let(:phrases) do
+ described_class.phrases("phrases" => ["Magic words", "bad food*", " food stand "])
+ end
+
+ it "matches whole phrases ignoring case, with watched word wildcards" do
+ expect(
+ described_class.matched_phrases(phrases, "Some MAGIC WORDS and bad foods"),
+ ).to contain_exactly("Magic words", "bad food*")
+ expect(described_class.matched_phrases(phrases, "food stands")).to be_empty
+ expect(described_class.matched_phrases(phrases, "food stand")).to eq(["food stand"])
+ end
+ end
+
+ describe ".validate_configuration" do
+ def errors_for(phrases)
+ errors = ActiveModel::Errors.new(DiscourseWorkflows::Workflow.new)
+ described_class.validate_configuration({ "phrases" => phrases }, errors)
+ errors.full_messages
+ end
+
+ it "accepts valid phrases" do
+ expect(errors_for(["Magic words", "bad food*"])).to be_empty
+ end
+
+ it "rejects phrases that match nearly any text" do
+ expect(errors_for(["*", "* *"]).size).to eq(2)
+ end
+
+ it "rejects invalid and match-anything regular expressions" do
+ SiteSetting.watched_words_regular_expressions = true
+
+ expect(errors_for(["Magic words|", ".", "(unclosed"]).size).to eq(3)
+ expect(errors_for(['\d{4}'])).to be_empty
+ end
+
+ it "rejects regular expressions that could take too long to match" do
+ SiteSetting.watched_words_regular_expressions = true
+
+ expect(errors_for(['(a+)+\1'])).to eq(
+ [I18n.t("discourse_workflows.errors.composer_paused.invalid_phrase", phrase: '(a+)+\1')],
+ )
+ expect(described_class.patterns("phrases" => ['(a+)+\1'])).to be_empty
+ end
+
+ it "rejects too many or too long phrases" do
+ expect(errors_for(Array.new(described_class::MAX_PHRASES + 1) { |i| "phrase #{i}" })).to eq(
+ [
+ I18n.t(
+ "discourse_workflows.errors.composer_paused.too_many_phrases",
+ max: described_class::MAX_PHRASES,
+ ),
+ ],
+ )
+ expect(errors_for(["a" * (described_class::MAX_PHRASE_LENGTH + 1)]).size).to eq(1)
+ end
+ end
+
+ describe ".matches_snapshot?" do
+ it "only fires for the configured composer actions" do
+ parameters = { "composer_actions" => ["reply"] }
+
+ expect(described_class.matches_snapshot?(parameters, snapshot)).to eq(false)
+ expect(
+ described_class.matches_snapshot?(
+ parameters,
+ snapshot(action: "reply", draft_key: "topic_#{topic.id}", topic:),
+ ),
+ ).to eq(true)
+ end
+
+ it "never fires for replies to personal messages" do
+ pm = Fabricate(:private_message_topic, user:)
+
+ expect(
+ described_class.matches_snapshot?(
+ {},
+ snapshot(action: "reply", draft_key: "topic_#{pm.id}", topic: pm),
+ ),
+ ).to eq(false)
+ end
+
+ it "filters by category, including subcategories unless disabled" do
+ parameters = { "category_ids" => [category.id] }
+
+ expect(described_class.matches_snapshot?(parameters, snapshot)).to eq(false)
+ expect(
+ described_class.matches_snapshot?(parameters, snapshot(category_id: subcategory.id)),
+ ).to eq(true)
+ expect(
+ described_class.matches_snapshot?(
+ parameters.merge("include_subcategories" => false),
+ snapshot(category_id: subcategory.id),
+ ),
+ ).to eq(false)
+ end
+
+ it "filters by group, firing for everyone without groups" do
+ group = Fabricate(:group)
+
+ expect(described_class.matches_snapshot?({}, snapshot)).to eq(true)
+ expect(described_class.matches_snapshot?({ "group_ids" => [group.id] }, snapshot)).to eq(
+ false,
+ )
+
+ group.add(user)
+ expect(
+ described_class.matches_snapshot?(
+ { "group_ids" => [group.id] },
+ snapshot(user: User.find(user.id)),
+ ),
+ ).to eq(true)
+ end
+
+ it "requires the user to be able to post there" do
+ staff_category = Fabricate(:private_category, group: Group[:staff])
+
+ expect(described_class.matches_snapshot?({}, snapshot(category_id: staff_category.id))).to eq(
+ false,
+ )
+ 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
index 07c7ec37085..c392167824e 100644
--- a/plugins/discourse-workflows/spec/models/discourse_workflows/workflow_dependency_spec.rb
+++ b/plugins/discourse-workflows/spec/models/discourse_workflows/workflow_dependency_spec.rb
@@ -59,4 +59,21 @@ RSpec.describe DiscourseWorkflows::WorkflowDependency do
expect(described_class.cached_user_modals?).to eq(false)
end
end
+
+ describe ".references_node_type?" do
+ it "is true for node types used by a draft or published workflow" do
+ graph =
+ build_workflow_graph do |g|
+ g.node "t1", "trigger:composer_paused"
+ g.node "c1", "action:composer_message", configuration: { "title" => "Hi", "body" => "Hi" }
+ g.chain "t1", "c1"
+ 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:)
+
+ expect(described_class.references_node_type?("action:composer_message")).to eq(true)
+ expect(described_class.references_node_type?("action:modal")).to eq(false)
+ end
+ end
end
diff --git a/plugins/discourse-workflows/spec/requests/discourse_workflows/composer_paused_controller_spec.rb b/plugins/discourse-workflows/spec/requests/discourse_workflows/composer_paused_controller_spec.rb
new file mode 100644
index 00000000000..3e15a722b94
--- /dev/null
+++ b/plugins/discourse-workflows/spec/requests/discourse_workflows/composer_paused_controller_spec.rb
@@ -0,0 +1,103 @@
+# frozen_string_literal: true
+
+RSpec.describe DiscourseWorkflows::ComposerPausedController do
+ fab!(:admin)
+ fab!(:user) { Fabricate(:user, refresh_auto_groups: true) }
+ fab!(:workflow) do
+ graph =
+ build_workflow_graph do |g|
+ g.node "trigger-1",
+ "trigger:composer_paused",
+ configuration: {
+ "phrases" => ["Magic words"],
+ }
+ end
+ Fabricate(:discourse_workflows_workflow, created_by: admin, published: true, **graph)
+ end
+
+ let(:params) do
+ {
+ draft_key: "new_topic",
+ session_id: "session-1",
+ composer_action: "create_topic",
+ raw: "Maybe I should just say the Magic words",
+ }
+ end
+
+ before { DiscourseWorkflows::WorkflowDependency.clear_cache! }
+
+ describe "POST /discourse-workflows/trigger-composer-paused" do
+ it "requires authentication" do
+ post "/discourse-workflows/trigger-composer-paused.json", params: params
+
+ expect(response).to have_http_status(:forbidden)
+ end
+
+ context "when signed in" do
+ before { sign_in(user) }
+
+ it "returns 204 and enqueues the workflow" do
+ expect {
+ post "/discourse-workflows/trigger-composer-paused.json", params: params
+ }.to change { Jobs::DiscourseWorkflows::ExecuteWorkflow.jobs.size }.by(1)
+
+ expect(response).to have_http_status(:no_content)
+ end
+
+ it "returns 400 when the contract is invalid" do
+ post "/discourse-workflows/trigger-composer-paused.json", params: params.except(:draft_key)
+
+ expect(response).to have_http_status(:bad_request)
+ end
+
+ it "returns 204 without firing when nothing matches" do
+ expect {
+ post "/discourse-workflows/trigger-composer-paused.json",
+ params: params.merge(raw: "Nothing to see")
+ }.not_to change { Jobs::DiscourseWorkflows::ExecuteWorkflow.jobs.size }
+
+ expect(response).to have_http_status(:no_content)
+ end
+
+ it "returns 429 when the rate limit runs out before every workflow fired" do
+ graph =
+ build_workflow_graph do |g|
+ g.node "trigger-1", "trigger:composer_paused", configuration: {}
+ end
+ Fabricate(:discourse_workflows_workflow, created_by: admin, published: true, **graph)
+
+ RateLimiter.enable
+ stub_const(DiscourseWorkflows::ComposerPausedClaims, "RATE_LIMIT", 1) do
+ expect {
+ post "/discourse-workflows/trigger-composer-paused.json", params: params
+ }.to change { Jobs::DiscourseWorkflows::ExecuteWorkflow.jobs.size }.by(1)
+ end
+
+ expect(response).to have_http_status(:too_many_requests)
+ expect(response.parsed_body.dig("extras", "wait_seconds")).to be_present
+ end
+
+ it "limits requests that fire nothing" do
+ RateLimiter.enable
+ stub_const(DiscourseWorkflows::ComposerPausedClaims, "ATTEMPT_LIMIT", 1) do
+ 2.times do
+ post "/discourse-workflows/trigger-composer-paused.json",
+ params: params.merge(raw: "Nothing to see")
+ end
+ end
+
+ expect(response).to have_http_status(:too_many_requests)
+ end
+
+ it "is rate limited" do
+ RateLimiter.enable
+ stub_const(DiscourseWorkflows::ComposerPausedClaims, "RATE_LIMIT", 1) do
+ post "/discourse-workflows/trigger-composer-paused.json", params: params
+ post "/discourse-workflows/trigger-composer-paused.json", params: params
+ end
+
+ expect(response).to have_http_status(:too_many_requests)
+ end
+ 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
index 064e9d66cb1..2972e8a7d19 100644
--- a/plugins/discourse-workflows/spec/serializers/current_user_modal_spec.rb
+++ b/plugins/discourse-workflows/spec/serializers/current_user_modal_spec.rb
@@ -41,4 +41,34 @@ RSpec.describe CurrentUserSerializer do
)
end
end
+
+ describe "discourse_workflows_composer_message_last_id" do
+ it "is omitted when no workflow uses a composer message node" do
+ expect(serialized_user).not_to have_key("discourse_workflows_composer_message_last_id")
+ end
+
+ it "is the channel's last id when a workflow uses a composer message node" do
+ graph =
+ build_workflow_graph do |g|
+ g.node "t1", "trigger:composer_paused"
+ g.node "c1",
+ "action:composer_message",
+ configuration: {
+ "title" => "Food resources",
+ "body" => "Our community can help.",
+ }
+ g.chain "t1", "c1"
+ 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:)
+
+ channel = DiscourseWorkflows::Nodes::ComposerMessage::V1.user_channel(user.id)
+ MessageBus.publish(channel, { type: "show_composer_message" }, user_ids: [user.id])
+
+ expect(serialized_user["discourse_workflows_composer_message_last_id"]).to eq(
+ MessageBus.last_id(channel),
+ )
+ end
+ end
end
diff --git a/plugins/discourse-workflows/spec/serializers/site_serializer_spec.rb b/plugins/discourse-workflows/spec/serializers/site_serializer_spec.rb
index 11d5d5bc9c5..c835aad51cc 100644
--- a/plugins/discourse-workflows/spec/serializers/site_serializer_spec.rb
+++ b/plugins/discourse-workflows/spec/serializers/site_serializer_spec.rb
@@ -179,4 +179,91 @@ RSpec.describe SiteSerializer do
)
end
end
+
+ describe "#composer_paused_workflows" do
+ before { DiscourseWorkflows::WorkflowDependency.clear_cache! }
+
+ fab!(:group)
+ fab!(:member) { Fabricate(:user).tap { |member| group.add(member) } }
+ fab!(:category)
+
+ fab!(:everyone_workflow) do
+ graph =
+ build_workflow_graph do |g|
+ g.node "trigger-1",
+ "trigger:composer_paused",
+ configuration: {
+ "phrases" => ["Magic words", "bad food*"],
+ "category_ids" => [category.id],
+ }
+ end
+ Fabricate(:discourse_workflows_workflow, created_by: admin, published: true, **graph)
+ end
+
+ fab!(:group_workflow) do
+ graph =
+ build_workflow_graph do |g|
+ g.node "trigger-1",
+ "trigger:composer_paused",
+ configuration: {
+ "composer_actions" => ["reply"],
+ "group_ids" => [group.id],
+ }
+ end
+ Fabricate(:discourse_workflows_workflow, created_by: admin, published: true, **graph)
+ end
+
+ fab!(:draft_saved_workflow) do
+ graph =
+ build_workflow_graph do |g|
+ g.node "trigger-1",
+ "trigger:composer_paused",
+ configuration: {
+ "fire_on" => "draft_saved",
+ "phrases" => ["food stand"],
+ }
+ end
+ Fabricate(:discourse_workflows_workflow, created_by: admin, published: true, **graph)
+ end
+
+ def serialize(user)
+ guardian = Guardian.new(user)
+ described_class.new(Site.new(guardian), scope: guardian, root: false).as_json
+ end
+
+ it "includes pause triggers for the user, as patterns and without group ids" do
+ expect(serialize(member)[:composer_paused_workflows]).to contain_exactly(
+ {
+ trigger_node_id: "trigger-1",
+ workflow_id: everyone_workflow.id,
+ patterns: [
+ WordWatcher.word_to_regexp("Magic words"),
+ WordWatcher.word_to_regexp("bad food*"),
+ ],
+ composer_actions: %w[create_topic reply],
+ category_ids: [category.id],
+ include_subcategories: true,
+ },
+ {
+ trigger_node_id: "trigger-1",
+ workflow_id: group_workflow.id,
+ patterns: [],
+ composer_actions: ["reply"],
+ category_ids: [],
+ include_subcategories: true,
+ },
+ )
+ end
+
+ it "leaves out triggers for other groups and draft-saved phrases" do
+ workflows = serialize(user)[:composer_paused_workflows]
+
+ expect(workflows.map { |workflow| workflow[:workflow_id] }).to eq([everyone_workflow.id])
+ expect(workflows.to_json).not_to include("food stand")
+ end
+
+ it "is not included for anonymous users" do
+ expect(serialize(nil)).not_to have_key(:composer_paused_workflows)
+ end
+ end
end
diff --git a/plugins/discourse-workflows/spec/services/discourse_workflows/workflow/trigger_composer_paused_spec.rb b/plugins/discourse-workflows/spec/services/discourse_workflows/workflow/trigger_composer_paused_spec.rb
new file mode 100644
index 00000000000..1db88632aee
--- /dev/null
+++ b/plugins/discourse-workflows/spec/services/discourse_workflows/workflow/trigger_composer_paused_spec.rb
@@ -0,0 +1,240 @@
+# frozen_string_literal: true
+
+RSpec.describe DiscourseWorkflows::Workflow::TriggerComposerPaused do
+ describe described_class::Contract, type: :model do
+ it { is_expected.to validate_presence_of(:draft_key) }
+ it { is_expected.to validate_presence_of(:session_id) }
+ it { is_expected.to validate_inclusion_of(:composer_action).in_array(%w[create_topic reply]) }
+
+ it "requires a topic for replies" do
+ contract = described_class.new(composer_action: "reply")
+ expect(contract).to validate_presence_of(:topic_id)
+ end
+
+ it "limits the text to what a post allows" do
+ SiteSetting.max_post_length = 20
+
+ expect(described_class.new(raw: "a" * 21).tap(&:valid?).errors[:raw]).to be_present
+ end
+ end
+
+ describe ".call" do
+ subject(:result) { described_class.call(params:, **dependencies) }
+
+ fab!(:admin)
+ fab!(:user) { Fabricate(:user, refresh_auto_groups: true) }
+ fab!(:topic)
+
+ let(:configuration) { { "phrases" => ["Magic words", "food stand"] } }
+ let!(:workflow) do
+ graph =
+ build_workflow_graph do |g|
+ g.node "trigger-1", "trigger:composer_paused", configuration: configuration
+ end
+ Fabricate(:discourse_workflows_workflow, created_by: admin, published: true, **graph)
+ end
+
+ let(:params) do
+ {
+ draft_key: "new_topic",
+ session_id: "session-1",
+ composer_action: "create_topic",
+ title: "Lunch review",
+ raw: "Meet me at the food stand",
+ }
+ end
+ let(:dependencies) { { guardian: user.guardian } }
+
+ before { DiscourseWorkflows::WorkflowDependency.clear_cache! }
+
+ context "when contract is invalid" do
+ let(:params) { super().except(:draft_key) }
+
+ it { is_expected.to fail_a_contract }
+ end
+
+ shared_examples "doesn't fire" do
+ it "enqueues nothing" do
+ expect { result }.not_to change { Jobs::DiscourseWorkflows::ExecuteWorkflow.jobs.size }
+ expect(result).to run_successfully
+ end
+ end
+
+ context "when the workflow is unpublished" do
+ before { unpublish_workflow!(workflow) }
+
+ include_examples "doesn't fire"
+ end
+
+ context "when the trigger fires on draft saves" do
+ let(:configuration) { super().merge("fire_on" => "draft_saved") }
+
+ include_examples "doesn't fire"
+ end
+
+ context "when the user is in none of the trigger's groups" do
+ let(:configuration) { super().merge("group_ids" => [Fabricate(:group).id]) }
+
+ include_examples "doesn't fire"
+ end
+
+ context "when replying to a personal message" do
+ fab!(:pm) { Fabricate(:private_message_topic, user:) }
+
+ let(:params) do
+ super().merge(composer_action: "reply", topic_id: pm.id, draft_key: "topic_#{pm.id}")
+ end
+
+ include_examples "doesn't fire"
+ end
+
+ context "when no phrase matches" do
+ let(:params) { super().merge(raw: "[quote=\"sam, post:1, topic:2\"]food stand[/quote]") }
+
+ include_examples "doesn't fire"
+ end
+
+ context "when everything's ok" do
+ it { is_expected.to run_successfully }
+
+ it "enqueues the workflow with the matched phrases" do
+ result
+
+ job_args = Jobs::DiscourseWorkflows::ExecuteWorkflow.jobs.last["args"].first
+ expect(job_args).to include(
+ "workflow_id" => workflow.id,
+ "trigger_node_id" => "trigger-1",
+ "user_id" => user.id,
+ )
+ expect(job_args["trigger_data"]["composer"]).to include(
+ "draft_key" => "new_topic",
+ "title" => "Lunch review",
+ "matched_phrases" => ["food stand"],
+ )
+ end
+ end
+
+ context "when the phrases already fired in this session" do
+ before { described_class.call(params:, **dependencies) }
+
+ include_examples "doesn't fire"
+ end
+
+ context "when several workflows match" do
+ let!(:other_workflow) do
+ graph =
+ build_workflow_graph do |g|
+ g.node "trigger-1", "trigger:composer_paused", configuration: {}
+ end
+ Fabricate(:discourse_workflows_workflow, created_by: admin, published: true, **graph)
+ end
+
+ it "fires each of them" do
+ result
+
+ expect(
+ Jobs::DiscourseWorkflows::ExecuteWorkflow.jobs.map do |job|
+ job["args"].first["workflow_id"]
+ end,
+ ).to contain_exactly(workflow.id, other_workflow.id)
+ end
+
+ it "fails when the rate limit runs out, and fires the rest once it allows" do
+ RateLimiter.enable
+ stub_const(DiscourseWorkflows::ComposerPausedClaims, "RATE_LIMIT", 1) do
+ expect(result).to fail_a_step(:fire_triggers)
+ end
+ expect(Jobs::DiscourseWorkflows::ExecuteWorkflow.jobs.size).to eq(1)
+
+ expect(described_class.call(params:, **dependencies)).to run_successfully
+ expect(
+ Jobs::DiscourseWorkflows::ExecuteWorkflow.jobs.map do |job|
+ job["args"].first["workflow_id"]
+ end,
+ ).to contain_exactly(workflow.id, other_workflow.id)
+ end
+ end
+
+ context "when the run can't be recorded" do
+ before do
+ allow_any_instance_of(RateLimiter).to receive(:performed!).and_return(false)
+ described_class.call(params:, **dependencies)
+ end
+
+ it "gives the phrase back, so it fires later" do
+ expect(Jobs::DiscourseWorkflows::ExecuteWorkflow.jobs).to be_empty
+
+ allow_any_instance_of(RateLimiter).to receive(:performed!).and_call_original
+ result
+
+ expect(
+ Jobs::DiscourseWorkflows::ExecuteWorkflow.jobs.sole["args"].first["trigger_data"][
+ "composer"
+ ][
+ "matched_phrases"
+ ],
+ ).to eq(["food stand"])
+ end
+ end
+
+ context "when a new phrase matches in the same session" do
+ before { described_class.call(params: params.merge(raw: "food stand"), **dependencies) }
+
+ let(:params) { super().merge(raw: "food stand and the Magic words") }
+
+ it "only sends the new phrase" do
+ result
+
+ expect(
+ Jobs::DiscourseWorkflows::ExecuteWorkflow.jobs.last["args"].first["trigger_data"][
+ "composer"
+ ][
+ "matched_phrases"
+ ],
+ ).to eq(["Magic words"])
+ end
+ end
+
+ context "when the composer was reopened" do
+ before { described_class.call(params: params.merge(session_id: "session-1"), **dependencies) }
+
+ let(:params) { super().merge(session_id: "session-2") }
+
+ it { is_expected.to run_successfully }
+ end
+
+ context "when the trigger has no phrases" do
+ let(:configuration) { {} }
+ let(:params) { super().merge(raw: "Anything at all") }
+
+ it "enqueues the workflow" do
+ expect { result }.to change { Jobs::DiscourseWorkflows::ExecuteWorkflow.jobs.size }.by(1)
+ expect(result).to run_successfully
+ end
+ end
+
+ context "when replying to a topic" do
+ let(:params) do
+ super().merge(
+ composer_action: "reply",
+ topic_id: topic.id,
+ draft_key: "topic_#{topic.id}",
+ reply_to_post_number: 1,
+ )
+ end
+
+ it "includes the topic" do
+ result
+
+ trigger_data =
+ Jobs::DiscourseWorkflows::ExecuteWorkflow.jobs.last["args"].first["trigger_data"]
+ expect(trigger_data["topic"]).to include("id" => topic.id)
+ expect(trigger_data["composer"]).to include(
+ "session_id" => "session-1",
+ "topic_id" => topic.id,
+ "reply_to_post_number" => 1,
+ )
+ end
+ end
+ end
+end
diff --git a/plugins/discourse-workflows/test/javascripts/acceptance/workflows-composer-paused-test.js b/plugins/discourse-workflows/test/javascripts/acceptance/workflows-composer-paused-test.js
new file mode 100644
index 00000000000..3de9f8399cc
--- /dev/null
+++ b/plugins/discourse-workflows/test/javascripts/acceptance/workflows-composer-paused-test.js
@@ -0,0 +1,179 @@
+import {
+ click,
+ fillIn,
+ settled,
+ triggerKeyEvent,
+ visit,
+} from "@ember/test-helpers";
+import { test } from "qunit";
+import {
+ acceptance,
+ loggedInUser,
+ publishToMessageBus,
+} from "discourse/tests/helpers/qunit-helpers";
+
+const WORD = "[\\p{L}\\p{M}\\p{N}\\p{Pc}]";
+
+acceptance("Discourse Workflows | Composer paused", function (needs) {
+ needs.user({ discourse_workflows_composer_message_last_id: 0 });
+ needs.settings({ allow_uncategorized_topics: true });
+ needs.site({
+ composer_paused_workflows: [
+ {
+ workflow_id: 1,
+ trigger_node_id: "trigger-1",
+ patterns: [`(?:(?<!${WORD}))(food stand)(?:(?!${WORD}))`],
+ composer_actions: ["create_topic", "reply"],
+ category_ids: [],
+ include_subcategories: true,
+ },
+ ],
+ });
+
+ let requests = [];
+ let drafts = [];
+
+ needs.pretender((server, helper) => {
+ server.post("/discourse-workflows/trigger-composer-paused", (request) => {
+ requests.push(helper.parsePostData(request.requestBody));
+ return helper.response(204, "");
+ });
+ server.post("/drafts.json", (request) => {
+ drafts.push(JSON.parse(helper.parsePostData(request.requestBody).data));
+ return helper.response({ success: "OK", draft_sequence: 1 });
+ });
+ });
+
+ needs.hooks.beforeEach(() => {
+ requests = [];
+ drafts = [];
+ });
+
+ function channel() {
+ return `/discourse-workflows/composer-message/${loggedInUser().id}`;
+ }
+
+ function composerModel(owner) {
+ return owner.lookup("service:composer").model;
+ }
+
+ function sessionId(owner) {
+ return owner
+ .lookup("service:workflows-composer-session")
+ .idFor(composerModel(owner));
+ }
+
+ test("fires the trigger when the user pauses after a phrase", async function (assert) {
+ await visit("/");
+ await click("#create-topic");
+ await fillIn(".d-editor-input", "Meet me at the food stand");
+ await triggerKeyEvent(".d-editor-input", "keyup", "Y");
+
+ assert.strictEqual(requests.length, 1);
+ assert.strictEqual(
+ requests[0].draft_key,
+ composerModel(this.owner).draftKey
+ );
+ assert.strictEqual(requests[0].raw, "Meet me at the food stand");
+ assert.strictEqual(requests[0].session_id, sessionId(this.owner));
+ });
+
+ test("a reply sends the post it targets, until it replies to the topic instead", async function (assert) {
+ await visit("/t/internationalization-localization/280");
+ await click("article#post_3 button.reply");
+ await fillIn(".d-editor-input", "Meet me at the food stand");
+ await triggerKeyEvent(".d-editor-input", "keyup", "Y");
+
+ assert.strictEqual(requests.length, 1);
+ assert.strictEqual(requests[0].reply_to_post_number, "3");
+
+ await click(".composer-actions-trigger");
+ await click("[data-action-id='reply_to_topic']");
+ await triggerKeyEvent(".d-editor-input", "keyup", "Y");
+
+ assert.strictEqual(requests.length, 2, "the new reply fires again");
+ assert.false(
+ "reply_to_post_number" in requests[1],
+ "the reply to the topic has no target"
+ );
+ });
+
+ test("autosaves carry the composer session", async function (assert) {
+ await visit("/");
+ await click("#create-topic");
+ await fillIn(".d-editor-input", "Meet me at the food stand");
+
+ assert.strictEqual(
+ drafts.at(-1)?.workflowsSessionId,
+ sessionId(this.owner)
+ );
+ });
+
+ test("shows a composer message for the open composer", async function (assert) {
+ await visit("/");
+ await click("#create-topic");
+ const draftKey = composerModel(this.owner).draftKey;
+
+ await publishToMessageBus(channel(), {
+ type: "show_composer_message",
+ draft_key: "topic_1",
+ session_id: sessionId(this.owner),
+ title: "Not this draft",
+ body: "<p>Ignored</p>",
+ });
+ await settled();
+ assert
+ .dom(".workflows-composer-message")
+ .doesNotExist("ignores messages for another draft");
+
+ await publishToMessageBus(channel(), {
+ type: "show_composer_message",
+ draft_key: draftKey,
+ session_id: "another-composer",
+ title: "Not this composer",
+ body: "<p>Ignored</p>",
+ });
+ await settled();
+ assert
+ .dom(".workflows-composer-message")
+ .doesNotExist(
+ "ignores messages for another composer with the same draft"
+ );
+
+ await publishToMessageBus(channel(), {
+ type: "show_composer_message",
+ draft_key: draftKey,
+ session_id: sessionId(this.owner),
+ title: "Food resources",
+ body: "<p>Our community can <a href='/categories'>help</a>.</p>",
+ });
+ await settled();
+
+ assert
+ .dom(".workflows-composer-message h3")
+ .hasText("Food resources", "shows the title");
+ assert
+ .dom(".workflows-composer-message a[href='/categories']")
+ .hasText("help", "renders the cooked body");
+ });
+
+ test("doesn't show a composer message once the composer is minimized", async function (assert) {
+ await visit("/");
+ await click("#create-topic");
+ const draftKey = composerModel(this.owner).draftKey;
+ const session = sessionId(this.owner);
+ await click(".toggle-minimize");
+
+ await publishToMessageBus(channel(), {
+ type: "show_composer_message",
+ draft_key: draftKey,
+ session_id: session,
+ title: "Food resources",
+ body: "<p>Hello</p>",
+ });
+ await settled();
+ await click("#reply-control");
+
+ assert.dom(".workflows-composer-message").doesNotExist();
+ });
+});
diff --git a/plugins/discourse-workflows/test/javascripts/unit/lib/phrase-matcher-test.js b/plugins/discourse-workflows/test/javascripts/unit/lib/phrase-matcher-test.js
new file mode 100644
index 00000000000..aed442097d1
--- /dev/null
+++ b/plugins/discourse-workflows/test/javascripts/unit/lib/phrase-matcher-test.js
@@ -0,0 +1,63 @@
+import { module, test } from "qunit";
+import PhraseMatcher from "discourse/plugins/discourse-workflows/discourse/lib/phrase-matcher";
+
+module("Discourse Workflows | Unit | Lib | phrase matcher", function () {
+ test("matches patterns ignoring case, skipping ones that don't compile", async function (assert) {
+ const matcher = new PhraseMatcher();
+
+ try {
+ const matched = await matcher.match("Some MAGIC WORDS", [
+ "(magic words)",
+ "(food stand)",
+ "(?<name>bad",
+ ]);
+
+ assert.deepEqual([...matched], ["(magic words)"]);
+ } finally {
+ matcher.destroy();
+ }
+ });
+
+ test("a pattern that keeps running too long is skipped from then on", async function (assert) {
+ const matcher = new PhraseMatcher({ timeoutMs: 100 });
+ const backtracking = "^(a+)+$";
+ const slowText = `${"a".repeat(40)}! food stand`;
+
+ try {
+ const matched = await matcher.match(slowText, [
+ backtracking,
+ "(food stand)",
+ ]);
+ assert.deepEqual(
+ [...matched],
+ ["(food stand)"],
+ "the other patterns still match"
+ );
+
+ const once = await matcher.match("aaaa", [backtracking]);
+ assert.deepEqual([...once], [backtracking], "one timeout is forgiven");
+
+ await matcher.match(slowText, [backtracking]);
+ const twice = await matcher.match("aaaa", [backtracking]);
+ assert.deepEqual([...twice], [], "a second timeout skips it");
+ } finally {
+ matcher.destroy();
+ }
+ });
+
+ test("overlapping matches each get their own answer", async function (assert) {
+ const matcher = new PhraseMatcher();
+
+ try {
+ const [first, second] = await Promise.all([
+ matcher.match("Magic words", ["(magic words)", "(food stand)"]),
+ matcher.match("food stand", ["(magic words)", "(food stand)"]),
+ ]);
+
+ assert.deepEqual([...first], ["(magic words)"]);
+ assert.deepEqual([...second], ["(food stand)"]);
+ } finally {
+ matcher.destroy();
+ }
+ });
+});
diff --git a/plugins/discourse-workflows/test/javascripts/unit/services/workflows-composer-paused-test.js b/plugins/discourse-workflows/test/javascripts/unit/services/workflows-composer-paused-test.js
new file mode 100644
index 00000000000..bba4178cf42
--- /dev/null
+++ b/plugins/discourse-workflows/test/javascripts/unit/services/workflows-composer-paused-test.js
@@ -0,0 +1,440 @@
+import { settled, waitUntil } from "@ember/test-helpers";
+import { setupTest } from "ember-qunit";
+import { module, test } from "qunit";
+import sinon from "sinon";
+import Composer, {
+ CREATE_TOPIC,
+ EDIT,
+ PRIVATE_MESSAGE,
+ REPLY,
+} from "discourse/models/composer";
+import pretender, {
+ parsePostData,
+ response,
+} from "discourse/tests/helpers/create-pretender";
+import { SESSION_ID_FIELD } from "discourse/plugins/discourse-workflows/discourse/services/workflows-composer-session";
+
+// Same shape as the server's watched word regexps.
+const WORD = "[\\p{L}\\p{M}\\p{N}\\p{Pc}]";
+const pattern = (phrase) => `(?:(?<!${WORD}))(${phrase})(?:(?!${WORD}))`;
+
+function trigger(attrs = {}) {
+ return {
+ workflow_id: 1,
+ trigger_node_id: "trigger-1",
+ patterns: [],
+ composer_actions: ["create_topic", "reply"],
+ category_ids: [],
+ include_subcategories: true,
+ ...attrs,
+ };
+}
+
+module(
+ "Discourse Workflows | Unit | Service | composer paused",
+ function (hooks) {
+ setupTest(hooks);
+
+ hooks.beforeEach(function () {
+ this.requests = [];
+ this.statuses = [];
+ pretender.post(
+ "/discourse-workflows/trigger-composer-paused",
+ (request) => {
+ this.requests.push(parsePostData(request.requestBody));
+ const [status, body] = [this.statuses.shift() ?? 204].flat();
+ return response(status, body ?? "");
+ }
+ );
+
+ this.setTriggers = (triggers) => {
+ this.owner
+ .lookup("service:site")
+ .set("composer_paused_workflows", triggers);
+ this.service = this.owner.lookup("service:workflows-composer-paused");
+ };
+
+ this.openDraft = (attrs = {}) =>
+ this.owner.lookup("service:store").createRecord("composer", {
+ action: CREATE_TOPIC,
+ composeState: Composer.OPEN,
+ draftKey: "new_topic",
+ disableDrafts: true,
+ ...attrs,
+ });
+
+ this.pause = async (composer, reply) => {
+ composer.set("reply", reply);
+ this.service.typingPaused(composer);
+ await settled();
+ };
+
+ this.sent = () => this.requests.map((request) => request.raw);
+ });
+
+ test("each phrase fires once per draft", async function (assert) {
+ this.setTriggers([
+ trigger({
+ patterns: [pattern("Magic words"), pattern("food stand")],
+ }),
+ ]);
+ const composer = this.openDraft({ title: "Lunch review" });
+
+ await this.pause(composer, "Some MAGIC WORDS");
+ assert.deepEqual(this.sent(), ["Some MAGIC WORDS"], "ignores case");
+ assert.propContains(
+ this.requests[0],
+ {
+ draft_key: "new_topic",
+ composer_action: "create_topic",
+ title: "Lunch review",
+ raw: "Some MAGIC WORDS",
+ },
+ "sends the draft"
+ );
+
+ await this.pause(composer, "Magic words, and more Magic words");
+ assert.strictEqual(
+ this.requests.length,
+ 1,
+ "a repeated phrase is skipped"
+ );
+
+ await this.pause(composer, "Magic words. food stand");
+ assert.strictEqual(this.requests.length, 2, "a new phrase fires");
+
+ await this.pause(this.openDraft(), "Magic words");
+ assert.strictEqual(this.requests.length, 3, "a new draft starts over");
+
+ assert.strictEqual(
+ this.requests[0].session_id,
+ this.requests[1].session_id,
+ "a draft keeps its session"
+ );
+ assert.notStrictEqual(
+ this.requests[1].session_id,
+ this.requests[2].session_id,
+ "a new draft gets a new session"
+ );
+ });
+
+ test("reopening a composer starts a new session", async function (assert) {
+ this.setTriggers([trigger({ patterns: [pattern("Magic words")] })]);
+ const composer = this.openDraft();
+
+ await this.pause(composer, "Magic words");
+ // opening the composer again restores the draft's fields
+ composer.set(SESSION_ID_FIELD, "saved-in-the-draft");
+ await this.pause(composer, "Magic words!");
+
+ assert.strictEqual(this.requests.length, 2, "the phrase fires again");
+ assert.notStrictEqual(
+ this.requests[0].session_id,
+ this.requests[1].session_id,
+ "in a new session"
+ );
+ assert.strictEqual(
+ composer.get(SESSION_ID_FIELD),
+ this.requests[1].session_id,
+ "which the draft keeps"
+ );
+ });
+
+ test("a reply sends the post it targets", async function (assert) {
+ this.setTriggers([trigger({ patterns: [pattern("Magic words")] })]);
+ const topic = { id: 2, category_id: 1 };
+
+ await this.pause(
+ this.openDraft({ action: REPLY, topic, post: { post_number: 3 } }),
+ "Magic words"
+ );
+ await this.pause(this.openDraft({ action: REPLY, topic }), "Magic words");
+
+ assert.strictEqual(this.requests[0].reply_to_post_number, "3");
+ assert.false(
+ "reply_to_post_number" in this.requests[1],
+ "a reply to the topic has no target"
+ );
+ });
+
+ test("a restored reply waits for its target post to load", async function (assert) {
+ this.setTriggers([trigger({ patterns: [pattern("Magic words")] })]);
+ const composer = this.openDraft({
+ action: REPLY,
+ topic: { id: 2, category_id: 1 },
+ loading: true,
+ });
+
+ await this.pause(composer, "Magic words");
+ assert.strictEqual(this.requests.length, 0, "skips pauses while loading");
+
+ composer.setProperties({ loading: false, post: { post_number: 3 } });
+ await this.pause(composer, "Magic words!");
+ assert.strictEqual(this.requests[0].reply_to_post_number, "3");
+ });
+
+ test("a pause sends one request for all the triggers it matched", async function (assert) {
+ this.setTriggers([
+ trigger({ workflow_id: 1, patterns: [pattern("Magic words")] }),
+ trigger({ workflow_id: 2, patterns: [pattern("food stand")] }),
+ trigger({ workflow_id: 3 }),
+ ]);
+
+ await this.pause(this.openDraft(), "Magic words at the food stand");
+
+ assert.deepEqual(this.sent(), ["Magic words at the food stand"]);
+ });
+
+ test("pauses during a request are folded into one check of the latest draft", async function (assert) {
+ this.setTriggers([
+ trigger({
+ patterns: [pattern("Magic words"), pattern("food stand")],
+ }),
+ ]);
+ const held = [];
+ pretender.post(
+ "/discourse-workflows/trigger-composer-paused",
+ (request) => {
+ this.requests.push(parsePostData(request.requestBody));
+ held.push(request);
+ return response(204, "");
+ },
+ true
+ );
+ const composer = this.openDraft();
+
+ composer.set("reply", "Magic words");
+ this.service.typingPaused(composer);
+ await waitUntil(() => held.length === 1);
+
+ composer.set("reply", "Magic words. food");
+ this.service.typingPaused(composer);
+ composer.set("reply", "Magic words. food stand");
+ this.service.typingPaused(composer);
+ await new Promise((resolve) => setTimeout(resolve, 100));
+ assert.strictEqual(this.requests.length, 1, "waits for the request");
+
+ pretender.resolve(held[0]);
+ await waitUntil(() => held.length === 2);
+ pretender.resolve(held[1]);
+ await settled();
+
+ assert.deepEqual(this.sent(), ["Magic words", "Magic words. food stand"]);
+ });
+
+ test("a failed request is retried after a wait", async function (assert) {
+ const clock = sinon.useFakeTimers({ now: 1000, toFake: ["Date"] });
+ this.setTriggers([trigger({ patterns: [pattern("Magic words")] })]);
+ const composer = this.openDraft();
+
+ try {
+ this.statuses = [500];
+ await this.pause(composer, "Magic words");
+ await this.pause(composer, "Magic words!");
+ assert.strictEqual(this.requests.length, 1, "waits after an error");
+
+ clock.tick(15000);
+ this.statuses = [[429, { extras: { wait_seconds: 30 } }]];
+ await this.pause(composer, "Magic words!");
+ assert.strictEqual(this.requests.length, 2, "then asks again");
+
+ clock.tick(15000);
+ await this.pause(composer, "Magic words!");
+ assert.strictEqual(
+ this.requests.length,
+ 2,
+ "waits as long as the rate limit says"
+ );
+
+ clock.tick(15000);
+ await this.pause(composer, "Magic words!");
+ await this.pause(composer, "Magic words!!");
+ assert.strictEqual(
+ this.requests.length,
+ 3,
+ "a phrase the server answered for doesn't fire again"
+ );
+ } finally {
+ clock.restore();
+ }
+ });
+
+ test("the title counts, quotes don't", async function (assert) {
+ this.setTriggers([trigger({ patterns: [pattern("Magic words")] })]);
+
+ await this.pause(
+ this.openDraft(),
+ '[quote="sam, post:1, topic:2"]Magic words[/quote]\n> Magic words\n<!-- Magic words -->'
+ );
+ assert.strictEqual(this.requests.length, 0, "quoted text is ignored");
+
+ await this.pause(
+ this.openDraft(),
+ "[quote]a [quote]b[/quote] Magic words[/quote] Hello"
+ );
+ assert.strictEqual(
+ this.requests.length,
+ 0,
+ "bare and nested quotes are ignored"
+ );
+
+ await this.pause(this.openDraft({ title: "Magic words" }), "Hello");
+ assert.strictEqual(this.requests.length, 1, "the title matches");
+ });
+
+ test("triggers without phrases fire on changed text, throttled", async function (assert) {
+ const clock = sinon.useFakeTimers({ now: 1000, toFake: ["Date"] });
+ this.setTriggers([trigger()]);
+ const composer = this.openDraft();
+
+ try {
+ await this.pause(composer, "Hello");
+ await this.pause(composer, "Hello there");
+ assert.strictEqual(this.requests.length, 1, "throttled");
+
+ clock.tick(15000);
+ await this.pause(composer, "Hello there");
+ assert.strictEqual(this.requests.length, 2, "fires after the interval");
+
+ clock.tick(15000);
+ await this.pause(composer, "Hello there");
+ assert.strictEqual(
+ this.requests.length,
+ 2,
+ "unchanged text is skipped"
+ );
+ } finally {
+ clock.restore();
+ }
+ });
+
+ test("a trigger without phrases retries the same text after a failed request", async function (assert) {
+ const clock = sinon.useFakeTimers({ now: 1000, toFake: ["Date"] });
+ this.setTriggers([trigger()]);
+ const composer = this.openDraft();
+
+ try {
+ this.statuses = [500];
+ await this.pause(composer, "Hello");
+ clock.tick(15000);
+ await this.pause(composer, "Hello");
+
+ assert.deepEqual(this.sent(), ["Hello", "Hello"]);
+ } finally {
+ clock.restore();
+ }
+ });
+
+ test("triggers without phrases share one interval", async function (assert) {
+ const clock = sinon.useFakeTimers({ now: 1000, toFake: ["Date"] });
+ this.setTriggers([
+ trigger({ workflow_id: 1 }),
+ trigger({
+ workflow_id: 2,
+ category_ids: [26],
+ include_subcategories: false,
+ }),
+ ]);
+ const composer = this.openDraft({ categoryId: 2 });
+
+ try {
+ await this.pause(composer, "Hello");
+ clock.tick(5000);
+ composer.set("categoryId", 26);
+ await this.pause(composer, "Hello there");
+ assert.strictEqual(
+ this.requests.length,
+ 2,
+ "a newly applying trigger fires"
+ );
+
+ clock.tick(10000);
+ await this.pause(composer, "Hello there again");
+ assert.strictEqual(
+ this.requests.length,
+ 2,
+ "the first trigger waits with the second"
+ );
+
+ clock.tick(5000);
+ await this.pause(composer, "Hello there once more");
+ assert.strictEqual(
+ this.requests.length,
+ 3,
+ "then both fire in one request"
+ );
+ } finally {
+ clock.restore();
+ }
+ });
+
+ test("only open new topics and replies fire", async function (assert) {
+ this.setTriggers([trigger({ patterns: [pattern("Magic words")] })]);
+
+ await this.pause(this.openDraft({ action: EDIT }), "Magic words");
+ await this.pause(
+ this.openDraft({ action: PRIVATE_MESSAGE }),
+ "Magic words"
+ );
+ await this.pause(
+ this.openDraft({
+ action: REPLY,
+ topic: { id: 2, archetype: "private_message" },
+ }),
+ "Magic words"
+ );
+ await this.pause(
+ this.openDraft({ composeState: Composer.DRAFT }),
+ "Magic words"
+ );
+ assert.strictEqual(this.requests.length, 0);
+
+ await this.pause(
+ this.openDraft({ action: REPLY, topic: { id: 2, category_id: 1 } }),
+ "Magic words"
+ );
+ assert.strictEqual(this.requests[0].composer_action, "reply");
+ assert.strictEqual(this.requests[0].topic_id, "2");
+ });
+
+ test("composer actions and categories filter triggers", async function (assert) {
+ this.setTriggers([
+ trigger({ workflow_id: 1, composer_actions: ["reply"] }),
+ trigger({
+ workflow_id: 2,
+ category_ids: [2],
+ include_subcategories: false,
+ }),
+ trigger({
+ workflow_id: 3,
+ category_ids: [2],
+ patterns: [pattern("Magic words")],
+ }),
+ ]);
+
+ await this.pause(this.openDraft({ categoryId: 26 }), "Hello");
+ assert.deepEqual(this.sent(), [], "no trigger applies");
+
+ await this.pause(this.openDraft({ categoryId: 26 }), "Magic words");
+ assert.deepEqual(
+ this.sent(),
+ ["Magic words"],
+ "a phrase matches in a subcategory"
+ );
+
+ await this.pause(this.openDraft({ categoryId: 2 }), "Hello");
+ assert.deepEqual(
+ this.sent(),
+ ["Magic words", "Hello"],
+ "a category without its subcategories matches"
+ );
+ });
+
+ test("phrases the browser can't compile are skipped", async function (assert) {
+ this.setTriggers([trigger({ patterns: ["(?<name>bad"] })]);
+
+ await this.pause(this.openDraft(), "bad");
+ assert.strictEqual(this.requests.length, 0);
+ });
+ }
+);
diff --git a/spec/requests/drafts_controller_spec.rb b/spec/requests/drafts_controller_spec.rb
index a32cadd6a22..9c0b5004813 100644
--- a/spec/requests/drafts_controller_spec.rb
+++ b/spec/requests/drafts_controller_spec.rb
@@ -122,6 +122,42 @@ RSpec.describe DraftsController do
expect(Draft.get(user, "xyz", 0)).to eq(%q({"my":"data"}))
end
+ it "triggers a draft_saved event" do
+ sign_in(user)
+
+ events =
+ DiscourseEvent.track_events(:draft_saved) do
+ post "/drafts.json",
+ params: {
+ draft_key: "xyz",
+ data: { reply: "Magic words" }.to_json,
+ sequence: 0,
+ }
+ end
+
+ expect(events).to contain_exactly(
+ { event_name: :draft_saved, params: [user, "xyz", { "reply" => "Magic words" }] },
+ )
+ end
+
+ it "does not trigger a draft_saved event when the save fails" do
+ sign_in(user)
+ Draft.set(user, "xyz", 0, { reply: "first" }.to_json)
+
+ events =
+ DiscourseEvent.track_events(:draft_saved) do
+ post "/drafts.json",
+ params: {
+ draft_key: "xyz",
+ data: { reply: "x" }.to_json,
+ sequence: 5,
+ }
+ end
+
+ expect(response.status).to eq(409)
+ expect(events).to be_empty
+ end
+
it "returns 404 when the key is missing" do
sign_in(Fabricate(:user))
post "/drafts.json", params: { data: { my: "data" }.to_json, sequence: 0 }