Skip to content

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

FEATURE: discourse-workflows (#40374)

Joffrey JAFFEUX0914b9fb32b6
diff --git a/.gitignore b/.gitignore
index cfd57af84b2..c10a7726878 100644
--- a/.gitignore
+++ b/.gitignore
@@ -75,6 +75,7 @@
!/plugins/discourse-ai
!/plugins/discourse-cakeday
!/plugins/discourse-rewind
+!/plugins/discourse-workflows
/plugins/*/auto_generated
/spec/fixtures/plugins/my_plugin/auto_generated
diff --git a/app/assets/stylesheets/common/components/d-segmented-control.scss b/app/assets/stylesheets/common/components/d-segmented-control.scss
index 0ab074cb252..7a2dbd2bcc0 100644
--- a/app/assets/stylesheets/common/components/d-segmented-control.scss
+++ b/app/assets/stylesheets/common/components/d-segmented-control.scss
@@ -2,12 +2,13 @@
position: relative;
display: inline-flex;
align-items: center;
+ box-sizing: border-box;
+ overflow: hidden;
background: var(--primary-very-low);
gap: var(--space-2);
border-radius: var(--d-border-radius);
padding: var(--space-1) var(--space-2);
height: var(--space-9);
- box-sizing: border-box;
&__legend {
position: absolute;
@@ -53,6 +54,27 @@
clip-path: inset(50%);
}
+ &--small {
+ gap: 2px;
+ padding: 1px;
+ height: auto;
+
+ .d-segmented-control__slider {
+ top: 1px;
+ height: calc(100% - 2px);
+ }
+
+ .d-segmented-control__label {
+ padding: 0 var(--space-1);
+ height: auto;
+ font-size: var(--font-down-2);
+
+ .d-icon {
+ font-size: var(--font-down-2);
+ }
+ }
+ }
+
&__label {
z-index: 1;
display: flex;
diff --git a/app/assets/stylesheets/common/components/d-stat-tiles.scss b/app/assets/stylesheets/common/components/d-stat-tiles.scss
index 560e52d42c6..229c343c2c9 100644
--- a/app/assets/stylesheets/common/components/d-stat-tiles.scss
+++ b/app/assets/stylesheets/common/components/d-stat-tiles.scss
@@ -23,4 +23,23 @@
font-weight: bold;
}
}
+
+ &.--compact {
+ display: flex;
+ gap: 0.5em;
+ margin-bottom: 0;
+
+ .d-stat-tile {
+ padding: 0.25em 0.5em;
+
+ &__label {
+ font-size: var(--font-down-2);
+ margin-bottom: 0;
+ }
+
+ &__value {
+ font-size: var(--font-down-1);
+ }
+ }
+ }
}
diff --git a/app/assets/stylesheets/common/float-kit/d-menu.scss b/app/assets/stylesheets/common/float-kit/d-menu.scss
index 63af9df7feb..b0f3d88943f 100644
--- a/app/assets/stylesheets/common/float-kit/d-menu.scss
+++ b/app/assets/stylesheets/common/float-kit/d-menu.scss
@@ -161,4 +161,12 @@
&__divider {
margin: 0;
}
+
+ &__subheader {
+ padding: var(--space-2) var(--d-sidebar-row-horizontal-padding)
+ var(--space-1);
+ color: var(--primary-medium);
+ font-size: var(--font-down-1-rem);
+ font-weight: bold;
+ }
}
diff --git a/app/assets/stylesheets/common/form-kit/_control-code.scss b/app/assets/stylesheets/common/form-kit/_control-code.scss
index 6c5bd244de7..94242f8ad86 100644
--- a/app/assets/stylesheets/common/form-kit/_control-code.scss
+++ b/app/assets/stylesheets/common/form-kit/_control-code.scss
@@ -1,4 +1,4 @@
-.form-kit__field-code {
+.form-kit__field[data-control-type="code"] {
.ace-wrapper {
width: 100%;
diff --git a/app/assets/stylesheets/common/select-kit/select-kit.scss b/app/assets/stylesheets/common/select-kit/select-kit.scss
index 7f8de5b7c36..702e5d00a19 100644
--- a/app/assets/stylesheets/common/select-kit/select-kit.scss
+++ b/app/assets/stylesheets/common/select-kit/select-kit.scss
@@ -84,7 +84,7 @@
}
.d-icon {
- color: var(--primary-high);
+ color: var(--primary-medium);
}
.select-kit-header {
@@ -173,7 +173,7 @@
margin-right: 0;
padding-left: 5px;
pointer-events: none;
- color: inherit;
+ color: var(--primary-medium);
}
.d-button-label {
diff --git a/app/models/topic.rb b/app/models/topic.rb
index bd9c5b11c06..24c8a141fe3 100644
--- a/app/models/topic.rb
+++ b/app/models/topic.rb
@@ -1148,6 +1148,8 @@ class Topic < ActiveRecord::Base
if SiteSetting.experimental_topic_category_change_notification
DB.after_commit { TopicTrackingState.publish_category_change(self, old_category) }
end
+
+ DiscourseEvent.trigger(:topic_category_changed, self, old_category)
end
Category.where(id: new_category.id).update_all("topic_count = topic_count + 1")
diff --git a/config/initializers/000-active_record.rb b/config/initializers/000-active_record.rb
index 7cd7f867ad9..8cb8bb63a42 100644
--- a/config/initializers/000-active_record.rb
+++ b/config/initializers/000-active_record.rb
@@ -8,4 +8,5 @@ ActiveRecord.schema_cache_ignored_tables.push(
"ai_posts_embeddings",
"ai_user_embeddings",
"ai_document_fragments_embeddings",
+ /\Adiscourse_workflows_data_table_\d+_rows\z/,
)
diff --git a/db/structure.sql b/db/structure.sql
index 7e1b7454b33..a3870dd245f 100644
--- a/db/structure.sql
+++ b/db/structure.sql
@@ -4276,6 +4276,334 @@ CREATE SEQUENCE public.discourse_templates_usage_count_id_seq
ALTER SEQUENCE public.discourse_templates_usage_count_id_seq OWNED BY public.discourse_templates_usage_count.id;
+--
+-- Name: discourse_workflows_credentials; Type: TABLE; Schema: public; Owner: -
+--
+
+CREATE TABLE public.discourse_workflows_credentials (
+ id bigint NOT NULL,
+ name character varying(128) NOT NULL,
+ credential_type character varying(64) NOT NULL,
+ data jsonb DEFAULT '{}'::jsonb NOT NULL,
+ created_by_id integer,
+ updated_by_id integer,
+ created_at timestamp(6) without time zone NOT NULL,
+ updated_at timestamp(6) without time zone NOT NULL
+);
+
+
+--
+-- Name: discourse_workflows_credentials_id_seq; Type: SEQUENCE; Schema: public; Owner: -
+--
+
+CREATE SEQUENCE public.discourse_workflows_credentials_id_seq
+ START WITH 1
+ INCREMENT BY 1
+ NO MINVALUE
+ NO MAXVALUE
+ CACHE 1;
+
+
+--
+-- Name: discourse_workflows_credentials_id_seq; Type: SEQUENCE OWNED BY; Schema: public; Owner: -
+--
+
+ALTER SEQUENCE public.discourse_workflows_credentials_id_seq OWNED BY public.discourse_workflows_credentials.id;
+
+
+--
+-- Name: discourse_workflows_data_tables; Type: TABLE; Schema: public; Owner: -
+--
+
+CREATE TABLE public.discourse_workflows_data_tables (
+ id bigint NOT NULL,
+ name character varying(100) NOT NULL,
+ created_by_id integer,
+ updated_by_id integer,
+ created_at timestamp(6) without time zone NOT NULL,
+ updated_at timestamp(6) without time zone NOT NULL
+);
+
+
+--
+-- Name: discourse_workflows_data_tables_id_seq; Type: SEQUENCE; Schema: public; Owner: -
+--
+
+CREATE SEQUENCE public.discourse_workflows_data_tables_id_seq
+ START WITH 1
+ INCREMENT BY 1
+ NO MINVALUE
+ NO MAXVALUE
+ CACHE 1;
+
+
+--
+-- Name: discourse_workflows_data_tables_id_seq; Type: SEQUENCE OWNED BY; Schema: public; Owner: -
+--
+
+ALTER SEQUENCE public.discourse_workflows_data_tables_id_seq OWNED BY public.discourse_workflows_data_tables.id;
+
+
+--
+-- Name: discourse_workflows_execution_data; Type: TABLE; Schema: public; Owner: -
+--
+
+CREATE TABLE public.discourse_workflows_execution_data (
+ execution_id bigint NOT NULL,
+ data jsonb DEFAULT '{}'::jsonb NOT NULL,
+ workflow_data jsonb DEFAULT '{}'::jsonb NOT NULL
+);
+
+
+--
+-- Name: discourse_workflows_executions; Type: TABLE; Schema: public; Owner: -
+--
+
+CREATE TABLE public.discourse_workflows_executions (
+ id bigint NOT NULL,
+ workflow_id bigint NOT NULL,
+ workflow_version_id character varying(36) NOT NULL,
+ status integer DEFAULT 0 NOT NULL,
+ execution_mode integer DEFAULT 0 NOT NULL,
+ trigger_data jsonb DEFAULT '{}'::jsonb,
+ error text,
+ waiting_node_id character varying(100),
+ waiting_until timestamp(6) without time zone,
+ resume_token character varying(64),
+ timeout_action character varying(32),
+ trigger_node_id character varying(100),
+ run_time_ms integer,
+ started_at timestamp(6) without time zone,
+ finished_at timestamp(6) without time zone,
+ created_at timestamp(6) without time zone NOT NULL,
+ updated_at timestamp(6) without time zone NOT NULL
+);
+
+
+--
+-- Name: discourse_workflows_executions_id_seq; Type: SEQUENCE; Schema: public; Owner: -
+--
+
+CREATE SEQUENCE public.discourse_workflows_executions_id_seq
+ START WITH 1
+ INCREMENT BY 1
+ NO MINVALUE
+ NO MAXVALUE
+ CACHE 1;
+
+
+--
+-- Name: discourse_workflows_executions_id_seq; Type: SEQUENCE OWNED BY; Schema: public; Owner: -
+--
+
+ALTER SEQUENCE public.discourse_workflows_executions_id_seq OWNED BY public.discourse_workflows_executions.id;
+
+
+--
+-- Name: discourse_workflows_variables; Type: TABLE; Schema: public; Owner: -
+--
+
+CREATE TABLE public.discourse_workflows_variables (
+ id bigint NOT NULL,
+ key character varying(100) NOT NULL,
+ value character varying(1000) DEFAULT ''::character varying NOT NULL,
+ description text,
+ created_by_id integer NOT NULL,
+ created_at timestamp(6) without time zone NOT NULL,
+ updated_at timestamp(6) without time zone NOT NULL
+);
+
+
+--
+-- Name: discourse_workflows_variables_id_seq; Type: SEQUENCE; Schema: public; Owner: -
+--
+
+CREATE SEQUENCE public.discourse_workflows_variables_id_seq
+ START WITH 1
+ INCREMENT BY 1
+ NO MINVALUE
+ NO MAXVALUE
+ CACHE 1;
+
+
+--
+-- Name: discourse_workflows_variables_id_seq; Type: SEQUENCE OWNED BY; Schema: public; Owner: -
+--
+
+ALTER SEQUENCE public.discourse_workflows_variables_id_seq OWNED BY public.discourse_workflows_variables.id;
+
+
+--
+-- Name: discourse_workflows_webhooks; Type: TABLE; Schema: public; Owner: -
+--
+
+CREATE TABLE public.discourse_workflows_webhooks (
+ id bigint NOT NULL,
+ workflow_id bigint NOT NULL,
+ workflow_version_id character varying(36),
+ node_name character varying(100) NOT NULL,
+ webhook_path character varying(500) NOT NULL,
+ http_method character varying(10) NOT NULL,
+ webhook_id character varying(36),
+ path_length integer,
+ test_webhook boolean DEFAULT false NOT NULL,
+ user_id integer,
+ workflow_snapshot jsonb,
+ expires_at timestamp(6) without time zone,
+ created_at timestamp(6) without time zone DEFAULT CURRENT_TIMESTAMP NOT NULL
+);
+
+
+--
+-- Name: discourse_workflows_webhooks_id_seq; Type: SEQUENCE; Schema: public; Owner: -
+--
+
+CREATE SEQUENCE public.discourse_workflows_webhooks_id_seq
+ START WITH 1
+ INCREMENT BY 1
+ NO MINVALUE
+ NO MAXVALUE
+ CACHE 1;
+
+
+--
+-- Name: discourse_workflows_webhooks_id_seq; Type: SEQUENCE OWNED BY; Schema: public; Owner: -
+--
+
+ALTER SEQUENCE public.discourse_workflows_webhooks_id_seq OWNED BY public.discourse_workflows_webhooks.id;
+
+
+--
+-- Name: discourse_workflows_workflow_dependencies; Type: TABLE; Schema: public; Owner: -
+--
+
+CREATE TABLE public.discourse_workflows_workflow_dependencies (
+ id bigint NOT NULL,
+ workflow_id bigint NOT NULL,
+ dependency_type character varying(50) NOT NULL,
+ dependency_key character varying(500) NOT NULL,
+ node_id character varying(100),
+ workflow_version_id character varying(36),
+ created_at timestamp(6) without time zone DEFAULT CURRENT_TIMESTAMP NOT NULL
+);
+
+
+--
+-- Name: discourse_workflows_workflow_dependencies_id_seq; Type: SEQUENCE; Schema: public; Owner: -
+--
+
+CREATE SEQUENCE public.discourse_workflows_workflow_dependencies_id_seq
+ START WITH 1
+ INCREMENT BY 1
+ NO MINVALUE
+ NO MAXVALUE
+ CACHE 1;
+
+
+--
+-- Name: discourse_workflows_workflow_dependencies_id_seq; Type: SEQUENCE OWNED BY; Schema: public; Owner: -
+--
+
+ALTER SEQUENCE public.discourse_workflows_workflow_dependencies_id_seq OWNED BY public.discourse_workflows_workflow_dependencies.id;
+
+
+--
+-- Name: discourse_workflows_workflow_publish_history; Type: TABLE; Schema: public; Owner: -
+--
+
+CREATE TABLE public.discourse_workflows_workflow_publish_history (
+ id bigint NOT NULL,
+ workflow_id bigint NOT NULL,
+ version_id character varying(36),
+ event character varying(32) NOT NULL,
+ user_id integer,
+ created_at timestamp(6) without time zone DEFAULT CURRENT_TIMESTAMP NOT NULL
+);
+
+
+--
+-- Name: discourse_workflows_workflow_publish_history_id_seq; Type: SEQUENCE; Schema: public; Owner: -
+--
+
+CREATE SEQUENCE public.discourse_workflows_workflow_publish_history_id_seq
+ START WITH 1
+ INCREMENT BY 1
+ NO MINVALUE
+ NO MAXVALUE
+ CACHE 1;
+
+
+--
+-- Name: discourse_workflows_workflow_publish_history_id_seq; Type: SEQUENCE OWNED BY; Schema: public; Owner: -
+--
+
+ALTER SEQUENCE public.discourse_workflows_workflow_publish_history_id_seq OWNED BY public.discourse_workflows_workflow_publish_history.id;
+
+
+--
+-- Name: discourse_workflows_workflow_versions; Type: TABLE; Schema: public; Owner: -
+--
+
+CREATE TABLE public.discourse_workflows_workflow_versions (
+ version_id character varying(36) NOT NULL,
+ workflow_id bigint NOT NULL,
+ version_number integer NOT NULL,
+ name character varying(100) NOT NULL,
+ nodes jsonb DEFAULT '[]'::jsonb NOT NULL,
+ connections jsonb DEFAULT '{}'::jsonb NOT NULL,
+ settings jsonb DEFAULT '{}'::jsonb NOT NULL,
+ autosaved boolean DEFAULT false NOT NULL,
+ authors text,
+ created_by_id integer NOT NULL,
+ updated_by_id integer,
+ created_at timestamp(6) without time zone NOT NULL,
+ updated_at timestamp(6) without time zone NOT NULL
+);
+
+
+--
+-- Name: discourse_workflows_workflows; Type: TABLE; Schema: public; Owner: -
+--
+
+CREATE TABLE public.discourse_workflows_workflows (
+ id bigint NOT NULL,
+ name character varying(100) NOT NULL,
+ nodes jsonb DEFAULT '[]'::jsonb NOT NULL,
+ connections jsonb DEFAULT '{}'::jsonb NOT NULL,
+ static_data jsonb DEFAULT '{}'::jsonb NOT NULL,
+ pin_data jsonb DEFAULT '{}'::jsonb NOT NULL,
+ trigger_state jsonb DEFAULT '{}'::jsonb NOT NULL,
+ settings jsonb DEFAULT '{}'::jsonb NOT NULL,
+ version_id character varying(36) NOT NULL,
+ active_version_id character varying(36),
+ version_counter integer DEFAULT 1 NOT NULL,
+ error_workflow_id bigint,
+ created_by_id integer NOT NULL,
+ updated_by_id integer,
+ created_at timestamp(6) without time zone NOT NULL,
+ updated_at timestamp(6) without time zone NOT NULL
+);
+
+
+--
+-- Name: discourse_workflows_workflows_id_seq; Type: SEQUENCE; Schema: public; Owner: -
+--
+
+CREATE SEQUENCE public.discourse_workflows_workflows_id_seq
+ START WITH 1
+ INCREMENT BY 1
+ NO MINVALUE
+ NO MAXVALUE
+ CACHE 1;
+
+
+--
+-- Name: discourse_workflows_workflows_id_seq; Type: SEQUENCE OWNED BY; Schema: public; Owner: -
+--
+
+ALTER SEQUENCE public.discourse_workflows_workflows_id_seq OWNED BY public.discourse_workflows_workflows.id;
+
+
--
-- Name: dismissed_topic_users; Type: TABLE; Schema: public; Owner: -
--
@@ -12179,6 +12507,62 @@ ALTER TABLE ONLY public.discourse_subscriptions_subscriptions ALTER COLUMN id SE
ALTER TABLE ONLY public.discourse_templates_usage_count ALTER COLUMN id SET DEFAULT nextval('public.discourse_templates_usage_count_id_seq'::regclass);
+--
+-- Name: discourse_workflows_credentials id; Type: DEFAULT; Schema: public; Owner: -
+--
+
+ALTER TABLE ONLY public.discourse_workflows_credentials ALTER COLUMN id SET DEFAULT nextval('public.discourse_workflows_credentials_id_seq'::regclass);
+
+
+--
+-- Name: discourse_workflows_data_tables id; Type: DEFAULT; Schema: public; Owner: -
+--
+
+ALTER TABLE ONLY public.discourse_workflows_data_tables ALTER COLUMN id SET DEFAULT nextval('public.discourse_workflows_data_tables_id_seq'::regclass);
+
+
+--
+-- Name: discourse_workflows_executions id; Type: DEFAULT; Schema: public; Owner: -
+--
+
+ALTER TABLE ONLY public.discourse_workflows_executions ALTER COLUMN id SET DEFAULT nextval('public.discourse_workflows_executions_id_seq'::regclass);
+
+
+--
+-- Name: discourse_workflows_variables id; Type: DEFAULT; Schema: public; Owner: -
+--
+
+ALTER TABLE ONLY public.discourse_workflows_variables ALTER COLUMN id SET DEFAULT nextval('public.discourse_workflows_variables_id_seq'::regclass);
+
+
+--
+-- Name: discourse_workflows_webhooks id; Type: DEFAULT; Schema: public; Owner: -
+--
+
+ALTER TABLE ONLY public.discourse_workflows_webhooks ALTER COLUMN id SET DEFAULT nextval('public.discourse_workflows_webhooks_id_seq'::regclass);
+
+
+--
+-- Name: discourse_workflows_workflow_dependencies id; Type: DEFAULT; Schema: public; Owner: -
+--
+
+ALTER TABLE ONLY public.discourse_workflows_workflow_dependencies ALTER COLUMN id SET DEFAULT nextval('public.discourse_workflows_workflow_dependencies_id_seq'::regclass);
+
+
+--
+-- Name: discourse_workflows_workflow_publish_history id; Type: DEFAULT; Schema: public; Owner: -
+--
+
+ALTER TABLE ONLY public.discourse_workflows_workflow_publish_history ALTER COLUMN id SET DEFAULT nextval('public.discourse_workflows_workflow_publish_history_id_seq'::regclass);
+
+
+--
+-- Name: discourse_workflows_workflows id; Type: DEFAULT; Schema: public; Owner: -
+--
+
+ALTER TABLE ONLY public.discourse_workflows_workflows ALTER COLUMN id SET DEFAULT nextval('public.discourse_workflows_workflows_id_seq'::regclass);
+
+
--
-- Name: dismissed_topic_users id; Type: DEFAULT; Schema: public; Owner: -
--
@@ -14365,6 +14749,78 @@ ALTER TABLE ONLY public.discourse_templates_usage_count
ADD CONSTRAINT discourse_templates_usage_count_pkey PRIMARY KEY (id);
+--
+-- Name: discourse_workflows_credentials discourse_workflows_credentials_pkey; Type: CONSTRAINT; Schema: public; Owner: -
+--
+
+ALTER TABLE ONLY public.discourse_workflows_credentials
+ ADD CONSTRAINT discourse_workflows_credentials_pkey PRIMARY KEY (id);
+
+
+--
+-- Name: discourse_workflows_data_tables discourse_workflows_data_tables_pkey; Type: CONSTRAINT; Schema: public; Owner: -
+--
+
+ALTER TABLE ONLY public.discourse_workflows_data_tables
+ ADD CONSTRAINT discourse_workflows_data_tables_pkey PRIMARY KEY (id);
+
+
+--
+-- Name: discourse_workflows_executions discourse_workflows_executions_pkey; Type: CONSTRAINT; Schema: public; Owner: -
+--
+
+ALTER TABLE ONLY public.discourse_workflows_executions
+ ADD CONSTRAINT discourse_workflows_executions_pkey PRIMARY KEY (id);
+
+
+--
+-- Name: discourse_workflows_variables discourse_workflows_variables_pkey; Type: CONSTRAINT; Schema: public; Owner: -
+--
+
+ALTER TABLE ONLY public.discourse_workflows_variables
+ ADD CONSTRAINT discourse_workflows_variables_pkey PRIMARY KEY (id);
+
+
+--
+-- Name: discourse_workflows_webhooks discourse_workflows_webhooks_pkey; Type: CONSTRAINT; Schema: public; Owner: -
+--
+
+ALTER TABLE ONLY public.discourse_workflows_webhooks
+ ADD CONSTRAINT discourse_workflows_webhooks_pkey PRIMARY KEY (id);
+
+
+--
+-- Name: discourse_workflows_workflow_dependencies discourse_workflows_workflow_dependencies_pkey; Type: CONSTRAINT; Schema: public; Owner: -
+--
+
+ALTER TABLE ONLY public.discourse_workflows_workflow_dependencies
+ ADD CONSTRAINT discourse_workflows_workflow_dependencies_pkey PRIMARY KEY (id);
+
+
+--
+-- Name: discourse_workflows_workflow_publish_history discourse_workflows_workflow_publish_history_pkey; Type: CONSTRAINT; Schema: public; Owner: -
+--
+
+ALTER TABLE ONLY public.discourse_workflows_workflow_publish_history
+ ADD CONSTRAINT discourse_workflows_workflow_publish_history_pkey PRIMARY KEY (id);
+
+
+--
+-- Name: discourse_workflows_workflow_versions discourse_workflows_workflow_versions_pkey; Type: CONSTRAINT; Schema: public; Owner: -
+--
+
+ALTER TABLE ONLY public.discourse_workflows_workflow_versions
+ ADD CONSTRAINT discourse_workflows_workflow_versions_pkey PRIMARY KEY (version_id);
+
+
+--
+-- Name: discourse_workflows_workflows discourse_workflows_workflows_pkey; Type: CONSTRAINT; Schema: public; Owner: -
+--
+
+ALTER TABLE ONLY public.discourse_workflows_workflows
+ ADD CONSTRAINT discourse_workflows_workflows_pkey PRIMARY KEY (id);
+
+
--
-- Name: dismissed_topic_users dismissed_topic_users_pkey; Type: CONSTRAINT; Schema: public; Owner: -
--
@@ -16164,6 +16620,237 @@ CREATE UNIQUE INDEX idx_discourse_automation_user_global_notices ON public.disco
CREATE UNIQUE INDEX idx_discourse_calendar_post_event_dates_event_id_starts_at_uniq ON public.discourse_calendar_post_event_dates USING btree (event_id, starts_at);
+--
+-- Name: idx_dwf_credentials_on_created_by_id; Type: INDEX; Schema: public; Owner: -
+--
+
+CREATE INDEX idx_dwf_credentials_on_created_by_id ON public.discourse_workflows_credentials USING btree (created_by_id);
+
+
+--
+-- Name: idx_dwf_credentials_on_credential_type; Type: INDEX; Schema: public; Owner: -
+--
+
+CREATE INDEX idx_dwf_credentials_on_credential_type ON public.discourse_workflows_credentials USING btree (credential_type);
+
+
+--
+-- Name: idx_dwf_credentials_on_name_credential_type; Type: INDEX; Schema: public; Owner: -
+--
+
+CREATE UNIQUE INDEX idx_dwf_credentials_on_name_credential_type ON public.discourse_workflows_credentials USING btree (name, credential_type);
+
+
+--
+-- Name: idx_dwf_credentials_on_updated_by_id; Type: INDEX; Schema: public; Owner: -
+--
+
+CREATE INDEX idx_dwf_credentials_on_updated_by_id ON public.discourse_workflows_credentials USING btree (updated_by_id);
+
+
+--
+-- Name: idx_dwf_data_tables_on_created_by_id; Type: INDEX; Schema: public; Owner: -
+--
+
+CREATE INDEX idx_dwf_data_tables_on_created_by_id ON public.discourse_workflows_data_tables USING btree (created_by_id);
+
+
+--
+-- Name: idx_dwf_data_tables_on_name; Type: INDEX; Schema: public; Owner: -
+--
+
+CREATE UNIQUE INDEX idx_dwf_data_tables_on_name ON public.discourse_workflows_data_tables USING btree (name);
+
+
+--
+-- Name: idx_dwf_data_tables_on_updated_by_id; Type: INDEX; Schema: public; Owner: -
+--
+
+CREATE INDEX idx_dwf_data_tables_on_updated_by_id ON public.discourse_workflows_data_tables USING btree (updated_by_id);
+
+
+--
+-- Name: idx_dwf_deps_on_type_key; Type: INDEX; Schema: public; Owner: -
+--
+
+CREATE INDEX idx_dwf_deps_on_type_key ON public.discourse_workflows_workflow_dependencies USING btree (dependency_type, dependency_key);
+
+
+--
+-- Name: idx_dwf_deps_on_workflow_id; Type: INDEX; Schema: public; Owner: -
+--
+
+CREATE INDEX idx_dwf_deps_on_workflow_id ON public.discourse_workflows_workflow_dependencies USING btree (workflow_id);
+
+
+--
+-- Name: idx_dwf_deps_on_workflow_version_id; Type: INDEX; Schema: public; Owner: -
+--
+
+CREATE INDEX idx_dwf_deps_on_workflow_version_id ON public.discourse_workflows_workflow_dependencies USING btree (workflow_version_id);
+
+
+--
+-- Name: idx_dwf_execution_data_on_execution_id; Type: INDEX; Schema: public; Owner: -
+--
+
+CREATE UNIQUE INDEX idx_dwf_execution_data_on_execution_id ON public.discourse_workflows_execution_data USING btree (execution_id);
+
+
+--
+-- Name: idx_dwf_executions_on_resume_token; Type: INDEX; Schema: public; Owner: -
+--
+
+CREATE INDEX idx_dwf_executions_on_resume_token ON public.discourse_workflows_executions USING btree (resume_token) WHERE (resume_token IS NOT NULL);
+
+
+--
+-- Name: idx_dwf_executions_on_retention; Type: INDEX; Schema: public; Owner: -
+--
+
+CREATE INDEX idx_dwf_executions_on_retention ON public.discourse_workflows_executions USING btree (created_at) WHERE (status = ANY (ARRAY[2, 3, 5, 6]));
+
+
+--
+-- Name: idx_dwf_executions_on_status_waiting_until; Type: INDEX; Schema: public; Owner: -
+--
+
+CREATE INDEX idx_dwf_executions_on_status_waiting_until ON public.discourse_workflows_executions USING btree (status, waiting_until);
+
+
+--
+-- Name: idx_dwf_executions_on_waiting_until; Type: INDEX; Schema: public; Owner: -
+--
+
+CREATE INDEX idx_dwf_executions_on_waiting_until ON public.discourse_workflows_executions USING btree (waiting_until) WHERE ((waiting_until IS NOT NULL) AND (status = 4));
+
+
+--
+-- Name: idx_dwf_executions_on_workflow_created_at_id_desc; Type: INDEX; Schema: public; Owner: -
+--
+
+CREATE INDEX idx_dwf_executions_on_workflow_created_at_id_desc ON public.discourse_workflows_executions USING btree (workflow_id, created_at DESC, id DESC);
+
+
+--
+-- Name: idx_dwf_executions_on_workflow_version_id; Type: INDEX; Schema: public; Owner: -
+--
+
+CREATE INDEX idx_dwf_executions_on_workflow_version_id ON public.discourse_workflows_executions USING btree (workflow_version_id);
+
+
+--
+-- Name: idx_dwf_publish_history_on_workflow_created_at_id_desc; Type: INDEX; Schema: public; Owner: -
+--
+
+CREATE INDEX idx_dwf_publish_history_on_workflow_created_at_id_desc ON public.discourse_workflows_workflow_publish_history USING btree (workflow_id, created_at DESC, id DESC);
+
+
+--
+-- Name: idx_dwf_variables_on_created_by_id; Type: INDEX; Schema: public; Owner: -
+--
+
+CREATE INDEX idx_dwf_variables_on_created_by_id ON public.discourse_workflows_variables USING btree (created_by_id);
+
+
+--
+-- Name: idx_dwf_variables_on_key; Type: INDEX; Schema: public; Owner: -
+--
+
+CREATE UNIQUE INDEX idx_dwf_variables_on_key ON public.discourse_workflows_variables USING btree (key);
+
+
+--
+-- Name: idx_dwf_versions_on_workflow_created_at; Type: INDEX; Schema: public; Owner: -
+--
+
+CREATE INDEX idx_dwf_versions_on_workflow_created_at ON public.discourse_workflows_workflow_versions USING btree (workflow_id, created_at DESC);
+
+
+--
+-- Name: idx_dwf_versions_on_workflow_id; Type: INDEX; Schema: public; Owner: -
+--
+
+CREATE INDEX idx_dwf_versions_on_workflow_id ON public.discourse_workflows_workflow_versions USING btree (workflow_id);
+
+
+--
+-- Name: idx_dwf_versions_on_workflow_version_number; Type: INDEX; Schema: public; Owner: -
+--
+
+CREATE UNIQUE INDEX idx_dwf_versions_on_workflow_version_number ON public.discourse_workflows_workflow_versions USING btree (workflow_id, version_number);
+
+
+--
+-- Name: idx_dwf_webhooks_on_expires_at; Type: INDEX; Schema: public; Owner: -
+--
+
+CREATE INDEX idx_dwf_webhooks_on_expires_at ON public.discourse_workflows_webhooks USING btree (expires_at) WHERE (expires_at IS NOT NULL);
+
+
+--
+-- Name: idx_dwf_webhooks_on_method_path_test; Type: INDEX; Schema: public; Owner: -
+--
+
+CREATE UNIQUE INDEX idx_dwf_webhooks_on_method_path_test ON public.discourse_workflows_webhooks USING btree (http_method, webhook_path, test_webhook);
+
+
+--
+-- Name: idx_dwf_webhooks_on_webhook_id_method_test; Type: INDEX; Schema: public; Owner: -
+--
+
+CREATE INDEX idx_dwf_webhooks_on_webhook_id_method_test ON public.discourse_workflows_webhooks USING btree (webhook_id, http_method, test_webhook) WHERE (webhook_id IS NOT NULL);
+
+
+--
+-- Name: idx_dwf_webhooks_on_workflow_id; Type: INDEX; Schema: public; Owner: -
+--
+
+CREATE INDEX idx_dwf_webhooks_on_workflow_id ON public.discourse_workflows_webhooks USING btree (workflow_id);
+
+
+--
+-- Name: idx_dwf_webhooks_on_workflow_version_id; Type: INDEX; Schema: public; Owner: -
+--
+
+CREATE INDEX idx_dwf_webhooks_on_workflow_version_id ON public.discourse_workflows_webhooks USING btree (workflow_version_id);
+
+
+--
+-- Name: idx_dwf_workflows_on_active_version_id; Type: INDEX; Schema: public; Owner: -
+--
+
+CREATE INDEX idx_dwf_workflows_on_active_version_id ON public.discourse_workflows_workflows USING btree (active_version_id);
+
+
+--
+-- Name: idx_dwf_workflows_on_created_by_id; Type: INDEX; Schema: public; Owner: -
+--
+
+CREATE INDEX idx_dwf_workflows_on_created_by_id ON public.discourse_workflows_workflows USING btree (created_by_id);
+
+
+--
+-- Name: idx_dwf_workflows_on_error_workflow_id; Type: INDEX; Schema: public; Owner: -
+--
+
+CREATE INDEX idx_dwf_workflows_on_error_workflow_id ON public.discourse_workflows_workflows USING btree (error_workflow_id);
+
+
+--
+-- Name: idx_dwf_workflows_on_updated_by_id; Type: INDEX; Schema: public; Owner: -
+--
+
+CREATE INDEX idx_dwf_workflows_on_updated_by_id ON public.discourse_workflows_workflows USING btree (updated_by_id);
+
+
+--
+-- Name: idx_dwf_workflows_on_version_id; Type: INDEX; Schema: public; Owner: -
+--
+
+CREATE UNIQUE INDEX idx_dwf_workflows_on_version_id ON public.discourse_workflows_workflows USING btree (version_id);
+
+
--
-- Name: idx_email_change_requests_on_requested_by; Type: INDEX; Schema: public; Owner: -
--
@@ -21169,6 +21856,7 @@ INSERT INTO "schema_migrations" (version) VALUES
('20260316071737'),
('20260316071736'),
('20260316071735'),
+('20260312000000'),
('20260311161955'),
('20260311064518'),
('20260311021412'),
diff --git a/frontend/discourse/admin/components/admin-plugin-config-page.gjs b/frontend/discourse/admin/components/admin-plugin-config-page.gjs
index 48fbec6201c..59e26a87ec4 100644
--- a/frontend/discourse/admin/components/admin-plugin-config-page.gjs
+++ b/frontend/discourse/admin/components/admin-plugin-config-page.gjs
@@ -52,6 +52,7 @@ export default class AdminPluginConfigPage extends Component {
}}
<DNavItem
@route={{navLink.route}}
+ @currentWhen={{navLink.currentWhen}}
@i18nLabel={{this.linkText navLink}}
title={{this.linkText navLink}}
class="admin-plugin-config-page__top-nav-item"
diff --git a/frontend/discourse/app/components/ace-editor.gjs b/frontend/discourse/app/components/ace-editor.gjs
index 33d53abdbfd..a6bede8b237 100644
--- a/frontend/discourse/app/components/ace-editor.gjs
+++ b/frontend/discourse/app/components/ace-editor.gjs
@@ -68,12 +68,14 @@ export default class AceEditor extends Component {
skipChangePropagation = false;
setContent = modifier(() => {
- if (this.args.content === this.editor.getSession().getValue()) {
+ const content = this.args.content || "";
+
+ if (content === this.editor.getSession().getValue()) {
return;
}
this.skipChangePropagation = true;
- this.editor.getSession().setValue(this.args.content || "");
+ this.editor.getSession().setValue(content);
this.skipChangePropagation = false;
const token = WAITER.beginAsync();
diff --git a/frontend/discourse/app/components/d-segmented-control.gjs b/frontend/discourse/app/components/d-segmented-control.gjs
index 5b2007927cd..b370b710de8 100644
--- a/frontend/discourse/app/components/d-segmented-control.gjs
+++ b/frontend/discourse/app/components/d-segmented-control.gjs
@@ -33,6 +33,14 @@ export default class DSegmentedControl extends Component {
return () => cancelAnimationFrame(frameId);
});
+ get classNames() {
+ const classes = ["d-segmented-control"];
+ if (this.args.size === "small") {
+ classes.push("d-segmented-control--small");
+ }
+ return classes.join(" ");
+ }
+
get legend() {
if (this.args.label) {
return i18n(this.args.label);
@@ -52,7 +60,7 @@ export default class DSegmentedControl extends Component {
<template>
<fieldset
- class="d-segmented-control"
+ class={{this.classNames}}
{{this.positionSlider @value}}
...attributes
>
diff --git a/frontend/discourse/app/components/topic-admin-menu.gjs b/frontend/discourse/app/components/topic-admin-menu.gjs
index 8a6feaaec77..ef304312043 100644
--- a/frontend/discourse/app/components/topic-admin-menu.gjs
+++ b/frontend/discourse/app/components/topic-admin-menu.gjs
@@ -12,6 +12,7 @@ import DButton from "discourse/ui-kit/d-button";
import DDropdownMenu from "discourse/ui-kit/d-dropdown-menu";
import dConcatClass from "discourse/ui-kit/helpers/d-concat-class";
import dIcon from "discourse/ui-kit/helpers/d-icon";
+import { i18n } from "discourse-i18n";
export default class TopicAdminMenu extends Component {
@service adminTopicMenuButtons;
@@ -43,6 +44,35 @@ export default class TopicAdminMenu extends Component {
.filter(Boolean);
}
+ get extraButtonGroups() {
+ const groups = [];
+ let currentGroup = null;
+
+ for (const button of this.extraButtons) {
+ const sectionId = button.section?.id ?? null;
+
+ if (!currentGroup || currentGroup.id !== sectionId) {
+ let sectionLabel = null;
+ if (button.section) {
+ sectionLabel =
+ button.section.translatedLabel ??
+ (button.section.label ? i18n(button.section.label) : null);
+ }
+
+ currentGroup = {
+ id: sectionId,
+ label: sectionLabel,
+ buttons: [],
+ };
+ groups.push(currentGroup);
+ }
+
+ currentGroup.buttons.push(button);
+ }
+
+ return groups;
+ }
+
get details() {
return this.args.topic.get("details");
}
@@ -338,16 +368,29 @@ export default class TopicAdminMenu extends Component {
</dropdown.item>
{{/if}}
- {{#each this.extraButtons as |button|}}
- <dropdown.item>
- <DButton
- @label={{button.label}}
- @translatedLabel={{button.translatedLabel}}
- @icon={{button.icon}}
- class={{dConcatClass "btn-transparent" button.className}}
- @action={{fn this.onExtraButtonAction button.action}}
- />
- </dropdown.item>
+ {{#each this.extraButtonGroups as |group index|}}
+ {{#if group.label}}
+ {{#if
+ (or
+ this.currentUser.staff this.showNestedRepliesToggle index
+ )
+ }}
+ <dropdown.divider />
+ {{/if}}
+ <dropdown.subheader>{{group.label}}</dropdown.subheader>
+ {{/if}}
+
+ {{#each group.buttons as |button|}}
+ <dropdown.item>
+ <DButton
+ @label={{button.label}}
+ @translatedLabel={{button.translatedLabel}}
+ @icon={{button.icon}}
+ class={{dConcatClass "btn-transparent" button.className}}
+ @action={{fn this.onExtraButtonAction button.action}}
+ />
+ </dropdown.item>
+ {{/each}}
{{/each}}
{{/if}}
</DDropdownMenu>
diff --git a/frontend/discourse/app/form-kit/components/fk/collection.gjs b/frontend/discourse/app/form-kit/components/fk/collection.gjs
index f4278bbd81b..0608b43b15a 100644
--- a/frontend/discourse/app/form-kit/components/fk/collection.gjs
+++ b/frontend/discourse/app/form-kit/components/fk/collection.gjs
@@ -40,7 +40,7 @@ export default class FKCollection extends Component {
}
get collectionData() {
- return this.args.data.get(this.name).map((item, index) => {
+ return (this.args.data.get(this.name) ?? []).map((item, index) => {
return {
identifier: `${this.name}-${index}`,
item,
@@ -63,7 +63,7 @@ export default class FKCollection extends Component {
<template>
{{#if this.collectionData.length}}
{{#let (dElement this.tagName) as |Wrapper|}}
- <Wrapper class="form-kit__collection">
+ <Wrapper class="form-kit__collection" ...attributes>
{{#each this.collectionData key="identifier" as |data index|}}
{{yield
(hash
diff --git a/frontend/discourse/app/form-kit/components/fk/field.gjs b/frontend/discourse/app/form-kit/components/fk/field.gjs
index 68ad626dc7e..3317607ad25 100644
--- a/frontend/discourse/app/form-kit/components/fk/field.gjs
+++ b/frontend/discourse/app/form-kit/components/fk/field.gjs
@@ -136,6 +136,7 @@ export default class FKField extends Component {
}}
data-disabled={{field.disabled}}
data-name={{field.name}}
+ ...attributes
{{this.applyControlType field}}
{{didInsert (fn @registerField field.name field)}}
{{willDestroy (fn @unregisterField field.name)}}
diff --git a/frontend/discourse/app/form-kit/components/fk/form.gjs b/frontend/discourse/app/form-kit/components/fk/form.gjs
index adce6dbe8c4..c520383fbb5 100644
--- a/frontend/discourse/app/form-kit/components/fk/form.gjs
+++ b/frontend/discourse/app/form-kit/components/fk/form.gjs
@@ -5,6 +5,7 @@ import { on } from "@ember/modifier";
import { action } from "@ember/object";
import { getOwner } from "@ember/owner";
import didInsert from "@ember/render-modifiers/modifiers/did-insert";
+import { scheduleOnce } from "@ember/runloop";
import { service } from "@ember/service";
import curryComponent from "ember-curry-component";
import { getScrollParent } from "discourse/float-kit/lib/get-scroll-parent";
@@ -40,6 +41,8 @@ class FKForm extends Component {
formData = new FKFormData(this.args.data ?? {});
+ #pendingRegistrations = new Set();
+
constructor() {
super(...arguments);
@@ -187,6 +190,11 @@ class FKForm extends Component {
if (this.fieldValidationEvent === VALIDATION_TYPES.change) {
await this.triggerRevalidationFor(name);
}
+
+ if (this.args.onSet) {
+ await this.args.onSet(name, value, this.formData.draftData);
+ this.formData.save();
+ }
}
@action
@@ -219,16 +227,29 @@ class FKForm extends Component {
}
if (this.fields.has(name)) {
- throw new Error(
- `@name="${name}", is already in use. Names of \`<form.Field />\` must be unique!`
- );
+ this.fields.delete(name);
}
this.fields.set(name, field);
+ if (this.fieldValidationEvent) {
+ this.#pendingRegistrations.add(field);
+ scheduleOnce("afterRender", this, this.validatePendingRegistrations);
+ }
+
return field;
}
+ @action
+ async validatePendingRegistrations() {
+ if (this.#pendingRegistrations.size === 0) {
+ return;
+ }
+ const fields = [...this.#pendingRegistrations];
+ this.#pendingRegistrations.clear();
+ await this.validate(fields);
+ }
+
@action
unregisterField(name) {
this.fields.delete(name);
@@ -280,7 +301,10 @@ class FKForm extends Component {
return;
}
- if (this.formData.errors[name]) {
+ if (
+ this.fieldValidationEvent === VALIDATION_TYPES.change ||
+ this.formData.errors[name]
+ ) {
await this.validate([field]);
}
}
@@ -374,6 +398,7 @@ const Form = <template>
@validateOn={{@validateOn}}
@onRegisterApi={{@onRegisterApi}}
@onReset={{@onReset}}
+ @onSet={{@onSet}}
@onDirtyCheck={{@onDirtyCheck}}
...attributes
as |components draftData|
diff --git a/frontend/discourse/app/lib/load-codemirror.js b/frontend/discourse/app/lib/load-codemirror.js
new file mode 100644
index 00000000000..1cd30f208dd
--- /dev/null
+++ b/frontend/discourse/app/lib/load-codemirror.js
@@ -0,0 +1,9 @@
+import { waitForPromise } from "@ember/test-waiters";
+
+export default async function loadCodemirrorEditor() {
+ return (
+ await waitForPromise(
+ import("discourse/static/codemirror/components/codemirror-editor")
+ )
+ ).default;
+}
diff --git a/frontend/discourse/app/lib/load-rete.js b/frontend/discourse/app/lib/load-rete.js
new file mode 100644
index 00000000000..4a021fa8e45
--- /dev/null
+++ b/frontend/discourse/app/lib/load-rete.js
@@ -0,0 +1,7 @@
+import { waitForPromise } from "@ember/test-waiters";
+
+export default async function loadRete() {
+ const promise = import("discourse/static/rete-bundle");
+ waitForPromise(promise);
+ return await promise;
+}
diff --git a/frontend/discourse/app/lib/plugin-api.gjs b/frontend/discourse/app/lib/plugin-api.gjs
index bc3e57a6fe5..4c6c047dbce 100644
--- a/frontend/discourse/app/lib/plugin-api.gjs
+++ b/frontend/discourse/app/lib/plugin-api.gjs
@@ -786,6 +786,10 @@ class _PluginApi {
/**
* Add a new button in the topic admin menu.
*
+ * Optionally pass a `section` to group buttons under a labelled subheader.
+ * Adjacent buttons sharing the same `section.id` are grouped together;
+ * provide either an i18n `label` key or a pre-translated `translatedLabel`.
+ *
* Example:
*
* ```
@@ -797,6 +801,7 @@ class _PluginApi {
* icon: 'mug-saucer',
* className: 'hot-coffee',
* label: 'coffee.title',
+ * section: { id: 'beverages', label: 'beverages.title' },
* };
* });
* ```
diff --git a/frontend/discourse/app/lib/registry/transformers.js b/frontend/discourse/app/lib/registry/transformers.js
index 505677d1f5d..d84faa13a9d 100644
--- a/frontend/discourse/app/lib/registry/transformers.js
+++ b/frontend/discourse/app/lib/registry/transformers.js
@@ -105,6 +105,7 @@ export const VALUE_TRANSFORMERS = Object.freeze([
"poster-name-user-title",
"preferences-save-attributes",
"quote-params",
+ "route-to-url",
"sidebar-anonymous-default-categories",
"small-user-attrs",
"tag-separator",
diff --git a/frontend/discourse/app/lib/url.js b/frontend/discourse/app/lib/url.js
index dce14d372c9..feaf0b79cd4 100644
--- a/frontend/discourse/app/lib/url.js
+++ b/frontend/discourse/app/lib/url.js
@@ -9,6 +9,7 @@ import { isTesting } from "discourse/lib/environment";
import getURL, { withoutPrefix } from "discourse/lib/get-url";
import LockOn from "discourse/lib/lock-on";
import offsetCalculator from "discourse/lib/offset-calculator";
+import { applyValueTransformer } from "discourse/lib/transformer";
import { defaultHomepage } from "discourse/lib/utilities";
import Category from "discourse/models/category";
import Session from "discourse/models/session";
@@ -312,7 +313,10 @@ class DiscourseURL extends EmberObject {
}
routeToUrl(url, opts = {}) {
- this.routeTo(getURL(url), opts);
+ const transformedUrl = applyValueTransformer("route-to-url", getURL(url), {
+ opts,
+ });
+ this.routeTo(transformedUrl, opts);
}
rewrite(regexp, replacement, opts) {
diff --git a/frontend/discourse/app/static/codemirror/build-extensions.js b/frontend/discourse/app/static/codemirror/build-extensions.js
new file mode 100644
index 00000000000..c5475750632
--- /dev/null
+++ b/frontend/discourse/app/static/codemirror/build-extensions.js
@@ -0,0 +1,17 @@
+import * as cmAutocomplete from "@codemirror/autocomplete";
+import * as cmLanguage from "@codemirror/language";
+import * as cmState from "@codemirror/state";
+import * as cmView from "@codemirror/view";
+import * as lezerHighlight from "@lezer/highlight";
+import { expressionUtils } from "./expression-utils";
+
+export function buildCmParams() {
+ return {
+ cmAutocomplete,
+ cmLanguage,
+ cmState,
+ cmView,
+ lezerHighlight,
+ utils: expressionUtils,
+ };
+}
diff --git a/frontend/discourse/app/static/codemirror/completions-data.js b/frontend/discourse/app/static/codemirror/completions-data.js
new file mode 100644
index 00000000000..17c7667165d
--- /dev/null
+++ b/frontend/discourse/app/static/codemirror/completions-data.js
@@ -0,0 +1,577 @@
+function sectionHeader(name) {
+ return () => {
+ const header = document.createElement("div");
+ header.className = "cm-expr-section-header";
+ header.textContent = name;
+ return header;
+ };
+}
+
+export function section(name, rank) {
+ return { name, rank, header: sectionHeader(name) };
+}
+
+export const SECTION_RECOMMENDED = section("Recommended", 0);
+export const SECTION_PROPERTIES = section("Properties", 2);
+export const SECTION_METHODS = section("Methods", 3);
+export const SECTION_METADATA = section("Metadata", 4);
+export const SECTION_GLOBALS = section("Globals", 5);
+
+export function info(signature, description, example) {
+ return () => {
+ const div = document.createElement("div");
+ div.className = "cm-expr-completion-info";
+
+ const sig = document.createElement("div");
+ sig.className = "cm-expr-completion-info__signature";
+ sig.textContent = signature;
+ div.appendChild(sig);
+
+ const desc = document.createElement("div");
+ desc.className = "cm-expr-completion-info__description";
+ desc.textContent = description;
+ div.appendChild(desc);
+
+ if (example) {
+ const ex = document.createElement("div");
+ ex.className = "cm-expr-completion-info__example";
+ const code = document.createElement("code");
+ code.textContent = example;
+ ex.appendChild(code);
+ div.appendChild(ex);
+ }
+
+ return div;
+ };
+}
+
+export const STRING_METHODS = [
+ {
+ label: "length",
+ type: "property",
+ detail: "number",
+ info: info("str.length", "The number of characters in the string."),
+ },
+ {
+ label: "includes",
+ type: "method",
+ detail: "(str) => boolean",
+ info: info(
+ "str.includes(searchString, position?)",
+ "Returns true if the string contains the substring.",
+ '"hello".includes("ell") → true'
+ ),
+ },
+ {
+ label: "startsWith",
+ type: "method",
+ detail: "(str) => boolean",
+ info: info(
+ "str.startsWith(searchString, position?)",
+ "Returns true if the string starts with the given characters."
+ ),
+ },
+ {
+ label: "endsWith",
+ type: "method",
+ detail: "(str) => boolean",
+ info: info(
+ "str.endsWith(searchString, length?)",
+ "Returns true if the string ends with the given characters."
+ ),
+ },
+ {
+ label: "split",
+ type: "method",
+ detail: "(sep) => string[]",
+ info: info(
+ "str.split(separator, limit?)",
+ "Splits the string into an array of substrings.",
+ '"a,b,c".split(",") → ["a","b","c"]'
+ ),
+ },
+ {
+ label: "replaceAll",
+ type: "method",
+ detail: "(search, replace) => string",
+ info: info(
+ "str.replaceAll(search, replacement)",
+ "Replaces all occurrences of a search string."
+ ),
+ },
+ {
+ label: "replace",
+ type: "method",
+ detail: "(search, replace) => string",
+ info: info(
+ "str.replace(search, replacement)",
+ "Replaces the first occurrence of a search string."
+ ),
+ },
+ {
+ label: "trim",
+ type: "method",
+ detail: "() => string",
+ info: info(
+ "str.trim()",
+ "Removes whitespace from both ends of the string."
+ ),
+ },
+ {
+ label: "trimStart",
+ type: "method",
+ detail: "() => string",
+ info: info(
+ "str.trimStart()",
+ "Removes whitespace from the beginning of the string."
+ ),
+ },
+ {
+ label: "trimEnd",
+ type: "method",
+ detail: "() => string",
+ info: info(
+ "str.trimEnd()",
+ "Removes whitespace from the end of the string."
+ ),
+ },
+ {
+ label: "toLowerCase",
+ type: "method",
+ detail: "() => string",
+ info: info("str.toLowerCase()", "Converts the string to lowercase."),
+ },
+ {
+ label: "toUpperCase",
+ type: "method",
+ detail: "() => string",
+ info: info("str.toUpperCase()", "Converts the string to uppercase."),
+ },
+ {
+ label: "slice",
+ type: "method",
+ detail: "(start, end?) => string",
+ info: info(
+ "str.slice(start, end?)",
+ "Extracts a section of the string.",
+ '"hello".slice(1, 4) → "ell"'
+ ),
+ },
+ {
+ label: "substring",
+ type: "method",
+ detail: "(start, end?) => string",
+ info: info(
+ "str.substring(start, end?)",
+ "Returns the part of the string between two indices."
+ ),
+ },
+ {
+ label: "indexOf",
+ type: "method",
+ detail: "(str) => number",
+ info: info(
+ "str.indexOf(searchValue, fromIndex?)",
+ "Returns the index of the first occurrence, or -1 if not found."
+ ),
+ },
+ {
+ label: "match",
+ type: "method",
+ detail: "(regex) => array",
+ info: info(
+ "str.match(regexp)",
+ "Matches the string against a regular expression."
+ ),
+ },
+ {
+ label: "concat",
+ type: "method",
+ detail: "(...strings) => string",
+ info: info("str.concat(...strings)", "Concatenates one or more strings."),
+ },
+];
+
+export const NUMBER_METHODS = [
+ {
+ label: "toFixed",
+ type: "method",
+ detail: "(digits?) => string",
+ info: info(
+ "num.toFixed(digits?)",
+ "Formats the number with a fixed number of decimal places.",
+ '(3.14159).toFixed(2) → "3.14"'
+ ),
+ },
+ {
+ label: "toString",
+ type: "method",
+ detail: "(radix?) => string",
+ info: info(
+ "num.toString(radix?)",
+ "Returns a string representation of the number."
+ ),
+ },
+ {
+ label: "toPrecision",
+ type: "method",
+ detail: "(precision?) => string",
+ info: info(
+ "num.toPrecision(precision?)",
+ "Formats the number to a specified precision."
+ ),
+ },
+ {
+ label: "toLocaleString",
+ type: "method",
+ detail: "() => string",
+ info: info(
+ "num.toLocaleString(locales?, options?)",
+ "Returns a locale-sensitive string representation."
+ ),
+ },
+];
+
+export const BOOLEAN_METHODS = [
+ {
+ label: "toString",
+ type: "method",
+ detail: "() => string",
+ info: info(
+ "bool.toString()",
+ "Converts true to 'true' and false to 'false'."
+ ),
+ },
+];
+
+export const ARRAY_METHODS = [
+ {
+ label: "length",
+ type: "property",
+ detail: "number",
+ info: info("arr.length", "The number of elements in the array."),
+ },
+ {
+ label: "map",
+ type: "method",
+ detail: "(fn) => array",
+ info: info(
+ "arr.map(callback)",
+ "Creates a new array with the results of calling a function on every element.",
+ "[1,2,3].map(x => x * 2) → [2,4,6]"
+ ),
+ },
+ {
+ label: "filter",
+ type: "method",
+ detail: "(fn) => array",
+ info: info(
+ "arr.filter(callback)",
+ "Creates a new array with elements that pass the test.",
+ "[1,2,3,4].filter(x => x > 2) → [3,4]"
+ ),
+ },
+ {
+ label: "find",
+ type: "method",
+ detail: "(fn) => item",
+ info: info(
+ "arr.find(callback)",
+ "Returns the first element that satisfies the testing function."
+ ),
+ },
+ {
+ label: "includes",
+ type: "method",
+ detail: "(item) => boolean",
+ info: info(
+ "arr.includes(value, fromIndex?)",
+ "Returns true if the array contains the specified value."
+ ),
+ },
+ {
+ label: "join",
+ type: "method",
+ detail: "(sep?) => string",
+ info: info(
+ "arr.join(separator?)",
+ "Joins all elements into a string.",
+ '["a","b","c"].join("-") → "a-b-c"'
+ ),
+ },
+ {
+ label: "slice",
+ type: "method",
+ detail: "(start, end?) => array",
+ info: info(
+ "arr.slice(start?, end?)",
+ "Returns a shallow copy of a portion of the array."
+ ),
+ },
+ {
+ label: "sort",
+ type: "method",
+ detail: "(fn?) => array",
+ info: info(
+ "arr.sort(compareFn?)",
+ "Sorts the elements of the array in place."
+ ),
+ },
+ {
+ label: "reverse",
+ type: "method",
+ detail: "() => array",
+ info: info("arr.reverse()", "Reverses the order of elements."),
+ },
+ {
+ label: "reduce",
+ type: "method",
+ detail: "(fn, init?) => any",
+ info: info(
+ "arr.reduce(callback, initialValue?)",
+ "Reduces the array to a single value.",
+ "[1,2,3].reduce((sum, x) => sum + x, 0) → 6"
+ ),
+ },
+ {
+ label: "indexOf",
+ type: "method",
+ detail: "(item) => number",
+ info: info(
+ "arr.indexOf(value, fromIndex?)",
+ "Returns the first index of the value, or -1 if not found."
+ ),
+ },
+ {
+ label: "concat",
+ type: "method",
+ detail: "(...arrays) => array",
+ info: info(
+ "arr.concat(...values)",
+ "Merges arrays and/or values into a new array."
+ ),
+ },
+];
+
+export const DATE_METHODS = [
+ {
+ label: "toISOString",
+ type: "method",
+ detail: "() => string",
+ info: info("date.toISOString()", "Returns the date as an ISO 8601 string."),
+ },
+ {
+ label: "toLocaleDateString",
+ type: "method",
+ detail: "() => string",
+ info: info(
+ "date.toLocaleDateString(locales?, options?)",
+ "Returns a locale-sensitive date string."
+ ),
+ },
+ {
+ label: "getTime",
+ type: "method",
+ detail: "() => number",
+ info: info("date.getTime()", "Returns milliseconds since Unix epoch."),
+ },
+ {
+ label: "getFullYear",
+ type: "method",
+ detail: "() => number",
+ info: info("date.getFullYear()", "Returns the four-digit year."),
+ },
+ {
+ label: "getMonth",
+ type: "method",
+ detail: "() => number",
+ info: info("date.getMonth()", "Returns the month (0-11)."),
+ },
+ {
+ label: "getDate",
+ type: "method",
+ detail: "() => number",
+ info: info("date.getDate()", "Returns the day of the month (1-31)."),
+ },
+ {
+ label: "getHours",
+ type: "method",
+ detail: "() => number",
+ info: info("date.getHours()", "Returns the hour (0-23)."),
+ },
+ {
+ label: "getMinutes",
+ type: "method",
+ detail: "() => number",
+ info: info("date.getMinutes()", "Returns the minutes (0-59)."),
+ },
+ {
+ label: "toLocaleString",
+ type: "method",
+ detail: "() => string",
+ info: info(
+ "date.toLocaleString(locales?, options?)",
+ "Returns a locale-sensitive date and time string."
+ ),
+ },
+];
+
+export const GLOBAL_COMPLETIONS = [
+ {
+ label: "Math",
+ type: "variable",
+ detail: "object",
+ info: "Mathematical constants and functions (Math.round, Math.random, etc.)",
+ },
+ {
+ label: "JSON",
+ type: "variable",
+ detail: "object",
+ info: "JSON parsing and serialization (JSON.parse, JSON.stringify).",
+ },
+ {
+ label: "Object",
+ type: "variable",
+ detail: "object",
+ info: "Object utilities (Object.keys, Object.values, Object.entries).",
+ },
+ {
+ label: "Array",
+ type: "variable",
+ detail: "object",
+ info: "Array utilities (Array.isArray, Array.from).",
+ },
+ {
+ label: "String",
+ type: "variable",
+ detail: "object",
+ info: "String constructor and utilities.",
+ },
+ {
+ label: "Number",
+ type: "variable",
+ detail: "object",
+ info: "Number utilities (Number.isInteger, Number.parseFloat).",
+ },
+ {
+ label: "Date",
+ type: "variable",
+ detail: "object",
+ info: "Date constructor. Use new Date() to create dates.",
+ },
+ {
+ label: "parseInt",
+ type: "function",
+ detail: "(string, radix?) => number",
+ info: "Parses a string and returns an integer.",
+ },
+ {
+ label: "parseFloat",
+ type: "function",
+ detail: "(string) => number",
+ info: "Parses a string and returns a floating-point number.",
+ },
+ {
+ label: "encodeURIComponent",
+ type: "function",
+ detail: "(string) => string",
+ info: "Encodes a URI component by replacing special characters.",
+ },
+ {
+ label: "decodeURIComponent",
+ type: "function",
+ detail: "(string) => string",
+ info: "Decodes an encoded URI component.",
+ },
+ {
+ label: "isNaN",
+ type: "function",
+ detail: "(value) => boolean",
+ info: "Returns true if the value is NaN.",
+ },
+ {
+ label: "isFinite",
+ type: "function",
+ detail: "(value) => boolean",
+ info: "Returns true if the value is a finite number.",
+ },
+];
+
+// Non-enumerable, so Object.keys won't find them — listed explicitly.
+export const GLOBAL_STATIC_METHODS = {
+ Math: [
+ { label: "abs", type: "function", detail: "(x) => number" },
+ { label: "ceil", type: "function", detail: "(x) => number" },
+ { label: "floor", type: "function", detail: "(x) => number" },
+ { label: "round", type: "function", detail: "(x) => number" },
+ { label: "max", type: "function", detail: "(...values) => number" },
+ { label: "min", type: "function", detail: "(...values) => number" },
+ { label: "random", type: "function", detail: "() => number" },
+ { label: "pow", type: "function", detail: "(base, exp) => number" },
+ { label: "sqrt", type: "function", detail: "(x) => number" },
+ { label: "trunc", type: "function", detail: "(x) => number" },
+ { label: "PI", type: "property", detail: "number" },
+ ],
+ JSON: [
+ { label: "parse", type: "function", detail: "(text) => any" },
+ { label: "stringify", type: "function", detail: "(value) => string" },
+ ],
+ Object: [
+ { label: "keys", type: "function", detail: "(obj) => string[]" },
+ { label: "values", type: "function", detail: "(obj) => any[]" },
+ { label: "entries", type: "function", detail: "(obj) => [string, any][]" },
+ {
+ label: "assign",
+ type: "function",
+ detail: "(target, ...sources) => object",
+ },
+ { label: "fromEntries", type: "function", detail: "(iterable) => object" },
+ ],
+ Array: [
+ { label: "isArray", type: "function", detail: "(value) => boolean" },
+ { label: "from", type: "function", detail: "(iterable) => array" },
+ ],
+ Number: [
+ { label: "isInteger", type: "function", detail: "(value) => boolean" },
+ { label: "isFinite", type: "function", detail: "(value) => boolean" },
+ { label: "isNaN", type: "function", detail: "(value) => boolean" },
+ { label: "parseInt", type: "function", detail: "(string) => number" },
+ { label: "parseFloat", type: "function", detail: "(string) => number" },
+ ],
+ String: [
+ { label: "fromCharCode", type: "function", detail: "(...codes) => string" },
+ ],
+ Date: [
+ { label: "now", type: "function", detail: "() => number" },
+ { label: "parse", type: "function", detail: "(string) => number" },
+ ],
+};
+
+function buildMethodMap(methods) {
+ return new Map(methods.map((m) => [m.label, m]));
+}
+
+const METHOD_DOCS_BY_TYPE = {
+ string: buildMethodMap(STRING_METHODS),
+ number: buildMethodMap(NUMBER_METHODS),
+ boolean: buildMethodMap(BOOLEAN_METHODS),
+ array: buildMethodMap(ARRAY_METHODS),
+ date: buildMethodMap(DATE_METHODS),
+};
+
+export function lookupMethodDoc(name, parentValue) {
+ if (parentValue === null || parentValue === undefined) {
+ return null;
+ }
+ let typeName;
+ if (Array.isArray(parentValue)) {
+ typeName = "array";
+ } else if (parentValue instanceof Date) {
+ typeName = "date";
+ } else {
+ typeName = typeof parentValue;
+ }
+ return METHOD_DOCS_BY_TYPE[typeName]?.get(name) ?? null;
+}
+
+export const GLOBAL_DOCS = new Map(GLOBAL_COMPLETIONS.map((g) => [g.label, g]));
diff --git a/frontend/discourse/app/static/codemirror/components/codemirror-editor.gjs b/frontend/discourse/app/static/codemirror/components/codemirror-editor.gjs
new file mode 100644
index 00000000000..cbcd6772395
--- /dev/null
+++ b/frontend/discourse/app/static/codemirror/components/codemirror-editor.gjs
@@ -0,0 +1,162 @@
+import Component from "@glimmer/component";
+import { tracked } from "@glimmer/tracking";
+import { action } from "@ember/object";
+import didInsert from "@ember/render-modifiers/modifiers/did-insert";
+import didUpdate from "@ember/render-modifiers/modifiers/did-update";
+import willDestroy from "@ember/render-modifiers/modifiers/will-destroy";
+import { closeCompletion, completionStatus } from "@codemirror/autocomplete";
+import { defaultKeymap, history, historyKeymap } from "@codemirror/commands";
+import { EditorState } from "@codemirror/state";
+import {
+ EditorView,
+ keymap,
+ lineNumbers,
+ placeholder,
+ ViewPlugin,
+} from "@codemirror/view";
+import { bind } from "discourse/lib/decorators";
+import { buildCmParams } from "../build-extensions";
+
+export default class CodemirrorEditor extends Component {
+ @tracked view = null;
+ #lastValue;
+ #suppressChange = false;
+
+ @action
+ setup(container) {
+ const extensions = [
+ history(),
+ keymap.of([...defaultKeymap, ...historyKeymap]),
+ EditorView.updateListener.of((update) => {
+ if (update.docChanged) {
+ const value = update.state.doc.toString();
+ this.#lastValue = value;
+ if (!this.#suppressChange) {
+ this.args.change?.(value);
+ }
+ }
+ if (update.focusChanged) {
+ if (update.view.hasFocus) {
+ this.args.focusIn?.();
+ } else {
+ this.args.focusOut?.();
+ }
+ }
+ }),
+ ];
+
+ if (this.args.placeholder) {
+ extensions.push(placeholder(this.args.placeholder));
+ }
+
+ if (this.args.lineNumbers) {
+ extensions.push(lineNumbers());
+ }
+
+ if (this.args.lineWrapping) {
+ extensions.push(EditorView.lineWrapping);
+ }
+
+ if (this.args.readOnly) {
+ extensions.push(
+ EditorState.readOnly.of(true),
+ EditorView.editable.of(false)
+ );
+ }
+
+ if (this.args.singleLine) {
+ extensions.push(
+ EditorState.transactionFilter.of((tr) => {
+ if (tr.newDoc.lines > 1) {
+ return [];
+ }
+ return tr;
+ })
+ );
+ }
+
+ extensions.push(
+ ViewPlugin.fromClass(
+ class {
+ constructor(view) {
+ this.view = view;
+ this.handler = (event) => {
+ if (event.key !== "Escape" || !this.view.hasFocus) {
+ return;
+ }
+ if (completionStatus(this.view.state)) {
+ closeCompletion(this.view);
+ } else {
+ this.view.contentDOM.blur();
+ }
+ event.preventDefault();
+ };
+ window.addEventListener("keydown", this.handler, { capture: true });
+ }
+
+ destroy() {
+ window.removeEventListener("keydown", this.handler, {
+ capture: true,
+ });
+ }
+ }
+ )
+ );
+
+ if (this.args.extensions) {
+ extensions.push(...this.args.extensions(buildCmParams()));
+ }
+
+ const initialValue = this.args.value ?? "";
+
+ this.view = new EditorView({
+ parent: container,
+ state: EditorState.create({
+ doc: initialValue,
+ extensions,
+ }),
+ });
+
+ this.#lastValue = initialValue;
+
+ this.args.onSetup?.(this.view);
+ }
+
+ @bind
+ updateValue() {
+ if (!this.view) {
+ return;
+ }
+
+ const value = this.args.value ?? "";
+ if (value === this.#lastValue) {
+ return;
+ }
+
+ this.#suppressChange = true;
+ this.view.dispatch({
+ changes: {
+ from: 0,
+ to: this.view.state.doc.length,
+ insert: value,
+ },
+ });
+ this.#lastValue = value;
+ this.#suppressChange = false;
+ }
+
+ @action
+ teardown() {
+ this.view?.destroy();
+ this.view = null;
+ }
+
+ <template>
+ <div
+ class="codemirror-editor {{@class}}"
+ {{didInsert this.setup}}
+ {{didUpdate this.updateValue @value}}
+ {{willDestroy this.teardown}}
+ ></div>
+ </template>
+}
diff --git a/frontend/discourse/app/static/codemirror/expression-utils.js b/frontend/discourse/app/static/codemirror/expression-utils.js
new file mode 100644
index 00000000000..e18d083de12
--- /dev/null
+++ b/frontend/discourse/app/static/codemirror/expression-utils.js
@@ -0,0 +1,70 @@
+import {
+ ARRAY_METHODS,
+ BOOLEAN_METHODS,
+ DATE_METHODS,
+ GLOBAL_COMPLETIONS,
+ GLOBAL_DOCS,
+ GLOBAL_STATIC_METHODS,
+ lookupMethodDoc,
+ NUMBER_METHODS,
+ section,
+ SECTION_GLOBALS,
+ SECTION_METADATA,
+ SECTION_METHODS,
+ SECTION_PROPERTIES,
+ SECTION_RECOMMENDED,
+ STRING_METHODS,
+} from "./completions-data";
+import { expressionLanguage } from "./lang-expression/index";
+import {
+ analyzePropertyAccess,
+ isInsideExpression,
+ isInsideExpressionAt,
+ resolveNodeValue,
+} from "./tree-utils";
+
+function methodsForType(value) {
+ if (value === null || value === undefined) {
+ return [];
+ }
+ if (Array.isArray(value)) {
+ return ARRAY_METHODS;
+ }
+ if (value instanceof Date) {
+ return DATE_METHODS;
+ }
+ switch (typeof value) {
+ case "string":
+ return STRING_METHODS;
+ case "number":
+ return NUMBER_METHODS;
+ case "boolean":
+ return BOOLEAN_METHODS;
+ default:
+ return [];
+ }
+}
+
+// Generic expression utilities for {{ }} editors. Domain-specific
+// analysis (like workflow $() node refs) should extend
+// analyzePropertyAccess in the consumer, not here.
+export const expressionUtils = {
+ expressionLanguage,
+ analyzePropertyAccess,
+ resolveNodeValue,
+ isInsideExpression,
+ isInsideExpressionAt,
+ lookupMethodDoc,
+ methodsForType,
+ section,
+ globalDocs: GLOBAL_DOCS,
+ sections: {
+ recommended: SECTION_RECOMMENDED,
+ properties: SECTION_PROPERTIES,
+ methods: SECTION_METHODS,
+ metadata: SECTION_METADATA,
+ globals: SECTION_GLOBALS,
+ },
+ globalCompletions: GLOBAL_COMPLETIONS,
+ globalStaticMethods: GLOBAL_STATIC_METHODS,
+};
diff --git a/frontend/discourse/app/static/codemirror/lang-expression/expression.grammar b/frontend/discourse/app/static/codemirror/lang-expression/expression.grammar
new file mode 100644
index 00000000000..d09e45208da
--- /dev/null
+++ b/frontend/discourse/app/static/codemirror/lang-expression/expression.grammar
@@ -0,0 +1,15 @@
+@top Template { entity* }
+
+entity { Text | Expression }
+
+Expression { OpenExpression expressionContent* CloseExpression }
+
+@tokens {
+ Text { ![{] Text? | "{" (@eof | ![{] Text?) }
+ OpenExpression[closedBy="CloseExpression"] { "{{" }
+ CloseExpression[openedBy="OpenExpression"] { "}}" }
+ expressionContent { unicodeChar | "}" ![}] | "\\}}" }
+ unicodeChar { $[\u0000-\u007C] | $[\u007E-\u{10FFFF}] }
+}
+
+@detectDelim
diff --git a/frontend/discourse/app/static/codemirror/lang-expression/expression.js b/frontend/discourse/app/static/codemirror/lang-expression/expression.js
new file mode 100644
index 00000000000..9124e62fe79
--- /dev/null
+++ b/frontend/discourse/app/static/codemirror/lang-expression/expression.js
@@ -0,0 +1,23 @@
+// This file was generated by lezer-generator. You probably shouldn't edit it.
+import { LRParser } from "@lezer/lr";
+
+export const parser = LRParser.deserialize({
+ version: 14,
+ states:
+ "!dQQOPOOOYOQO'#CaOOOO'#Ce'#CeOOOO'#Cb'#CbQQOPOOOOOO'#Cc'#CcObOQO,58{OOOO,58{,58{OOOO-E6`-E6`OOOO-E6a-E6aOOOO1G.g1G.g",
+ stateData: "j~OQQOSPO~ORVOYTO~ORYOYTO~O",
+ goto: "oYPPPPPZ_ePkTQOSQSORWSQUPRXUTROS",
+ nodeNames: "⚠ Template Text CloseExpression OpenExpression Expression",
+ maxTerm: 10,
+ nodeProps: [
+ ["openedBy", 3, "OpenExpression"],
+ ["closedBy", 4, "CloseExpression"],
+ ],
+ skippedNodes: [0],
+ repeatNodeCount: 2,
+ tokenData:
+ "&tRRXO#On#O#P#[#P#on#o#p$d#p#qn#q#r%T#r;'Sn;'S;=`&n<%lOnRuTQPYQO#o!U#o#p!j#p;'S!U;'S;=`#P<%lO!UP!ZTQPO#o!U#o#p!j#p;'S!U;'S;=`#P<%lO!UP!mUO#o!U#p;'S!U;'S;=`#P<%l~!U~O!U~~#VP#SP;=`<%l!UP#[OQPR#cVQPYQO#o!U#o#p!j#p#q!U#q#r#x#r;'S!U;'S;=`#P<%lO!UR#}VQPO#o!U#o#p!j#p#q!U#q#rn#r;'S!U;'S;=`#P<%lO!UR$iVYQO#o!U#o#p%O#p;'S!U;'S;=`#P<%l~!U~O!U~~#VP%TOSPR%YVQPO#on#o#p%o#p#qn#q#r&W#r;'Sn;'S;=`&n<%lOnR%tUYQO#o!U#p;'S!U;'S;=`#P<%l~!U~O!U~~#VR&_TRQQPO#o!U#o#p!j#p;'S!U;'S;=`#P<%lO!UR&qP;=`<%ln",
+ tokenizers: [0, 1],
+ topRules: { Template: [0, 1] },
+ tokenPrec: 0,
+});
diff --git a/frontend/discourse/app/static/codemirror/lang-expression/expression.terms.js b/frontend/discourse/app/static/codemirror/lang-expression/expression.terms.js
new file mode 100644
index 00000000000..aa18dd0752f
--- /dev/null
+++ b/frontend/discourse/app/static/codemirror/lang-expression/expression.terms.js
@@ -0,0 +1,6 @@
+// This file was generated by lezer-generator. You probably shouldn't edit it.
+export const Template = 1,
+ Text = 2,
+ CloseExpression = 3,
+ OpenExpression = 4,
+ Expression = 5;
diff --git a/frontend/discourse/app/static/codemirror/lang-expression/index.js b/frontend/discourse/app/static/codemirror/lang-expression/index.js
new file mode 100644
index 00000000000..99ec0ecca9a
--- /dev/null
+++ b/frontend/discourse/app/static/codemirror/lang-expression/index.js
@@ -0,0 +1,57 @@
+import { javascriptLanguage } from "@codemirror/lang-javascript";
+import { LanguageSupport, LRLanguage } from "@codemirror/language";
+import { parseMixed } from "@lezer/common";
+import { styleTags, tags as t } from "@lezer/highlight";
+import { parser } from "./expression";
+import {
+ CloseExpression,
+ Expression,
+ OpenExpression,
+} from "./expression.terms";
+
+const mixedParser = parser.configure({
+ props: [
+ styleTags({
+ Text: t.content,
+ Expression: t.string,
+ "OpenExpression CloseExpression": t.brace,
+ }),
+ ],
+ wrap: parseMixed((node) => {
+ if (node.type.id === Expression) {
+ let from = node.from;
+ let to = node.to;
+
+ const first = node.node.firstChild;
+ if (first?.type.id === OpenExpression) {
+ from = first.to;
+ }
+ const last = node.node.lastChild;
+ if (last?.type.id === CloseExpression) {
+ to = last.from;
+ }
+
+ if (from >= to) {
+ return null;
+ }
+ return {
+ parser: javascriptLanguage.parser,
+ overlay: [{ from, to }],
+ };
+ }
+ return null;
+ }),
+});
+
+const expressionLang = LRLanguage.define({
+ name: "expression",
+ parser: mixedParser,
+ languageData: {
+ closeBrackets: { brackets: ["(", "[", "'", '"'] },
+ commentTokens: { line: "//" },
+ },
+});
+
+export function expressionLanguage() {
+ return new LanguageSupport(expressionLang);
+}
diff --git a/frontend/discourse/app/static/codemirror/tree-utils.js b/frontend/discourse/app/static/codemirror/tree-utils.js
new file mode 100644
index 00000000000..4142c23f13d
--- /dev/null
+++ b/frontend/discourse/app/static/codemirror/tree-utils.js
@@ -0,0 +1,94 @@
+import { syntaxTree } from "@codemirror/language";
+
+function findDot(memberExpr) {
+ for (let child = memberExpr.lastChild; child; child = child.prevSibling) {
+ if (child.name === ".") {
+ return child.from;
+ }
+ }
+ return null;
+}
+
+export function resolveNodeValue(node, doc) {
+ if (!node) {
+ return null;
+ }
+
+ if (node.name === "VariableName" || node.name === "VariableDefinition") {
+ return doc.sliceString(node.from, node.to);
+ }
+
+ if (node.name === "MemberExpression") {
+ const obj = resolveNodeValue(node.firstChild, doc);
+ const prop = node.lastChild;
+ if (obj && prop && prop.name === "PropertyName") {
+ return `${obj}.${doc.sliceString(prop.from, prop.to)}`;
+ }
+ return obj;
+ }
+
+ if (node.name === "CallExpression") {
+ const callee = node.firstChild;
+ if (callee) {
+ const calleeName = doc.sliceString(callee.from, callee.to);
+ const argList = node.getChild("ArgList");
+ if (argList) {
+ const strNode = argList.getChild("String");
+ if (strNode) {
+ const raw = doc.sliceString(strNode.from, strNode.to);
+ return `${calleeName}(${raw})`;
+ }
+ }
+ }
+ }
+
+ return null;
+}
+
+export function analyzePropertyAccess(state, pos) {
+ const tree = syntaxTree(state);
+ const node = tree.resolveInner(pos, -1);
+ const doc = state.doc;
+
+ let cur = node;
+ while (cur) {
+ if (cur.name === "MemberExpression") {
+ const dotPos = findDot(cur);
+ if (dotPos !== null && pos > dotPos) {
+ const obj = resolveNodeValue(cur.firstChild, doc);
+ const partial = doc.sliceString(dotPos + 1, pos);
+ return { kind: "property", object: obj, partial, from: dotPos + 1 };
+ }
+ }
+
+ if (cur.name === "MemberExpression" && cur.getChild("[")) {
+ const obj = resolveNodeValue(cur.firstChild, doc);
+ return { kind: "bracket", object: obj, from: pos };
+ }
+
+ cur = cur.parent;
+ }
+
+ if (node.name === "VariableName" || node.name === "VariableDefinition") {
+ const text = doc.sliceString(node.from, pos);
+ return { kind: "identifier", partial: text, from: node.from };
+ }
+
+ return { kind: "blank", from: pos };
+}
+
+export function isInsideExpressionAt(state, pos) {
+ const tree = syntaxTree(state);
+ let node = tree.resolve(pos, -1);
+ while (node) {
+ if (node.name === "Expression") {
+ return true;
+ }
+ node = node.parent;
+ }
+ return false;
+}
+
+export function isInsideExpression(context) {
+ return isInsideExpressionAt(context.state, context.pos);
+}
diff --git a/frontend/discourse/app/static/rete-bundle.js b/frontend/discourse/app/static/rete-bundle.js
new file mode 100644
index 00000000000..9fcf49bec9a
--- /dev/null
+++ b/frontend/discourse/app/static/rete-bundle.js
@@ -0,0 +1,12 @@
+export { ClassicPreset, NodeEditor, Scope } from "rete";
+export { AreaExtensions, AreaPlugin, Zoom } from "rete-area-plugin";
+export {
+ ConnectionPlugin,
+ Presets as ConnectionPresets,
+} from "rete-connection-plugin";
+export { HistoryPlugin, HistoryExtensions } from "rete-history-plugin";
+export {
+ AutoArrangePlugin,
+ Presets as ArrangePresets,
+} from "rete-auto-arrange-plugin";
+export { classicConnectionPath, getElementCenter } from "rete-render-utils";
diff --git a/frontend/discourse/app/ui-kit/d-dropdown-menu.gjs b/frontend/discourse/app/ui-kit/d-dropdown-menu.gjs
index e32dd79c7a0..ed29ba0a930 100644
--- a/frontend/discourse/app/ui-kit/d-dropdown-menu.gjs
+++ b/frontend/discourse/app/ui-kit/d-dropdown-menu.gjs
@@ -8,9 +8,17 @@ const DropdownDivider = <template>
<li ...attributes><hr class="dropdown-menu__divider" /></li>
</template>;
+const DropdownSubheader = <template>
+ <li class="dropdown-menu__subheader" ...attributes>{{yield}}</li>
+</template>;
+
const DDropdownMenu = <template>
<ul class="dropdown-menu" ...attributes>
- {{yield (hash item=DropdownItem divider=DropdownDivider)}}
+ {{yield
+ (hash
+ item=DropdownItem divider=DropdownDivider subheader=DropdownSubheader
+ )
+ }}
</ul>
</template>;
diff --git a/frontend/discourse/app/ui-kit/d-stat-tiles.gjs b/frontend/discourse/app/ui-kit/d-stat-tiles.gjs
index 947de95dc18..f8eed9c7650 100644
--- a/frontend/discourse/app/ui-kit/d-stat-tiles.gjs
+++ b/frontend/discourse/app/ui-kit/d-stat-tiles.gjs
@@ -1,6 +1,7 @@
-import { hash } from "@ember/helper";
+import { concat, hash } from "@ember/helper";
import DTooltip from "discourse/float-kit/components/d-tooltip";
import { number } from "discourse/lib/formatter";
+import dConcatClass from "discourse/ui-kit/helpers/d-concat-class";
const DStatTile = <template>
<div class="d-stat-tile" role="group">
@@ -16,16 +17,21 @@ const DStatTile = <template>
</div>
{{#if @url}}
<a href={{@url}} class="d-stat-tile__value" title={{@value}}>
- {{number @value}}
+ {{if @formattedValue @formattedValue (number @value)}}
</a>
{{else}}
- <span class="d-stat-tile__value" title={{@value}}>{{number @value}}</span>
+ <span class="d-stat-tile__value" title={{@value}}>
+ {{if @formattedValue @formattedValue (number @value)}}
+ </span>
{{/if}}
</div>
</template>;
const DStatTiles = <template>
- <div class="d-stat-tiles" ...attributes>
+ <div
+ class={{dConcatClass "d-stat-tiles" (if @format (concat "--" @format))}}
+ ...attributes
+ >
{{yield (hash Tile=DStatTile)}}
</div>
</template>;
diff --git a/frontend/discourse/package.json b/frontend/discourse/package.json
index 1750a2d9236..03290ca0875 100644
--- a/frontend/discourse/package.json
+++ b/frontend/discourse/package.json
@@ -25,6 +25,12 @@
"test": "ember test"
},
"dependencies": {
+ "@codemirror/autocomplete": "^6.20.1",
+ "@codemirror/commands": "^6.10.3",
+ "@codemirror/lang-javascript": "^6.2.5",
+ "@codemirror/language": "^6.12.3",
+ "@codemirror/state": "^6.6.0",
+ "@codemirror/view": "^6.40.0",
"@faker-js/faker": "^10.4.0",
"@fullcalendar/core": "^6.1.20",
"@fullcalendar/daygrid": "^6.1.20",
@@ -38,6 +44,10 @@
"@glint/template": "^1.7.7",
"@highlightjs/cdn-assets": "11.11.1",
"@json-editor/json-editor": "2.15.2",
+ "@lezer/common": "^1.5.2",
+ "@lezer/highlight": "^1.2.3",
+ "@lezer/javascript": "^1.5.4",
+ "@lezer/lr": "^1.4.8",
"@discourse/gif": "^1.0.0",
"@discourse/heic": "^1.0.0",
"@discourse/jpeg": "^1.0.0",
@@ -50,8 +60,10 @@
"chartjs-adapter-moment": "^1.0.1",
"chartjs-plugin-datalabels": "2.2.0",
"decorator-transforms": "^2.3.2",
+ "codemirror": "^6.0.2",
"diff": "^9.0.0",
"ember-curry-component": "^0.4.0",
+ "elkjs": "^0.8.2",
"ember-resolver": "^13.2.0",
"ember-route-template": "^1.0.3",
"ember-source": "~6.10.0",
@@ -81,7 +93,14 @@
"prosemirror-state": "^1.4.4",
"prosemirror-transform": "^1.12.0",
"prosemirror-view": "^1.41.8",
- "rrule": "^2.8.1"
+ "rete": "^2.0.6",
+ "rete-area-plugin": "^2.1.5",
+ "rete-auto-arrange-plugin": "^2.0.2",
+ "rete-connection-plugin": "^2.0.5",
+ "rete-history-plugin": "^2.1.1",
+ "rete-render-utils": "^2.0.3",
+ "rrule": "^2.8.1",
+ "web-worker": "^1.5.0"
},
"devDependencies": {
"@babel/core": "^7.28.5",
diff --git a/frontend/discourse/select-kit/components/multi-select.gjs b/frontend/discourse/select-kit/components/multi-select.gjs
index 1d23da2cecd..3e0b15e7e59 100644
--- a/frontend/discourse/select-kit/components/multi-select.gjs
+++ b/frontend/discourse/select-kit/components/multi-select.gjs
@@ -1,6 +1,5 @@
import { concat } from "@ember/helper";
import { computed } from "@ember/object";
-import { next } from "@ember/runloop";
import { isPresent } from "@ember/utils";
import { classNames } from "@ember-decorators/component";
import componentForCollection from "discourse/helpers/component-for-collection";
@@ -93,10 +92,8 @@ export default class MultiSelect extends SelectKitComponent {
select(value, item) {
if (this.selectKit.hasSelection && this.selectKit.options.maximum === 1) {
- this.selectKit.deselectByValue(this.getValue(this.selectedContent[0]));
- next(() => {
- this.selectKit.select(value, item);
- });
+ const newItem = item || this.defaultItem(value, value);
+ this.selectKit.change(makeArray(value), makeArray(newItem));
return;
}
diff --git a/frontend/discourse/tests/acceptance/topic-admin-menu-test.js b/frontend/discourse/tests/acceptance/topic-admin-menu-test.js
index d24746cae1a..99e0657b926 100644
--- a/frontend/discourse/tests/acceptance/topic-admin-menu-test.js
+++ b/frontend/discourse/tests/acceptance/topic-admin-menu-test.js
@@ -71,4 +71,26 @@ acceptance("Topic - Admin Menu", function (needs) {
await click(".extra-button");
assert.true(this.actionCalled, "The action was called");
});
+
+ test("Buttons with a section are rendered under a subheader", async function (assert) {
+ updateCurrentUser({ admin: true });
+
+ withPluginApi((api) => {
+ api.addTopicAdminMenuButton(() => ({
+ className: "section-button",
+ icon: "heart",
+ translatedLabel: "Section button",
+ action: () => {},
+ section: { id: "test-section", translatedLabel: "Test section" },
+ }));
+ });
+
+ await visit("/t/internationalization-localization/280");
+ await click(".toggle-admin-menu");
+
+ assert
+ .dom(".dropdown-menu__subheader")
+ .hasText("Test section", "The section subheader is rendered");
+ assert.dom(".section-button").exists("The section button is rendered");
+ });
});
diff --git a/frontend/discourse/tests/integration/components/form-kit/collection-test.gjs b/frontend/discourse/tests/integration/components/form-kit/collection-test.gjs
index 9a16f0e9b36..72cc2aff94f 100644
--- a/frontend/discourse/tests/integration/components/form-kit/collection-test.gjs
+++ b/frontend/discourse/tests/integration/components/form-kit/collection-test.gjs
@@ -197,6 +197,22 @@ module("Integration | Component | FormKit | Collection", function (hooks) {
assert.dom("ul.form-kit__collection").doesNotExist();
});
+ test("renders nothing when collection is missing", async function (assert) {
+ await render(
+ <template>
+ <Form @data={{hash}} as |form|>
+ <form.Collection @name="foo" @tagName="ul" as |collection|>
+ <collection.Field @type="input" @title="Bar" as |field|>
+ <field.Control />
+ </collection.Field>
+ </form.Collection>
+ </Form>
+ </template>
+ );
+
+ assert.dom("ul.form-kit__collection").doesNotExist();
+ });
+
test("emptying a collection field", async function (assert) {
const onSubmit = (data) => {
assert.deepEqual(
diff --git a/frontend/discourse/tests/integration/components/form-kit/form-test.gjs b/frontend/discourse/tests/integration/components/form-kit/form-test.gjs
index 164031d9320..f884675cee7 100644
--- a/frontend/discourse/tests/integration/components/form-kit/form-test.gjs
+++ b/frontend/discourse/tests/integration/components/form-kit/form-test.gjs
@@ -21,6 +21,30 @@ module("Integration | Component | FormKit | Form", function (hooks) {
await formKit().submit();
});
+ test("@onSet", async function (assert) {
+ const calls = [];
+ const onSet = (name, value, data) => {
+ calls.push({ name, value, data: { ...data } });
+ };
+
+ await render(
+ <template>
+ <Form @data={{hash foo=1}} @onSet={{onSet}} as |form|>
+ <form.Field @type="input" @name="foo" @title="Foo" as |field|>
+ <field.Control />
+ </form.Field>
+ </Form>
+ </template>
+ );
+
+ await formKit().field("foo").fillIn("2");
+
+ assert.strictEqual(calls.length, 1);
+ assert.strictEqual(calls[0].name, "foo");
+ assert.strictEqual(calls[0].value, "2");
+ assert.strictEqual(calls[0].data.foo, "2");
+ });
+
test("addItemToCollection", async function (assert) {
await render(
<template>
diff --git a/frontend/discourse/tests/integration/ui-kit/d-stat-tiles-test.gjs b/frontend/discourse/tests/integration/ui-kit/d-stat-tiles-test.gjs
index d0c680dee15..9a72904672c 100644
--- a/frontend/discourse/tests/integration/ui-kit/d-stat-tiles-test.gjs
+++ b/frontend/discourse/tests/integration/ui-kit/d-stat-tiles-test.gjs
@@ -69,4 +69,16 @@ module("Integration | ui-kit | DStatTiles", function (hooks) {
.dom(".d-stat-tiles .d-stat-tile a.d-stat-tile__value")
.hasAttribute("href", "https://meta.discourse.org");
});
+
+ test("applies a BEM modifier class when @format is set", async function (assert) {
+ await render(
+ <template>
+ <DStatTiles @format="compact" as |tiles|>
+ <tiles.Tile @value="1" @label={{label}} />
+ </DStatTiles>
+ </template>
+ );
+
+ assert.dom(".d-stat-tiles.--compact").exists();
+ });
});
diff --git a/plugins/chat/app/jobs/regular/chat/resume_workflow_approval.rb b/plugins/chat/app/jobs/regular/chat/resume_workflow_approval.rb
new file mode 100644
index 00000000000..9d5d8211c0a
--- /dev/null
+++ b/plugins/chat/app/jobs/regular/chat/resume_workflow_approval.rb
@@ -0,0 +1,16 @@
+# frozen_string_literal: true
+
+module Jobs
+ module Chat
+ class ResumeWorkflowApproval < ::Jobs::Base
+ def execute(args)
+ ::Chat::Workflows::Approval::Resume.call(
+ params: {
+ action_id: args[:action_id],
+ channel_id: args[:channel_id],
+ },
+ )
+ end
+ end
+ end
+end
diff --git a/plugins/chat/app/services/chat/workflows/approval/resume.rb b/plugins/chat/app/services/chat/workflows/approval/resume.rb
new file mode 100644
index 00000000000..e7279ec8ca4
--- /dev/null
+++ b/plugins/chat/app/services/chat/workflows/approval/resume.rb
@@ -0,0 +1,55 @@
+# frozen_string_literal: true
+
+module Chat
+ module Workflows
+ module Approval
+ class Resume
+ include Service::Base
+
+ policy :workflows_enabled
+
+ params do
+ attribute :action_id, :string
+ attribute :channel_id, :integer
+
+ validates :action_id, presence: true
+ validates :channel_id, presence: true
+ end
+
+ model :resume_request
+ model :claimed_resume_request
+ step :resume_execution
+
+ private
+
+ def workflows_enabled
+ SiteSetting.discourse_workflows_enabled
+ end
+
+ def fetch_resume_request(params:)
+ ::DiscourseWorkflows::InteractiveResume.from_action_id(
+ params.action_id,
+ expected_node_type: "action:chat_approval",
+ allowed_actions: %w[approve deny],
+ )
+ end
+
+ def fetch_claimed_resume_request(resume_request:)
+ resume_request.claim
+ end
+
+ def resume_execution(claimed_resume_request:, params:)
+ response_items = [
+ {
+ "json" => {
+ "approved" => claimed_resume_request.action == "approve",
+ "channel_id" => params.channel_id,
+ },
+ },
+ ]
+ claimed_resume_request.resume!(response_items)
+ end
+ end
+ end
+ end
+end
diff --git a/plugins/chat/config/locales/client.en.yml b/plugins/chat/config/locales/client.en.yml
index 7a6a8eb6599..43620533b0e 100644
--- a/plugins/chat/config/locales/client.en.yml
+++ b/plugins/chat/config/locales/client.en.yml
@@ -835,3 +835,30 @@ en:
panels:
chat:
label: "Chat"
+
+ discourse_workflows:
+ node_unavailable:
+ requires_chat: "Requires the Chat plugin to be enabled"
+ nodes:
+ "action:send_chat_message": "Send chat message"
+ "action:chat_approval": "Chat approval"
+ node_descriptions:
+ "action:send_chat_message": "Send a message to a chat channel"
+ "action:chat_approval": "Send an approval request to a chat channel and wait for a response"
+ send_chat_message:
+ channel_id: "Channel"
+ message: "Message"
+ chat_approval:
+ message: "Message"
+ approve_label: "Approve button label"
+ approve_label_description: "Defaults to \"Approve\" if left blank."
+ deny_label: "Deny button label"
+ deny_label_description: "Defaults to \"Deny\" if left blank."
+ channel_id: "Channel"
+ channel_id_description: "The chat channel to send the approval message to."
+ timeout_minutes: "Timeout (minutes)"
+ timeout_minutes_description: "Leave blank for no timeout."
+ timeout_action: "On timeout"
+ timeout_action_description: "What happens when the approval times out."
+ timeout_action_deny: "Resume as denied"
+ timeout_action_fail: "Fail the workflow"
diff --git a/plugins/chat/config/locales/server.en.yml b/plugins/chat/config/locales/server.en.yml
index 702c90d17b7..158871829b9 100644
--- a/plugins/chat/config/locales/server.en.yml
+++ b/plugins/chat/config/locales/server.en.yml
@@ -246,6 +246,21 @@ en:
send_chat_message:
title: Send chat message
+ discourse_workflows:
+ chat_approval:
+ default_approve_label: "Approve"
+ default_deny_label: "Deny"
+ errors:
+ send_chat_message:
+ invalid_params: "Invalid params: %{errors}"
+ channel_not_found: "Channel not found: %{channel_id}"
+ failed: "Failed to send chat message."
+ chat_approval:
+ channel_not_found: "Chat message failed: channel %{channel_id} not found."
+ invalid_params: "Chat message failed: %{errors}"
+ failed: "Chat message failed: %{steps}"
+ timeout_must_be_positive: "Timeout minutes must be greater than 0."
+
reviewable_score_types:
needs_review:
title: "Needs Review"
diff --git a/plugins/chat/lib/discourse_workflows/nodes/chat_approval/v1.rb b/plugins/chat/lib/discourse_workflows/nodes/chat_approval/v1.rb
new file mode 100644
index 00000000000..18ac9474a8a
--- /dev/null
+++ b/plugins/chat/lib/discourse_workflows/nodes/chat_approval/v1.rb
@@ -0,0 +1,189 @@
+# frozen_string_literal: true
+
+if defined?(DiscourseWorkflows)
+ module DiscourseWorkflows
+ module Nodes
+ module ChatApproval
+ class V1 < DiscourseWorkflows::NodeType
+ include ChatChannelSelection
+
+ description(
+ name: "action:chat_approval",
+ version: "1.0",
+ defaults: {
+ icon: "comments",
+ color: "cyan",
+ },
+ group: "human_review",
+ available: -> { SiteSetting.chat_enabled },
+ unavailable_reason_key: "discourse_workflows.node_unavailable.requires_chat",
+ capabilities: {
+ waits_for_resume: true,
+ },
+ properties: {
+ message: {
+ type: :string,
+ required: true,
+ ui: {
+ control: :textarea,
+ },
+ },
+ approve_label: {
+ type: :string,
+ required: false,
+ },
+ deny_label: {
+ type: :string,
+ required: false,
+ },
+ channel_id: {
+ type: :integer,
+ required: true,
+ type_options: {
+ load_options_method: "chat_channels",
+ },
+ no_data_expression: true,
+ ui: {
+ control: :combo_box,
+ },
+ control_options: {
+ filterable: true,
+ value_property: :id,
+ name_property: :name,
+ set_from_option: {
+ channel_name: "name",
+ },
+ },
+ },
+ channel_name: {
+ type: :string,
+ ui: {
+ hidden: true,
+ },
+ },
+ timeout_minutes: {
+ type: :integer,
+ required: false,
+ min: 1,
+ },
+ timeout_action: {
+ type: :options,
+ required: false,
+ options: %w[deny fail],
+ default: "deny",
+ no_data_expression: true,
+ },
+ },
+ )
+
+ def self.load_options_context(context)
+ case context.method_name
+ when "chat_channels"
+ ChatChannelSelection.load_options(context)
+ end
+ end
+
+ def execute(exec_ctx)
+ message_text = exec_ctx.get_node_parameter("message", 0)
+ approve_label =
+ exec_ctx.get_node_parameter("approve_label", 0).presence ||
+ I18n.t("discourse_workflows.chat_approval.default_approve_label")
+ deny_label =
+ exec_ctx.get_node_parameter("deny_label", 0).presence ||
+ I18n.t("discourse_workflows.chat_approval.default_deny_label")
+ channel_id = exec_ctx.get_node_parameter("channel_id", 0).to_i
+ timeout_minutes = exec_ctx.get_node_parameter("timeout_minutes", 0).presence&.to_i
+ if timeout_minutes && timeout_minutes < 1
+ raise_node_error!(
+ I18n.t("discourse_workflows.errors.chat_approval.timeout_must_be_positive"),
+ )
+ end
+
+ approve_action_id = exec_ctx.resume_action_id("approve")
+ deny_action_id = exec_ctx.resume_action_id("deny")
+
+ blocks = approval_blocks(approve_action_id, deny_action_id, approve_label, deny_label)
+ send_chat_message(channel_id, message_text, blocks)
+
+ exec_ctx.put_execution_to_wait(timeout_minutes&.minutes&.from_now)
+ [exec_ctx.input_items]
+ end
+
+ private
+
+ def send_chat_message(channel_id, message, blocks)
+ channel = selectable_chat_channel(channel_id)
+
+ if channel.blank?
+ raise_node_error!(
+ I18n.t(
+ "discourse_workflows.errors.chat_approval.channel_not_found",
+ channel_id: channel_id,
+ ),
+ )
+ end
+
+ Chat::CreateMessage.call(
+ guardian: Discourse.system_user.guardian,
+ params: {
+ chat_channel_id: channel.id,
+ message: message,
+ blocks: blocks,
+ },
+ ) do |result|
+ on_success { return result.message_instance }
+ on_model_not_found(:channel) do
+ raise_node_error!(
+ I18n.t(
+ "discourse_workflows.errors.chat_approval.channel_not_found",
+ channel_id: channel_id,
+ ),
+ )
+ end
+ on_failed_contract do |contract|
+ raise_node_error!(
+ I18n.t(
+ "discourse_workflows.errors.chat_approval.invalid_params",
+ errors: contract.errors.full_messages.join(", "),
+ ),
+ )
+ end
+ on_failure do
+ raise_node_error!(
+ I18n.t(
+ "discourse_workflows.errors.chat_approval.failed",
+ steps: result.inspect_steps,
+ ),
+ )
+ end
+ end
+ end
+
+ def approval_blocks(approve_token, deny_token, approve_label, deny_label)
+ [
+ {
+ "type" => "actions",
+ "elements" => [
+ button_block(approve_label, approve_token, "approve"),
+ button_block(deny_label, deny_token, "deny"),
+ ],
+ },
+ ]
+ end
+
+ def button_block(label, action_id, value)
+ {
+ "type" => "button",
+ "text" => {
+ "type" => "plain_text",
+ "text" => label,
+ },
+ "action_id" => action_id,
+ "value" => value,
+ }
+ end
+ end
+ end
+ end
+ end
+end
diff --git a/plugins/chat/lib/discourse_workflows/nodes/chat_channel_selection.rb b/plugins/chat/lib/discourse_workflows/nodes/chat_channel_selection.rb
new file mode 100644
index 00000000000..b43f2176578
--- /dev/null
+++ b/plugins/chat/lib/discourse_workflows/nodes/chat_channel_selection.rb
@@ -0,0 +1,40 @@
+# frozen_string_literal: true
+
+if defined?(DiscourseWorkflows)
+ module DiscourseWorkflows
+ module Nodes
+ module ChatChannelSelection
+ MAX_LOAD_OPTIONS = 200
+ CHANNEL_NAME_SQL = "COALESCE(chat_channels.name, categories.name)"
+
+ def self.selectable_channels
+ ::Chat::Channel.public_channels.where(status: ::Chat::Channel.statuses[:open])
+ end
+
+ def self.load_options(context)
+ channels = selectable_channels
+
+ if context.filter.present?
+ channels =
+ channels.where(
+ "LOWER(#{CHANNEL_NAME_SQL}) LIKE ?",
+ "%#{ActiveRecord::Base.sanitize_sql_like(context.filter.downcase)}%",
+ )
+ end
+
+ channels
+ .order("LOWER(#{CHANNEL_NAME_SQL}) ASC")
+ .limit(MAX_LOAD_OPTIONS)
+ .pluck(:id, :name, "categories.name")
+ .map do |id, channel_name, category_name|
+ { id:, name: channel_name.presence || category_name }
+ end
+ end
+
+ def selectable_chat_channel(channel_id)
+ ChatChannelSelection.selectable_channels.find_by(id: channel_id)
+ end
+ end
+ end
+ end
+end
diff --git a/plugins/chat/lib/discourse_workflows/nodes/send_chat_message/v1.rb b/plugins/chat/lib/discourse_workflows/nodes/send_chat_message/v1.rb
new file mode 100644
index 00000000000..e4e2b2f1e63
--- /dev/null
+++ b/plugins/chat/lib/discourse_workflows/nodes/send_chat_message/v1.rb
@@ -0,0 +1,128 @@
+# frozen_string_literal: true
+
+if defined?(DiscourseWorkflows)
+ module DiscourseWorkflows
+ module Nodes
+ module SendChatMessage
+ class V1 < DiscourseWorkflows::NodeType
+ include ChatChannelSelection
+
+ description(
+ name: "action:send_chat_message",
+ version: "1.0",
+ defaults: {
+ icon: "comment",
+ color: "teal",
+ },
+ group: "discourse_actions",
+ available: -> { SiteSetting.chat_enabled },
+ unavailable_reason_key: "discourse_workflows.node_unavailable.requires_chat",
+ capabilities: {
+ run_scope: "per_item",
+ },
+ properties: {
+ channel_id: {
+ type: :integer,
+ required: true,
+ type_options: {
+ load_options_method: "chat_channels",
+ },
+ ui: {
+ control: :combo_box,
+ dynamic_value: :chat_channel_id,
+ },
+ control_options: {
+ filterable: true,
+ value_property: :id,
+ name_property: :name,
+ set_from_option: {
+ channel_name: "name",
+ },
+ },
+ },
+ channel_name: {
+ type: :string,
+ ui: {
+ hidden: true,
+ },
+ },
+ message: {
+ type: :string,
+ required: true,
+ ui: {
+ control: :textarea,
+ },
+ },
+ },
+ )
+
+ def self.load_options_context(context)
+ case context.method_name
+ when "chat_channels"
+ ChatChannelSelection.load_options(context)
+ end
+ end
+
+ def execute(exec_ctx)
+ items =
+ exec_ctx.input_items.map.with_index do |_item, item_index|
+ config = {
+ "channel_id" => exec_ctx.get_node_parameter("channel_id", item_index),
+ "message" => exec_ctx.get_node_parameter("message", item_index),
+ }
+ result = process(config)
+ wrap(result)
+ end
+ [items]
+ end
+
+ private
+
+ def process(config)
+ channel_id = config["channel_id"]
+ message = config["message"]
+ channel = selectable_chat_channel(channel_id)
+
+ if channel.blank?
+ raise_node_error!(
+ I18n.t(
+ "discourse_workflows.errors.send_chat_message.channel_not_found",
+ channel_id: channel_id,
+ ),
+ )
+ end
+
+ Chat::CreateMessage.call(
+ guardian: Discourse.system_user.guardian,
+ params: {
+ chat_channel_id: channel.id,
+ message: message,
+ },
+ ) do
+ on_success { { "channel_id" => channel.id, "message" => message } }
+ on_failed_contract do |contract|
+ raise_node_error!(
+ I18n.t(
+ "discourse_workflows.errors.send_chat_message.invalid_params",
+ errors: contract.errors.full_messages.join(", "),
+ ),
+ )
+ end
+ on_model_not_found(:channel) do
+ raise_node_error!(
+ I18n.t(
+ "discourse_workflows.errors.send_chat_message.channel_not_found",
+ channel_id: channel_id,
+ ),
+ )
+ end
+ on_failure do
+ raise_node_error!(I18n.t("discourse_workflows.errors.send_chat_message.failed"))
+ end
+ end
+ end
+ end
+ end
+ end
+ end
+end
diff --git a/plugins/chat/plugin.rb b/plugins/chat/plugin.rb
index 5eb6bb32760..bbf6ea6abf0 100644
--- a/plugins/chat/plugin.rb
+++ b/plugins/chat/plugin.rb
@@ -45,7 +45,6 @@ module ::Chat
end
require_relative "lib/chat/engine"
-
after_initialize do
register_seedfu_fixtures(Rails.root.join("plugins/chat/db/fixtures"))
@@ -98,6 +97,36 @@ after_initialize do
register_reviewable_type Chat::ReviewableMessage
+ if respond_to?(:register_discourse_workflows_node)
+ register_discourse_workflows_node do
+ require_relative "lib/discourse_workflows/nodes/chat_channel_selection"
+ require_relative "lib/discourse_workflows/nodes/send_chat_message/v1"
+ require_relative "lib/discourse_workflows/nodes/chat_approval/v1"
+
+ [DiscourseWorkflows::Nodes::SendChatMessage::V1, DiscourseWorkflows::Nodes::ChatApproval::V1]
+ end
+
+ on(:chat_message_interaction) do |interaction|
+ next unless SiteSetting.discourse_workflows_enabled
+
+ action_id = interaction.action&.dig("action_id").to_s
+ next if action_id.blank?
+ unless DiscourseWorkflows::InteractiveResume.action_id?(
+ action_id,
+ expected_node_type: "action:chat_approval",
+ allowed_actions: %w[approve deny],
+ )
+ next
+ end
+
+ Jobs.enqueue(
+ Jobs::Chat::ResumeWorkflowApproval,
+ action_id: action_id,
+ channel_id: interaction.message.chat_channel_id,
+ )
+ end
+ end
+
reloadable_patch do |plugin|
Site.preloaded_category_custom_fields << Chat::HAS_CHAT_ENABLED
diff --git a/plugins/chat/spec/integration/workflows_chat_approval_spec.rb b/plugins/chat/spec/integration/workflows_chat_approval_spec.rb
new file mode 100644
index 00000000000..8a12c433548
--- /dev/null
+++ b/plugins/chat/spec/integration/workflows_chat_approval_spec.rb
@@ -0,0 +1,128 @@
+# frozen_string_literal: true
+
+RSpec.describe "Wait for Approval end-to-end" do
+ fab!(:user)
+ fab!(:approver, :user)
+ fab!(:channel, :chat_channel)
+
+ before do
+ SiteSetting.chat_enabled = true
+ SiteSetting.discourse_workflows_enabled = true
+ end
+
+ def run_pending_approval_job
+ job_args = Jobs::Chat::ResumeWorkflowApproval.jobs.last&.dig("args", 0)
+ Jobs::Chat::ResumeWorkflowApproval.new.execute(job_args.symbolize_keys) if job_args
+ end
+
+ def trigger_approval_interaction(user:, message:, action_id:, value: "approve")
+ interaction =
+ Chat::MessageInteraction.new(
+ user: user,
+ message: message,
+ action: {
+ "action_id" => action_id,
+ "value" => value,
+ },
+ )
+ DiscourseEvent.trigger(:chat_message_interaction, interaction)
+ end
+
+ it "pauses, receives approval via chat interaction, and completes the workflow" do
+ graph =
+ build_workflow_graph do |g|
+ g.node "trigger-1", "trigger:manual"
+ g.node "wait-1",
+ "action:chat_approval",
+ name: "Approval",
+ configuration: {
+ "message" => "Please review",
+ "approve_label" => "LGTM",
+ "deny_label" => "Reject",
+ "channel_id" => channel.id.to_s,
+ "timeout_minutes" => "30",
+ }
+ g.node "final-1",
+ "action:set_fields",
+ name: "Final",
+ configuration: {
+ "mode" => "raw",
+ "include_other_fields" => true,
+ "json_output" => '{"completed": "true"}',
+ }
+ g.chain "trigger-1", "wait-1", "final-1"
+ end
+
+ workflow = Fabricate(:discourse_workflows_workflow, created_by: user, **graph)
+ publish_workflow!(workflow)
+
+ execution = nil
+ freeze_time do
+ execution = DiscourseWorkflows::Executor.new(workflow, "trigger-1", { "topic_id" => 1 }).run
+ expect(execution.status).to eq("waiting")
+ expect(execution.waiting_until).to eq_time(30.minutes.from_now)
+ end
+
+ chat_message = Chat::Message.where(chat_channel_id: channel.id).last
+ buttons = chat_message.blocks.first["elements"]
+ expect(chat_message.message).to eq("Please review")
+ expect(buttons.first["text"]["text"]).to eq("LGTM")
+ expect(buttons.last["text"]["text"]).to eq("Reject")
+
+ trigger_approval_interaction(
+ user: approver,
+ message: chat_message,
+ action_id: buttons.first["action_id"],
+ )
+ run_pending_approval_job
+
+ execution.reload
+ expect(execution.status).to eq("success")
+ expect(execution.execution_data.context_data["Final"].first["json"]).to include(
+ "completed" => "true",
+ "approved" => true,
+ )
+ end
+
+ it "rejects a stale approval button when the execution revisits the same approval node" do
+ graph =
+ build_workflow_graph do |g|
+ g.node "trigger-1", "trigger:manual"
+ g.node "wait-1",
+ "action:chat_approval",
+ name: "Approval",
+ configuration: {
+ "message" => "Please review",
+ "channel_id" => channel.id.to_s,
+ }
+ g.chain "trigger-1", "wait-1"
+ end
+
+ workflow = Fabricate(:discourse_workflows_workflow, created_by: user, **graph)
+ publish_workflow!(workflow)
+
+ execution = DiscourseWorkflows::Executor.new(workflow, "trigger-1", {}).run
+ expect(execution.status).to eq("waiting")
+
+ first_message = Chat::Message.where(chat_channel_id: channel.id).last
+ original_action_id = first_message.blocks.first["elements"].first["action_id"]
+
+ trigger_approval_interaction(
+ user: approver,
+ message: first_message,
+ action_id: original_action_id,
+ )
+ run_pending_approval_job
+ expect(execution.reload.status).to eq("success")
+
+ execution.update!(status: :waiting, waiting_node_id: "wait-1", resume_token: SecureRandom.uuid)
+
+ trigger_approval_interaction(
+ user: approver,
+ message: first_message,
+ action_id: original_action_id,
+ )
+ run_pending_approval_job
+ expect(execution.reload.status).to eq("waiting")
+ end
+end
diff --git a/plugins/chat/spec/integration/workflows_chat_interaction_spec.rb b/plugins/chat/spec/integration/workflows_chat_interaction_spec.rb
new file mode 100644
index 00000000000..24c05fdf56c
--- /dev/null
+++ b/plugins/chat/spec/integration/workflows_chat_interaction_spec.rb
@@ -0,0 +1,90 @@
+# frozen_string_literal: true
+
+RSpec.describe "Chat interaction listener for workflow approvals" do
+ fab!(:user)
+ fab!(:channel, :chat_channel)
+ fab!(:chat_message) { Fabricate(:chat_message, chat_channel: channel) }
+
+ before do
+ SiteSetting.chat_enabled = true
+ SiteSetting.discourse_workflows_enabled = true
+ end
+
+ it "enqueues ResumeWorkflowApproval when an approve button is clicked" do
+ graph =
+ build_workflow_graph do |g|
+ g.node "trigger-1", "trigger:manual"
+ g.node "wait-1",
+ "action:chat_approval",
+ configuration: {
+ "message" => "Approve?",
+ "channel_id" => channel.id.to_s,
+ }
+ g.chain "trigger-1", "wait-1"
+ end
+ workflow = Fabricate(:discourse_workflows_workflow, created_by: user, **graph)
+ publish_workflow!(workflow)
+
+ execution = DiscourseWorkflows::Executor.new(workflow, "trigger-1", {}).run
+ expect(execution.status).to eq("waiting")
+
+ approve_action_id = Chat::Message.last.blocks.first["elements"].first["action_id"]
+
+ interaction =
+ Chat::MessageInteraction.new(
+ user: user,
+ message: Chat::Message.last,
+ action: {
+ "action_id" => approve_action_id,
+ "value" => "approve",
+ },
+ )
+
+ expect_enqueued_with(
+ job: Jobs::Chat::ResumeWorkflowApproval,
+ args: {
+ action_id: approve_action_id,
+ channel_id: channel.id,
+ },
+ ) { DiscourseEvent.trigger(:chat_message_interaction, interaction) }
+ end
+
+ it "ignores interactions whose action_id does not match any waiting execution" do
+ interaction =
+ Chat::MessageInteraction.new(
+ user: user,
+ message: chat_message,
+ action: {
+ "action_id" => "unknown-token:approve",
+ },
+ )
+
+ expect { DiscourseEvent.trigger(:chat_message_interaction, interaction) }.not_to change(
+ Jobs::Chat::ResumeWorkflowApproval.jobs,
+ :size,
+ )
+ end
+
+ it "ignores interactions with an unrecognized action type" do
+ action_id =
+ DiscourseWorkflows::InteractiveResume.action_id(
+ execution_id: 1,
+ resume_token: "some-token",
+ action: "unknown",
+ )
+
+ interaction =
+ Chat::MessageInteraction.new(
+ user: user,
+ message: chat_message,
+ action: {
+ "action_id" => action_id,
+ },
+ )
+
+ expect { DiscourseEvent.trigger(:chat_message_interaction, interaction) }.not_to change(
+ Jobs::Chat::ResumeWorkflowApproval.jobs,
+ :size,
+ )
+ end
+end
diff --git a/plugins/chat/spec/lib/discourse_workflows/nodes/chat_approval_spec.rb b/plugins/chat/spec/lib/discourse_workflows/nodes/chat_approval_spec.rb
new file mode 100644
index 00000000000..dd7f38ec30f
--- /dev/null
+++ b/plugins/chat/spec/lib/discourse_workflows/nodes/chat_approval_spec.rb
@@ -0,0 +1,183 @@
+# frozen_string_literal: true
+
+RSpec.describe DiscourseWorkflows::Nodes::ChatApproval::V1 do
+ fab!(:channel, :chat_channel)
+ fab!(:execution, :discourse_workflows_execution)
+
+ before { SiteSetting.chat_enabled = true }
+
+ describe ".identifier" do
+ it "returns the correct identifier" do
+ expect(described_class.identifier).to eq("action:chat_approval")
+ end
+ end
+
+ describe ".load_options_context" do
+ fab!(:other_channel) { Fabricate(:chat_channel, name: "Approvals") }
+ fab!(:closed_channel) { Fabricate(:chat_channel, name: "Archived", status: :closed) }
+ fab!(:dm_channel, :direct_message_channel)
+
+ def load_options(filter: nil)
+ context =
+ DiscourseWorkflows::LoadOptionsContext.new(
+ method_name: "chat_channels",
+ filter: filter,
+ node_class: described_class,
+ )
+
+ described_class.load_options_context(context)
+ end
+
+ it "returns open public channels with id and name" do
+ ids = load_options.map { |option| option[:id] }
+
+ expect(ids).to include(channel.id, other_channel.id)
+ expect(ids).not_to include(closed_channel.id, dm_channel.id)
+ end
+
+ it "filters channels by the filter term" do
+ expect(load_options(filter: "approv")).to contain_exactly(
+ { id: other_channel.id, name: other_channel.name },
+ )
+ end
+ end
+
+ describe "#execute" do
+ let(:resume_token) { SecureRandom.uuid }
+ let(:sandbox) { DiscourseWorkflows::JsSandbox.new({}) }
+
+ after { sandbox.dispose }
+
+ def build_exec_ctx(config)
+ resolver = DiscourseWorkflows::ExpressionResolver.new({ "$json" => {} }, sandbox: sandbox)
+ DiscourseWorkflows::Executor::NodeExecutionContext.new(
+ input_items: [{ "json" => {} }],
+ node_context: {
+ },
+ resolver: resolver,
+ parameters: config,
+ property_schema: described_class.property_schema,
+ execution_id: execution.id,
+ node_id: "node_abc",
+ resume_token: resume_token,
+ )
+ end
+
+ it "sends a chat message and returns input items" do
+ config = {
+ "message" => "Please approve this",
+ "approve_label" => "Yes",
+ "deny_label" => "No",
+ "channel_id" => channel.id.to_s,
+ "timeout_minutes" => "30",
+ "timeout_action" => "fail",
+ }
+ instance = described_class.new(parameters: config)
+ exec_ctx = build_exec_ctx(config)
+
+ result = instance.execute(exec_ctx)
+
+ expect(Chat::Message.last.message).to eq("Please approve this")
+ expect(result).to eq([exec_ctx.input_items])
+ end
+
+ it "creates buttons with signed action IDs" do
+ config = {
+ "message" => "Please approve this",
+ "approve_label" => "Yes",
+ "deny_label" => "No",
+ "channel_id" => channel.id.to_s,
+ "timeout_action" => "fail",
+ }
+ instance = described_class.new(parameters: config)
+ exec_ctx = build_exec_ctx(config)
+ instance.execute(exec_ctx)
+
+ message = Chat::Message.last
+ buttons = message.blocks.first["elements"]
+ payloads =
+ buttons.map do |button|
+ DiscourseWorkflows::InteractiveResume.action_payload(button["action_id"])
+ end
+
+ expect(payloads).to match(
+ [
+ hash_including("execution_id" => execution.id, "action" => "approve"),
+ hash_including("execution_id" => execution.id, "action" => "deny"),
+ ],
+ )
+ action_ids = buttons.map { |button| button["action_id"] }
+ expect(action_ids).to all(satisfy { |id| id.length <= 255 && id.exclude?(resume_token) })
+ end
+
+ it "uses default labels when none provided" do
+ config = {
+ "message" => "Approve?",
+ "channel_id" => channel.id.to_s,
+ "timeout_action" => "deny",
+ }
+ instance = described_class.new(parameters: config)
+ exec_ctx = build_exec_ctx(config)
+ instance.execute(exec_ctx)
+
+ buttons = Chat::Message.last.blocks.first["elements"]
+ expect(buttons.first["text"]["text"]).to eq("Approve")
+ expect(buttons.last["text"]["text"]).to eq("Deny")
+ end
+
+ it "rejects negative timeout values" do
+ config = {
+ "message" => "Approve?",
+ "channel_id" => channel.id.to_s,
+ "timeout_minutes" => "-1",
+ "timeout_action" => "deny",
+ }
+ instance = described_class.new(parameters: config)
+ exec_ctx = build_exec_ctx(config)
+
+ expect { instance.execute(exec_ctx) }.to raise_error(
+ DiscourseWorkflows::NodeError,
+ "Timeout minutes must be greater than 0.",
+ )
+ expect(channel.chat_messages).to be_empty
+ end
+
+ it "rejects closed channels outside the selectable channel scope" do
+ closed_channel = Fabricate(:chat_channel, name: "Closed", status: :closed)
+ config = {
+ "message" => "Approve?",
+ "channel_id" => closed_channel.id.to_s,
+ "timeout_action" => "deny",
+ }
+ instance = described_class.new(parameters: config)
+ exec_ctx = build_exec_ctx(config)
+
+ expect { instance.execute(exec_ctx) }.to raise_error(
+ I18n.t(
+ "discourse_workflows.errors.chat_approval.channel_not_found",
+ channel_id: closed_channel.id,
+ ),
+ )
+ expect(closed_channel.chat_messages).to be_empty
+ end
+
+ it "rejects direct message channels outside the selectable channel scope" do
+ dm_channel = Fabricate(:direct_message_channel)
+ config = {
+ "message" => "Approve?",
+ "channel_id" => dm_channel.id.to_s,
+ "timeout_action" => "deny",
+ }
+ instance = described_class.new(parameters: config)
+ exec_ctx = build_exec_ctx(config)
+
+ expect { instance.execute(exec_ctx) }.to raise_error(
+ I18n.t(
+ "discourse_workflows.errors.chat_approval.channel_not_found",
+ channel_id: dm_channel.id,
+ ),
+ )
+ expect(dm_channel.chat_messages).to be_empty
+ end
+ end
+end
diff --git a/plugins/chat/spec/lib/discourse_workflows/nodes/send_chat_message_spec.rb b/plugins/chat/spec/lib/discourse_workflows/nodes/send_chat_message_spec.rb
new file mode 100644
index 00000000000..5ff7fdbb7da
--- /dev/null
+++ b/plugins/chat/spec/lib/discourse_workflows/nodes/send_chat_message_spec.rb
@@ -0,0 +1,152 @@
+# frozen_string_literal: true
+
+RSpec.describe DiscourseWorkflows::Nodes::SendChatMessage::V1 do
+ fab!(:channel, :chat_channel)
+
+ before { SiteSetting.chat_enabled = true }
+
+ describe ".load_options_context" do
+ fab!(:other_channel) { Fabricate(:chat_channel, name: "Announcements") }
+ fab!(:closed_channel) { Fabricate(:chat_channel, name: "Closed", status: :closed) }
+ fab!(:dm_channel, :direct_message_channel)
+
+ def load_options(filter: nil)
+ context =
+ DiscourseWorkflows::LoadOptionsContext.new(
+ method_name: "chat_channels",
+ filter: filter,
+ node_class: described_class,
+ )
+
+ described_class.load_options_context(context)
+ end
+
+ it "returns open public channels with id and name" do
+ ids = load_options.map { |option| option[:id] }
+
+ expect(ids).to include(channel.id, other_channel.id)
+ expect(ids).not_to include(closed_channel.id, dm_channel.id)
+ end
+
+ it "falls back to category name when channel name is blank" do
+ blank_channel = Fabricate(:chat_channel, name: nil)
+
+ option = load_options.find { |opt| opt[:id] == blank_channel.id }
+
+ expect(option[:name]).to eq(blank_channel.chatable.name)
+ end
+
+ it "filters channels by the filter term" do
+ expect(load_options(filter: "announce")).to contain_exactly(
+ { id: other_channel.id, name: other_channel.name },
+ )
+ end
+
+ it "limits channel options after applying the filter" do
+ 201.times { |index| Fabricate(:chat_channel, name: "Load option channel #{index}") }
+ matching_channel = Fabricate(:chat_channel, name: "Targeted workflow channel")
+
+ expect(load_options.size).to eq(
+ DiscourseWorkflows::Nodes::ChatChannelSelection::MAX_LOAD_OPTIONS,
+ )
+ expect(load_options(filter: "targeted")).to contain_exactly(
+ { id: matching_channel.id, name: matching_channel.name },
+ )
+ end
+ end
+
+ describe "#execute" do
+ def build_exec_ctx(input_items:, parameters:, resolver_context:)
+ sandbox = DiscourseWorkflows::JsSandbox.new(resolver_context)
+ resolver = DiscourseWorkflows::ExpressionResolver.new(resolver_context, sandbox: sandbox)
+ exec_ctx =
+ DiscourseWorkflows::Executor::NodeExecutionContext.new(
+ input_items: input_items,
+ resolver: resolver,
+ parameters: parameters,
+ property_schema: described_class.property_schema,
+ node_identifier: described_class.identifier,
+ resolver_context: resolver_context,
+ )
+
+ [exec_ctx, resolver, sandbox]
+ end
+
+ it "resolves message expressions for each input item" do
+ input_items = [
+ { "json" => { "text" => "First message" } },
+ { "json" => { "text" => "Second message" } },
+ ]
+ parameters = { "channel_id" => channel.id.to_s, "message" => "={{ $json.text }}" }
+ resolver_context = { "$json" => {} }
+ exec_ctx, resolver, sandbox = build_exec_ctx(input_items:, parameters:, resolver_context:)
+
+ output = described_class.new(parameters: parameters).execute(exec_ctx)
+
+ expect(output.first.map { |item| item["json"]["message"] }).to eq(
+ ["First message", "Second message"],
+ )
+ expect(channel.chat_messages.order(:id).last(2).map(&:message)).to eq(
+ ["First message", "Second message"],
+ )
+ ensure
+ resolver&.dispose
+ sandbox&.dispose
+ end
+
+ it "resolves channel_id expressions" do
+ input_items = [{ "json" => { "target_channel" => channel.id } }]
+ parameters = {
+ "channel_id" => "={{ $json.target_channel }}",
+ "message" => "Hello from expression",
+ }
+ resolver_context = { "$json" => {} }
+ exec_ctx, resolver, sandbox = build_exec_ctx(input_items:, parameters:, resolver_context:)
+
+ described_class.new(parameters: parameters).execute(exec_ctx)
+
+ expect(channel.chat_messages.order(:id).last.message).to eq("Hello from expression")
+ ensure
+ resolver&.dispose
+ sandbox&.dispose
+ end
+
+ it "rejects expression-resolved channels outside the selectable channel scope" do
+ closed_channel = Fabricate(:chat_channel, name: "Closed", status: :closed)
+ input_items = [{ "json" => { "target_channel" => closed_channel.id } }]
+ parameters = { "channel_id" => "={{ $json.target_channel }}", "message" => "Hidden target" }
+ resolver_context = { "$json" => {} }
+ exec_ctx, resolver, sandbox = build_exec_ctx(input_items:, parameters:, resolver_context:)
+
+ expect { described_class.new(parameters: parameters).execute(exec_ctx) }.to raise_error(
+ I18n.t(
+ "discourse_workflows.errors.send_chat_message.channel_not_found",
+ channel_id: closed_channel.id,
+ ),
+ )
+ expect(closed_channel.chat_messages).to be_empty
+ ensure
+ resolver&.dispose
+ sandbox&.dispose
+ end
+
+ it "rejects direct message channels outside the selectable channel scope" do
+ dm_channel = Fabricate(:direct_message_channel)
+ parameters = { "channel_id" => dm_channel.id.to_s, "message" => "Hidden target" }
+ resolver_context = { "$json" => {} }
+ exec_ctx, resolver, sandbox =
+ build_exec_ctx(input_items: [{ "json" => {} }], parameters:, resolver_context:)
+
+ expect { described_class.new(parameters: parameters).execute(exec_ctx) }.to raise_error(
+ I18n.t(
+ "discourse_workflows.errors.send_chat_message.channel_not_found",
+ channel_id: dm_channel.id.to_s,
+ ),
+ )
+ expect(dm_channel.chat_messages).to be_empty
+ ensure
+ resolver&.dispose
+ sandbox&.dispose
+ end
+ end
+end
diff --git a/plugins/chat/spec/services/chat/workflows/approval/resume_spec.rb b/plugins/chat/spec/services/chat/workflows/approval/resume_spec.rb
new file mode 100644
index 00000000000..4c250b4e14e
--- /dev/null
+++ b/plugins/chat/spec/services/chat/workflows/approval/resume_spec.rb
@@ -0,0 +1,155 @@
+# frozen_string_literal: true
+
+RSpec.describe Chat::Workflows::Approval::Resume do
+ describe described_class::Contract, type: :model do
+ it { is_expected.to validate_presence_of(:action_id) }
+ it { is_expected.to validate_presence_of(:channel_id) }
+ end
+
+ describe ".call" do
+ subject(:result) { described_class.call(params:) }
+
+ fab!(:user)
+ fab!(:channel, :chat_channel)
+
+ let(:params) { { action_id: action_id, channel_id: channel.id } }
+ let(:execution_id) { 1 }
+ let(:resume_token) { "resume-token" }
+ let(:action_type) { "approve" }
+ let(:action_id) do
+ DiscourseWorkflows::InteractiveResume.action_id(
+ execution_id: execution_id,
+ resume_token: resume_token,
+ action: action_type,
+ )
+ end
+
+ before do
+ SiteSetting.chat_enabled = true
+ SiteSetting.discourse_workflows_enabled = true
+ end
+
+ context "when plugin is disabled" do
+ before { SiteSetting.discourse_workflows_enabled = false }
+
+ it { is_expected.to fail_a_policy(:workflows_enabled) }
+ end
+
+ context "when contract is invalid" do
+ let(:action_id) { nil }
+
+ it { is_expected.to fail_a_contract }
+ end
+
+ context "when execution does not exist" do
+ let(:execution_id) { 999_999 }
+
+ it { is_expected.to fail_to_find_a_model(:resume_request) }
+ end
+
+ context "when execution is not waiting" do
+ fab!(:execution) do
+ Fabricate(:discourse_workflows_execution, status: :success, resume_token: "abc")
+ end
+
+ let(:execution_id) { execution.id }
+ let(:resume_token) { execution.resume_token }
+
+ it { is_expected.to fail_to_find_a_model(:resume_request) }
+ end
+
+ context "when action id does not match" do
+ fab!(:execution) do
+ Fabricate(:discourse_workflows_execution, status: :waiting, resume_token: "correct-token")
+ end
+
+ let(:execution_id) { execution.id }
+ let(:action_id) do
+ DiscourseWorkflows::InteractiveResume.action_id(
+ execution_id: execution.id,
+ resume_token: "wrong-token",
+ action: "approve",
+ )
+ end
+
+ it { is_expected.to fail_to_find_a_model(:resume_request) }
+ end
+
+ context "when action type is unrecognized" do
+ let(:action_type) { "unknown" }
+
+ it { is_expected.to fail_to_find_a_model(:resume_request) }
+ end
+
+ context "when the execution cannot be claimed" do
+ fab!(:workflow) do
+ graph =
+ build_workflow_graph do |g|
+ g.node "trigger-1", "trigger:manual"
+ g.node "wait-1",
+ "action:chat_approval",
+ configuration: {
+ "message" => "Approve?",
+ "channel_id" => channel.id.to_s,
+ }
+ g.chain "trigger-1", "wait-1"
+ end
+ Fabricate(:discourse_workflows_workflow, created_by: user, **graph).tap do |wf|
+ publish_workflow!(wf)
+ end
+ end
+
+ let(:execution) { DiscourseWorkflows::Executor.new(workflow, "trigger-1", {}).run }
+ let(:execution_id) { execution.id }
+ let(:resume_token) { execution.resume_token }
+
+ before do
+ allow(::DiscourseWorkflows::Execution).to receive(:claim_for_resume).and_return(nil)
+ end
+
+ it { is_expected.to fail_to_find_a_model(:claimed_resume_request) }
+ end
+
+ context "when everything is valid" do
+ fab!(:workflow) do
+ graph =
+ build_workflow_graph do |g|
+ g.node "trigger-1", "trigger:manual", name: "Manual"
+ g.node "wait-1",
+ "action:chat_approval",
+ name: "Wait",
+ configuration: {
+ "message" => "Approve?",
+ "channel_id" => channel.id.to_s,
+ }
+ g.chain "trigger-1", "wait-1"
+ end
+ Fabricate(:discourse_workflows_workflow, created_by: user, **graph).tap do |wf|
+ publish_workflow!(wf)
+ end
+ end
+
+ let(:execution) { DiscourseWorkflows::Executor.new(workflow, "trigger-1", {}).run }
+ let(:execution_id) { execution.id }
+ let(:resume_token) { execution.resume_token }
+
+ it { is_expected.to run_successfully }
+
+ it "resumes the execution" do
+ result
+ expect(execution.reload.status).to eq("success")
+ end
+
+ context "when denied" do
+ let(:action_type) { "deny" }
+
+ it { is_expected.to run_successfully }
+
+ it "resumes the execution as denied" do
+ result
+ expect(execution.reload.status).to eq("success")
+ end
+ end
+ end
+ end
+end
diff --git a/plugins/discourse-ai/config/locales/client.en.yml b/plugins/discourse-ai/config/locales/client.en.yml
index d332547f3f5..02505d0e3b3 100644
--- a/plugins/discourse-ai/config/locales/client.en.yml
+++ b/plugins/discourse-ai/config/locales/client.en.yml
@@ -46,6 +46,13 @@ en:
update_ai_spam_settings: "Update AI spam settings"
js:
+ discourse_workflows:
+ node_unavailable:
+ requires_ai: "Requires the AI plugin to be enabled"
+ nodes:
+ "action:ai_agent": "AI Agent"
+ node_descriptions:
+ "action:ai_agent": "Run an AI agent to process data or generate content"
discourse_automation:
scriptables:
llm_report:
@@ -225,6 +232,11 @@ en:
discourse_ai:
title: "AI"
+ discourse_workflows:
+ ai_agent:
+ agent_id: "Agent"
+ prompt: "Prompt"
+ select_agent: "Select an agent..."
bot_chats:
tab_label: "Bot chats"
@@ -625,6 +637,7 @@ en:
confirm_delete: "Are you sure you want to delete this agent?"
new: "New agent"
no_agents: "You have not created any agents yet"
+ manage_agents: "Manage agents"
title: "Agents"
short_title: "Agents"
delete: "Delete"
diff --git a/plugins/discourse-ai/discourse_workflows/nodes/ai_agent/v1.rb b/plugins/discourse-ai/discourse_workflows/nodes/ai_agent/v1.rb
new file mode 100644
index 00000000000..42d75e8504d
--- /dev/null
+++ b/plugins/discourse-ai/discourse_workflows/nodes/ai_agent/v1.rb
@@ -0,0 +1,145 @@
+# frozen_string_literal: true
+
+if defined?(DiscourseWorkflows)
+ module DiscourseWorkflows
+ module Nodes
+ module AiAgent
+ class V1 < DiscourseWorkflows::NodeType
+ description(
+ name: "action:ai_agent",
+ version: "1.0",
+ defaults: {
+ icon: "robot",
+ color: "pink",
+ },
+ group: "ai",
+ available: -> { SiteSetting.discourse_ai_enabled },
+ unavailable_reason_key: "discourse_workflows.node_unavailable.requires_ai",
+ i18n_prefix: "discourse_ai.discourse_workflows",
+ capabilities: {
+ run_scope: "per_item",
+ },
+ properties: {
+ agent_id: {
+ type: :integer,
+ required: true,
+ type_options: {
+ load_options_method: "agents",
+ },
+ no_data_expression: true,
+ ui: {
+ control: :combo_box,
+ },
+ control_options: {
+ action_icon: "robot",
+ action_label: "discourse_ai.ai_agent.manage_agents",
+ action_route: "adminPlugins.show.discourse-ai-agents",
+ action_route_models: ["discourse-ai"],
+ filterable: true,
+ value_property: :id,
+ name_property: :name,
+ set_from_option: {
+ agent_name: "name",
+ },
+ },
+ },
+ agent_name: {
+ type: :string,
+ ui: {
+ hidden: true,
+ },
+ },
+ prompt: {
+ type: :string,
+ ui: {
+ control: :textarea,
+ },
+ },
+ },
+ )
+
+ def self.group_definition
+ { icon: "robot", label_key: "discourse_workflows.add_node.categories.ai", order: 40 }
+ end
+
+ def self.load_options_context(context)
+ case context.method_name
+ when "agents"
+ agent_options.select { |agent| context.matches_filter?(agent[:name]) }
+ end
+ end
+
+ def self.agent_options
+ ::AiAgent
+ .where(enabled: true)
+ .order(:name)
+ .pluck(:id, :name)
+ .map { |id, name| { id: id, name: name } }
+ end
+
+ def execute(exec_ctx)
+ items =
+ exec_ctx.input_items.map.with_index do |item, item_index|
+ config = {
+ "agent_id" => exec_ctx.get_node_parameter("agent_id", item_index),
+ "prompt" => exec_ctx.get_node_parameter("prompt", item_index),
+ }
+ result = run_agent(config, exec_ctx.log)
+
+ wrap({ "result" => result }, paired_item: exec_ctx.paired_item_for(item))
+ end
+
+ [items]
+ end
+
+ private
+
+ def run_agent(config, log)
+ agent_id = config["agent_id"]
+ prompt = config["prompt"].to_s
+
+ agent_record = ::AiAgent.find_by(id: agent_id)
+ raise_node_error!("AI Agent with id #{agent_id} not found") if agent_record.nil?
+
+ if !agent_record.enabled
+ raise_node_error!("AI Agent '#{agent_record.name}' is disabled")
+ end
+
+ log.info("Agent: #{agent_record.name}")
+ log.info("LLM: #{agent_record.default_llm_id}")
+ log.info("Prompt: #{prompt.to_s[0..200]}")
+
+ agent_instance = agent_record.class_instance.new
+ bot = DiscourseAi::Agents::Bot.as(Discourse.system_user, agent: agent_instance)
+
+ bot_context =
+ DiscourseAi::Agents::BotContext.new(
+ user: Discourse.system_user,
+ messages: [{ type: :user, content: prompt }],
+ feature_name: "workflow",
+ )
+
+ result = +""
+ tool_calls = 0
+
+ bot.reply(bot_context) do |partial, _, type|
+ if type == :tool_call
+ tool_calls += 1
+ log.info("Tool call: #{partial}") if partial.is_a?(String)
+ elsif type == :structured_output
+ result = partial.to_s
+ elsif type.blank?
+ result << partial
+ end
+ end
+
+ log.info("Tool calls: #{tool_calls}") if tool_calls > 0
+ log.info("Result length: #{result.size} chars")
+
+ result
+ end
+ end
+ end
+ end
+ end
+end
diff --git a/plugins/discourse-ai/plugin.rb b/plugins/discourse-ai/plugin.rb
index f5fff147ead..a1814909e6c 100644
--- a/plugins/discourse-ai/plugin.rb
+++ b/plugins/discourse-ai/plugin.rb
@@ -101,6 +101,13 @@ after_initialize do
require_relative "discourse_automation/llm_agent_triage"
require_relative "discourse_automation/llm_tagger"
+ if respond_to?(:register_discourse_workflows_node)
+ register_discourse_workflows_node do
+ require_relative "discourse_workflows/nodes/ai_agent/v1"
+ DiscourseWorkflows::Nodes::AiAgent::V1
+ end
+ end
+
add_admin_route("discourse_ai.title", "discourse-ai", { use_new_show_route: true })
register_seedfu_fixtures(Rails.root.join("plugins/discourse-ai/db/fixtures/agents"))
diff --git a/plugins/discourse-ai/spec/lib/discourse_workflows/nodes/ai_agent_spec.rb b/plugins/discourse-ai/spec/lib/discourse_workflows/nodes/ai_agent_spec.rb
new file mode 100644
index 00000000000..9ea0792c210
--- /dev/null
+++ b/plugins/discourse-ai/spec/lib/discourse_workflows/nodes/ai_agent_spec.rb
@@ -0,0 +1,76 @@
+# frozen_string_literal: true
+
+RSpec.describe DiscourseWorkflows::Nodes::AiAgent::V1 do
+ fab!(:agent) { Fabricate(:ai_agent, name: "Workflow agent", enabled: true) }
+
+ let(:bot) { instance_double(DiscourseAi::Agents::Bot) }
+ let(:prompts) { [] }
+
+ before do
+ SiteSetting.discourse_ai_enabled = true
+
+ allow(DiscourseAi::Agents::Bot).to receive(:as).and_return(bot)
+ allow(bot).to receive(:reply) do |bot_context, &block|
+ prompt = bot_context.messages.first[:content]
+
+ prompts << prompt
+ block.call("Reply to #{prompt}", nil, nil)
+ end
+ end
+
+ describe ".load_options_context" do
+ fab!(:disabled_agent) { Fabricate(:ai_agent, name: "Disabled agent", enabled: false) }
+ fab!(:matching_agent) { Fabricate(:ai_agent, name: "Alpha agent", enabled: true) }
+ fab!(:other_agent) { Fabricate(:ai_agent, name: "Gamma agent", enabled: true) }
+
+ def load_options(filter: nil)
+ context =
+ DiscourseWorkflows::LoadOptionsContext.new(
+ method_name: "agents",
+ filter: filter,
+ node_class: described_class,
+ )
+
+ described_class.load_options_context(context)
+ end
+
+ it "returns enabled AI agents for the chooser" do
+ option_ids = [agent.id, disabled_agent.id]
+ options = load_options.select { |option| option_ids.include?(option[:id]) }
+
+ expect(options).to contain_exactly({ id: agent.id, name: agent.name })
+ end
+
+ it "filters AI agents by the filter term" do
+ option_ids = [matching_agent.id, other_agent.id]
+ options = load_options(filter: "alpha").select { |option| option_ids.include?(option[:id]) }
+
+ expect(options).to contain_exactly({ id: matching_agent.id, name: matching_agent.name })
+ end
+ end
+
+ it "runs the agent once per input item with item-specific parameters" do
+ items =
+ execute_node_output(
+ configuration: {
+ "agent_id" => agent.id,
+ "prompt" => "={{ 'Prompt ' + $json.name }}",
+ },
+ input_items: [{ "json" => { "name" => "Ada" } }, { "json" => { "name" => "Grace" } }],
+ ).first
+
+ expect(prompts).to eq(["Prompt Ada", "Prompt Grace"])
+ expect(items.map { |item| item["json"]["result"] }).to eq(
+ ["Reply to Prompt Ada", "Reply to Prompt Grace"],
+ )
+ expect(items.map { |item| item["pairedItem"] }).to eq([{ "item" => 0 }, { "item" => 1 }])
+ expect(bot).to have_received(:reply).twice
+ end
+
+ it "uses an empty string when the optional prompt is blank" do
+ items = execute_node_output(configuration: { "agent_id" => agent.id }).first
+
+ expect(prompts).to eq([""])
+ expect(items.first["json"]["result"]).to eq("Reply to ")
+ end
+end
diff --git a/plugins/discourse-assign/config/locales/client.en.yml b/plugins/discourse-assign/config/locales/client.en.yml
index 77da61a423c..ccbd6a32223 100644
--- a/plugins/discourse-assign/config/locales/client.en.yml
+++ b/plugins/discourse-assign/config/locales/client.en.yml
@@ -197,3 +197,18 @@ en:
title: "Edit assignments"
topic: "Topic"
post: "Post"
+ discourse_workflows:
+ node_unavailable:
+ requires_assign: "Requires the Assign plugin to be enabled"
+ nodes:
+ "action:assign_topic": "Assign topic"
+ node_descriptions:
+ "action:assign_topic": "Assign or unassign a topic"
+ assign_topic:
+ operation: "Operation"
+ operations:
+ assign: "Assign"
+ unassign: "Unassign"
+ topic_id: "Topic ID"
+ assignee: "Assignee"
+ replace_existing: "Replace existing assignment"
diff --git a/plugins/discourse-assign/config/locales/server.en.yml b/plugins/discourse-assign/config/locales/server.en.yml
index 5239a8bb9a0..2602865948a 100644
--- a/plugins/discourse-assign/config/locales/server.en.yml
+++ b/plugins/discourse-assign/config/locales/server.en.yml
@@ -56,6 +56,9 @@ en:
weekly: "weekly"
monthly: "monthly"
quarterly: "quarterly"
+ discourse_workflows:
+ assign_topic:
+ error: "Failed to assign topic: %{reason}"
assign_mailer:
title: "Assign Mailer"
subject_template: "[%{email_prefix}] %{assignee_name} assigned you to '%{topic_title}'!"
diff --git a/plugins/discourse-assign/lib/discourse_workflows/nodes/assign_topic/v1.rb b/plugins/discourse-assign/lib/discourse_workflows/nodes/assign_topic/v1.rb
new file mode 100644
index 00000000000..108f4710468
--- /dev/null
+++ b/plugins/discourse-assign/lib/discourse_workflows/nodes/assign_topic/v1.rb
@@ -0,0 +1,143 @@
+# frozen_string_literal: true
+
+if defined?(DiscourseWorkflows)
+ module DiscourseWorkflows
+ module Nodes
+ module AssignTopic
+ class V1 < DiscourseWorkflows::NodeType
+ OPERATIONS = %w[assign unassign].freeze
+
+ description(
+ name: "action:assign_topic",
+ version: "1.0",
+ defaults: {
+ icon: "user-plus",
+ color: "cyan",
+ },
+ available: -> { SiteSetting.assign_enabled },
+ unavailable_reason_key: "discourse_workflows.node_unavailable.requires_assign",
+ capabilities: {
+ run_scope: "per_item",
+ },
+ properties: {
+ operation: {
+ type: :options,
+ required: true,
+ options: OPERATIONS,
+ default: "assign",
+ ui: {
+ expression: true,
+ },
+ },
+ topic_id: {
+ type: :string,
+ required: true,
+ },
+ assignee: {
+ type: :string,
+ required: true,
+ display_options: {
+ show: {
+ operation: ["assign"],
+ },
+ },
+ ui: {
+ control: :user_or_group,
+ },
+ },
+ replace_existing: {
+ type: :boolean,
+ default: true,
+ display_options: {
+ show: {
+ operation: ["assign"],
+ },
+ },
+ },
+ },
+ )
+
+ def execute(exec_ctx)
+ actor = exec_ctx.user || Discourse.system_user
+ items =
+ exec_ctx.input_items.map.with_index do |_item, item_index|
+ config = {
+ "operation" =>
+ exec_ctx.get_node_parameter("operation", item_index, default: "assign"),
+ "topic_id" => exec_ctx.get_node_parameter("topic_id", item_index),
+ "assignee" => exec_ctx.get_node_parameter("assignee", item_index),
+ "replace_existing" =>
+ exec_ctx.get_node_parameter("replace_existing", item_index, default: true),
+ }
+ result = process(actor, config)
+ wrap(result)
+ end
+ [items]
+ end
+
+ private
+
+ def process(actor, config)
+ topic = ::Topic.find(config["topic_id"])
+ assigner = ::Assigner.new(topic, actor)
+ previously_assigned = topic.assignment&.assigned_to
+
+ case config["operation"]
+ when "unassign"
+ assigner.unassign
+
+ { previously_assigned: assignee_data(previously_assigned, actor.guardian) }
+ else
+ assignee = find_assignee(config["assignee"])
+ if config["replace_existing"] != false && topic.assignment
+ assigner.unassign
+ topic.association(:assignment).reset
+ end
+
+ result = assigner.assign(assignee)
+
+ unless result[:success]
+ raise_node_error!(
+ I18n.t(
+ "discourse_assign.discourse_workflows.assign_topic.error",
+ reason: result[:reason],
+ ),
+ )
+ end
+
+ {
+ assignee: assignee_data(assignee, actor.guardian),
+ previously_assigned: assignee_data(previously_assigned, actor.guardian),
+ }
+ end
+ end
+
+ def find_assignee(identifier)
+ ::User.find_by(username: identifier) || ::Group.find_by!(name: identifier)
+ end
+
+ def assignee_data(assignee, guardian)
+ case assignee
+ when ::User
+ {
+ type: "user",
+ user: serialize_record(assignee, BasicUserSerializer, scope: guardian),
+ group: {
+ },
+ }
+ when ::Group
+ {
+ type: "group",
+ user: {
+ },
+ group: serialize_record(assignee, BasicGroupSerializer, scope: guardian),
+ }
+ else
+ { type: nil, user: {}, group: {} }
+ end
+ end
+ end
+ end
+ end
+ end
+end
diff --git a/plugins/discourse-assign/plugin.rb b/plugins/discourse-assign/plugin.rb
index 60609011fd4..c070e1cfe14 100644
--- a/plugins/discourse-assign/plugin.rb
+++ b/plugins/discourse-assign/plugin.rb
@@ -22,6 +22,12 @@ require_relative "lib/discourse_assign/engine"
require_relative "lib/validators/assign_statuses_validator"
after_initialize do
+ if respond_to?(:register_discourse_workflows_node)
+ register_discourse_workflows_node do
+ require_relative "lib/discourse_workflows/nodes/assign_topic/v1"
+ DiscourseWorkflows::Nodes::AssignTopic::V1
+ end
+ end
UserUpdater::OPTION_ATTR.push(:notification_level_when_assigned)
reloadable_patch do |plugin|
diff --git a/plugins/discourse-assign/spec/lib/discourse_workflows/nodes/assign_topic/v1_spec.rb b/plugins/discourse-assign/spec/lib/discourse_workflows/nodes/assign_topic/v1_spec.rb
new file mode 100644
index 00000000000..784cf7e2c76
--- /dev/null
+++ b/plugins/discourse-assign/spec/lib/discourse_workflows/nodes/assign_topic/v1_spec.rb
@@ -0,0 +1,198 @@
+# frozen_string_literal: true
+
+RSpec.describe DiscourseWorkflows::Nodes::AssignTopic::V1 do
+ fab!(:post)
+ fab!(:topic) { post.topic }
+ fab!(:user, :moderator)
+ fab!(:group)
+
+ let(:assign_allowed_group) { Group.find_by(name: "staff") }
+ let(:sandbox) { DiscourseWorkflows::JsSandbox.new({ "$json" => {} }) }
+ after { sandbox.dispose }
+
+ before do
+ SiteSetting.discourse_workflows_enabled = true
+ SiteSetting.assign_enabled = true
+ end
+
+ def execute_node(configuration:, item:, run_as_user: Discourse.system_user)
+ action = described_class.new(parameters: configuration)
+ input_items = [item]
+ resolver =
+ DiscourseWorkflows::ExpressionResolver.new(
+ { "$json" => item.fetch("json") { {} } },
+ sandbox: sandbox,
+ )
+ exec_ctx =
+ DiscourseWorkflows::Executor::NodeExecutionContext.new(
+ input_items: input_items,
+ user: run_as_user,
+ resolver: resolver,
+ parameters: configuration,
+ property_schema: described_class.property_schema,
+ node_context: {
+ },
+ )
+ items = action.execute(exec_ctx)[0]
+ items.first["json"]
+ end
+
+ describe "#execute" do
+ let(:item) { { "json" => {} } }
+
+ context "with assign operation" do
+ it "assigns the topic to a user" do
+ config = {
+ "operation" => "assign",
+ "topic_id" => topic.id.to_s,
+ "assignee" => user.username,
+ }
+
+ result = execute_node(configuration: config, item: item)
+
+ expect(result["assignee"]["type"]).to eq("user")
+ expect(result["assignee"]["user"]["id"]).to eq(user.id)
+ expect(result["assignee"]["user"]["username"]).to eq(user.username)
+ expect(Assignment.exists?(target: topic, assigned_to: user)).to eq(true)
+ end
+
+ it "assigns the topic to a group" do
+ SiteSetting.assign_allowed_on_groups = "#{assign_allowed_group.id}|#{group.id}"
+ group.update!(assignable_level: Group::ALIAS_LEVELS[:everyone])
+
+ config = { "operation" => "assign", "topic_id" => topic.id.to_s, "assignee" => group.name }
+
+ result = execute_node(configuration: config, item: item)
+
+ expect(result["assignee"]["type"]).to eq("group")
+ expect(result["assignee"]["group"]["id"]).to eq(group.id)
+ expect(result["assignee"]["group"]["name"]).to eq(group.name)
+ expect(Assignment.exists?(target: topic, assigned_to: group)).to eq(true)
+ end
+
+ it "raises when assignee does not exist" do
+ config = {
+ "operation" => "assign",
+ "topic_id" => topic.id.to_s,
+ "assignee" => "nonexistent",
+ }
+
+ expect { execute_node(configuration: config, item: item) }.to raise_error(
+ ActiveRecord::RecordNotFound,
+ )
+ end
+
+ context "when topic is already assigned" do
+ fab!(:other_user, :moderator)
+
+ before { ::Assigner.new(topic, Discourse.system_user).assign(other_user) }
+
+ it "replaces the existing assignment by default" do
+ config = {
+ "operation" => "assign",
+ "topic_id" => topic.id.to_s,
+ "assignee" => user.username,
+ }
+
+ result = execute_node(configuration: config, item: item)
+
+ expect(result["assignee"]["user"]["username"]).to eq(user.username)
+ expect(result["previously_assigned"]["type"]).to eq("user")
+ expect(result["previously_assigned"]["user"]["username"]).to eq(other_user.username)
+ expect(Assignment.find_by(target: topic).assigned_to).to eq(user)
+ end
+
+ it "replaces the existing assignment when replace_existing is true" do
+ config = {
+ "operation" => "assign",
+ "topic_id" => topic.id.to_s,
+ "assignee" => user.username,
+ "replace_existing" => true,
+ }
+
+ result = execute_node(configuration: config, item: item)
+
+ expect(result["assignee"]["user"]["username"]).to eq(user.username)
+ expect(Assignment.find_by(target: topic).assigned_to).to eq(user)
+ end
+
+ it "replaces the existing assignment when assigning the same user" do
+ ::Assigner.new(topic, Discourse.system_user).assign(user)
+
+ config = {
+ "operation" => "assign",
+ "topic_id" => topic.id.to_s,
+ "assignee" => user.username,
+ "replace_existing" => true,
+ }
+
+ result = execute_node(configuration: config, item: item)
+
+ expect(result["assignee"]["user"]["username"]).to eq(user.username)
+ expect(Assignment.find_by(target: topic).assigned_to).to eq(user)
+ end
+
+ it "raises when replace_existing is false and same user is assigned" do
+ config = {
+ "operation" => "assign",
+ "topic_id" => topic.id.to_s,
+ "assignee" => other_user.username,
+ "replace_existing" => false,
+ }
+
+ expect { execute_node(configuration: config, item: item) }.to raise_error(
+ DiscourseWorkflows::NodeError,
+ )
+ end
+ end
+
+ it "uses run_as_user for the assigner" do
+ run_as = Fabricate(:moderator)
+
+ config = {
+ "operation" => "assign",
+ "topic_id" => topic.id.to_s,
+ "assignee" => user.username,
+ }
+
+ execute_node(configuration: config, item: item, run_as_user: run_as)
+
+ expect(topic.assignment.assigned_by_user_id).to eq(run_as.id)
+ end
+
+ it "uses system when the workflow has no current user" do
+ config = {
+ "operation" => "assign",
+ "topic_id" => topic.id.to_s,
+ "assignee" => user.username,
+ }
+
+ execute_node(configuration: config, item: item, run_as_user: nil)
+
+ expect(topic.assignment.assigned_by_user_id).to eq(Discourse.system_user.id)
+ end
+ end
+
+ context "with unassign operation" do
+ before { ::Assigner.new(topic, Discourse.system_user).assign(user) }
+
+ it "unassigns the topic" do
+ config = { "operation" => "unassign", "topic_id" => topic.id.to_s }
+
+ result = execute_node(configuration: config, item: item)
+
+ expect(result["previously_assigned"]["type"]).to eq("user")
+ expect(result["previously_assigned"]["user"]["username"]).to eq(user.username)
+ expect(Assignment.exists?(target: topic)).to eq(false)
+ end
+
+ it "is idempotent when topic is not assigned" do
+ ::Assigner.new(topic, Discourse.system_user).unassign
+
+ config = { "operation" => "unassign", "topic_id" => topic.id.to_s }
+
+ expect { execute_node(configuration: config, item: item) }.not_to raise_error
+ end
+ end
+ end
+end
diff --git a/plugins/discourse-data-explorer/config/locales/client.en.yml b/plugins/discourse-data-explorer/config/locales/client.en.yml
index eda51b303be..6eccb7b8120 100644
--- a/plugins/discourse-data-explorer/config/locales/client.en.yml
+++ b/plugins/discourse-data-explorer/config/locales/client.en.yml
@@ -156,6 +156,32 @@ en:
descriptions:
data_explorer:
run_queries: "Run Data Explorer queries. Restrict the API key to a set of queries by specifying queries IDs."
+ discourse_workflows:
+ node_unavailable:
+ requires_data_explorer: "Requires the Data Explorer plugin to be enabled"
+ nodes:
+ "action:sql": "Data Explorer"
+ node_descriptions:
+ "action:sql": "Run a read-only SQL query against the database"
+ sql:
+ operation: "Operation"
+ operation_description: "How to run the query"
+ queries: "Queries"
+ raw: "Raw SQL"
+ query_id: "Query"
+ query_id_description: "Select a saved query to run"
+ query_params: "Query parameters"
+ query_params_description: "Fill in the parameters for the selected query"
+ query: "SQL query"
+ query_description: "Write a read-only SQL query. Declare parameters with Data Explorer syntax and map their values below."
+ params: "Query parameters"
+ params_description: "Parameters can be used as :my_param in the SQL query."
+ add_param: "Add parameter"
+ param_name: "Param"
+ param_value: "Value"
+ output:
+ results: "Results"
+ no_results: "No results"
discourse_automation:
scriptables:
recurring_data_explorer_result_pm:
diff --git a/plugins/discourse-data-explorer/config/locales/server.en.yml b/plugins/discourse-data-explorer/config/locales/server.en.yml
index 7591f452563..800f76f39b8 100644
--- a/plugins/discourse-data-explorer/config/locales/server.en.yml
+++ b/plugins/discourse-data-explorer/config/locales/server.en.yml
@@ -20,6 +20,10 @@ en:
error_no_sql_returned: "AI did not return a valid SQL query. Please try again or write the query manually."
errors:
tool_not_allowed: "You are not allowed to use this tool"
+ discourse_workflows:
+ sql_action:
+ no_query_selected: "No query selected."
+ no_sql_provided: "No SQL query provided."
discourse_automation:
scriptables:
recurring_data_explorer_result_pm:
diff --git a/plugins/discourse-data-explorer/lib/discourse_data_explorer/workflows/sql_action/v1.rb b/plugins/discourse-data-explorer/lib/discourse_data_explorer/workflows/sql_action/v1.rb
new file mode 100644
index 00000000000..764ed4bc519
--- /dev/null
+++ b/plugins/discourse-data-explorer/lib/discourse_data_explorer/workflows/sql_action/v1.rb
@@ -0,0 +1,235 @@
+# frozen_string_literal: true
+
+module DiscourseDataExplorer
+ module Workflows
+ module SqlAction
+ class V1 < DiscourseWorkflows::NodeType
+ OPERATIONS = %w[queries raw].freeze
+
+ description(
+ name: "action:sql",
+ version: "1.0",
+ defaults: {
+ icon: "database",
+ color: "purple",
+ },
+ available: -> { SiteSetting.data_explorer_enabled },
+ unavailable_reason_key: "discourse_workflows.node_unavailable.requires_data_explorer",
+ outputs: [
+ { key: "main", label_key: "discourse_workflows.sql.output.results" },
+ { key: "empty", label_key: "discourse_workflows.sql.output.no_results" },
+ ],
+ capabilities: {
+ run_scope: "all_items",
+ },
+ properties: {
+ operation: {
+ type: :options,
+ required: true,
+ options: OPERATIONS,
+ default: "queries",
+ },
+ query_id: {
+ type: :integer,
+ required: true,
+ type_options: {
+ load_options_method: "queries",
+ },
+ display_options: {
+ show: {
+ operation: ["queries"],
+ },
+ },
+ ui: {
+ control: :combo_box,
+ dynamic_value: :query_id,
+ },
+ control_options: {
+ value_property: "id",
+ name_property: "name",
+ filterable: true,
+ resets: %w[query_params],
+ },
+ },
+ query_params: {
+ type: :object,
+ required: false,
+ display_options: {
+ show: {
+ operation: ["queries"],
+ },
+ },
+ ui: {
+ control: :query_params,
+ },
+ },
+ params: {
+ type: :fixed_collection,
+ required: false,
+ display_options: {
+ show: {
+ operation: ["raw"],
+ },
+ },
+ type_options: {
+ multiple_values: true,
+ },
+ options: [
+ {
+ name: "values",
+ values: {
+ name: {
+ type: :string,
+ required: true,
+ },
+ value: {
+ type: :string,
+ required: true,
+ },
+ },
+ },
+ ],
+ },
+ query: {
+ type: :string,
+ required: true,
+ display_options: {
+ show: {
+ operation: ["raw"],
+ },
+ },
+ no_data_expression: true,
+ ui: {
+ control: :code,
+ },
+ control_options: {
+ height: 200,
+ lang: :sql,
+ },
+ },
+ },
+ )
+
+ def self.load_options_context(context)
+ case context.method_name
+ when "queries"
+ queries.select { |query| context.matches_filter?(query[:name]) }
+ end
+ end
+
+ def self.queries
+ persisted = DiscourseDataExplorer::Query.where(hidden: false).order(:name).to_a
+
+ persisted_ids = persisted.map(&:id).to_set
+
+ unpersisted_defaults =
+ DiscourseDataExplorer::Queries.default.filter_map do |_, attributes|
+ next if persisted_ids.include?(attributes[:id])
+ DiscourseDataExplorer::Query.new(
+ id: attributes[:id],
+ name: attributes[:name],
+ sql: attributes[:sql],
+ ) { |q| q.user_id = Discourse::SYSTEM_USER_ID }
+ end
+
+ (persisted + unpersisted_defaults)
+ .sort_by(&:name)
+ .map do |q|
+ { id: q.id, name: q.name, params: q.params.reject(&:internal?).map(&:to_hash) }
+ end
+ end
+
+ def execute(exec_ctx)
+ config = {
+ "operation" => exec_ctx.get_node_parameter("operation", 0, default: "queries"),
+ "query_id" => exec_ctx.get_node_parameter("query_id", 0),
+ "query_params" => exec_ctx.get_node_parameter("query_params", 0, default: {}),
+ "query" => exec_ctx.get_node_parameter("query", 0),
+ }
+ operation = config.fetch("operation") { "queries" }
+
+ if operation == "queries"
+ execute_saved_query(config)
+ else
+ execute_raw_sql(config, exec_ctx)
+ end
+ end
+
+ private
+
+ def execute_saved_query(config)
+ query_id = config["query_id"]
+ if query_id.blank?
+ raise_node_error!(
+ I18n.t("discourse_data_explorer.discourse_workflows.sql_action.no_query_selected"),
+ )
+ end
+
+ query = DiscourseDataExplorer::Query.find(query_id)
+ raw_params = config.fetch("query_params") { {} }
+
+ result =
+ DiscourseDataExplorer::DataExplorer.run_query(
+ query,
+ raw_params,
+ { limit: SiteSetting.data_explorer_query_result_limit },
+ )
+
+ raise_node_error!(result[:error].message) if result[:error]
+
+ rows_to_items(result[:pg_result])
+ end
+
+ def execute_raw_sql(config, exec_ctx)
+ sql = config["query"].to_s
+ if sql.blank?
+ raise_node_error!(
+ I18n.t("discourse_data_explorer.discourse_workflows.sql_action.no_sql_provided"),
+ )
+ end
+
+ req_params = {}
+ exec_ctx
+ .get_node_parameter("params.values", 0, default: [])
+ .each do |param|
+ req_params[param["name"].to_sym] = param["value"] if param["name"].present?
+ end
+
+ if req_params.present?
+ sql =
+ MiniSql::InlineParamEncoder.new(ActiveRecord::Base.connection.raw_connection).encode(
+ sql,
+ req_params,
+ )
+ end
+
+ query = DiscourseDataExplorer::Query.new(name: "workflow", sql: sql)
+ result =
+ DiscourseDataExplorer::DataExplorer.run_query(
+ query,
+ {},
+ { limit: SiteSetting.data_explorer_query_result_limit },
+ )
+
+ raise_node_error!(result[:error].message) if result[:error]
+
+ rows_to_items(result[:pg_result])
+ end
+
+ def rows_to_items(pg_result)
+ columns = pg_result.fields
+ rows =
+ pg_result.values.map do |row|
+ json = {}
+ columns.each_with_index { |col, i| json[col] = row[i] }
+ { "json" => json }
+ end
+
+ return [], [{ "json" => {} }] if rows.empty?
+
+ [rows, []]
+ end
+ end
+ end
+ end
+end
diff --git a/plugins/discourse-data-explorer/plugin.rb b/plugins/discourse-data-explorer/plugin.rb
index 2256272351c..8e72fb4b334 100644
--- a/plugins/discourse-data-explorer/plugin.rb
+++ b/plugins/discourse-data-explorer/plugin.rb
@@ -41,6 +41,14 @@ after_initialize do
# - block
GlobalSetting.add_default(:max_data_explorer_api_req_mode, "warn")
+ if respond_to?(:register_discourse_workflows_node)
+ register_svg_icon "database"
+ register_discourse_workflows_node do
+ require_relative "lib/discourse_data_explorer/workflows/sql_action/v1"
+ DiscourseDataExplorer::Workflows::SqlAction::V1
+ end
+ end
+
add_to_class(:guardian, :user_is_a_member_of_group?) do |group|
return false if !current_user
return true if current_user.admin?
diff --git a/plugins/discourse-data-explorer/spec/lib/data_explorer/workflows/sql_action/v1_spec.rb b/plugins/discourse-data-explorer/spec/lib/data_explorer/workflows/sql_action/v1_spec.rb
new file mode 100644
index 00000000000..712c49dd65c
--- /dev/null
+++ b/plugins/discourse-data-explorer/spec/lib/data_explorer/workflows/sql_action/v1_spec.rb
@@ -0,0 +1,245 @@
+# frozen_string_literal: true
+
+RSpec.describe DiscourseDataExplorer::Workflows::SqlAction::V1 do
+ fab!(:user)
+
+ describe "#execute" do
+ context "with raw operation" do
+ it "substitutes named params into the query" do
+ result =
+ execute_node(
+ configuration: {
+ "operation" => "raw",
+ "query" => "SELECT username FROM users WHERE id = :user_id",
+ "params" => {
+ "values" => [{ "name" => "user_id", "value" => user.id.to_s }],
+ },
+ },
+ )
+
+ expect(result["username"]).to eq(user.username)
+ end
+
+ it "resolves named params against the current input item" do
+ result =
+ execute_node(
+ configuration: {
+ "operation" => "raw",
+ "query" => "SELECT username FROM users WHERE id = :user_id",
+ "params" => {
+ "values" => [{ "name" => "user_id", "value" => "={{ $json.user_id }}" }],
+ },
+ },
+ item: {
+ "json" => {
+ "user_id" => user.id,
+ },
+ },
+ )
+
+ expect(result["username"]).to eq(user.username)
+ end
+
+ it "raises when no query is provided" do
+ expect {
+ execute_node(configuration: { "operation" => "raw", "query" => "" })
+ }.to raise_error(DiscourseWorkflows::NodeError, "No SQL query provided.")
+ end
+
+ it "emits on the empty port when the query returns no rows" do
+ result =
+ execute_node_output(
+ configuration: {
+ "operation" => "raw",
+ "query" => "SELECT username FROM users WHERE 1=0",
+ },
+ )
+
+ rows, empty = result
+ expect(rows).to be_empty
+ expect(empty.size).to eq(1)
+ expect(empty.first).to eq({ "json" => {} })
+ end
+
+ it "emits on the main port when the query returns rows" do
+ result =
+ execute_node_output(
+ configuration: {
+ "operation" => "raw",
+ "query" => "SELECT username FROM users WHERE id = :user_id",
+ "params" => {
+ "values" => [{ "name" => "user_id", "value" => user.id.to_s }],
+ },
+ },
+ )
+
+ rows, empty = result
+ expect(empty).to be_empty
+ expect(rows.size).to eq(1)
+ expect(rows.first["json"]["username"]).to eq(user.username)
+ end
+ end
+
+ context "with queries operation" do
+ fab!(:data_explorer_query) do
+ DiscourseDataExplorer::Query.create!(
+ name: "User lookup",
+ sql: "-- [params]\n-- int :user_id\nSELECT username FROM users WHERE id = :user_id",
+ user_id: Discourse::SYSTEM_USER_ID,
+ )
+ end
+
+ it "runs a saved query with parameters" do
+ result =
+ execute_node(
+ configuration: {
+ "operation" => "queries",
+ "query_id" => data_explorer_query.id,
+ "query_params" => {
+ "user_id" => user.id.to_s,
+ },
+ },
+ )
+
+ expect(result["username"]).to eq(user.username)
+ end
+
+ it "runs a saved query without parameters" do
+ no_params_query =
+ DiscourseDataExplorer::Query.create!(
+ name: "All users",
+ sql: "SELECT username FROM users ORDER BY id LIMIT 1",
+ user_id: Discourse::SYSTEM_USER_ID,
+ )
+
+ result =
+ execute_node(
+ configuration: {
+ "operation" => "queries",
+ "query_id" => no_params_query.id,
+ },
+ )
+
+ expect(result["username"]).to be_present
+ end
+
+ it "raises when query_id is missing" do
+ expect { execute_node(configuration: { "operation" => "queries" }) }.to raise_error(
+ DiscourseWorkflows::NodeError,
+ "No query selected.",
+ )
+ end
+ end
+ end
+
+ describe ".property_schema" do
+ it "includes operation field" do
+ schema = described_class.property_schema
+ expect(schema[:operation][:type]).to eq(:options)
+ expect(schema[:operation][:options]).to eq(%w[queries raw])
+ expect(schema[:operation][:default]).to eq("queries")
+ end
+
+ it "includes query_id visible only for queries operation" do
+ schema = described_class.property_schema
+ expect(schema[:query_id][:display_options]).to eq(show: { operation: ["queries"] })
+ end
+
+ it "includes query visible only for raw operation" do
+ schema = described_class.property_schema
+ expect(schema[:query][:display_options]).to eq(show: { operation: ["raw"] })
+ end
+ end
+
+ describe ".outputs" do
+ it "declares main and empty output ports" do
+ keys = described_class.outputs.map { |port| port[:key].to_s }
+ expect(keys).to eq(%w[main empty])
+ end
+ end
+
+ describe ".load_options_context" do
+ it "returns non-hidden query options" do
+ query =
+ DiscourseDataExplorer::Query.create!(
+ name: "Visible query",
+ sql: "SELECT 1",
+ user_id: Discourse::SYSTEM_USER_ID,
+ )
+ hidden_query =
+ DiscourseDataExplorer::Query.create!(
+ name: "Hidden query",
+ sql: "SELECT 1",
+ user_id: Discourse::SYSTEM_USER_ID,
+ hidden: true,
+ )
+ context =
+ DiscourseWorkflows::LoadOptionsContext.new(
+ method_name: "queries",
+ node_class: described_class,
+ )
+
+ options = described_class.load_options_context(context)
+ query_ids = options.map { |option| option[:id] }
+
+ expect(query_ids).to include(query.id)
+ expect(query_ids).not_to include(hidden_query.id)
+ end
+
+ it "filters query options by the filter term" do
+ matching_query =
+ DiscourseDataExplorer::Query.create!(
+ name: "Needle query",
+ sql: "SELECT 1",
+ user_id: Discourse::SYSTEM_USER_ID,
+ )
+ other_query =
+ DiscourseDataExplorer::Query.create!(
+ name: "Haystack query",
+ sql: "SELECT 1",
+ user_id: Discourse::SYSTEM_USER_ID,
+ )
+ context =
+ DiscourseWorkflows::LoadOptionsContext.new(
+ method_name: "queries",
+ filter: "needle",
+ node_class: described_class,
+ )
+
+ options = described_class.load_options_context(context)
+ query_ids = options.map { |option| option[:id] }
+
+ expect(query_ids).to include(matching_query.id)
+ expect(query_ids).not_to include(other_query.id)
+ end
+ end
+
+ describe ".queries" do
+ it "includes non-hidden queries with their params" do
+ query =
+ DiscourseDataExplorer::Query.create!(
+ name: "Test query",
+ sql: "-- [params]\n-- int :user_id\nSELECT 1",
+ user_id: Discourse::SYSTEM_USER_ID,
+ )
+ hidden_query =
+ DiscourseDataExplorer::Query.create!(
+ name: "Hidden",
+ sql: "SELECT 1",
+ user_id: Discourse::SYSTEM_USER_ID,
+ hidden: true,
+ )
+
+ queries = described_class.queries
+ query_ids = queries.map { |q| q[:id] }
+
+ expect(query_ids).to include(query.id)
+ expect(query_ids).not_to include(hidden_query.id)
+
+ entry = queries.find { |q| q[:id] == query.id }
+ expect(entry[:name]).to eq("Test query")
+ expect(entry[:params].first[:identifier]).to eq("user_id")
+ expect(entry[:params].first[:type]).to eq(:int)
+ end
+ end
+end
diff --git a/plugins/discourse-workflows/admin/assets/javascripts/admin/adapters/discourse-workflows-workflow.js b/plugins/discourse-workflows/admin/assets/javascripts/admin/adapters/discourse-workflows-workflow.js
new file mode 100644
index 00000000000..e4595e7cd11
--- /dev/null
+++ b/plugins/discourse-workflows/admin/assets/javascripts/admin/adapters/discourse-workflows-workflow.js
@@ -0,0 +1,17 @@
+import RestAdapter from "discourse/adapters/rest";
+
+export default class DiscourseWorkflowsWorkflowAdapter extends RestAdapter {
+ jsonMode = true;
+
+ basePath() {
+ return "/admin/plugins/discourse-workflows/";
+ }
+
+ pathFor(store, type, findArgs) {
+ return super.pathFor(store, type, findArgs) + ".json";
+ }
+
+ apiNameFor() {
+ return "workflow";
+ }
+}
diff --git a/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/admin-table.gjs b/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/admin-table.gjs
new file mode 100644
index 00000000000..c9c45bdabad
--- /dev/null
+++ b/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/admin-table.gjs
@@ -0,0 +1,160 @@
+import Component from "@glimmer/component";
+import { tracked } from "@glimmer/tracking";
+import { fn, hash } from "@ember/helper";
+import { on } from "@ember/modifier";
+import { action } from "@ember/object";
+import { modifier } from "ember-modifier";
+import { eq } from "discourse/truth-helpers";
+import DConditionalLoadingSpinner from "discourse/ui-kit/d-conditional-loading-spinner";
+import DLoadMore from "discourse/ui-kit/d-load-more";
+import dConcatClass from "discourse/ui-kit/helpers/d-concat-class";
+
+const indeterminate = modifier((element, [value]) => {
+ element.indeterminate = value;
+});
+
+export default class AdminTable extends Component {
+ @tracked selectedIds = new Set();
+
+ lastClickedRowIndex = null;
+
+ get hasSelection() {
+ return this.selectedIds.size > 0;
+ }
+
+ get allSelected() {
+ return (
+ this.args.items?.length > 0 &&
+ this.selectedIds.size === this.args.items.length
+ );
+ }
+
+ get headerCheckboxState() {
+ if (this.selectedIds.size === 0) {
+ return "none";
+ }
+ if (this.selectedIds.size === this.args.items?.length) {
+ return "all";
+ }
+ return "indeterminate";
+ }
+
+ @action
+ itemId(item) {
+ return item[this.args.itemKey ?? "id"];
+ }
+
+ @action
+ isRowSelected(item) {
+ return this.selectedIds.has(this.itemId(item));
+ }
+
+ @action
+ toggleRowSelection(item, event) {
+ const id = this.itemId(item);
+ const items = this.args.items;
+ const currentIndex = items.findIndex((i) => this.itemId(i) === id);
+ const next = new Set(this.selectedIds);
+
+ if (event?.shiftKey && this.lastClickedRowIndex !== null) {
+ const from = Math.min(this.lastClickedRowIndex, currentIndex);
+ const to = Math.max(this.lastClickedRowIndex, currentIndex);
+ for (let i = from; i <= to; i++) {
+ next.add(this.itemId(items[i]));
+ }
+ } else if (next.has(id)) {
+ next.delete(id);
+ } else {
+ next.add(id);
+ }
+
+ this.lastClickedRowIndex = currentIndex;
+ this.selectedIds = next;
+ }
+
+ @action
+ clearSelection() {
+ this.selectedIds = new Set();
+ this.lastClickedRowIndex = null;
+ }
+
+ @action
+ toggleAllSelection() {
+ if (this.allSelected) {
+ this.selectedIds = new Set();
+ } else {
+ this.selectedIds = new Set(this.args.items.map((i) => this.itemId(i)));
+ }
+ }
+
+ <template>
+ <div class="workflows-admin-table" ...attributes>
+ <DConditionalLoadingSpinner @condition={{@isLoading}}>
+ {{#if @items.length}}
+ {{#if (has-block "toolbar")}}
+ <div class="workflows-admin-table__toolbar">
+ {{yield
+ (hash
+ hasSelection=this.hasSelection
+ selectedIds=this.selectedIds
+ clearSelection=this.clearSelection
+ )
+ to="toolbar"
+ }}
+ </div>
+ {{/if}}
+
+ <DLoadMore @action={{@loadMore}} @enabled={{@canLoadMore}}>
+ <table class="d-table workflows-admin-table__table">
+ <thead class="d-table__header">
+ <tr class="d-table__row">
+ {{#if @selectable}}
+ <th
+ class="d-table__header-cell workflows-admin-table__checkbox-cell"
+ >
+ <input
+ type="checkbox"
+ checked={{this.allSelected}}
+ {{indeterminate
+ (eq this.headerCheckboxState "indeterminate")
+ }}
+ {{on "change" this.toggleAllSelection}}
+ class="workflows-admin-table__checkbox"
+ />
+ </th>
+ {{/if}}
+ {{yield to="head"}}
+ </tr>
+ </thead>
+ <tbody>
+ {{#each @items as |item|}}
+ <tr
+ class={{dConcatClass "d-table__row" @rowClass}}
+ data-item-id={{this.itemId item}}
+ >
+ {{#if @selectable}}
+ <td
+ class="d-table__cell workflows-admin-table__checkbox-cell"
+ >
+ <input
+ type="checkbox"
+ checked={{this.isRowSelected item}}
+ {{on "click" (fn this.toggleRowSelection item)}}
+ class="workflows-admin-table__checkbox"
+ />
+ </td>
+ {{/if}}
+ {{yield item to="row"}}
+ </tr>
+ {{/each}}
+ </tbody>
+ </table>
+ <DConditionalLoadingSpinner @condition={{@loadingMore}} />
+ </DLoadMore>
+ {{else}}
+ {{yield to="empty"}}
+ {{/if}}
+ </DConditionalLoadingSpinner>
+ </div>
+ </template>
+}
diff --git a/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/canvas/canvas-context-menu.gjs b/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/canvas/canvas-context-menu.gjs
new file mode 100644
index 00000000000..2944d6e3b70
--- /dev/null
+++ b/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/canvas/canvas-context-menu.gjs
@@ -0,0 +1,134 @@
+import Component from "@glimmer/component";
+import { tracked } from "@glimmer/tracking";
+import { action } from "@ember/object";
+import { trustHTML } from "@ember/template";
+import DButton from "discourse/ui-kit/d-button";
+import { i18n } from "discourse-i18n";
+
+export default class CanvasContextMenu extends Component {
+ @tracked contextMenu = null;
+
+ constructor() {
+ super(...arguments);
+ this.args.onRegister?.(this);
+ }
+
+ get style() {
+ if (!this.contextMenu || !this.args.canvasElement) {
+ return "";
+ }
+ const rect = this.args.canvasElement.getBoundingClientRect();
+ const left = this.contextMenu.screenX - rect.left;
+ const top = this.contextMenu.screenY - rect.top;
+ return trustHTML(`left: ${left}px; top: ${top}px`);
+ }
+
+ @action
+ open(event) {
+ event.preventDefault();
+ this.contextMenu = null;
+
+ if (!this.args.rete) {
+ return;
+ }
+
+ const nodeEl = event.target.closest(".workflow-rete-node");
+ if (nodeEl) {
+ const clientId = nodeEl.dataset.clientId;
+ if (clientId && !this.args.rete.getSelectedIds().nodeIds.has(clientId)) {
+ this.args.rete.selectableNodes.select(clientId, false);
+ }
+ this.contextMenu = {
+ nodeId: clientId,
+ isUnavailable: nodeEl.dataset.unavailable === "true",
+ screenX: event.clientX,
+ screenY: event.clientY,
+ };
+ return;
+ }
+
+ const rect = this.args.containerElement.getBoundingClientRect();
+ const canvasPos = this.args.rete.containerToCanvas(
+ event.clientX - rect.left,
+ event.clientY - rect.top
+ );
+ this.contextMenu = {
+ isCanvas: true,
+ canvasPos,
+ screenX: event.clientX,
+ screenY: event.clientY,
+ };
+ }
+
+ @action
+ close() {
+ this.contextMenu = null;
+ }
+
+ @action
+ editNode() {
+ const nodeId = this.contextMenu.nodeId;
+ this.contextMenu = null;
+ this.args.onEditNode?.(nodeId);
+ }
+
+ @action
+ deleteNode() {
+ this.contextMenu = null;
+ this.args.onDeleteSelected?.();
+ }
+
+ @action
+ addNode() {
+ const canvasPos = this.contextMenu?.canvasPos;
+ this.contextMenu = null;
+ if (canvasPos) {
+ this.args.onOpenNodePanel?.(canvasPos);
+ }
+ }
+
+ @action
+ addStickyNote() {
+ const canvasPos = this.contextMenu?.canvasPos;
+ this.contextMenu = null;
+ if (canvasPos) {
+ this.args.onAddStickyNote?.(canvasPos);
+ }
+ }
+
+ <template>
+ {{#if this.contextMenu}}
+ <div class="workflows-canvas__context-menu" style={{this.style}}>
+ {{#if this.contextMenu.isCanvas}}
+ <DButton
+ @action={{this.addNode}}
+ @icon="plus"
+ @translatedLabel={{i18n "discourse_workflows.canvas.add_step"}}
+ class="btn-transparent workflows-canvas__context-menu-item"
+ />
+ <DButton
+ @action={{this.addStickyNote}}
+ @icon="note-sticky"
+ @translatedLabel={{i18n "discourse_workflows.sticky_note.add"}}
+ class="btn-transparent workflows-canvas__context-menu-item"
+ />
+ {{else}}
+ {{#unless this.contextMenu.isUnavailable}}
+ <DButton
+ @action={{this.editNode}}
+ @icon="pencil"
+ @translatedLabel={{i18n "discourse_workflows.edit"}}
+ class="btn-transparent workflows-canvas__context-menu-item"
+ />
+ {{/unless}}
+ <DButton
+ @action={{this.deleteNode}}
+ @icon="trash-can"
+ @translatedLabel={{i18n "discourse_workflows.delete"}}
+ class="btn-transparent btn-danger workflows-canvas__context-menu-item"
+ />
+ {{/if}}
+ </div>
+ {{/if}}
+ </template>
+}
diff --git a/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/canvas/canvas-file-io.js b/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/canvas/canvas-file-io.js
new file mode 100644
index 00000000000..ddb933b6b38
--- /dev/null
+++ b/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/canvas/canvas-file-io.js
@@ -0,0 +1,193 @@
+import { isStaticDataMap } from "../../../lib/workflows/static-data";
+import StickyNote, { STICKY_NOTE_TYPE } from "../../../models/sticky-note";
+import {
+ deserializeConnections,
+ serializeConnections,
+} from "../../../models/workflow-connection";
+import WorkflowNode, {
+ NODE_DIRECT_SETTING_KEYS,
+} from "../../../models/workflow-node";
+
+function sanitizeImportedObject(value) {
+ if (!value || typeof value !== "object" || Array.isArray(value)) {
+ return {};
+ }
+
+ const sanitized = structuredClone(value);
+ delete sanitized.credentials;
+ return sanitized;
+}
+
+function cloneObject(value) {
+ if (!value || typeof value !== "object" || Array.isArray(value)) {
+ return {};
+ }
+
+ return structuredClone(value);
+}
+
+function importedStaticData(data) {
+ if (!Object.hasOwn(data, "staticData")) {
+ return undefined;
+ }
+
+ const staticData = data.staticData;
+ if (!isStaticDataMap(staticData)) {
+ return { error: "invalid" };
+ }
+
+ return structuredClone(staticData);
+}
+
+function directSettingsFromImportedNode(node) {
+ const settings = {};
+
+ for (const key of NODE_DIRECT_SETTING_KEYS) {
+ if (Object.hasOwn(node, key)) {
+ settings[key] = structuredClone(node[key]);
+ }
+ }
+
+ return settings;
+}
+
+function hasUnsupportedNodeKey(node) {
+ if (!node || typeof node !== "object") {
+ return false;
+ }
+
+ return ["type_version", "webhook_id", "position_index", "settings"].some(
+ (key) => Object.hasOwn(node, key)
+ );
+}
+
+export function buildWorkflowExportPayload(
+ nodes,
+ connections,
+ stickyNotes,
+ workflow = {}
+) {
+ const workflowMetadata = workflow || {};
+ const exportedNodes = (nodes || []).map(WorkflowNode.serialize);
+
+ const exportedStickyNotes = (stickyNotes || []).map(StickyNote.serialize);
+
+ const allNodes = [...exportedNodes, ...exportedStickyNotes];
+
+ return {
+ id: workflowMetadata.id?.toString() || null,
+ name: workflowMetadata.name || null,
+ nodes: allNodes,
+ connections: serializeConnections(connections || [], [
+ ...(nodes || []),
+ ...(stickyNotes || []),
+ ]),
+ settings: cloneObject(workflowMetadata.settings),
+ staticData: cloneObject(workflowMetadata.staticData),
+ pinData: cloneObject(workflowMetadata.pinData),
+ versionId: workflowMetadata.versionId || null,
+ activeVersionId: workflowMetadata.activeVersionId || null,
+ versionCounter: workflowMetadata.versionCounter || null,
+ };
+}
+
+export function exportWorkflowToFile(
+ nodes,
+ connections,
+ stickyNotes,
+ workflow
+) {
+ const payload = buildWorkflowExportPayload(
+ nodes,
+ connections,
+ stickyNotes,
+ workflow
+ );
+ const data = JSON.stringify(payload, null, 2);
+ const date = new Date().toISOString().slice(0, 10);
+ const file = new File([data], `workflow-nodes-${date}.json`, {
+ type: "application/json",
+ });
+
+ const url = URL.createObjectURL(file);
+ const a = document.createElement("a");
+ a.href = url;
+ a.download = file.name;
+ a.click();
+ URL.revokeObjectURL(url);
+}
+
+export function parseWorkflowImport(text) {
+ const data = JSON.parse(text);
+
+ if (!data || typeof data !== "object" || Array.isArray(data)) {
+ return { error: "invalid" };
+ }
+
+ if (
+ data.version ||
+ data.sticky_notes ||
+ Array.isArray(data.connections) ||
+ data.nodes?.some(hasUnsupportedNodeKey)
+ ) {
+ return { error: "invalid" };
+ }
+
+ if (!Array.isArray(data.nodes) || data.nodes.length === 0) {
+ return { error: "invalid" };
+ }
+
+ const staticData = importedStaticData(data);
+ if (staticData?.error) {
+ return staticData;
+ }
+
+ const allImportedNodes = data.nodes.map((n) =>
+ WorkflowNode.create({
+ clientId: crypto.randomUUID(),
+ type: n.type,
+ typeVersion: n.typeVersion,
+ name: n.name,
+ parameters: sanitizeImportedObject(n.parameters),
+ credentials: {},
+ webhookId: n.webhookId || null,
+ position: n.position || null,
+ ...directSettingsFromImportedNode(n),
+ })
+ );
+
+ const regularNodes = allImportedNodes.filter(
+ (n) => n.type !== STICKY_NOTE_TYPE
+ );
+
+ const newStickyNotes = allImportedNodes
+ .filter((n) => n.type === STICKY_NOTE_TYPE)
+ .map((n) =>
+ StickyNote.create({
+ position: n.position,
+ size: {
+ width: n.parameters?.width,
+ height: n.parameters?.height,
+ },
+ color: n.parameters?.color,
+ text: n.parameters?.content,
+ })
+ );
+
+ const newConnections = deserializeConnections(data.connections || {}, [
+ ...regularNodes,
+ ...newStickyNotes,
+ ]);
+
+ const result = {
+ nodes: regularNodes,
+ connections: newConnections,
+ stickyNotes: newStickyNotes,
+ };
+
+ if (staticData !== undefined) {
+ result.staticData = staticData;
+ }
+
+ return result;
+}
diff --git a/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/canvas/canvas-keyboard.js b/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/canvas/canvas-keyboard.js
new file mode 100644
index 00000000000..e6180966c81
--- /dev/null
+++ b/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/canvas/canvas-keyboard.js
@@ -0,0 +1,67 @@
+const PAUSED_SHORTCUTS = ["-", "="];
+
+function isInputElement(target) {
+ return target.tagName === "INPUT" || target.tagName === "TEXTAREA";
+}
+
+export function setupCanvasKeyboard(
+ keyboardShortcutsService,
+ actions,
+ canvasElement
+) {
+ keyboardShortcutsService.pause(PAUSED_SHORTCUTS);
+
+ const bindings = {
+ "meta::z": (e) => {
+ e.preventDefault();
+ actions.onUndo?.();
+ },
+ "meta:shift:z": (e) => {
+ e.preventDefault();
+ actions.onRedo?.();
+ },
+ "meta::y": (e) => {
+ e.preventDefault();
+ actions.onRedo?.();
+ },
+ "meta::c": () => actions.onCopy?.(),
+ "meta::v": () => actions.onPaste?.(),
+ "::delete": () => actions.onDelete?.(),
+ "::backspace": () => actions.onDelete?.(),
+ "::escape": () => actions.onEscape?.(),
+ "::+": () => actions.onZoomIn?.(),
+ "::=": () => actions.onZoomIn?.(),
+ "::-": () => actions.onZoomOut?.(),
+ "::Digit1": () => actions.onFitToView?.(),
+ "::Digit2": () => actions.onAutoLayout?.(),
+ };
+
+ const handler = (event) => {
+ if (event.repeat) {
+ return;
+ }
+ if (isInputElement(event.target)) {
+ return;
+ }
+ const meta = event.metaKey || event.ctrlKey ? "meta" : "";
+ const shift = event.shiftKey ? "shift" : "";
+ const key = event.key.toLowerCase();
+ const binding =
+ bindings[`${meta}:${shift}:${key}`] ??
+ bindings[`${meta}:${shift}:${event.code}`];
+ binding?.(event);
+ };
+
+ canvasElement.addEventListener("keydown", handler);
+
+ return {
+ teardown() {
+ canvasElement.removeEventListener("keydown", handler);
+ try {
+ keyboardShortcutsService.unpause(PAUSED_SHORTCUTS);
+ } catch {
+ // keyboard shortcuts may not be fully initialized
+ }
+ },
+ };
+}
diff --git a/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/canvas/canvas-manual-trigger.js b/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/canvas/canvas-manual-trigger.js
new file mode 100644
index 00000000000..c5bbb210898
--- /dev/null
+++ b/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/canvas/canvas-manual-trigger.js
@@ -0,0 +1,94 @@
+import { ajax } from "discourse/lib/ajax";
+import { popupAjaxError } from "discourse/lib/ajax-error";
+import { getAbsoluteURL } from "discourse/lib/get-url";
+import { clipboardCopy } from "discourse/lib/utilities";
+import { i18n } from "discourse-i18n";
+
+async function createFormTestSession(workflowId, triggerNodeId) {
+ return await ajax(
+ `/admin/plugins/discourse-workflows/workflows/${workflowId}/form-test-sessions.json`,
+ {
+ type: "POST",
+ data: { trigger_node_id: triggerNodeId },
+ }
+ );
+}
+
+export async function runManualTrigger({
+ node,
+ clientId,
+ workflowId,
+ toasts,
+ router,
+ session,
+}) {
+ if (node?.type === "trigger:form") {
+ const result = await createFormTestSession(workflowId, clientId);
+ window.open(getAbsoluteURL(result.test_url), "_blank");
+ return;
+ }
+
+ if (node?.type === "trigger:webhook" && node.configuration?.path) {
+ const listener = await session.startWebhookTestListener(clientId);
+ const testUrl = getAbsoluteURL(listener.testUrl);
+ toasts.success({
+ data: {
+ message: i18n("discourse_workflows.manual_trigger.listening"),
+ actions: [
+ {
+ label: i18n("discourse_workflows.webhook.copy_test_url"),
+ class: "btn-primary btn-small",
+ action: async ({ close }) => {
+ await clipboardCopy(testUrl);
+ close();
+ },
+ },
+ ],
+ },
+ });
+ return;
+ }
+
+ let result;
+ try {
+ result = await ajax(`/admin/plugins/discourse-workflows/executions.json`, {
+ type: "POST",
+ data: { workflow_id: workflowId, trigger_node_id: clientId },
+ });
+ } catch (error) {
+ // Service refuses to run when the trigger has no pinned sample data and no
+ // synthesised manual payload (e.g. event-based triggers like post_created).
+ if (error?.jqXHR?.status === 422) {
+ toasts.error({
+ data: {
+ message: i18n("discourse_workflows.manual_trigger.needs_pin_data"),
+ },
+ });
+ return;
+ }
+ popupAjaxError(error);
+ return;
+ }
+
+ const { workflow_id, id } = result.execution;
+
+ toasts.success({
+ data: {
+ message: i18n("discourse_workflows.manual_trigger.triggered"),
+ actions: [
+ {
+ label: i18n("discourse_workflows.manual_trigger.view_execution"),
+ class: "btn-primary btn-small",
+ action: ({ close }) => {
+ close();
+ router.transitionTo(
+ "adminPlugins.show.discourse-workflows.show.executions.show",
+ workflow_id,
+ id
+ );
+ },
+ },
+ ],
+ },
+ });
+}
diff --git a/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/canvas/canvas-sticky-notes.js b/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/canvas/canvas-sticky-notes.js
new file mode 100644
index 00000000000..27963a1dbaf
--- /dev/null
+++ b/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/canvas/canvas-sticky-notes.js
@@ -0,0 +1,20 @@
+export function computeStickyNoteRects(stickyNotes) {
+ return (stickyNotes || []).map((n) => ({
+ x: n.position.x,
+ y: n.position.y,
+ width: n.size.width,
+ height: n.size.height,
+ }));
+}
+
+export function buildStickyNoteTranslateHandler(stickyNotes, onMove) {
+ return (id, dx, dy) => {
+ const note = (stickyNotes || []).find((n) => n.clientId === id);
+ if (note) {
+ onMove?.(id, {
+ x: note.position.x + dx,
+ y: note.position.y + dy,
+ });
+ }
+ };
+}
diff --git a/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/canvas/connection-entry.gjs b/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/canvas/connection-entry.gjs
new file mode 100644
index 00000000000..dc95ec31469
--- /dev/null
+++ b/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/canvas/connection-entry.gjs
@@ -0,0 +1,60 @@
+import { fn } from "@ember/helper";
+import { trustHTML } from "@ember/template";
+import dConcatClass from "discourse/ui-kit/helpers/d-concat-class";
+import ConnectionToolbar from "./connection-toolbar";
+
+const SVG_STYLE = trustHTML(
+ "overflow:visible;position:absolute;pointer-events:none;width:9999px;height:9999px"
+);
+
+<template>
+ <svg
+ class={{dConcatClass "workflow-connection" (if @entry.isPseudo "--pseudo")}}
+ style={{SVG_STYLE}}
+ >
+ <path
+ class="workflow-connection__hit"
+ fill="none"
+ stroke="transparent"
+ stroke-width="12"
+ pointer-events="stroke"
+ style="cursor:pointer"
+ d={{@entry.pathD}}
+ />
+ <path
+ class="workflow-connection__visible"
+ fill="none"
+ stroke={{if @entry.isPseudo "var(--tertiary)" "var(--primary-low-mid)"}}
+ stroke-width="1.5"
+ stroke-dasharray={{if @entry.isPseudo "6 3" ""}}
+ opacity={{if @entry.isPseudo "0.6" ""}}
+ d={{@entry.pathD}}
+ />
+ <path
+ class="workflow-connection__arrow"
+ d="M -9 -5 L 0 0 L -9 5 Z"
+ fill={{if @entry.isPseudo "var(--tertiary)" "var(--primary-low-mid)"}}
+ stroke={{if @entry.isPseudo "var(--tertiary)" "var(--primary-low-mid)"}}
+ stroke-width="2"
+ stroke-linejoin="round"
+ transform={{@entry.arrowTransform}}
+ />
+ {{#unless @entry.isPseudo}}
+ <foreignObject
+ class="workflow-connection__toolbar-fo"
+ width="48"
+ height="22"
+ x={{@entry.toolbarX}}
+ y={{@entry.toolbarY}}
+ >
+ <ConnectionToolbar
+ @hitPathSelector=".workflow-connection__hit"
+ @foreignObjectSelector=".workflow-connection__toolbar-fo"
+ @svgElement={{@entry.element}}
+ @onAdd={{fn @onAdd @entry.connectionInfo}}
+ @onDelete={{fn @onDelete @entry.connectionInfo}}
+ />
+ </foreignObject>
+ {{/unless}}
+ </svg>
+</template>
diff --git a/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/canvas/connection-toolbar.gjs b/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/canvas/connection-toolbar.gjs
new file mode 100644
index 00000000000..c1a786b05a8
--- /dev/null
+++ b/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/canvas/connection-toolbar.gjs
@@ -0,0 +1,48 @@
+import { fn } from "@ember/helper";
+import { on } from "@ember/modifier";
+import DTooltip from "discourse/float-kit/components/d-tooltip";
+import dIcon from "discourse/ui-kit/helpers/d-icon";
+import { i18n } from "discourse-i18n";
+import CanvasHoverToolbar from "./hover-toolbar";
+
+function stopAndCall(callback, e) {
+ e.stopPropagation();
+ callback?.();
+}
+
+<template>
+ <CanvasHoverToolbar
+ @hoverQuery=".workflow-connection__hit"
+ @visibilityQuery=".workflow-connection__toolbar-fo"
+ @inline={{true}}
+ >
+ <DTooltip
+ @identifier="workflow-connection-add-step"
+ @content={{i18n "discourse_workflows.canvas.add_step"}}
+ >
+ <:trigger>
+ <button
+ type="button"
+ class="workflow-canvas-toolbar__btn"
+ {{on "click" (fn stopAndCall @onAdd)}}
+ >
+ {{dIcon "plus"}}
+ </button>
+ </:trigger>
+ </DTooltip>
+ <DTooltip
+ @identifier="workflow-connection-remove"
+ @content={{i18n "discourse_workflows.canvas.remove_connection"}}
+ >
+ <:trigger>
+ <button
+ type="button"
+ class="workflow-canvas-toolbar__btn"
+ {{on "click" (fn stopAndCall @onDelete)}}
+ >
+ {{dIcon "trash-can"}}
+ </button>
+ </:trigger>
+ </DTooltip>
+ </CanvasHoverToolbar>
+</template>
diff --git a/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/canvas/controls.gjs b/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/canvas/controls.gjs
new file mode 100644
index 00000000000..034c1568665
--- /dev/null
+++ b/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/canvas/controls.gjs
@@ -0,0 +1,86 @@
+import DTooltip from "discourse/float-kit/components/d-tooltip";
+import { translateModKey } from "discourse/lib/utilities";
+import { not } from "discourse/truth-helpers";
+import DButton from "discourse/ui-kit/d-button";
+import { i18n } from "discourse-i18n";
+
+function undoTitle() {
+ return `${i18n("discourse_workflows.canvas.undo")} [${translateModKey("Meta+Z")}]`;
+}
+
+function redoTitle() {
+ return `${i18n("discourse_workflows.canvas.redo")} [${translateModKey("Meta+Y")}]`;
+}
+
+<template>
+ <div class="workflows-canvas__controls">
+ <DTooltip @identifier="workflow-canvas-undo" @content={{(undoTitle)}}>
+ <:trigger>
+ <DButton
+ @action={{@onUndo}}
+ @icon="arrow-rotate-left"
+ @disabled={{not @canUndo}}
+ class="btn-flat btn-small"
+ />
+ </:trigger>
+ </DTooltip>
+ <DTooltip @identifier="workflow-canvas-redo" @content={{(redoTitle)}}>
+ <:trigger>
+ <DButton
+ @action={{@onRedo}}
+ @icon="arrow-rotate-right"
+ @disabled={{not @canRedo}}
+ class="btn-flat btn-small"
+ />
+ </:trigger>
+ </DTooltip>
+ <DTooltip
+ @identifier="workflow-canvas-zoom-out"
+ @content={{i18n "discourse_workflows.canvas.zoom_out"}}
+ >
+ <:trigger>
+ <DButton
+ @action={{@onZoomOut}}
+ @icon="magnifying-glass-minus"
+ class="btn-flat btn-small"
+ />
+ </:trigger>
+ </DTooltip>
+ <DTooltip
+ @identifier="workflow-canvas-zoom-in"
+ @content={{i18n "discourse_workflows.canvas.zoom_in"}}
+ >
+ <:trigger>
+ <DButton
+ @action={{@onZoomIn}}
+ @icon="magnifying-glass-plus"
+ class="btn-flat btn-small"
+ />
+ </:trigger>
+ </DTooltip>
+ <DTooltip
+ @identifier="workflow-canvas-zoom-to-fit"
+ @content={{i18n "discourse_workflows.canvas.zoom_to_fit"}}
+ >
+ <:trigger>
+ <DButton
+ @action={{@onFitToView}}
+ @icon="expand"
+ class="btn-flat btn-small"
+ />
+ </:trigger>
+ </DTooltip>
+ <DTooltip
+ @identifier="workflow-canvas-auto-layout"
+ @content={{i18n "discourse_workflows.canvas.auto_layout"}}
+ >
+ <:trigger>
+ <DButton
+ @action={{@onAutoLayout}}
+ @icon="broom"
+ class="btn-flat btn-small"
+ />
+ </:trigger>
+ </DTooltip>
+ </div>
+</template>
diff --git a/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/canvas/custom-renderer.js b/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/canvas/custom-renderer.js
new file mode 100644
index 00000000000..32b814a562f
--- /dev/null
+++ b/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/canvas/custom-renderer.js
@@ -0,0 +1,469 @@
+import { trackedMap } from "@ember/reactive/collections";
+import {
+ buildWorkflowGraphIndex,
+ getConnectionKind,
+ normalizeSourceOutput,
+} from "../../../lib/workflows/graph-constants";
+import { updateInputHandles, updateOutputHandles } from "./handles";
+import { loopBackLayout, loopBodyPath } from "./rete-path-utils";
+
+function resolveCurve(classicPath, kind) {
+ if (kind === "loopBody") {
+ return (start, end) => loopBodyPath(start, end, "right");
+ }
+ if (kind === "loopReturn") {
+ return (start, end) => loopBodyPath(start, end, "left");
+ }
+ return (start, end) => classicPath([start, end], 0.4);
+}
+
+export function createCustomRenderer(Scope, getElementCenter, classicPath) {
+ return class CustomRenderer extends Scope {
+ nodeEntries = trackedMap();
+
+ connectionEntries = trackedMap();
+
+ outputHandleEntries = trackedMap();
+
+ inputHandleEntries = trackedMap();
+
+ onSocketRendered = (nodeId, side, key, socketOrOutputs, element) => {
+ const socket =
+ side === "input" ? socketOrOutputs : socketOrOutputs[key]?.socket;
+
+ if (!socket) {
+ return;
+ }
+
+ this.#updateSocketPulseState(element, { side, key });
+
+ this.parentScope().emit({
+ type: "render",
+ data: { element, type: "socket", nodeId, side, key, socket },
+ });
+ };
+
+ constructor() {
+ super("workflow-renderer");
+ this.connectionElements = new Map();
+ this.connectionUpdateFrame = null;
+ this.graphIndex = buildWorkflowGraphIndex([], []);
+ this.hasSeenRealConnection = false;
+
+ this.measureSvg = document.createElementNS(
+ "http://www.w3.org/2000/svg",
+ "svg"
+ );
+ this.measurePath = document.createElementNS(
+ "http://www.w3.org/2000/svg",
+ "path"
+ );
+ this.measureSvg.appendChild(this.measurePath);
+ this.measureSvg.style.cssText =
+ "position:absolute;width:0;height:0;overflow:hidden;pointer-events:none";
+ document.body.appendChild(this.measureSvg);
+
+ this.addPipe(async (context) => {
+ switch (context.type) {
+ case "render":
+ return await this.#handleRender(context);
+ case "unmount": {
+ const { element } = context.data;
+ for (const [id, entry] of this.nodeEntries) {
+ if (entry.element === element) {
+ this.nodeEntries.delete(id);
+ for (const handleKey of this.outputHandleEntries.keys()) {
+ if (handleKey.startsWith(id + ":")) {
+ this.outputHandleEntries.delete(handleKey);
+ }
+ }
+ this.inputHandleEntries.delete(id);
+ break;
+ }
+ }
+ for (const [id, entry] of this.connectionElements) {
+ if (entry.element === element) {
+ this.connectionElements.delete(id);
+ this.connectionEntries.delete(id);
+ break;
+ }
+ }
+ break;
+ }
+ case "nodetranslated":
+ this.scheduleConnectionUpdate(context.data.id);
+ break;
+ }
+
+ return context;
+ });
+ }
+
+ get nodeEntryList() {
+ return [...this.nodeEntries.values()];
+ }
+
+ get connectionEntryList() {
+ return [...this.connectionEntries.values()];
+ }
+
+ get outputHandleEntryList() {
+ return [...this.outputHandleEntries.values()];
+ }
+
+ get inputHandleEntryList() {
+ return [...this.inputHandleEntries.values()];
+ }
+
+ async #handleRender(context) {
+ if (context.data.filled) {
+ return context;
+ }
+
+ const { data } = context;
+ switch (data.type) {
+ case "node":
+ data.element.classList.add("workflow-rete-node-view");
+ this.nodeEntries.set(data.payload.id, {
+ element: data.element,
+ node: data.payload,
+ });
+ break;
+ case "connection":
+ data.element.style.zIndex = "0";
+ await this.renderConnection(data);
+ break;
+ case "socket":
+ break;
+ default:
+ return context;
+ }
+
+ return { ...context, data: { ...data, filled: true } };
+ }
+
+ scheduleConnectionUpdate(nodeId) {
+ if (nodeId) {
+ this.dirtyNodeIds ??= new Set();
+ this.dirtyNodeIds.add(nodeId);
+ } else {
+ this.dirtyNodeIds = null;
+ }
+
+ if (!this.connectionUpdateFrame) {
+ this.connectionUpdateFrame = requestAnimationFrame(async () => {
+ this.connectionUpdateFrame = null;
+ const dirtyNodes = this.dirtyNodeIds;
+ this.dirtyNodeIds = null;
+ await this.updateConnections(dirtyNodes);
+ });
+ }
+ }
+
+ cancelScheduledConnectionUpdate() {
+ if (this.connectionUpdateFrame) {
+ cancelAnimationFrame(this.connectionUpdateFrame);
+ this.connectionUpdateFrame = null;
+ }
+ }
+
+ #ensureConnectionElement(id) {
+ let entry = this.connectionElements.get(id);
+ if (!entry) {
+ entry = {};
+ this.connectionElements.set(id, entry);
+ }
+ return entry;
+ }
+
+ #createConnectionEntry(element, payload, isPseudo, isLoopBack) {
+ return {
+ element,
+ isPseudo,
+ isLoopBack,
+ loopNodeClientId: isLoopBack ? payload.source : null,
+ connectionInfo:
+ isPseudo || isLoopBack
+ ? null
+ : {
+ sourceClientId: payload.source,
+ targetClientId: payload.target,
+ sourceOutput: payload.sourceOutput,
+ targetInput: payload.targetInput,
+ },
+ pathD: "",
+ arrowTransform: "",
+ toolbarX: 0,
+ toolbarY: 0,
+ loopArrowPoints: "",
+ loopButtonX: 0,
+ loopButtonY: 0,
+ };
+ }
+
+ async renderConnection(data) {
+ const { element, payload } = data;
+ const isPseudo = payload.isPseudo;
+ const isLoopBack =
+ !isPseudo &&
+ payload.source === payload.target &&
+ payload.sourceOutput === "loop";
+
+ if (!this.connectionEntries.has(payload.id)) {
+ this.connectionEntries.set(
+ payload.id,
+ this.#createConnectionEntry(element, payload, isPseudo, isLoopBack)
+ );
+ }
+
+ const entry = this.#ensureConnectionElement(payload.id);
+ entry.element = element;
+ entry.payload = payload;
+ entry.isLoopBack = isLoopBack;
+
+ if (isLoopBack) {
+ await this.#updateLoopBackEntry(payload);
+ } else {
+ const d = await this.computeConnectionPath(payload, {
+ explicitStart: data.start,
+ explicitEnd: data.end,
+ });
+ if (d) {
+ this.#applyPathToEntry(payload.id, d);
+ }
+ }
+ }
+
+ computeArrowLayout(pathD) {
+ this.measurePath.setAttribute("d", pathD);
+ const len = this.measurePath.getTotalLength();
+
+ const socketRadius = 9;
+ const arrowLen = 10;
+ const tip = this.measurePath.getPointAtLength(len - socketRadius);
+ const base = this.measurePath.getPointAtLength(
+ len - socketRadius - arrowLen
+ );
+ const angle =
+ Math.atan2(tip.y - base.y, tip.x - base.x) * (180 / Math.PI);
+
+ const mid = this.measurePath.getPointAtLength(len / 2);
+
+ return {
+ arrowTransform: `translate(${tip.x}, ${tip.y}) rotate(${angle})`,
+ toolbarX: mid.x - 24,
+ toolbarY: mid.y - 11,
+ };
+ }
+
+ destroyMeasureSvg() {
+ this.measureSvg?.remove();
+ }
+
+ #updateConnectionEntry(id, updates) {
+ const tracked = this.connectionEntries.get(id);
+ if (tracked) {
+ this.connectionEntries.set(id, { ...tracked, ...updates });
+ }
+ }
+
+ #applyPathToEntry(connectionId, pathD) {
+ this.#updateConnectionEntry(connectionId, {
+ pathD,
+ ...this.computeArrowLayout(pathD),
+ });
+ }
+
+ #hasRealConnections() {
+ return [...this.connectionElements.values()].some(
+ (entry) => entry.payload && !entry.payload.isPseudo
+ );
+ }
+
+ #shouldPulseSockets() {
+ const hasRealConnections = this.#hasRealConnections();
+ this.hasSeenRealConnection ||= hasRealConnections;
+ return !hasRealConnections && !this.hasSeenRealConnection;
+ }
+
+ #updateSocketPulseState(socketElement, { side, key } = {}) {
+ const isConnectableSocket = side !== "output" || key !== "loop";
+ socketElement.classList.toggle(
+ "is-connectable-hint",
+ isConnectableSocket && this.#shouldPulseSockets()
+ );
+ }
+
+ #updateAllSocketPulseStates() {
+ const shouldPulse = this.#shouldPulseSockets();
+
+ for (const { element } of this.nodeEntries.values()) {
+ for (const socketElement of element.querySelectorAll(
+ ".workflow-rete-node__socket"
+ )) {
+ socketElement.classList.toggle(
+ "is-connectable-hint",
+ shouldPulse && !socketElement.classList.contains("--loop")
+ );
+ }
+ }
+ }
+
+ async #updateLoopBackEntry(payload) {
+ const [startPos, endPos] = await Promise.all([
+ this.getSocketCanvasPos(payload.source, "output", "loop"),
+ this.getSocketCanvasPos(payload.source, "input", "main"),
+ ]);
+
+ if (!startPos || !endPos) {
+ return;
+ }
+
+ const layout = loopBackLayout(startPos, endPos);
+ this.#updateConnectionEntry(payload.id, {
+ pathD: layout.d,
+ loopArrowPoints: layout.arrowPoints,
+ loopButtonX: layout.buttonPosition.x,
+ loopButtonY: layout.buttonPosition.y,
+ });
+ }
+
+ async computeConnectionPath(payload, { explicitStart, explicitEnd } = {}) {
+ if (explicitStart || explicitEnd) {
+ const [startPos, endPos] = await Promise.all([
+ explicitStart ??
+ this.getSocketCanvasPos(
+ payload.source,
+ "output",
+ normalizeSourceOutput(payload.sourceOutput)
+ ),
+ explicitEnd ??
+ this.getSocketCanvasPos(
+ payload.target,
+ "input",
+ payload.targetInput || "main"
+ ),
+ ]);
+ return startPos && endPos ? classicPath([startPos, endPos], 0.4) : null;
+ }
+
+ const { startPos, endPos, kind } =
+ await this.getConnectionEndpoints(payload);
+ if (!startPos || !endPos) {
+ return null;
+ }
+ return resolveCurve(classicPath, kind)(startPos, endPos);
+ }
+
+ async getConnectionEndpoints(payload) {
+ const kind = getConnectionKind(this.graphIndex, payload);
+ const srcOutput = normalizeSourceOutput(payload.sourceOutput);
+ const isLoopSrc = kind === "loopChain" || kind === "loopReturn";
+ const isLoopTgt = kind === "loopBody" || kind === "loopChain";
+ const tgtKey =
+ kind === "loopBody"
+ ? "main"
+ : isLoopTgt
+ ? srcOutput
+ : payload.targetInput || "main";
+
+ const [startPos, endPos] = await Promise.all([
+ this.getSocketCanvasPos(
+ payload.source,
+ isLoopSrc ? "input" : "output",
+ isLoopSrc ? "main" : srcOutput
+ ),
+ this.getSocketCanvasPos(
+ payload.target,
+ isLoopTgt ? "output" : "input",
+ tgtKey
+ ),
+ ]);
+
+ return { startPos, endPos, kind };
+ }
+
+ async getSocketCanvasPos(nodeId, side, key) {
+ const area = this.parentScope();
+ const nodeView = area.nodeViews.get(nodeId);
+ if (!nodeView) {
+ return null;
+ }
+
+ const nodeEl = nodeView.element.querySelector(".workflow-rete-node");
+ if (!nodeEl) {
+ return null;
+ }
+
+ const selector =
+ side === "input"
+ ? `.workflow-rete-node__socket.--input[data-socket-key="${CSS.escape(key)}"]`
+ : `.workflow-rete-node__socket.--output[data-socket-key="${CSS.escape(key)}"]`;
+ const socketEl = nodeEl.querySelector(selector);
+ if (!socketEl) {
+ return null;
+ }
+
+ const pos = nodeView.position;
+ const center = await getElementCenter(socketEl, nodeView.element);
+
+ let finalX = pos.x + center.x;
+ if (side === "output" && key !== "loop") {
+ const pill = socketEl.parentElement?.querySelector(
+ ".workflow-rete-node__port-pill"
+ );
+ if (pill) {
+ finalX += pill.offsetWidth + 12;
+ }
+ }
+
+ return { x: finalX, y: pos.y + center.y };
+ }
+
+ async updateConnections(dirtyNodeIds) {
+ for (const [, entry] of this.connectionElements) {
+ if (entry.payload.isPseudo) {
+ continue;
+ }
+
+ if (
+ dirtyNodeIds &&
+ !dirtyNodeIds.has(entry.payload.source) &&
+ !dirtyNodeIds.has(entry.payload.target)
+ ) {
+ continue;
+ }
+
+ if (entry.isLoopBack) {
+ await this.#updateLoopBackEntry(entry.payload);
+ continue;
+ }
+
+ const d = await this.computeConnectionPath(entry.payload);
+ if (d) {
+ this.#applyPathToEntry(entry.payload.id, d);
+ }
+ }
+
+ await updateOutputHandles(
+ this.outputHandleEntries,
+ this.nodeEntries,
+ this.connectionElements,
+ (nodeId, side, key) => this.getSocketCanvasPos(nodeId, side, key),
+ dirtyNodeIds
+ );
+
+ await updateInputHandles(
+ this.inputHandleEntries,
+ this.nodeEntries,
+ this.connectionElements,
+ (nodeId, side, key) => this.getSocketCanvasPos(nodeId, side, key),
+ dirtyNodeIds,
+ this.graphIndex,
+ this.parentScope().area.content.holder
+ );
+
+ this.#updateAllSocketPulseStates();
+ }
+ };
+}
diff --git a/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/canvas/handles.js b/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/canvas/handles.js
new file mode 100644
index 00000000000..b3794655999
--- /dev/null
+++ b/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/canvas/handles.js
@@ -0,0 +1,192 @@
+import {
+ buildConnectedOutputsIndex,
+ normalizeTargetInput,
+} from "../../../lib/workflows/graph-constants";
+
+const HANDLE_LENGTH = 30;
+const HANDLE_TOTAL = HANDLE_LENGTH + 14;
+const SOCKET_RADIUS = 5;
+
+function buildHandleEntry(
+ nodeEntry,
+ nodeId,
+ startPos,
+ toRight,
+ outputKey,
+ inputKey,
+ areaElement
+) {
+ // SVG positioned at button's canvas location so foreignObject x is always positive (outside viewport = no pointer events).
+ // Paths start at socket edge (not center) to avoid drawing inside the socket circle.
+ if (toRight) {
+ return {
+ areaElement,
+ nodeClientId: nodeId,
+ outputKey,
+ inputKey,
+ svgLeft: startPos.x,
+ svgTop: startPos.y - 7,
+ pathD: `M ${SOCKET_RADIUS} 7 L ${HANDLE_LENGTH} 7`,
+ buttonX: HANDLE_LENGTH,
+ buttonY: 0,
+ };
+ } else {
+ return {
+ areaElement,
+ nodeClientId: nodeId,
+ outputKey,
+ inputKey,
+ svgLeft: startPos.x - HANDLE_TOTAL,
+ svgTop: startPos.y - 7,
+ pathD: `M ${HANDLE_TOTAL - SOCKET_RADIUS} 7 L 14 7`,
+ buttonX: 0,
+ buttonY: 0,
+ };
+ }
+}
+
+function updateHandles(
+ entries,
+ nodeEntries,
+ connectionElements,
+ getSocketCanvasPos,
+ dirtyNodeIds,
+ { buildIndex, getHandles }
+) {
+ const connectedIndex = buildIndex(
+ [...connectionElements.values()]
+ .filter((e) => !e.payload?.isPseudo)
+ .map((e) => e.payload)
+ );
+ const activeHandleKeys = new Set();
+ const promises = [];
+
+ for (const [nodeId, nodeEntry] of nodeEntries) {
+ for (const spec of getHandles(nodeId, nodeEntry.node, connectedIndex)) {
+ if (spec.connected) {
+ entries.delete(spec.handleKey);
+ continue;
+ }
+
+ activeHandleKeys.add(spec.handleKey);
+
+ if (dirtyNodeIds && !dirtyNodeIds.has(nodeId)) {
+ continue;
+ }
+
+ promises.push(
+ (async () => {
+ const pos = await getSocketCanvasPos(
+ nodeId,
+ spec.side,
+ spec.socketKey
+ );
+ if (pos) {
+ entries.set(
+ spec.handleKey,
+ buildHandleEntry(
+ nodeEntry,
+ nodeId,
+ pos,
+ spec.toRight,
+ spec.outputKey,
+ spec.inputKey,
+ spec.areaElement ?? nodeEntry.element.parentElement
+ )
+ );
+ }
+ })()
+ );
+ }
+ }
+
+ return Promise.all(promises).then(() => {
+ for (const key of entries.keys()) {
+ if (!activeHandleKeys.has(key)) {
+ entries.delete(key);
+ }
+ }
+ });
+}
+
+export function updateOutputHandles(
+ entries,
+ nodeEntries,
+ connectionElements,
+ getSocketCanvasPos,
+ dirtyNodeIds
+) {
+ return updateHandles(
+ entries,
+ nodeEntries,
+ connectionElements,
+ getSocketCanvasPos,
+ dirtyNodeIds,
+ {
+ buildIndex: buildConnectedOutputsIndex,
+ getHandles(nodeId, node, connectedOutputs) {
+ return Object.keys(node.outputs)
+ .map((outputKey, outputIndex) => ({ outputKey, outputIndex }))
+ .filter(({ outputKey }) => outputKey !== "loop")
+ .map(({ outputKey, outputIndex }) => ({
+ handleKey: `${nodeId}:${outputKey}`,
+ connected: connectedOutputs.get(nodeId)?.has(outputIndex) ?? false,
+ side: "output",
+ socketKey: outputKey,
+ toRight: true,
+ outputKey,
+ inputKey: null,
+ }));
+ },
+ }
+ );
+}
+
+export function updateInputHandles(
+ entries,
+ nodeEntries,
+ connectionElements,
+ getSocketCanvasPos,
+ dirtyNodeIds,
+ graphIndex,
+ areaContentElement
+) {
+ return updateHandles(
+ entries,
+ nodeEntries,
+ connectionElements,
+ getSocketCanvasPos,
+ dirtyNodeIds,
+ {
+ buildIndex(connections) {
+ const connected = new Set();
+ for (const conn of connections) {
+ if (
+ conn.source !== conn.target &&
+ graphIndex.loopOwnerByNodeId.get(conn.source) !== conn.target
+ ) {
+ connected.add(
+ `${conn.target}:${normalizeTargetInput(conn.targetInput)}`
+ );
+ }
+ }
+ return connected;
+ },
+ getHandles(nodeId, node, connectedInputs) {
+ if (!Object.keys(node.inputs).length) {
+ return [];
+ }
+ return Object.keys(node.inputs).map((inputKey) => ({
+ handleKey: `${nodeId}:${inputKey}`,
+ connected: connectedInputs.has(`${nodeId}:${inputKey}`),
+ side: "input",
+ socketKey: inputKey,
+ toRight: false,
+ outputKey: null,
+ inputKey,
+ areaElement: areaContentElement,
+ }));
+ },
+ }
+ );
+}
diff --git a/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/canvas/hover-toolbar.gjs b/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/canvas/hover-toolbar.gjs
new file mode 100644
index 00000000000..fb90a300bd7
--- /dev/null
+++ b/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/canvas/hover-toolbar.gjs
@@ -0,0 +1,60 @@
+import { cancel, later } from "@ember/runloop";
+import { modifier } from "ember-modifier";
+import dConcatClass from "discourse/ui-kit/helpers/d-concat-class";
+
+const DEFAULT_HIDE_DELAY = 500;
+
+const hoverVisibility = modifier(function (element, _, named) {
+ const delay = named.delay ?? DEFAULT_HIDE_DELAY;
+ const svg = element.closest("svg");
+ const target =
+ named.hoverTarget ??
+ (named.hoverSelector
+ ? element.closest(named.hoverSelector)
+ : (svg?.querySelector(named.hoverQuery) ?? element.parentElement));
+
+ const el =
+ named.visibilityTarget ??
+ svg?.querySelector(named.visibilityQuery) ??
+ element;
+ let timer = null;
+
+ function show() {
+ cancel(timer);
+ el.classList.add("is-visible");
+ }
+
+ function scheduleHide() {
+ cancel(timer);
+ timer = later(() => el.classList.remove("is-visible"), delay);
+ }
+
+ target?.addEventListener("mouseenter", show);
+ target?.addEventListener("mouseleave", scheduleHide);
+ element.addEventListener("mouseenter", show);
+ element.addEventListener("mouseleave", scheduleHide);
+
+ return () => {
+ cancel(timer);
+ target?.removeEventListener("mouseenter", show);
+ target?.removeEventListener("mouseleave", scheduleHide);
+ element.removeEventListener("mouseenter", show);
+ element.removeEventListener("mouseleave", scheduleHide);
+ };
+});
+
+<template>
+ <div
+ class={{dConcatClass "workflow-canvas-toolbar" (if @inline "--inline")}}
+ {{hoverVisibility
+ hoverTarget=@hoverTarget
+ hoverSelector=@hoverSelector
+ hoverQuery=@hoverQuery
+ visibilityTarget=@visibilityTarget
+ visibilityQuery=@visibilityQuery
+ delay=@hideDelay
+ }}
+ >
+ {{yield}}
+ </div>
+</template>
diff --git a/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/canvas/index.gjs b/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/canvas/index.gjs
new file mode 100644
index 00000000000..682657c67af
--- /dev/null
+++ b/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/canvas/index.gjs
@@ -0,0 +1,931 @@
+import Component from "@glimmer/component";
+import { tracked } from "@glimmer/tracking";
+import { fn } from "@ember/helper";
+import { on } from "@ember/modifier";
+import { action } from "@ember/object";
+import didInsert from "@ember/render-modifiers/modifiers/did-insert";
+import didUpdate from "@ember/render-modifiers/modifiers/did-update";
+import { service } from "@ember/service";
+import { trustHTML } from "@ember/template";
+import DMenu from "discourse/float-kit/components/d-menu";
+import { ajax } from "discourse/lib/ajax";
+import { popupAjaxError } from "discourse/lib/ajax-error";
+import DButton from "discourse/ui-kit/d-button";
+import DDropdownMenu from "discourse/ui-kit/d-dropdown-menu";
+import dIcon from "discourse/ui-kit/helpers/d-icon";
+import { i18n } from "discourse-i18n";
+import CanvasContextMenu from "./canvas-context-menu";
+import { exportWorkflowToFile, parseWorkflowImport } from "./canvas-file-io";
+import { setupCanvasKeyboard } from "./canvas-keyboard";
+import { runManualTrigger } from "./canvas-manual-trigger";
+import {
+ buildStickyNoteTranslateHandler,
+ computeStickyNoteRects,
+} from "./canvas-sticky-notes";
+import ConnectionEntry from "./connection-entry";
+import Controls from "./controls";
+import LoopBackConnection from "./loop-back-connection";
+import { createReteEditor } from "./rete-editor";
+import StickyNoteComponent from "./sticky-note";
+import WorkflowNode from "./workflow-node";
+
+export default class WorkflowCanvas extends Component {
+ @service keyboardShortcuts;
+ @service dialog;
+ @service menu;
+ @service router;
+ @service workflowsNodeTypes;
+ @service toasts;
+
+ @tracked isLoading = true;
+ @tracked rete = null;
+ @tracked areaTransform = { x: 0, y: 0, k: 1 };
+ @tracked workflowPublishedOverride = null;
+ @tracked hasUnpublishedChangesOverride = null;
+ @tracked selectionVersion = 0;
+ copiedEntities = { nodes: [], stickyNotes: [] };
+ pasteOffset = 0;
+ isFirstSync = true;
+ lastAutoArrangeRequest = 0;
+ didHydrateInitialAutoLayout = false;
+ #hasSetupStarted = false;
+ #pendingSync = false;
+ #syncTask = null;
+ #ZOOM_STEP = 0.1;
+ #ZOOM_MIN = 0.25;
+ #ZOOM_MAX = 4;
+
+ willDestroy() {
+ super.willDestroy();
+ this.rete?.destroy();
+ this.keyboard?.teardown();
+ }
+
+ get workflowPublished() {
+ return (
+ this.workflowPublishedOverride ?? Boolean(this.args.workflowPublished)
+ );
+ }
+
+ get hasUnpublishedChanges() {
+ return (
+ this.hasUnpublishedChangesOverride ??
+ Boolean(this.args.hasUnpublishedChanges)
+ );
+ }
+
+ get publishDisabled() {
+ return this.workflowPublished && !this.hasUnpublishedChanges;
+ }
+
+ get hasNodes() {
+ return (this.args.nodes || []).length > 0;
+ }
+
+ get showPublishButton() {
+ return this.hasNodes && !this.publishDisabled;
+ }
+
+ get showToolbarPublishButton() {
+ return this.showPublishButton && !this.showUnpublishedChangesMessage;
+ }
+
+ get showUnpublishedChangesMessage() {
+ return this.showPublishButton;
+ }
+
+ get showDiscardChangesButton() {
+ return this.workflowPublished && this.hasUnpublishedChanges;
+ }
+
+ @action
+ isStickyNoteSelected(clientId) {
+ this.selectionVersion;
+ return this.rete.isStickyNoteSelected(clientId);
+ }
+
+ @action
+ async publishWorkflow() {
+ if (!this.hasNodes) {
+ return;
+ }
+
+ this.workflowPublishedOverride = true;
+ this.hasUnpublishedChangesOverride = false;
+ try {
+ await ajax(
+ `/admin/plugins/discourse-workflows/workflows/${this.args.workflowId}.json`,
+ {
+ type: "PUT",
+ data: {
+ workflow: {
+ name: this.args.workflowName,
+ published: true,
+ },
+ },
+ }
+ );
+ if (this.args.workflow) {
+ this.args.workflow.activeVersionId = this.args.workflow.versionId;
+ this.args.workflow.hasUnpublishedChanges = false;
+ }
+ this.workflowPublishedOverride = null;
+ this.hasUnpublishedChangesOverride = null;
+ } catch {
+ this.workflowPublishedOverride = this.args.workflowPublished;
+ this.hasUnpublishedChangesOverride = this.args.hasUnpublishedChanges;
+ }
+ }
+
+ @action
+ async discardWorkflow() {
+ const confirmed = await this.dialog.confirm({
+ message: i18n("discourse_workflows.discard_changes_confirmation"),
+ confirmButtonLabel: "discourse_workflows.discard_changes",
+ cancelButtonLabel: "discourse_workflows.keep_editing",
+ });
+
+ if (!confirmed) {
+ return;
+ }
+
+ this.hasUnpublishedChangesOverride = false;
+
+ try {
+ const response = await ajax(
+ `/admin/plugins/discourse-workflows/workflows/${this.args.workflowId}/discard-draft.json`,
+ {
+ type: "POST",
+ }
+ );
+
+ this.args.onDiscardWorkflow?.(response.workflow);
+ this.hasUnpublishedChangesOverride = null;
+ } catch (e) {
+ this.hasUnpublishedChangesOverride = this.args.hasUnpublishedChanges;
+ popupAjaxError(e);
+ }
+ }
+
+ @action
+ async unpublishWorkflow(closeMenu) {
+ if (typeof closeMenu === "function") {
+ closeMenu();
+ }
+ this.workflowPublishedOverride = false;
+ try {
+ await ajax(
+ `/admin/plugins/discourse-workflows/workflows/${this.args.workflowId}.json`,
+ {
+ type: "PUT",
+ data: {
+ workflow: {
+ name: this.args.workflowName,
+ published: false,
+ },
+ },
+ }
+ );
+ if (this.args.workflow) {
+ this.args.workflow.activeVersionId = null;
+ this.args.workflow.hasUnpublishedChanges = true;
+ }
+ this.workflowPublishedOverride = null;
+ } catch {
+ this.workflowPublishedOverride = this.args.workflowPublished;
+ }
+ }
+
+ @action
+ registerCanvas(element) {
+ this.canvasElement = element;
+ this.#maybeSetupCanvas();
+ }
+
+ @action
+ registerContainer(element) {
+ this.containerElement = element;
+ this.#maybeSetupCanvas();
+ }
+
+ #keyboardActions() {
+ return {
+ onUndo: () => this.args.onUndo?.(),
+ onRedo: () => this.args.onRedo?.(),
+ onCopy: () => this.#copy(),
+ onPaste: () => this.#paste(),
+ onDelete: () => this.deleteSelected(),
+ onEscape: () => {
+ this.contextMenuApi?.close();
+ this.rete.selector.unselectAll();
+ this.selectionVersion++;
+ },
+ onZoomIn: () => this.zoomIn(),
+ onZoomOut: () => this.zoomOut(),
+ onFitToView: () => this.fitToView(),
+ onAutoLayout: () => this.autoLayout(),
+ };
+ }
+
+ async #handleManualTrigger(clientId) {
+ try {
+ await runManualTrigger({
+ node: this.#nodes().find((n) => n.clientId === clientId),
+ clientId,
+ workflowId: this.args.workflowId,
+ toasts: this.toasts,
+ router: this.router,
+ session: this.args.session,
+ });
+ } catch (e) {
+ popupAjaxError(e);
+ }
+ }
+
+ #reteCallbacks() {
+ return {
+ onNodeDragged: (...a) => this.args.onUpdateNodePosition?.(...a),
+ onNodePicked: () => this.selectionVersion++,
+ onCanvasPointerDown: () => {
+ this.selectionVersion++;
+ this.contextMenuApi?.close();
+ this.menu.close("workflows-canvas-menu");
+ this.args.onCloseNodePanel?.();
+ },
+ onNodeDragEnd: () => this.args.onNodeDragEnd?.(),
+ onConnectionCreated: (...a) => this.args.onCreateConnection?.(...a),
+ onNodeDelete: (clientId) => this.args.onRemoveNodes?.([clientId]),
+ onManualTrigger: (clientId) => this.#handleManualTrigger(clientId),
+ onNodeDoubleClick: (clientId) => this.args.onEditNode?.(clientId),
+ onTransformChanged: (t) => (this.areaTransform = t),
+ };
+ }
+
+ #nodes() {
+ return this.args.nodes || [];
+ }
+
+ #connections() {
+ return this.args.connections || [];
+ }
+
+ #stickyNoteRects() {
+ return computeStickyNoteRects(this.args.stickyNotes);
+ }
+
+ #shouldHydrateInitialAutoLayout(nodes) {
+ return (
+ !this.didHydrateInitialAutoLayout && nodes.some((node) => !node.position)
+ );
+ }
+
+ #consumeAutoArrangeRequest(autoArrangeRequest) {
+ if (autoArrangeRequest <= this.lastAutoArrangeRequest) {
+ return false;
+ }
+
+ this.lastAutoArrangeRequest = autoArrangeRequest;
+ return true;
+ }
+
+ async #applyAutoArrange(callback) {
+ const positions = await this.rete.autoArrange();
+ callback?.(positions);
+ }
+
+ async #syncViewport(prevNodeCount, stickyNoteRects) {
+ if (this.isFirstSync || this.rete.nodeCount !== prevNodeCount) {
+ this.isFirstSync = false;
+ await this.rete.fitToView(stickyNoteRects);
+ }
+ }
+
+ async #performSync() {
+ const snapshot = {
+ nodes: this.#nodes(),
+ connections: this.#connections(),
+ stickyNoteRects: this.#stickyNoteRects(),
+ autoArrangeRequest: this.args.autoArrangeRequest || 0,
+ };
+ const prevNodeCount = this.rete.nodeCount;
+
+ await this.rete.syncState(snapshot.nodes, snapshot.connections);
+
+ if (this.#shouldHydrateInitialAutoLayout(snapshot.nodes)) {
+ this.didHydrateInitialAutoLayout = true;
+ await this.#applyAutoArrange(this.args.onHydrateAutoLayout);
+ }
+
+ if (this.#consumeAutoArrangeRequest(snapshot.autoArrangeRequest)) {
+ await this.#applyAutoArrange(this.args.onSyncAutoLayout);
+ }
+
+ await this.#syncViewport(prevNodeCount, snapshot.stickyNoteRects);
+ }
+
+ async #flushSyncQueue() {
+ try {
+ while (this.#pendingSync) {
+ this.#pendingSync = false;
+ await this.#performSync();
+ }
+ } catch {
+ this.#pendingSync = false;
+ this.toasts.error({
+ data: { message: i18n("discourse_workflows.canvas.sync_error") },
+ });
+ } finally {
+ this.#syncTask = null;
+ }
+ }
+
+ async #queueSync() {
+ if (!this.rete) {
+ return;
+ }
+
+ this.#pendingSync = true;
+
+ if (!this.#syncTask) {
+ this.#syncTask = this.#flushSyncQueue();
+ }
+
+ await this.#syncTask;
+ }
+
+ async #maybeSetupCanvas() {
+ if (
+ this.#hasSetupStarted ||
+ !this.canvasElement ||
+ !this.containerElement
+ ) {
+ return;
+ }
+
+ this.#hasSetupStarted = true;
+ const element = this.canvasElement;
+ const nodeTypes = await this.workflowsNodeTypes.load();
+
+ this.rete = await createReteEditor(this.containerElement, {
+ nodeTypes,
+ callbacks: this.#reteCallbacks(),
+ });
+
+ this.keyboard = setupCanvasKeyboard(
+ this.keyboardShortcuts,
+ this.#keyboardActions(),
+ element
+ );
+
+ this.args.onAreaReady?.(this.rete.area);
+
+ await this.#queueSync();
+ this.isLoading = false;
+ element.focus();
+ }
+
+ @action
+ async syncToRete() {
+ await this.#queueSync();
+ }
+
+ get nodeEntries() {
+ return this.rete.renderer.nodeEntryList;
+ }
+
+ get connectionEntries() {
+ return this.rete.renderer.connectionEntryList;
+ }
+
+ get handleEntries() {
+ return [
+ ...this.rete.renderer.outputHandleEntryList,
+ ...this.rete.renderer.inputHandleEntryList,
+ ].map((entry) => ({
+ ...entry,
+ svgStyle: trustHTML(
+ `overflow:visible;position:absolute;pointer-events:none;z-index:2;left:${entry.svgLeft}px;top:${entry.svgTop}px;width:50px;height:20px`
+ ),
+ }));
+ }
+
+ get areaContentElement() {
+ return this.rete.areaContentElement;
+ }
+
+ @action
+ handleConnectionToolbarAdd(connectionInfo) {
+ this.args.onOpenNodePanel?.({
+ connectionSource: connectionInfo.sourceClientId,
+ connectionSourceOutput: connectionInfo.sourceOutput,
+ connectionTarget: connectionInfo.targetClientId,
+ connectionTargetInput: connectionInfo.targetInput,
+ });
+ }
+
+ @action
+ handleConnectionToolbarDelete(connectionInfo) {
+ this.args.onConnectionDelete?.(
+ connectionInfo.sourceClientId,
+ connectionInfo.sourceOutput,
+ connectionInfo.targetClientId,
+ connectionInfo.targetInput
+ );
+ }
+
+ @action
+ handleLoopBackAdd(loopNodeClientId) {
+ this.args.onOpenNodePanel?.({ loopNodeClientId });
+ }
+
+ @action
+ handleHandleAdd(nodeClientId, outputKey, inputKey, e) {
+ e.stopPropagation();
+ this.args.onOpenNodePanel?.(
+ outputKey !== null
+ ? { sourceClientId: nodeClientId, sourceOutput: outputKey }
+ : { targetClientId: nodeClientId, targetInput: inputKey || "main" }
+ );
+ }
+
+ get showEmptyState() {
+ return !this.isLoading && (this.args.nodes || []).length === 0;
+ }
+
+ @action
+ registerContextMenu(api) {
+ this.contextMenuApi = api;
+ }
+
+ @action
+ handleContextMenu(event) {
+ this.contextMenuApi?.open(event);
+ }
+
+ #invokeAtViewportCenter(callback) {
+ this.contextMenuApi?.close();
+ callback?.(this.rete.viewportCenter());
+ }
+
+ @action
+ openNodePanelAtCenter() {
+ this.#invokeAtViewportCenter(this.args.onOpenNodePanel);
+ }
+
+ @action
+ browseTemplates() {
+ this.args.onBrowseTemplates?.();
+ }
+
+ @action
+ async selectStickyNote(clientId) {
+ await this.rete.selectStickyNote(clientId, {
+ onStickyNoteTranslate: buildStickyNoteTranslateHandler(
+ this.args.stickyNotes,
+ this.args.onStickyNoteMove
+ ),
+ onStickyNoteUnselect: () => {
+ this.selectionVersion++;
+ },
+ });
+ this.selectionVersion++;
+ }
+
+ #copy() {
+ const { nodeIds, stickyNoteIds } = this.rete.getSelectedIds();
+ const cloneMatching = (items, ids) =>
+ (items || []).filter((n) => ids.has(n.clientId)).map(structuredClone);
+ const nodes = cloneMatching(this.args.nodes, nodeIds);
+ const stickyNotes = cloneMatching(this.args.stickyNotes, stickyNoteIds);
+ if (nodes.length > 0 || stickyNotes.length > 0) {
+ this.copiedEntities = { nodes, stickyNotes };
+ this.pasteOffset = 0;
+ }
+ }
+
+ #paste() {
+ const { nodes, stickyNotes } = this.copiedEntities;
+ if (nodes.length === 0 && stickyNotes.length === 0) {
+ return;
+ }
+ this.pasteOffset += 20;
+ const offset = this.pasteOffset;
+ const shift = (items) =>
+ items.map((item) => ({
+ ...item,
+ position: item.position
+ ? { x: item.position.x + offset, y: item.position.y + offset }
+ : null,
+ }));
+ this.args.onPasteEntities?.({
+ nodes: shift(nodes),
+ stickyNotes: shift(stickyNotes),
+ });
+ }
+
+ @action
+ addStickyNoteAtCenter(closeFn) {
+ closeFn?.();
+ this.#invokeAtViewportCenter(this.args.onAddStickyNote);
+ }
+
+ @action
+ deleteStickyNote(clientId) {
+ this.args.onRemoveSelected?.({
+ nodeIds: [],
+ stickyNoteIds: [clientId],
+ });
+ this.selectionVersion++;
+ }
+
+ @action
+ async translateSelected(draggedClientId, dx, dy) {
+ await this.rete.translateSelectedEntities(
+ draggedClientId,
+ "sticky-note",
+ dx,
+ dy
+ );
+ }
+
+ @action
+ deleteSelected() {
+ const { nodeIds, stickyNoteIds } = this.rete.getSelectedIds();
+ if (nodeIds.size > 0 || stickyNoteIds.size > 0) {
+ this.args.onRemoveSelected?.({
+ nodeIds: [...nodeIds],
+ stickyNoteIds: [...stickyNoteIds],
+ });
+ this.rete.selector.unselectAll();
+ this.selectionVersion++;
+ }
+ }
+
+ async #applyZoom(delta) {
+ const currentK = this.rete.transform.k;
+ const newK = Math.max(
+ this.#ZOOM_MIN,
+ Math.min(this.#ZOOM_MAX, currentK + delta)
+ );
+ await this.rete.zoomAtViewportCenter(newK);
+ }
+
+ @action
+ async zoomIn() {
+ await this.#applyZoom(this.#ZOOM_STEP);
+ }
+
+ @action
+ async zoomOut() {
+ await this.#applyZoom(-this.#ZOOM_STEP);
+ }
+
+ @action
+ async fitToView() {
+ await this.rete.fitToView(this.#stickyNoteRects());
+ }
+
+ @action
+ async autoLayout() {
+ const positions = await this.rete.autoArrange();
+ this.args.onAutoLayout?.(positions);
+ await this.rete.fitToView(this.#stickyNoteRects());
+ }
+
+ @action
+ exportWorkflow(closeFn) {
+ closeFn();
+ exportWorkflowToFile(
+ this.args.nodes,
+ this.args.connections,
+ this.args.stickyNotes,
+ this.args.workflow
+ );
+ }
+
+ @action
+ openImportDialog(closeFn) {
+ closeFn();
+ this.fileInput?.click();
+ }
+
+ @action
+ registerFileInput(element) {
+ this.fileInput = element;
+ }
+
+ #showImportError(key = "import_error") {
+ this.toasts.error({
+ data: { message: i18n(`discourse_workflows.canvas.${key}`) },
+ });
+ }
+
+ @action
+ async handleFileSelected(event) {
+ const file = event.target.files?.[0];
+ event.target.value = "";
+ if (!file) {
+ return;
+ }
+ try {
+ const result = parseWorkflowImport(await file.text());
+ if (result.error) {
+ this.#showImportError(
+ result.error === "version" ? "import_version_error" : "import_error"
+ );
+ return;
+ }
+ this.args.onImportNodes?.(
+ result.nodes,
+ result.connections,
+ result.stickyNotes,
+ result.staticData
+ );
+ } catch {
+ this.#showImportError();
+ }
+ }
+
+ <template>
+ <div
+ class="workflows-canvas"
+ tabindex="0"
+ {{on "contextmenu" this.handleContextMenu}}
+ {{didInsert this.registerCanvas}}
+ {{didUpdate this.syncToRete @nodes @connections @autoArrangeRequest}}
+ >
+ {{#if this.isLoading}}
+ <div class="workflows-canvas__spinner-overlay">
+ <div class="spinner"></div>
+ </div>
+ {{/if}}
+
+ <div
+ class="workflows-canvas__rete-container"
+ {{didInsert this.registerContainer}}
+ ></div>
+
+ {{#if this.rete}}
+ {{#if this.showEmptyState}}
+ <div class="workflows-canvas__empty-state">
+ <div class="workflows-canvas__empty-state-options">
+ <button
+ type="button"
+ class="workflows-canvas__empty-state-trigger"
+ {{on "click" this.openNodePanelAtCenter}}
+ >
+ <span class="workflows-canvas__empty-state-tile">
+ {{dIcon "plus"}}
+ </span>
+ <span class="workflows-canvas__empty-state-label">
+ {{i18n "discourse_workflows.add_node.first_step"}}
+ </span>
+ </button>
+
+ <button
+ type="button"
+ class="workflows-canvas__empty-state-trigger"
+ {{on "click" this.browseTemplates}}
+ >
+ <span class="workflows-canvas__empty-state-tile">
+ {{dIcon "layer-group"}}
+ </span>
+ <span class="workflows-canvas__empty-state-label">
+ {{i18n "discourse_workflows.add_node.browse_templates"}}
+ </span>
+ </button>
+ </div>
+ </div>
+ {{/if}}
+
+ {{#each this.nodeEntries as |entry|}}
+ {{#in-element entry.element insertBefore=null}}
+ <WorkflowNode
+ @node={{entry.node}}
+ @onDelete={{this.rete.renderer.onNodeDelete}}
+ @onManualTrigger={{this.rete.renderer.onManualTrigger}}
+ @onSocketRendered={{this.rete.renderer.onSocketRendered}}
+ @onEditNode={{@onEditNode}}
+ @workflowPublished={{this.workflowPublished}}
+ @session={{@session}}
+ />
+ {{/in-element}}
+ {{/each}}
+
+ {{#each this.connectionEntries as |entry|}}
+ {{#in-element entry.element insertBefore=null}}
+ {{#if entry.isLoopBack}}
+ <LoopBackConnection
+ @entry={{entry}}
+ @onAdd={{this.handleLoopBackAdd}}
+ />
+ {{else}}
+ <ConnectionEntry
+ @entry={{entry}}
+ @onAdd={{this.handleConnectionToolbarAdd}}
+ @onDelete={{this.handleConnectionToolbarDelete}}
+ />
+ {{/if}}
+ {{/in-element}}
+ {{/each}}
+
+ {{#each this.handleEntries as |entry|}}
+ {{#in-element entry.areaElement insertBefore=null}}
+
+ <svg class="workflow-handle" style={{entry.svgStyle}}>
+ <path
+ fill="none"
+ stroke="var(--primary-low-mid)"
+ stroke-width="1.5"
+ d={{entry.pathD}}
+ />
+ <foreignObject
+ class="workflow-handle__button-fo"
+ width="14"
+ height="14"
+ x={{entry.buttonX}}
+ y={{entry.buttonY}}
+ >
+ <button
+ type="button"
+ class="workflow-handle__add-btn"
+ {{on
+ "click"
+ (fn
+ this.handleHandleAdd
+ entry.nodeClientId
+ entry.outputKey
+ entry.inputKey
+ )
+ }}
+ >
+ {{dIcon "plus"}}
+ </button>
+ </foreignObject>
+ </svg>
+ {{/in-element}}
+ {{/each}}
+
+ {{#if this.areaContentElement}}
+ {{#each @stickyNotes key="clientId" as |note|}}
+ {{#in-element this.areaContentElement insertBefore=null}}
+ <StickyNoteComponent
+ @note={{note}}
+ @isSelected={{this.isStickyNoteSelected note.clientId}}
+ @zoom={{this.areaTransform.k}}
+ @onSelect={{fn this.selectStickyNote note.clientId}}
+ @onBeforeMutation={{@onStickyNoteBeforeMutation}}
+ @onMove={{fn @onStickyNoteMove note.clientId}}
+ @onResize={{fn @onStickyNoteResize note.clientId}}
+ @onUpdateText={{fn @onStickyNoteUpdateText note.clientId}}
+ @onChangeColor={{fn @onStickyNoteChangeColor note.clientId}}
+ @onDelete={{fn this.deleteStickyNote note.clientId}}
+ @onTranslateSelected={{fn this.translateSelected note.clientId}}
+ @onAfterMutation={{@onNodeDragEnd}}
+ />
+ {{/in-element}}
+ {{/each}}
+ {{/if}}
+
+ <Controls
+ @onUndo={{@onUndo}}
+ @onRedo={{@onRedo}}
+ @canUndo={{@canUndo}}
+ @canRedo={{@canRedo}}
+ @onZoomIn={{this.zoomIn}}
+ @onZoomOut={{this.zoomOut}}
+ @onFitToView={{this.fitToView}}
+ @onAutoLayout={{this.autoLayout}}
+ />
+
+ <input
+ type="file"
+ accept=".json"
+ class="hidden"
+ {{didInsert this.registerFileInput}}
+ {{on "change" this.handleFileSelected}}
+ />
+
+ {{#if @onOpenNodePanel}}
+ {{#if this.showUnpublishedChangesMessage}}
+ <div class="workflows-canvas__publish-status">
+ <span class="workflows-canvas__publish-status-body" role="status">
+ <span class="workflows-canvas__publish-status-icon">
+ {{dIcon "triangle-exclamation"}}
+ </span>
+ <span class="workflows-canvas__publish-status-text">
+ <span class="workflows-canvas__publish-status-title">
+ {{i18n "discourse_workflows.unpublished_changes_message"}}
+ </span>
+ <span class="workflows-canvas__publish-status-detail">
+ {{i18n
+ "discourse_workflows.unpublished_changes_message_detail"
+ }}
+ </span>
+ </span>
+ </span>
+
+ <span class="workflows-canvas__publish-status-actions">
+ <DButton
+ @action={{this.publishWorkflow}}
+ @translatedLabel={{i18n "discourse_workflows.publish"}}
+ class="btn-primary btn-small workflows-canvas__publish-status-btn"
+ />
+
+ {{#if this.showDiscardChangesButton}}
+ <DButton
+ @action={{this.discardWorkflow}}
+ @translatedLabel={{i18n
+ "discourse_workflows.discard_changes"
+ }}
+ class="btn-default btn-small workflows-canvas__publish-status-btn"
+ />
+ {{/if}}
+ </span>
+ </div>
+ {{/if}}
+
+ <div class="workflows-canvas__toolbar-top-right">
+ {{#if this.showToolbarPublishButton}}
+ <DButton
+ @action={{this.publishWorkflow}}
+ @translatedLabel={{i18n "discourse_workflows.publish"}}
+ class="btn-primary workflows-canvas__publish-btn"
+ />
+ {{/if}}
+
+ <DButton
+ @action={{this.openNodePanelAtCenter}}
+ @icon="plus"
+ class="btn-default workflows-canvas__add-node-btn"
+ />
+
+ <DMenu
+ @identifier="workflows-canvas-menu"
+ @icon="ellipsis-vertical"
+ class="btn-default workflows-canvas__menu-btn"
+ >
+ <:content as |args|>
+ <DDropdownMenu as |dropdown|>
+ {{#if this.workflowPublished}}
+ <dropdown.item>
+ <DButton
+ @action={{fn this.unpublishWorkflow args.close}}
+ @translatedLabel={{i18n
+ "discourse_workflows.unpublish"
+ }}
+ class="btn-transparent"
+ />
+ </dropdown.item>
+ {{/if}}
+ <dropdown.item>
+ <DButton
+ @action={{fn this.addStickyNoteAtCenter args.close}}
+ @icon="note-sticky"
+ @translatedLabel={{i18n
+ "discourse_workflows.sticky_note.add"
+ }}
+ class="btn-transparent"
+ />
+ </dropdown.item>
+ <dropdown.item>
+ <DButton
+ @action={{fn this.exportWorkflow args.close}}
+ @icon="download"
+ @translatedLabel={{i18n
+ "discourse_workflows.canvas.export_nodes"
+ }}
+ @disabled={{this.showEmptyState}}
+ class="btn-transparent"
+ />
+ </dropdown.item>
+ <dropdown.item>
+ <DButton
+ @action={{fn this.openImportDialog args.close}}
+ @icon="upload"
+ @translatedLabel={{i18n
+ "discourse_workflows.canvas.import_nodes"
+ }}
+ class="btn-transparent"
+ />
+ </dropdown.item>
+ </DDropdownMenu>
+ </:content>
+ </DMenu>
+ </div>
+ {{/if}}
+
+ <CanvasContextMenu
+ @canvasElement={{this.canvasElement}}
+ @containerElement={{this.containerElement}}
+ @rete={{this.rete}}
+ @onEditNode={{@onEditNode}}
+ @onDeleteSelected={{this.deleteSelected}}
+ @onOpenNodePanel={{@onOpenNodePanel}}
+ @onAddStickyNote={{@onAddStickyNote}}
+ @onRegister={{this.registerContextMenu}}
+ />
+ {{/if}}
+ </div>
+ </template>
+}
diff --git a/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/canvas/loop-back-connection.gjs b/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/canvas/loop-back-connection.gjs
new file mode 100644
index 00000000000..04f8fa15014
--- /dev/null
+++ b/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/canvas/loop-back-connection.gjs
@@ -0,0 +1,43 @@
+import { fn } from "@ember/helper";
+import { on } from "@ember/modifier";
+import { trustHTML } from "@ember/template";
+
+const SVG_STYLE = trustHTML(
+ "overflow:visible;position:absolute;pointer-events:none;width:9999px;height:9999px"
+);
+
+function handleAdd(callback, loopNodeClientId, e) {
+ e.stopPropagation();
+ e.preventDefault();
+ callback?.(loopNodeClientId);
+}
+
+<template>
+ <svg class="workflow-loop-back" style={{SVG_STYLE}}>
+ <path
+ class="workflow-loop-back__path"
+ fill="none"
+ stroke="var(--primary-low-mid)"
+ stroke-width="1.5"
+ d={{@entry.pathD}}
+ />
+ <polygon
+ class="workflow-loop-back__arrow"
+ fill="var(--primary-low-mid)"
+ points={{@entry.loopArrowPoints}}
+ />
+ <foreignObject
+ class="workflow-loop-back__button-fo"
+ width="28"
+ height="28"
+ x={{@entry.loopButtonX}}
+ y={{@entry.loopButtonY}}
+ >
+ <button
+ type="button"
+ class="workflow-loop-back__add-btn"
+ {{on "click" (fn handleAdd @onAdd @entry.loopNodeClientId)}}
+ >+</button>
+ </foreignObject>
+ </svg>
+</template>
diff --git a/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/canvas/node-panel.gjs b/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/canvas/node-panel.gjs
new file mode 100644
index 00000000000..d976cc1adc5
--- /dev/null
+++ b/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/canvas/node-panel.gjs
@@ -0,0 +1,296 @@
+import Component from "@glimmer/component";
+import { tracked } from "@glimmer/tracking";
+import { fn } from "@ember/helper";
+import { on } from "@ember/modifier";
+import { action } from "@ember/object";
+import DButton from "discourse/ui-kit/d-button";
+import dIcon from "discourse/ui-kit/helpers/d-icon";
+import dAutoFocus from "discourse/ui-kit/modifiers/d-auto-focus";
+import { i18n } from "discourse-i18n";
+import { nodeTypePresenter } from "../../../lib/workflows/node-types";
+
+const NodeTypeItem = <template>
+ <button
+ type="button"
+ class="workflows-node-panel__item"
+ style={{@presenter.style}}
+ {{on "click" @onClick}}
+ >
+ <span class="workflows-node-panel__item-icon">
+ {{dIcon @presenter.icon}}
+ </span>
+ <span class="workflows-node-panel__item-content">
+ <span class="workflows-node-panel__item-name">
+ {{@presenter.label}}
+ </span>
+ {{#if @presenter.description}}
+ <span class="workflows-node-panel__item-description">
+ {{@presenter.description}}
+ </span>
+ {{/if}}
+ </span>
+ {{#if @presenter.hasOperations}}
+ <span class="workflows-node-panel__item-arrow">
+ {{dIcon "chevron-right"}}
+ </span>
+ {{/if}}
+ </button>
+</template>;
+
+const OperationItem = <template>
+ <button
+ type="button"
+ class="workflows-node-panel__item"
+ style={{@presenter.style}}
+ {{on "click" @onClick}}
+ >
+ <span class="workflows-node-panel__item-icon">
+ {{dIcon @presenter.icon}}
+ </span>
+ <span class="workflows-node-panel__item-content">
+ <span class="workflows-node-panel__item-name">
+ {{@presenter.operationLabel @operation}}
+ </span>
+ </span>
+ <span class="workflows-node-panel__item-arrow">
+ {{dIcon "chevron-right"}}
+ </span>
+ </button>
+</template>;
+
+function presenterFor(nodeType) {
+ return nodeType ? nodeTypePresenter(nodeType) : null;
+}
+
+export default class NodePanel extends Component {
+ @tracked selectedCategory = null;
+ @tracked selectedOperationNodeType = null;
+
+ get isSearching() {
+ return this.args.searchTerm?.trim().length > 0;
+ }
+
+ get availableNodeTypes() {
+ return (this.args.nodeTypes || []).filter(
+ (nodeType) => nodeType.available !== false
+ );
+ }
+
+ get categories() {
+ const groups = new Map();
+
+ for (const nodeType of this.availableNodeTypes) {
+ const presenter = nodeTypePresenter(nodeType);
+
+ if (!presenter.paletteGroup || groups.has(presenter.paletteGroup.id)) {
+ continue;
+ }
+
+ groups.set(presenter.paletteGroup.id, {
+ ...presenter.paletteGroup,
+ label: i18n(presenter.paletteGroup.label_key),
+ });
+ }
+
+ return [...groups.values()].sort((a, b) => a.order - b.order);
+ }
+
+ get categoryNodeTypes() {
+ if (!this.selectedCategory) {
+ return [];
+ }
+
+ return this.availableNodeTypes.filter(
+ (nodeType) =>
+ nodeTypePresenter(nodeType).paletteGroup?.id ===
+ this.selectedCategory.id
+ );
+ }
+
+ get selectedOperationPresenter() {
+ return presenterFor(this.selectedOperationNodeType);
+ }
+
+ get showCategories() {
+ return !this.isSearching && !this.selectedCategory;
+ }
+
+ get showCategoryNodes() {
+ return (
+ !this.isSearching &&
+ this.selectedCategory &&
+ !this.selectedOperationNodeType
+ );
+ }
+
+ get showSearchResults() {
+ return this.isSearching && !this.selectedOperationNodeType;
+ }
+
+ get showOperations() {
+ return !!this.selectedOperationNodeType;
+ }
+
+ @action
+ handleSearchInput(event) {
+ this.selectedOperationNodeType = null;
+ this.args.onSearch?.(event.target.value);
+ }
+
+ @action
+ selectCategory(category) {
+ this.selectedCategory = category;
+ }
+
+ @action
+ backToCategories() {
+ this.selectedCategory = null;
+ this.selectedOperationNodeType = null;
+ }
+
+ @action
+ selectOperationNodeType(nodeType) {
+ this.selectedOperationNodeType = nodeType;
+ }
+
+ @action
+ backFromOperations() {
+ this.selectedOperationNodeType = null;
+ }
+
+ @action
+ selectOperation(nodeType, operation) {
+ this.args.onSelectNodeType?.(nodeType, operation);
+ }
+
+ @action
+ handleNodeItemClick(nodeType) {
+ if (nodeTypePresenter(nodeType).hasOperations) {
+ this.selectedOperationNodeType = nodeType;
+ } else {
+ this.args.onSelectNodeType?.(nodeType);
+ }
+ }
+
+ @action
+ handleSearchKeyDown(event) {
+ if (event.key === "Enter") {
+ event.preventDefault();
+ const firstNodeType = this.availableNodeTypes[0];
+ if (this.isSearching && firstNodeType) {
+ this.handleNodeItemClick(firstNodeType);
+ }
+ }
+ }
+
+ @action
+ handleKeyDown(event) {
+ if (event.key === "Escape") {
+ event.stopPropagation();
+ this.args.onClose?.();
+ }
+ }
+
+ <template>
+ {{! eslint-disable ember/template-no-invalid-interactive }}
+ <div class="workflows-node-panel" {{on "keydown" this.handleKeyDown}}>
+ <div class="workflows-node-panel__header">
+ {{#if this.showOperations}}
+ <DButton
+ @action={{this.backFromOperations}}
+ @icon="chevron-left"
+ class="btn-transparent btn-small workflows-node-panel__back"
+ />
+ <span
+ class="workflows-node-panel__item-icon"
+ style={{this.selectedOperationPresenter.style}}
+ >
+ {{dIcon this.selectedOperationPresenter.icon}}
+ </span>
+ <span class="workflows-node-panel__title">
+ {{this.selectedOperationPresenter.label}}
+ </span>
+ {{else if this.showCategoryNodes}}
+ <DButton
+ @action={{this.backToCategories}}
+ @icon="chevron-left"
+ class="btn-transparent btn-small workflows-node-panel__back"
+ />
+ <span class="workflows-node-panel__title">
+ {{this.selectedCategory.label}}
+ </span>
+ {{else}}
+ <span class="workflows-node-panel__title">
+ {{i18n "discourse_workflows.add_node.title"}}
+ </span>
+ {{/if}}
+ <DButton
+ @action={{@onClose}}
+ @icon="xmark"
+ class="btn-transparent btn-small workflows-node-panel__close"
+ />
+ </div>
+
+ <div class="workflows-node-panel__search">
+ {{dIcon "magnifying-glass"}}
+ <input
+ type="text"
+ placeholder={{i18n "discourse_workflows.add_node.search"}}
+ value={{@searchTerm}}
+ class="workflows-node-panel__search-input"
+ {{dAutoFocus}}
+ {{on "input" this.handleSearchInput}}
+ {{on "keydown" this.handleSearchKeyDown}}
+ />
+ </div>
+
+ <div class="workflows-node-panel__list">
+ {{#if this.showCategories}}
+ {{#each this.categories as |category|}}
+ <button
+ type="button"
+ class="workflows-node-panel__category"
+ {{on "click" (fn this.selectCategory category)}}
+ >
+ <span class="workflows-node-panel__category-icon">
+ {{dIcon category.icon}}
+ </span>
+ <span class="workflows-node-panel__category-name">
+ {{category.label}}
+ </span>
+ <span class="workflows-node-panel__category-arrow">
+ {{dIcon "chevron-right"}}
+ </span>
+ </button>
+ {{/each}}
+ {{else if this.showCategoryNodes}}
+ {{#each this.categoryNodeTypes as |nodeType|}}
+ <NodeTypeItem
+ @presenter={{nodeTypePresenter nodeType}}
+ @onClick={{fn this.handleNodeItemClick nodeType}}
+ />
+ {{/each}}
+ {{else if this.showOperations}}
+ {{#each this.selectedOperationPresenter.operations as |operation|}}
+ <OperationItem
+ @presenter={{this.selectedOperationPresenter}}
+ @operation={{operation.value}}
+ @onClick={{fn
+ this.selectOperation
+ this.selectedOperationNodeType
+ operation.value
+ }}
+ />
+ {{/each}}
+ {{else if this.showSearchResults}}
+ {{#each this.availableNodeTypes as |nodeType|}}
+ <NodeTypeItem
+ @presenter={{nodeTypePresenter nodeType}}
+ @onClick={{fn this.handleNodeItemClick nodeType}}
+ />
+ {{/each}}
+ {{/if}}
+ </div>
+ </div>
+ </template>
+}
diff --git a/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/canvas/rete-editor.js b/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/canvas/rete-editor.js
new file mode 100644
index 00000000000..905ee42d46e
--- /dev/null
+++ b/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/canvas/rete-editor.js
@@ -0,0 +1,855 @@
+import loadRete from "discourse/lib/load-rete";
+import {
+ buildConnectedOutputsIndex,
+ buildOutgoingIndex,
+ buildWorkflowGraphIndex,
+ graphConnectionKey,
+ LOOP_OUTPUT,
+ normalizeSourceOutput,
+ normalizeSourceOutputIndex,
+ normalizeTargetInput,
+ normalizeTargetInputIndex,
+} from "../../../lib/workflows/graph-constants";
+import {
+ nodeTypeInputs,
+ nodeTypeOutputKeys,
+} from "../../../lib/workflows/node-types";
+import {
+ NODE_WIDTH,
+ nodeHeight,
+ nodeLabel,
+ nodeWidth,
+} from "../../../lib/workflows/node-utils";
+import { createCustomRenderer } from "./custom-renderer";
+
+export class ReteEditorBridge {
+ static async create(container, { callbacks, nodeTypes = [] }) {
+ const {
+ ClassicPreset,
+ NodeEditor,
+ Scope,
+ AreaPlugin,
+ AreaExtensions,
+ ConnectionPlugin,
+ ConnectionPresets,
+ Zoom,
+ AutoArrangePlugin,
+ ArrangePresets,
+ classicConnectionPath,
+ getElementCenter,
+ } = await loadRete();
+
+ const socket = new ClassicPreset.Socket("workflow");
+ const nodeTypesByIdentifier = new Map(
+ (nodeTypes || []).flatMap((nodeType) => [
+ [nodeType.name, nodeType],
+ [nodeType.identifier, nodeType],
+ ])
+ );
+ const getNodeWidth = (data) =>
+ nodeWidth(data, {
+ nodeType: nodeTypesByIdentifier.get(data.type),
+ });
+ const getNodeHeight = (data) =>
+ nodeHeight(data, nodeTypesByIdentifier.get(data.type));
+ const getNodeLabel = (data) =>
+ nodeLabel(data, nodeTypesByIdentifier.get(data.type));
+ const inputKeysFor = (data) =>
+ data.type?.startsWith("trigger:")
+ ? []
+ : nodeTypeInputs(
+ nodeTypesByIdentifier.get(data.type) || data.type,
+ data
+ ).map((input) => input.key || "main");
+
+ class WorkflowNode extends ClassicPreset.Node {
+ constructor(data) {
+ super(getNodeLabel(data) || data.name || "Node");
+ this.id = data.clientId;
+ this.workflowData = data;
+ this.width = getNodeWidth(data);
+ this.height = getNodeHeight(data);
+
+ if (!data.type?.startsWith("trigger:")) {
+ for (const input of nodeTypeInputs(
+ nodeTypesByIdentifier.get(data.type) || data.type,
+ data
+ )) {
+ const key = input.key || "main";
+ this.addInput(
+ key,
+ new ClassicPreset.Input(
+ socket,
+ key === "main" ? "" : key,
+ data.type === "flow:loop_over_items" ||
+ (data.type === "flow:merge" &&
+ (data.configuration?.mode || "append") === "append")
+ )
+ );
+ }
+ }
+
+ for (const key of nodeTypeOutputKeys(
+ nodeTypesByIdentifier.get(data.type) || data.type,
+ data
+ )) {
+ this.addOutput(key, new ClassicPreset.Output(socket, key, true));
+ }
+ }
+ }
+
+ const CustomRenderer = createCustomRenderer(
+ Scope,
+ getElementCenter,
+ classicConnectionPath
+ );
+
+ const editor = new NodeEditor();
+ const area = new AreaPlugin(container);
+ const connectionPlugin = new ConnectionPlugin();
+ const renderer = new CustomRenderer();
+ renderer.onManualTrigger = callbacks.onManualTrigger;
+
+ connectionPlugin.addPreset(ConnectionPresets.classic.setup());
+
+ const arrange = new AutoArrangePlugin();
+ arrange.addPreset(ArrangePresets.classic.setup());
+
+ editor.use(area);
+ area.use(connectionPlugin);
+ area.use(renderer);
+ area.use(arrange);
+ area.area.setZoomHandler(new Zoom(0.05));
+
+ AreaExtensions.simpleNodesOrder(area);
+
+ class ToggleSelector extends AreaExtensions.Selector {
+ async add(entity, accumulate) {
+ if (accumulate && this.entities.has(`${entity.label}_${entity.id}`)) {
+ await this.remove(entity);
+ return;
+ }
+ await super.add(entity, accumulate);
+ }
+ }
+
+ const selector = new ToggleSelector();
+ let shiftPressed = false;
+ const shiftAbort = new AbortController();
+ const opts = { signal: shiftAbort.signal };
+ document.addEventListener(
+ "keydown",
+ (e) => {
+ if (e.key === "Shift") {
+ shiftPressed = true;
+ }
+ },
+ opts
+ );
+ document.addEventListener(
+ "keyup",
+ (e) => {
+ if (e.key === "Shift") {
+ shiftPressed = false;
+ }
+ },
+ opts
+ );
+ document.addEventListener(
+ "visibilitychange",
+ () => {
+ shiftPressed = false;
+ },
+ opts
+ );
+ const accumulating = { active: () => shiftPressed };
+
+ area.addPipe((context) => {
+ if (context.type === "pointerdown") {
+ const target = context.data.event.target;
+ if (target?.closest?.(".workflow-sticky-note")) {
+ return;
+ }
+ }
+ return context;
+ });
+
+ const selectableNodes = AreaExtensions.selectableNodes(area, selector, {
+ accumulating,
+ });
+
+ const bridge = new ReteEditorBridge({
+ editor,
+ area,
+ renderer,
+ selector,
+ selectableNodes,
+ connectionPlugin,
+ arrange,
+ container,
+ callbacks,
+ WorkflowNode,
+ ClassicPreset,
+ AreaExtensions,
+ accumulating,
+ shiftAbort,
+ getNodeWidth,
+ getNodeHeight,
+ getNodeLabel,
+ inputKeysFor,
+ });
+
+ renderer.onNodeDelete = (clientId) => {
+ if (!bridge.isSyncing) {
+ callbacks.onNodeDelete?.(clientId);
+ }
+ };
+
+ bridge.setupPipes();
+ return bridge;
+ }
+
+ constructor({
+ editor,
+ area,
+ renderer,
+ selector,
+ selectableNodes,
+ connectionPlugin,
+ arrange,
+ container,
+ callbacks,
+ WorkflowNode,
+ ClassicPreset,
+ AreaExtensions,
+ accumulating,
+ shiftAbort,
+ getNodeWidth,
+ getNodeHeight,
+ getNodeLabel,
+ inputKeysFor,
+ }) {
+ this.editor = editor;
+ this.area = area;
+ this.renderer = renderer;
+ this.selector = selector;
+ this.selectableNodes = selectableNodes;
+ this.connectionPlugin = connectionPlugin;
+ this.arrange = arrange;
+ this.container = container;
+ this.callbacks = callbacks;
+ this.accumulating = accumulating;
+ this.shiftAbort = shiftAbort;
+ this.WorkflowNode = WorkflowNode;
+ this.ClassicPreset = ClassicPreset;
+ this.AreaExtensions = AreaExtensions;
+ this.getNodeWidth = getNodeWidth;
+ this.getNodeHeight = getNodeHeight;
+ this.getNodeLabel = getNodeLabel;
+ this.inputKeysFor = inputKeysFor;
+ this.isSyncing = false;
+ this.isAutoArranging = false;
+ this.wasDragging = false;
+ this.lastPickedId = null;
+ this.lastPickedTime = 0;
+ }
+
+ setupPipes() {
+ this.area.addPipe((context) => {
+ if (this.isSyncing || this.isAutoArranging) {
+ return context;
+ }
+
+ switch (context.type) {
+ case "nodetranslated":
+ this.callbacks.onNodeDragged?.(
+ context.data.id,
+ context.data.position
+ );
+ if (!this.wasDragging) {
+ this.container.classList.add("is-dragging");
+ }
+ this.wasDragging = true;
+ // falls through to emit transform
+ case "translated":
+ case "zoomed": {
+ const { x, y, k } = this.area.area.transform;
+ this.callbacks.onTransformChanged?.({ x, y, k });
+ break;
+ }
+
+ case "nodepicked": {
+ this.callbacks.onNodePicked?.();
+ const now = Date.now();
+ const pickedId = context.data.id;
+ if (
+ pickedId === this.lastPickedId &&
+ now - this.lastPickedTime < 500
+ ) {
+ this.callbacks.onNodeDoubleClick?.(pickedId);
+ this.lastPickedId = null;
+ } else {
+ this.lastPickedId = pickedId;
+ }
+ this.lastPickedTime = now;
+ break;
+ }
+
+ case "pointerup":
+ if (this.wasDragging) {
+ this.wasDragging = false;
+ this.container.classList.remove("is-dragging");
+ this.callbacks.onNodeDragEnd?.();
+ }
+ break;
+
+ case "pointerdown": {
+ const target = context.data.event.target;
+ if (!target?.closest?.(".workflow-rete-node")) {
+ this.callbacks.onCanvasPointerDown?.(context.data.event);
+ }
+ break;
+ }
+ }
+
+ return context;
+ });
+
+ this.connectionPlugin.addPipe((context) => {
+ if (context.type === "connectionpick") {
+ const pickedSide = context.data.socket?.side;
+ this.container.classList.add("is-connection-dragging");
+ this.updateInvalidConnectionTargets(pickedSide);
+ } else if (context.type === "connectiondrop") {
+ this.container.classList.remove("is-connection-dragging");
+ this.clearInvalidConnectionTargets();
+ }
+ return context;
+ });
+
+ this.editor.addPipe((context) => {
+ if (this.isSyncing) {
+ return context;
+ }
+
+ if (
+ context.type === "connectioncreated" ||
+ context.type === "connectionremoved"
+ ) {
+ this.updateRendererGraphIndex();
+ this.renderer.scheduleConnectionUpdate();
+
+ if (context.type === "connectioncreated") {
+ const conn = context.data;
+ this.callbacks.onConnectionCreated?.(
+ conn.source,
+ conn.sourceOutput,
+ conn.target,
+ conn.targetInput
+ );
+ }
+ }
+
+ return context;
+ });
+ }
+
+ clearInvalidConnectionTargets() {
+ for (const socket of this.container.querySelectorAll(
+ ".workflow-rete-node__socket.is-invalid-connection-target"
+ )) {
+ socket.classList.remove("is-invalid-connection-target");
+ }
+ }
+
+ updateInvalidConnectionTargets(pickedSide) {
+ this.clearInvalidConnectionTargets();
+
+ if (!pickedSide) {
+ return;
+ }
+
+ for (const socket of this.container.querySelectorAll(
+ ".workflow-rete-node__socket"
+ )) {
+ const socketSide = socket.classList.contains("--input")
+ ? "input"
+ : "output";
+ const isLoopSocket = socket.classList.contains("--loop");
+
+ socket.classList.toggle(
+ "is-invalid-connection-target",
+ isLoopSocket || socketSide === pickedSide
+ );
+ }
+ }
+
+ getSelectedIds() {
+ const nodeIds = new Set();
+ const stickyNoteIds = new Set();
+ for (const entity of this.selector.entities.values()) {
+ if (entity.label === "sticky-note") {
+ stickyNoteIds.add(entity.id);
+ } else {
+ nodeIds.add(entity.id);
+ }
+ }
+ return { nodeIds, stickyNoteIds };
+ }
+
+ async selectStickyNote(clientId, stickyCallbacks) {
+ const accumulate = this.accumulating.active();
+ const entityKey = `sticky-note_${clientId}`;
+
+ if (this.selector.entities.has(entityKey)) {
+ this.selector.pick({ id: clientId, label: "sticky-note" });
+ return;
+ }
+
+ this.selector.pick({ id: clientId, label: "sticky-note" });
+ await this.selector.add(
+ {
+ label: "sticky-note",
+ id: clientId,
+ translate(dx, dy) {
+ stickyCallbacks.onStickyNoteTranslate?.(clientId, dx, dy);
+ },
+ unselect() {
+ stickyCallbacks.onStickyNoteUnselect?.(clientId);
+ },
+ },
+ accumulate
+ );
+ }
+
+ isStickyNoteSelected(clientId) {
+ return this.selector.entities.has(`sticky-note_${clientId}`);
+ }
+
+ async translateSelectedEntities(draggedId, draggedLabel, dx, dy) {
+ for (const entity of this.selector.entities.values()) {
+ if (entity.id === draggedId && entity.label === draggedLabel) {
+ continue;
+ }
+ await entity.translate(dx, dy);
+ }
+ }
+
+ connectionKeyFromClientIds(connection) {
+ return graphConnectionKey({
+ source: connection.sourceClientId,
+ sourceOutputIndex: normalizeSourceOutputIndex(connection),
+ target: connection.targetClientId,
+ targetInputIndex: normalizeTargetInputIndex(connection),
+ });
+ }
+
+ outputKeyFor(sourceNode, connection) {
+ return (
+ Object.keys(sourceNode.outputs || {})[
+ normalizeSourceOutputIndex(connection)
+ ] || normalizeSourceOutput(connection.sourceOutput)
+ );
+ }
+
+ inputKeyFor(targetNode, connection) {
+ return (
+ Object.keys(targetNode.inputs || {})[
+ normalizeTargetInputIndex(connection)
+ ] || normalizeTargetInput(connection.targetInput)
+ );
+ }
+
+ buildDesiredGraphConnections(connections) {
+ const graphConnections = [];
+ const seen = new Set();
+
+ for (const connection of connections) {
+ const sourceNode = this.editor.getNode(connection.sourceClientId);
+ const targetNode = this.editor.getNode(connection.targetClientId);
+ if (!sourceNode || !targetNode) {
+ continue;
+ }
+
+ const key = this.connectionKeyFromClientIds(connection);
+ if (seen.has(key)) {
+ continue;
+ }
+
+ seen.add(key);
+ graphConnections.push({
+ source: connection.sourceClientId,
+ sourceOutput: this.outputKeyFor(sourceNode, connection),
+ sourceOutputIndex: normalizeSourceOutputIndex(connection),
+ target: connection.targetClientId,
+ targetInput: this.inputKeyFor(targetNode, connection),
+ targetInputIndex: normalizeTargetInputIndex(connection),
+ });
+ }
+
+ return graphConnections;
+ }
+
+ updateRendererGraphIndex(connections = this.editor.getConnections()) {
+ this.renderer.graphIndex = buildWorkflowGraphIndex(
+ this.editor.getNodes().map((node) => ({
+ id: node.id,
+ type: node.workflowData.type,
+ })),
+ connections
+ );
+ }
+
+ async addNode(data) {
+ const node = new this.WorkflowNode(data);
+ await this.editor.addNode(node);
+ if (data.position) {
+ await this.area.translate(node.id, data.position);
+ }
+ return node;
+ }
+
+ async removeNode(clientId) {
+ if (!this.editor.getNode(clientId)) {
+ return;
+ }
+
+ const connections = this.editor
+ .getConnections()
+ .filter((c) => c.source === clientId || c.target === clientId);
+ for (const conn of connections) {
+ await this.editor.removeConnection(conn.id);
+ }
+ await this.editor.removeNode(clientId);
+ }
+
+ async addConnection(
+ sourceClientId,
+ sourceOutput,
+ targetClientId,
+ targetInput = "main",
+ sourceOutputIndex = null,
+ targetInputIndex = null
+ ) {
+ const sourceNode = this.editor.getNode(sourceClientId);
+ const targetNode = this.editor.getNode(targetClientId);
+ if (!sourceNode || !targetNode) {
+ return;
+ }
+
+ await this.editor.addConnection(
+ new this.ClassicPreset.Connection(
+ sourceNode,
+ this.outputKeyFor(sourceNode, { sourceOutput, sourceOutputIndex }),
+ targetNode,
+ this.inputKeyFor(targetNode, { targetInput, targetInputIndex })
+ )
+ );
+ }
+
+ async syncState(nodes, connections) {
+ this.isSyncing = true;
+ try {
+ const targetClientIds = new Set(nodes.map((n) => n.clientId));
+
+ for (const node of [...this.editor.getNodes()]) {
+ if (!targetClientIds.has(node.id)) {
+ await this.removeNode(node.id);
+ }
+ }
+
+ for (const nodeData of nodes) {
+ const reteNode = this.editor.getNode(nodeData.clientId);
+
+ if (!reteNode) {
+ await this.addNode(nodeData);
+ continue;
+ }
+
+ const currentInputKeys = Object.keys(reteNode.inputs || {});
+ const nextInputKeys = this.inputKeysFor(nodeData);
+ const inputsChanged =
+ currentInputKeys.length !== nextInputKeys.length ||
+ currentInputKeys.some((key, index) => key !== nextInputKeys[index]);
+
+ if (reteNode.workflowData.type !== nodeData.type || inputsChanged) {
+ await this.removeNode(nodeData.clientId);
+ await this.addNode(nodeData);
+ continue;
+ }
+
+ if (nodeData.position && !this.wasDragging) {
+ const view = this.area.nodeViews.get(nodeData.clientId);
+ if (view) {
+ const pos = view.position;
+ if (
+ Math.abs(pos.x - nodeData.position.x) > 0.5 ||
+ Math.abs(pos.y - nodeData.position.y) > 0.5
+ ) {
+ await this.area.translate(nodeData.clientId, nodeData.position);
+ }
+ }
+ }
+
+ const newLabel =
+ this.getNodeLabel(nodeData) || nodeData.name || reteNode.label;
+ const newWidth = this.getNodeWidth(nodeData);
+ const newHeight = this.getNodeHeight(nodeData);
+ const needsUpdate =
+ reteNode.label !== newLabel ||
+ reteNode.width !== newWidth ||
+ reteNode.height !== newHeight ||
+ JSON.stringify(reteNode.workflowData.configuration) !==
+ JSON.stringify(nodeData.configuration);
+
+ reteNode.workflowData = nodeData;
+ reteNode.label = newLabel;
+ reteNode.width = newWidth;
+ reteNode.height = newHeight;
+
+ if (needsUpdate && !this.wasDragging) {
+ this.area.update("node", reteNode.id);
+ }
+ }
+
+ const desiredGraphConnections =
+ this.buildDesiredGraphConnections(connections);
+ this.updateRendererGraphIndex(desiredGraphConnections);
+
+ const desiredConnectionKeys = new Set(
+ connections.map((c) => this.connectionKeyFromClientIds(c))
+ );
+ const existingConnections = this.editor.getConnections();
+ const existingConnectionKeys = new Map();
+
+ for (const connection of existingConnections) {
+ const key = graphConnectionKey(connection);
+
+ if (!desiredConnectionKeys.has(key)) {
+ await this.editor.removeConnection(connection.id);
+ continue;
+ }
+
+ existingConnectionKeys.set(key, connection.id);
+ }
+
+ for (const connection of connections) {
+ const key = this.connectionKeyFromClientIds(connection);
+
+ if (existingConnectionKeys.has(key)) {
+ continue;
+ }
+
+ await this.addConnection(
+ connection.sourceClientId,
+ normalizeSourceOutput(connection.sourceOutput),
+ connection.targetClientId,
+ normalizeTargetInput(connection.targetInput),
+ normalizeSourceOutputIndex(connection),
+ normalizeTargetInputIndex(connection)
+ );
+ existingConnectionKeys.set(key, true);
+ }
+ } finally {
+ this.isSyncing = false;
+ }
+
+ this.renderer.scheduleConnectionUpdate();
+ }
+
+ async fitToView(extraRects) {
+ const nodes = this.editor.getNodes();
+ if (nodes.length === 0) {
+ return;
+ }
+
+ const bbox = this.AreaExtensions.getBoundingBox(this.area, nodes);
+ let { left: minX, top: minY, right: maxX, bottom: maxY } = bbox;
+
+ const connectedOutputs = buildConnectedOutputsIndex(
+ this.editor.getConnections()
+ );
+ for (const node of nodes) {
+ const nodeConns = connectedOutputs.get(node.id);
+ if (
+ !Object.keys(node.outputs).some((key, outputIndex) => {
+ return key !== "loop" && !nodeConns?.has(outputIndex);
+ })
+ ) {
+ continue;
+ }
+ const view = this.area.nodeViews.get(node.id);
+ if (view) {
+ maxX = Math.max(maxX, view.position.x + (node.width || 0) + 48);
+ }
+ }
+
+ for (const rect of extraRects || []) {
+ minX = Math.min(minX, rect.x);
+ minY = Math.min(minY, rect.y);
+ maxX = Math.max(maxX, rect.x + rect.width);
+ maxY = Math.max(maxY, rect.y + rect.height);
+ }
+
+ const bw = maxX - minX;
+ const bh = maxY - minY;
+ if (bw === 0 && bh === 0) {
+ return;
+ }
+
+ const cx = (minX + maxX) / 2;
+ const cy = (minY + maxY) / 2;
+ const w = this.container.clientWidth;
+ const h = this.container.clientHeight;
+
+ const padding = 0.9;
+ const kw = bw > 0 ? w / bw : 1;
+ const kh = bh > 0 ? h / bh : 1;
+ const k = Math.min(kw * padding, kh * padding, 1.5);
+
+ this.area.area.transform.x = w / 2 - cx * k;
+ this.area.area.transform.y = h / 2 - cy * k;
+ await this.area.area.zoom(k, 0, 0);
+ }
+
+ async zoomAtViewportCenter(newK) {
+ const t = this.area.area.transform;
+ const cx = this.container.clientWidth / 2;
+ const cy = this.container.clientHeight / 2;
+ const ox = (cx - t.x) * (1 - newK / t.k);
+ const oy = (cy - t.y) * (1 - newK / t.k);
+ await this.area.area.zoom(newK, ox, oy);
+ }
+
+ async autoArrange() {
+ this.isAutoArranging = true;
+ try {
+ const allConns = this.editor.getConnections();
+ const outgoing = buildOutgoingIndex(allConns, "source");
+ const loopBodyIds = new Set(
+ this.renderer.graphIndex.loopOwnerByNodeId.keys()
+ );
+
+ const removedConns = allConns.filter(
+ (c) =>
+ c.source === c.target ||
+ loopBodyIds.has(c.source) ||
+ loopBodyIds.has(c.target) ||
+ (c.sourceOutput === LOOP_OUTPUT && c.source !== c.target)
+ );
+ for (const conn of removedConns) {
+ await this.editor.removeConnection(conn.id);
+ }
+
+ await this.arrange.layout({
+ options: {
+ "elk.algorithm": "layered",
+ "elk.direction": "RIGHT",
+ "elk.spacing.nodeNode": "30",
+ "elk.layered.spacing.nodeNodeBetweenLayers": "20",
+ },
+ });
+
+ for (const conn of removedConns) {
+ await this.editor.addConnection(conn);
+ }
+
+ const loopBodies = new Map();
+ for (const [nodeId, owner] of this.renderer.graphIndex
+ .loopOwnerByNodeId) {
+ if (!loopBodies.has(owner)) {
+ loopBodies.set(owner, new Set());
+ }
+ loopBodies.get(owner).add(nodeId);
+ }
+
+ for (const [loopId, bodyIds] of loopBodies) {
+ const loopView = this.area.nodeViews.get(loopId);
+ if (!loopView) {
+ continue;
+ }
+
+ const ordered = [];
+ const visited = new Set();
+ let current = allConns.find(
+ (c) =>
+ c.source === loopId &&
+ c.sourceOutput === LOOP_OUTPUT &&
+ c.target !== loopId
+ )?.target;
+ while (current && bodyIds.has(current) && !visited.has(current)) {
+ ordered.push(current);
+ visited.add(current);
+ current = outgoing
+ .get(current)
+ ?.find((c) => c.target !== loopId)?.target;
+ }
+
+ ordered.reverse();
+ const orderedNodes = ordered
+ .map((id) => this.editor.getNode(id))
+ .filter(Boolean);
+ const totalWidth =
+ orderedNodes.reduce(
+ (width, node) => width + (node.width || NODE_WIDTH),
+ 0
+ ) +
+ Math.max(0, orderedNodes.length - 1) * 50;
+ let currentX = loopView.position.x + (NODE_WIDTH - totalWidth) / 2;
+
+ for (const bodyNode of orderedNodes) {
+ const bodyView = this.area.nodeViews.get(bodyNode.id);
+ if (bodyView) {
+ await bodyView.translate(currentX, loopView.position.y + 160);
+ }
+ currentX += (bodyNode.width || NODE_WIDTH) + 50;
+ }
+ }
+
+ const positions = new Map();
+ for (const node of this.editor.getNodes()) {
+ const view = this.area.nodeViews.get(node.id);
+ if (view) {
+ positions.set(node.id, { x: view.position.x, y: view.position.y });
+ }
+ }
+ return positions;
+ } finally {
+ this.isAutoArranging = false;
+ }
+ }
+
+ get areaContentElement() {
+ return this.area.area.content.holder;
+ }
+
+ get transform() {
+ const { x, y, k } = this.area.area.transform;
+ return { x, y, k };
+ }
+
+ get nodeCount() {
+ return this.editor.getNodes().length;
+ }
+
+ containerToCanvas(localX, localY) {
+ const { x, y, k } = this.area.area.transform;
+ return { canvasX: (localX - x) / k, canvasY: (localY - y) / k };
+ }
+
+ viewportCenter() {
+ const rect = this.container.getBoundingClientRect();
+ return this.containerToCanvas(rect.width / 2, rect.height / 2);
+ }
+
+ destroy() {
+ this.shiftAbort?.abort();
+ this.renderer.cancelScheduledConnectionUpdate();
+ this.renderer.destroyMeasureSvg();
+ this.area.destroy();
+ }
+}
+
+export async function createReteEditor(container, options) {
+ return ReteEditorBridge.create(container, options);
+}
diff --git a/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/canvas/rete-path-utils.js b/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/canvas/rete-path-utils.js
new file mode 100644
index 00000000000..70e02557165
--- /dev/null
+++ b/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/canvas/rete-path-utils.js
@@ -0,0 +1,26 @@
+export function loopBodyPath(start, end, side) {
+ const dy = end.y - start.y;
+ const bow = Math.max(40, Math.abs(dy) * 0.25);
+ const offset = side === "right" ? bow : -bow;
+
+ return `M ${start.x} ${start.y} C ${start.x + offset} ${start.y}, ${end.x + offset} ${end.y}, ${end.x} ${end.y}`;
+}
+
+export function loopBackLayout(start, end, padding = 40) {
+ const bottomY = Math.max(start.y, end.y) + padding;
+ const midX = (start.x + end.x) / 2;
+
+ return {
+ d: [
+ `M ${start.x} ${start.y}`,
+ `C ${start.x + 20} ${start.y}, ${start.x + 20} ${bottomY}, ${start.x} ${bottomY}`,
+ `L ${end.x} ${bottomY}`,
+ `C ${end.x - 20} ${bottomY}, ${end.x - 20} ${end.y}, ${end.x} ${end.y}`,
+ ].join(" "),
+ arrowPoints: `${midX},${bottomY} ${midX + 4},${bottomY + 6} ${midX - 4},${bottomY + 6}`,
+ buttonPosition: {
+ x: midX - 14,
+ y: bottomY + 8,
+ },
+ };
+}
diff --git a/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/canvas/sticky-note.gjs b/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/canvas/sticky-note.gjs
new file mode 100644
index 00000000000..f74c0430d5d
--- /dev/null
+++ b/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/canvas/sticky-note.gjs
@@ -0,0 +1,286 @@
+import Component from "@glimmer/component";
+import { tracked } from "@glimmer/tracking";
+import { fn } from "@ember/helper";
+import { on } from "@ember/modifier";
+import { action } from "@ember/object";
+import { trustHTML } from "@ember/template";
+import DMenu from "discourse/float-kit/components/d-menu";
+import DTooltip from "discourse/float-kit/components/d-tooltip";
+import { eq } from "discourse/truth-helpers";
+import DCookText from "discourse/ui-kit/d-cook-text";
+import dConcatClass from "discourse/ui-kit/helpers/d-concat-class";
+import dIcon from "discourse/ui-kit/helpers/d-icon";
+import dAutoFocus from "discourse/ui-kit/modifiers/d-auto-focus";
+import { i18n } from "discourse-i18n";
+import CanvasHoverToolbar from "./hover-toolbar";
+
+const COLORS = ["yellow", "blue", "green", "pink", "purple", "orange"].map(
+ (name) => ({
+ name,
+ bg: `var(--workflow-sticky-${name})`,
+ border: `var(--workflow-sticky-${name}-border)`,
+ })
+);
+
+const MIN_WIDTH = 140;
+const MIN_HEIGHT = 80;
+const RESIZE_EDGES = ["n", "s", "w", "e", "nw", "ne", "sw", "se"];
+
+function swatchStyle(colorBg) {
+ return trustHTML(`background:${colorBg}`);
+}
+
+function stopPropagation(event) {
+ event.stopPropagation();
+}
+
+export default class StickyNote extends Component {
+ @tracked isEditing = false;
+ colorOptions = COLORS;
+ resizeEdges = RESIZE_EDGES;
+
+ get style() {
+ const { position, size, color } = this.args.note;
+ const match = COLORS.find((c) => c.name === color) || COLORS[0];
+ const x = Number(position.x) || 0;
+ const y = Number(position.y) || 0;
+ const w = Number(size.width) || 200;
+ const h = Number(size.height) || 150;
+ return trustHTML(
+ `left:${x}px;top:${y}px;width:${w}px;height:${h}px;background:${match.bg};border-color:${match.border};`
+ );
+ }
+
+ #startDrag(event, { onMove, onEnd }) {
+ event.stopPropagation();
+ event.preventDefault();
+ const zoom = this.args.zoom ?? 1;
+ const startX = event.clientX;
+ const startY = event.clientY;
+
+ const moveHandler = (e) => {
+ const dx = (e.clientX - startX) / zoom;
+ const dy = (e.clientY - startY) / zoom;
+ onMove(dx, dy);
+ };
+
+ const upHandler = () => {
+ document.removeEventListener("pointermove", moveHandler);
+ document.removeEventListener("pointerup", upHandler);
+ onEnd?.();
+ };
+
+ document.addEventListener("pointermove", moveHandler);
+ document.addEventListener("pointerup", upHandler);
+ }
+
+ @action
+ handlePointerDown(event) {
+ if (
+ event.target.closest(".workflow-sticky-note__edge") ||
+ event.target.closest(".workflow-canvas-toolbar") ||
+ event.target.tagName === "TEXTAREA"
+ ) {
+ return;
+ }
+
+ this.args.onSelect?.();
+ this.args.onBeforeMutation?.();
+
+ const { x, y } = this.args.note.position;
+ let prevDx = 0;
+ let prevDy = 0;
+ this.#startDrag(event, {
+ onMove: (dx, dy) => {
+ this.args.onMove?.({ x: x + dx, y: y + dy });
+ const incrementalDx = dx - prevDx;
+ const incrementalDy = dy - prevDy;
+ if (incrementalDx !== 0 || incrementalDy !== 0) {
+ this.args.onTranslateSelected?.(incrementalDx, incrementalDy);
+ }
+ prevDx = dx;
+ prevDy = dy;
+ },
+ onEnd: () => this.args.onAfterMutation?.(),
+ });
+ }
+
+ @action
+ handleResizePointerDown(event) {
+ const edge = event.target.dataset.edge;
+ if (!edge) {
+ return;
+ }
+
+ this.args.onBeforeMutation?.();
+
+ const { width, height } = this.args.note.size;
+ const { x, y } = this.args.note.position;
+ const resizeN = edge.includes("n");
+ const resizeS = edge.includes("s");
+ const resizeW = edge.includes("w");
+ const resizeE = edge.includes("e");
+
+ this.#startDrag(event, {
+ onMove: (dx, dy) => {
+ let newW = width;
+ let newH = height;
+ let newX = x;
+ let newY = y;
+
+ if (resizeE) {
+ newW = Math.max(MIN_WIDTH, width + dx);
+ }
+ if (resizeS) {
+ newH = Math.max(MIN_HEIGHT, height + dy);
+ }
+ if (resizeW) {
+ newW = Math.max(MIN_WIDTH, width - dx);
+ newX = x + width - newW;
+ }
+ if (resizeN) {
+ newH = Math.max(MIN_HEIGHT, height - dy);
+ newY = y + height - newH;
+ }
+
+ this.args.onResize?.({ width: newW, height: newH });
+ this.args.onMove?.({ x: newX, y: newY });
+ },
+ onEnd: () => this.args.onAfterMutation?.(),
+ });
+ }
+
+ @action
+ startEditing(event) {
+ event.stopPropagation();
+ this.args.onBeforeMutation?.();
+ this.isEditing = true;
+ }
+
+ @action
+ handleTextInput(event) {
+ this.args.onUpdateText?.(event.target.value);
+ }
+
+ @action
+ stopEditing() {
+ this.isEditing = false;
+ this.args.onAfterMutation?.();
+ }
+
+ @action
+ selectColor(colorName, close) {
+ this.args.onChangeColor?.(colorName);
+ close();
+ this.args.onAfterMutation?.();
+ }
+
+ @action
+ handleDelete(event) {
+ event.stopPropagation();
+ this.args.onDelete?.();
+ }
+
+ <template>
+ {{! eslint-disable ember/template-no-pointer-down-event-binding, ember/template-no-invalid-interactive }}
+ <div
+ class={{dConcatClass
+ "workflow-sticky-note"
+ (if @isSelected "is-selected")
+ }}
+ style={{this.style}}
+ {{on "pointerdown" this.handlePointerDown}}
+ {{on "dblclick" this.startEditing}}
+ >
+ <CanvasHoverToolbar>
+ <DTooltip
+ @identifier="sticky-note-change-color"
+ @content={{i18n "discourse_workflows.sticky_note.change_color"}}
+ >
+ <:trigger>
+ <DMenu
+ @identifier="sticky-note-color-picker"
+ @inline={{true}}
+ class="workflow-canvas-toolbar__btn"
+ >
+ <:trigger>
+ {{dIcon "palette"}}
+ </:trigger>
+ <:content as |args|>
+ <div class="workflow-sticky-note__color-picker">
+ {{#each this.colorOptions as |colorOpt|}}
+ <button
+ type="button"
+ class={{dConcatClass
+ "workflow-sticky-note__color-swatch"
+ (if (eq @note.color colorOpt.name) "is-active")
+ }}
+ style={{swatchStyle colorOpt.bg}}
+ title={{colorOpt.name}}
+ {{on
+ "click"
+ (fn this.selectColor colorOpt.name args.close)
+ }}
+ />
+ {{/each}}
+ </div>
+ </:content>
+ </DMenu>
+ </:trigger>
+ </DTooltip>
+ <DTooltip
+ @identifier="sticky-note-delete"
+ @content={{i18n "discourse_workflows.sticky_note.delete"}}
+ >
+ <:trigger>
+ <button
+ type="button"
+ class="workflow-canvas-toolbar__btn"
+ {{on "pointerdown" stopPropagation}}
+ {{on "click" this.handleDelete}}
+ >
+ {{dIcon "trash-can"}}
+ </button>
+ </:trigger>
+ </DTooltip>
+ </CanvasHoverToolbar>
+
+ <div class="workflow-sticky-note__content">
+ {{#if this.isEditing}}
+ <textarea
+ class="workflow-sticky-note__textarea"
+ value={{@note.text}}
+ placeholder={{i18n "discourse_workflows.sticky_note.placeholder"}}
+ {{dAutoFocus}}
+ {{on "input" this.handleTextInput}}
+ {{on "blur" this.stopEditing}}
+ {{on "keydown" stopPropagation}}
+ {{on "pointerdown" stopPropagation}}
+ />
+ {{else}}
+ <div class="workflow-sticky-note__text">
+ {{#if @note.text}}
+ <DCookText @rawText={{@note.text}} />
+ {{else}}
+ <span class="workflow-sticky-note__placeholder">
+ {{i18n "discourse_workflows.sticky_note.placeholder"}}
+ </span>
+ {{/if}}
+ </div>
+ {{/if}}
+ </div>
+
+ <div
+ class="workflow-sticky-note__edges"
+ {{on "pointerdown" this.handleResizePointerDown}}
+ >
+ {{#each this.resizeEdges as |edge|}}
+ <div
+ class="workflow-sticky-note__edge --{{edge}}"
+ data-edge={{edge}}
+ />
+ {{/each}}
+ </div>
+ </div>
+ </template>
+}
diff --git a/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/canvas/workflow-node.gjs b/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/canvas/workflow-node.gjs
new file mode 100644
index 00000000000..8c81a0f1039
--- /dev/null
+++ b/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/canvas/workflow-node.gjs
@@ -0,0 +1,384 @@
+import Component from "@glimmer/component";
+import { fn } from "@ember/helper";
+import { on } from "@ember/modifier";
+import { action } from "@ember/object";
+import didInsert from "@ember/render-modifiers/modifiers/did-insert";
+import { service } from "@ember/service";
+import { trustHTML } from "@ember/template";
+import DTooltip from "discourse/float-kit/components/d-tooltip";
+import { eq } from "discourse/truth-helpers";
+import dConcatClass from "discourse/ui-kit/helpers/d-concat-class";
+import dIcon from "discourse/ui-kit/helpers/d-icon";
+import { i18n } from "discourse-i18n";
+import formatNodeIssue from "../../../lib/workflows/format-node-issue";
+import getNodeIssues from "../../../lib/workflows/node-issues";
+import {
+ nodeTypeIcon,
+ nodeTypeInputLabel,
+ nodeTypeIsManuallyTriggerable,
+ nodeTypePortLabel,
+ nodeTypeRunScopeLabelKey,
+ nodeTypeStyle,
+ resolveNodeTypeVersion,
+} from "../../../lib/workflows/node-types";
+import { nodeDescription, nodeLabel } from "../../../lib/workflows/node-utils";
+import CanvasHoverToolbar from "./hover-toolbar";
+
+function resolveType(workflowsNodeTypes, node) {
+ const nodeType = workflowsNodeTypes.findNodeType(node.type);
+ if (!nodeType) {
+ return null;
+ }
+
+ return resolveNodeTypeVersion(nodeType, node.typeVersion);
+}
+
+export function shouldShowManualTrigger(node) {
+ return Boolean(node?.type?.startsWith("trigger:"));
+}
+
+export function shouldEnableManualTrigger(node, nodeType, session) {
+ if (!node?.type?.startsWith("trigger:")) {
+ return false;
+ }
+
+ return Boolean(
+ nodeTypeIsManuallyTriggerable(nodeType, node.typeVersion) ||
+ session?.isNodePinned(node.name)
+ );
+}
+
+export default class WorkflowNode extends Component {
+ @service router;
+ @service workflowsNodeTypes;
+
+ stopPropagation = (e) => e.stopPropagation();
+
+ handleDelete = (e) => {
+ e.stopPropagation();
+ e.preventDefault();
+ this.args.onDelete?.(this.data.clientId);
+ };
+
+ handleManualTrigger = (e) => {
+ e.stopPropagation();
+ this.args.onManualTrigger?.(this.data.clientId);
+ };
+
+ handleOpenIssues = (e) => {
+ e.stopPropagation();
+ e.preventDefault();
+ this.args.onEditNode?.(this.data.clientId);
+ };
+
+ portLabel = (key) => {
+ return nodeTypePortLabel(this.resolvedNodeType, key);
+ };
+
+ formatIssue = (issue) => {
+ return formatNodeIssue(issue, this.resolvedNodeType);
+ };
+
+ get data() {
+ return this.args.node.workflowData;
+ }
+
+ get resolvedNodeType() {
+ return resolveType(this.workflowsNodeTypes, this.data);
+ }
+
+ get isTrigger() {
+ return this.data.type?.startsWith("trigger:");
+ }
+
+ get isBranching() {
+ return Object.keys(this.args.node.outputs).length > 1;
+ }
+
+ get label() {
+ return nodeLabel(this.data, this.resolvedNodeType);
+ }
+
+ get description() {
+ return nodeDescription(this.data);
+ }
+
+ get runScopeLabel() {
+ const labelKey = nodeTypeRunScopeLabelKey(this.resolvedNodeType, this.data);
+ return labelKey ? i18n(labelKey) : null;
+ }
+
+ get outputKeys() {
+ return Object.keys(this.args.node.outputs);
+ }
+
+ get hasMultipleInputs() {
+ return Object.keys(this.args.node.inputs).length > 1;
+ }
+
+ get inputEntries() {
+ return Object.keys(this.args.node.inputs).map((key) => ({
+ key,
+ input: this.args.node.inputs[key],
+ label: nodeTypeInputLabel(this.resolvedNodeType, key, this.data),
+ }));
+ }
+
+ get isUnavailable() {
+ const nodeType = this.resolvedNodeType;
+ return !nodeType || nodeType.available === false;
+ }
+
+ get unavailableReasonKey() {
+ return this.resolvedNodeType?.unavailable_reason_key;
+ }
+
+ get unavailableReason() {
+ return i18n(
+ this.unavailableReasonKey ||
+ "discourse_workflows.node_unavailable.default"
+ );
+ }
+
+ get unavailableLabel() {
+ return i18n("discourse_workflows.node_unavailable.short");
+ }
+
+ get isManuallyTriggerable() {
+ return shouldEnableManualTrigger(
+ this.data,
+ this.resolvedNodeType,
+ this.args.session
+ );
+ }
+
+ get showManualTrigger() {
+ return shouldShowManualTrigger(this.data);
+ }
+
+ get manualTriggerLabel() {
+ return this.isManuallyTriggerable
+ ? i18n("discourse_workflows.manual_trigger.run")
+ : i18n("discourse_workflows.manual_trigger.needs_pin_data");
+ }
+
+ get dataTableId() {
+ if (this.data.type !== "action:data_table") {
+ return null;
+ }
+ return this.data.configuration?.data_table_id;
+ }
+
+ @action
+ handleEditDataTable(e) {
+ e.stopPropagation();
+ e.preventDefault();
+ this.router.transitionTo(
+ "adminPlugins.show.discourse-workflows-data-tables.show",
+ this.dataTableId
+ );
+ }
+
+ get iconBlockStyle() {
+ return nodeTypeStyle(this.resolvedNodeType);
+ }
+
+ get dimensionsStyle() {
+ return trustHTML(
+ `width: ${this.args.node.width}px; height: ${this.args.node.height}px;`
+ );
+ }
+
+ get issues() {
+ const nodeType = this.resolvedNodeType;
+ if (!nodeType || typeof nodeType === "string") {
+ return [];
+ }
+ return getNodeIssues(this.data.configuration, nodeType.properties);
+ }
+
+ <template>
+ {{! eslint-disable ember/template-no-pointer-down-event-binding }}
+ <div
+ class={{dConcatClass
+ "workflow-rete-node"
+ (if this.isTrigger "is-trigger")
+ (if this.isBranching "is-branching")
+ (if @node.selected "is-selected")
+ (if this.isUnavailable "is-unavailable")
+ }}
+ style={{this.dimensionsStyle}}
+ data-client-id={{this.data.clientId}}
+ data-unavailable={{if this.isUnavailable "true" "false"}}
+ >
+ {{#if @node.selected}}
+ {{#if this.runScopeLabel}}
+ <div class="workflow-rete-node__run-scope-tooltip">
+ {{this.runScopeLabel}}
+ </div>
+ {{/if}}
+ {{/if}}
+
+ <div class="workflow-rete-node__icon-row">
+ <div
+ class={{dConcatClass
+ "workflow-rete-node__inputs"
+ (if this.hasMultipleInputs "has-multiple-inputs")
+ }}
+ >
+ {{#each this.inputEntries as |entry|}}
+ <div class="workflow-rete-node__input-row">
+ {{#if this.hasMultipleInputs}}
+ <span class="workflow-rete-node__input-label">
+ {{entry.label}}
+ </span>
+ {{/if}}
+ <div
+ class="workflow-rete-node__socket --input"
+ data-socket-key={{entry.key}}
+ {{didInsert
+ (fn
+ @onSocketRendered
+ @node.id
+ "input"
+ entry.key
+ entry.input.socket
+ )
+ }}
+ />
+ </div>
+ {{/each}}
+ </div>
+
+ <div
+ class="workflow-rete-node__icon-block"
+ style={{this.iconBlockStyle}}
+ >
+ <CanvasHoverToolbar @hoverSelector=".workflow-rete-node">
+ {{#if this.showManualTrigger}}
+ <DTooltip
+ @identifier="workflow-node-manual-trigger"
+ @content={{this.manualTriggerLabel}}
+ >
+ <:trigger>
+ <button
+ type="button"
+ class={{dConcatClass
+ "workflow-canvas-toolbar__btn --success"
+ (if this.isManuallyTriggerable "" "is-disabled")
+ }}
+ disabled={{if this.isManuallyTriggerable false true}}
+ aria-label={{this.manualTriggerLabel}}
+ {{on "pointerdown" this.stopPropagation}}
+ {{on "click" this.handleManualTrigger}}
+ >
+ {{dIcon "play"}}
+ </button>
+ </:trigger>
+ </DTooltip>
+ {{/if}}
+ {{#if this.dataTableId}}
+ <button
+ type="button"
+ class="workflow-canvas-toolbar__btn"
+ {{on "pointerdown" this.stopPropagation}}
+ {{on "click" this.handleEditDataTable}}
+ >
+ {{dIcon "eye"}}
+ </button>
+ {{/if}}
+ <button
+ type="button"
+ class="workflow-canvas-toolbar__btn"
+ {{on "pointerdown" this.stopPropagation}}
+ {{on "click" this.handleDelete}}
+ >
+ {{dIcon "trash-can"}}
+ </button>
+ </CanvasHoverToolbar>
+
+ {{#if this.isUnavailable}}
+ <span
+ class="workflow-rete-node__unavailable-icon"
+ aria-label={{this.unavailableReason}}
+ >
+ {{dIcon "triangle-exclamation"}}
+ </span>
+ {{else if (nodeTypeIcon this.resolvedNodeType)}}
+ <span class="workflow-rete-node__icon">
+ {{dIcon (nodeTypeIcon this.resolvedNodeType)}}
+ </span>
+ {{/if}}
+
+ {{#if this.issues.length}}
+ <DTooltip
+ @identifier="workflow-node-issues"
+ class="workflow-rete-node__issues-badge"
+ {{on "pointerdown" this.stopPropagation}}
+ {{on "click" this.handleOpenIssues}}
+ >
+ <:trigger>
+ {{dIcon "triangle-exclamation"}}
+ </:trigger>
+ <:content>
+ <div class="workflow-rete-node__issues">
+ <div class="workflow-rete-node__issues-title">
+ {{i18n "discourse_workflows.node_issues.title"}}
+ </div>
+ <ul class="workflow-rete-node__issues-list">
+ {{#each this.issues as |issue|}}
+ <li>{{this.formatIssue issue}}</li>
+ {{/each}}
+ </ul>
+ </div>
+ </:content>
+ </DTooltip>
+ {{/if}}
+ </div>
+
+ <div class="workflow-rete-node__outputs">
+ {{#each this.outputKeys as |key|}}
+ <div class="workflow-rete-node__output-row">
+ <div
+ class={{dConcatClass
+ "workflow-rete-node__socket --output"
+ (if (eq key "loop") "--loop")
+ }}
+ data-socket-key={{key}}
+ {{didInsert
+ (fn @onSocketRendered @node.id "output" key @node.outputs)
+ }}
+ />
+ {{#if this.isBranching}}
+ <span class="workflow-rete-node__port-pill">
+ {{this.portLabel key}}
+ </span>
+ {{/if}}
+ </div>
+ {{/each}}
+ </div>
+ </div>
+
+ <span class="workflow-rete-node__label">{{this.label}}</span>
+
+ {{#if this.isUnavailable}}
+ <DTooltip
+ @identifier="workflow-node-unavailable"
+ @content={{this.unavailableReason}}
+ >
+ <:trigger>
+ <span class="workflow-rete-node__unavailable-pill">
+ {{this.unavailableLabel}}
+ </span>
+ </:trigger>
+ </DTooltip>
+ {{/if}}
+
+ {{#if this.description}}
+ <span
+ class="workflow-rete-node__description"
+ >{{this.description}}</span>
+ {{/if}}
+ </div>
+ </template>
+}
diff --git a/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/configurators/assignment-collection.gjs b/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/configurators/assignment-collection.gjs
new file mode 100644
index 00000000000..6a37b4793ca
--- /dev/null
+++ b/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/configurators/assignment-collection.gjs
@@ -0,0 +1,235 @@
+import Component from "@glimmer/component";
+import { tracked } from "@glimmer/tracking";
+import { fn } from "@ember/helper";
+import { action } from "@ember/object";
+import DButton from "discourse/ui-kit/d-button";
+import { i18n } from "discourse-i18n";
+import {
+ findNodeType,
+ propertyDescription,
+ propertyLabel,
+} from "../../../lib/workflows/property-engine";
+import Field from "./field";
+
+export default class AssignmentCollection extends Component {
+ @tracked
+ itemCount = (this.args.formApi?.get(this.assignmentsPath) || []).length;
+
+ get assignmentsPath() {
+ return `${this.args.fieldName}.assignments`;
+ }
+
+ get nodeDefinition() {
+ return (
+ this.args.nodeDefinition ||
+ findNodeType(this.args.nodeTypes, this.args.nodeType)
+ );
+ }
+
+ get label() {
+ return propertyLabel(this.nodeDefinition, this.args.fieldName);
+ }
+
+ get description() {
+ return propertyDescription(this.nodeDefinition, this.args.fieldName);
+ }
+
+ get type_options() {
+ return this.args.schema.type_options || {};
+ }
+
+ get assignment_types() {
+ return (
+ this.type_options.assignment_types || [
+ "string",
+ "number",
+ "boolean",
+ "array",
+ "object",
+ ]
+ );
+ }
+
+ get nameSchema() {
+ return {
+ type: "string",
+ required: true,
+ no_data_expression: true,
+ };
+ }
+
+ get typeSchema() {
+ return {
+ type: "options",
+ required: true,
+ default: "string",
+ options: this.assignment_types,
+ no_data_expression: true,
+ };
+ }
+
+ get showEmptyState() {
+ return this.itemCount === 0;
+ }
+
+ @action
+ emptyAssignment() {
+ return {
+ id: crypto.randomUUID(),
+ name: "",
+ value: "",
+ type: "string",
+ };
+ }
+
+ @action
+ addAssignment() {
+ this.args.form.addItemToCollection(
+ this.assignmentsPath,
+ this.emptyAssignment()
+ );
+ this.itemCount++;
+ this.args.onChange?.();
+ }
+
+ @action
+ removeAssignment(removeFn, index) {
+ removeFn(index);
+ this.itemCount--;
+ this.args.onChange?.();
+ }
+
+ @action
+ clearAssignments() {
+ this.args.formApi.set(this.assignmentsPath, []);
+ this.itemCount = 0;
+ }
+
+ @action
+ valueSchema(item) {
+ switch (item?.type) {
+ case "number":
+ return { type: "number" };
+ case "boolean":
+ return { type: "boolean" };
+ case "array":
+ case "object":
+ return {
+ type: "string",
+ ui: {
+ control: "code",
+ },
+ control_options: {
+ height: 120,
+ lang: "json",
+ },
+ };
+ default:
+ return { type: "string" };
+ }
+ }
+
+ <template>
+ <@form.Section @title={{this.label}} @subtitle={{this.description}}>
+ <@form.Collection
+ @name={{this.assignmentsPath}}
+ @tagName="div"
+ as |collection index item|
+ >
+ <div class="workflows-property-engine__collection-row">
+ <div class="workflows-property-engine__collection-delete">
+ <DButton
+ @action={{fn this.removeAssignment collection.remove index}}
+ @icon="trash-can"
+ class="btn-transparent btn-small btn-danger"
+ />
+ </div>
+
+ <collection.Object
+ class="workflows-property-engine__collection-fields"
+ as |object|
+ >
+ <Field
+ @form={{object}}
+ @formApi={{@formApi}}
+ @connections={{@connections}}
+ @credentials={{@credentials}}
+ @fieldName="name"
+ @label={{i18n
+ "discourse_workflows.property_engine.assignment_name"
+ }}
+ @node={{@node}}
+ @nodeDefinition={{this.nodeDefinition}}
+ @nodeParameters={{@nodeParameters}}
+ @nodeType={{@nodeType}}
+ @nodes={{@nodes}}
+ @nodeTypes={{@nodeTypes}}
+ @schema={{this.nameSchema}}
+ @session={{@session}}
+ />
+
+ <Field
+ @form={{object}}
+ @formApi={{@formApi}}
+ @connections={{@connections}}
+ @credentials={{@credentials}}
+ @fieldName="type"
+ @label={{i18n
+ "discourse_workflows.property_engine.assignment_type"
+ }}
+ @node={{@node}}
+ @nodeDefinition={{this.nodeDefinition}}
+ @nodeParameters={{@nodeParameters}}
+ @nodeType={{@nodeType}}
+ @nodes={{@nodes}}
+ @nodeTypes={{@nodeTypes}}
+ @schema={{this.typeSchema}}
+ @session={{@session}}
+ />
+
+ <Field
+ @form={{object}}
+ @formApi={{@formApi}}
+ @connections={{@connections}}
+ @credentials={{@credentials}}
+ @fieldName="value"
+ @label={{i18n
+ "discourse_workflows.property_engine.assignment_value"
+ }}
+ @node={{@node}}
+ @nodeDefinition={{this.nodeDefinition}}
+ @nodeParameters={{@nodeParameters}}
+ @nodeType={{@nodeType}}
+ @nodes={{@nodes}}
+ @nodeTypes={{@nodeTypes}}
+ @schema={{this.valueSchema item}}
+ @session={{@session}}
+ />
+ </collection.Object>
+ </div>
+ </@form.Collection>
+
+ <div class="workflows-property-engine__block-actions">
+ <DButton
+ @action={{this.addAssignment}}
+ @icon="plus"
+ @translatedLabel={{i18n
+ "discourse_workflows.property_engine.add_field"
+ }}
+ class="btn-default"
+ />
+
+ {{#unless this.showEmptyState}}
+ <DButton
+ @action={{this.clearAssignments}}
+ @icon="xmark"
+ @translatedLabel={{i18n
+ "discourse_workflows.property_engine.clear_fields"
+ }}
+ class="btn-flat"
+ />
+ {{/unless}}
+ </div>
+ </@form.Section>
+ </template>
+}
diff --git a/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/configurators/boolean-control.gjs b/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/configurators/boolean-control.gjs
new file mode 100644
index 00000000000..065d2fe7a16
--- /dev/null
+++ b/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/configurators/boolean-control.gjs
@@ -0,0 +1,139 @@
+import Component from "@glimmer/component";
+import { tracked } from "@glimmer/tracking";
+import { fn } from "@ember/helper";
+import { action } from "@ember/object";
+import DSegmentedControl from "discourse/components/d-segmented-control";
+import { i18n } from "discourse-i18n";
+import {
+ fieldFormat,
+ fieldShowDescription,
+ fieldSupportsExpression,
+ isExpression,
+ propertyDescription,
+ propertyLabel,
+ propertyPlaceholder,
+} from "../../../lib/workflows/property-engine";
+import ExpressionWrapper from "./expression-wrapper";
+
+const MODE_ITEMS = [
+ {
+ value: "plain",
+ icon: "paragraph",
+ label: i18n("discourse_workflows.parameter_field.plain"),
+ },
+ {
+ value: "dynamic",
+ icon: "code",
+ label: i18n("discourse_workflows.parameter_field.dynamic"),
+ },
+];
+
+export default class BooleanControl extends Component {
+ @tracked expressionMode = this.#initialExpressionMode();
+
+ #initialExpressionMode() {
+ if (!fieldSupportsExpression(this.args.schema)) {
+ return false;
+ }
+ return isExpression(this.args.configuration?.[this.args.fieldName]);
+ }
+
+ get supportsExpression() {
+ return fieldSupportsExpression(this.args.schema);
+ }
+
+ get format() {
+ return fieldFormat(this.args.schema);
+ }
+
+ get label() {
+ return (
+ this.args.label ||
+ propertyLabel(this.args.nodeDefinition, this.args.fieldName)
+ );
+ }
+
+ get placeholder() {
+ return propertyPlaceholder(this.args.nodeDefinition, this.args.fieldName);
+ }
+
+ get tooltip() {
+ if (!fieldShowDescription(this.args.schema)) {
+ return undefined;
+ }
+ return propertyDescription(this.args.nodeDefinition, this.args.fieldName);
+ }
+
+ get validation() {
+ return this.args.schema?.required ? "required" : undefined;
+ }
+
+ @action
+ onModeChange(field, value) {
+ const wantsDynamic = value === "dynamic";
+ if (wantsDynamic === this.expressionMode) {
+ return;
+ }
+
+ this.expressionMode = wantsDynamic;
+ const currentValue = field.value || "";
+
+ if (wantsDynamic) {
+ field.set(
+ currentValue.startsWith("=") ? currentValue : `=${currentValue}`
+ );
+ } else {
+ field.set(
+ currentValue.startsWith("=") ? currentValue.slice(1) : currentValue
+ );
+ }
+ }
+
+ <template>
+ {{#if this.expressionMode}}
+ <@form.Field
+ @name={{@fieldName}}
+ @title={{this.label}}
+ @showTitle={{true}}
+ @type="custom"
+ @format={{this.format}}
+ @onSet={{@onSet}}
+ as |field|
+ >
+ <field.Control>
+ <ExpressionWrapper
+ @expressionMode={{true}}
+ @field={{field}}
+ @placeholder={{this.placeholder}}
+ @supportsExpression={{this.supportsExpression}}
+ @dynamicValueHint={{@dynamicValueHint}}
+ @session={{@session}}
+ @modeItems={{MODE_ITEMS}}
+ @onModeChange={{fn this.onModeChange field}}
+ />
+ </field.Control>
+ </@form.Field>
+ {{else}}
+ <@form.Field
+ @name={{@fieldName}}
+ @title={{this.label}}
+ @tooltip={{this.tooltip}}
+ @type="toggle"
+ @format={{this.format}}
+ @validation={{this.validation}}
+ as |field|
+ >
+ <field.Control />
+ {{#if this.supportsExpression}}
+ <DSegmentedControl
+ @items={{MODE_ITEMS}}
+ @value="plain"
+ @onSelect={{fn this.onModeChange field}}
+ @size="small"
+ class="workflows-property-engine__mode-control --toggle"
+ />
+ {{/if}}
+ </@form.Field>
+ {{/if}}
+ </template>
+}
diff --git a/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/configurators/category-control.gjs b/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/configurators/category-control.gjs
new file mode 100644
index 00000000000..33b1f1673eb
--- /dev/null
+++ b/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/configurators/category-control.gjs
@@ -0,0 +1,26 @@
+import Component from "@glimmer/component";
+import { action } from "@ember/object";
+import CategoryChooser from "discourse/select-kit/components/category-chooser";
+import ExpressionWrapper from "./expression-wrapper";
+
+export default class CategoryControl extends Component {
+ @action
+ handleChange(categoryId) {
+ this.args.field.set(categoryId == null ? "" : String(categoryId));
+ }
+
+ <template>
+ <ExpressionWrapper
+ @field={{@field}}
+ @supportsExpression={{@supportsExpression}}
+ @placeholder={{@placeholder}}
+ @dynamicValueHint={{@dynamicValueHint}}
+ @session={{@session}}
+ >
+ <CategoryChooser
+ @value={{if @field.value @field.value null}}
+ @onChange={{this.handleChange}}
+ />
+ </ExpressionWrapper>
+ </template>
+}
diff --git a/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/configurators/code-control.gjs b/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/configurators/code-control.gjs
new file mode 100644
index 00000000000..47b1114c7d9
--- /dev/null
+++ b/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/configurators/code-control.gjs
@@ -0,0 +1,74 @@
+import Component from "@glimmer/component";
+import { action } from "@ember/object";
+import didInsert from "@ember/render-modifiers/modifiers/did-insert";
+import { trustHTML } from "@ember/template";
+import AceEditor from "discourse/components/ace-editor";
+import { escapeExpression } from "discourse/lib/utilities";
+
+export function normalizeCodeEditorValue(value, lang = "text") {
+ if (value === null || value === undefined) {
+ return "";
+ }
+
+ if (typeof value === "string") {
+ return value;
+ }
+
+ if (lang?.toString() === "json" || typeof value === "object") {
+ return JSON.stringify(value, null, 2);
+ }
+
+ return String(value);
+}
+
+export default class CodeControl extends Component {
+ get height() {
+ return this.args.schema?.control_options?.height;
+ }
+
+ get lang() {
+ return this.args.schema?.control_options?.lang || "text";
+ }
+
+ get content() {
+ return normalizeCodeEditorValue(this.args.field.value, this.lang);
+ }
+
+ get style() {
+ if (!this.height) {
+ return;
+ }
+
+ return trustHTML(`height: ${escapeExpression(this.height)}px`);
+ }
+
+ @action
+ normalizeFieldValue() {
+ if (this.content !== this.args.field.value) {
+ this.args.field.set(this.content);
+ }
+ }
+
+ @action
+ handleInput(content) {
+ this.args.field.set(content);
+ }
+
+ <template>
+ <div class="workflows-code-control" {{didInsert this.normalizeFieldValue}}>
+ <AceEditor
+ @content={{this.content}}
+ @onChange={{this.handleInput}}
+ @mode={{this.lang}}
+ @disabled={{@field.disabled}}
+ @resizable={{true}}
+ class="form-kit__control-code"
+ style={{this.style}}
+ id={{@field.id}}
+ name={{@field.name}}
+ aria-invalid={{if @field.error "true"}}
+ aria-describedby={{@field.describedBy}}
+ />
+ </div>
+ </template>
+}
diff --git a/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/configurators/collection.gjs b/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/configurators/collection.gjs
new file mode 100644
index 00000000000..a652f1c2d09
--- /dev/null
+++ b/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/configurators/collection.gjs
@@ -0,0 +1,226 @@
+import Component from "@glimmer/component";
+import { fn, hash } from "@ember/helper";
+import { action } from "@ember/object";
+import DMenu from "discourse/float-kit/components/d-menu";
+import DButton from "discourse/ui-kit/d-button";
+import DDropdownMenu from "discourse/ui-kit/d-dropdown-menu";
+import dIcon from "discourse/ui-kit/helpers/d-icon";
+import { i18n } from "discourse-i18n";
+import {
+ fieldValue,
+ findNodeType,
+ normalizePropertyOptions,
+ propertyDescription,
+ propertyLabel,
+} from "../../../lib/workflows/property-engine";
+import WorkflowsEmptyState from "../empty-state";
+import Field from "./field";
+
+export default class Collection extends Component {
+ get nodeDefinition() {
+ return (
+ this.args.nodeDefinition ||
+ findNodeType(this.args.nodeTypes, this.args.nodeType)
+ );
+ }
+
+ get label() {
+ return (
+ this.args.label || propertyLabel(this.nodeDefinition, this.args.fieldName)
+ );
+ }
+
+ get description() {
+ return propertyDescription(this.nodeDefinition, this.args.fieldName);
+ }
+
+ get addLabel() {
+ return (
+ this.args.addLabel || i18n("discourse_workflows.property_engine.add_item")
+ );
+ }
+
+ get isArrayCollection() {
+ return Boolean(this.args.emptyItem);
+ }
+
+ get arrayItems() {
+ return this.args.formApi?.get(this.args.fieldName) || [];
+ }
+
+ get showEmptyState() {
+ return this.args.emptyStateDescription && this.arrayItems.length === 0;
+ }
+
+ get currentValue() {
+ return this.args.formApi?.get(this.args.fieldName) || {};
+ }
+
+ get options() {
+ return normalizePropertyOptions(this.args.schema.options || []);
+ }
+
+ get selectedOptions() {
+ return this.options.filter((option) =>
+ Object.hasOwn(this.currentValue, option.name)
+ );
+ }
+
+ get availableOptions() {
+ return this.options.filter(
+ (option) => !Object.hasOwn(this.currentValue, option.name)
+ );
+ }
+
+ get hasAvailableOptions() {
+ return this.availableOptions.length > 0;
+ }
+
+ @action
+ optionPath(name) {
+ return `${this.args.fieldName}.${name}`;
+ }
+
+ @action
+ optionLabel(option) {
+ return (
+ propertyLabel(this.nodeDefinition, option.name) ||
+ option.display_name ||
+ option.name
+ );
+ }
+
+ @action
+ addOption(option, close) {
+ this.args.formApi.set(this.args.fieldName, {
+ ...this.currentValue,
+ [option.name]: fieldValue(option),
+ });
+ close?.();
+ }
+
+ @action
+ removeOption(option) {
+ const nextValue = { ...this.currentValue };
+ delete nextValue[option.name];
+ this.args.formApi.set(this.args.fieldName, nextValue);
+ }
+
+ @action
+ addItem() {
+ const item = this.args.emptyItem();
+ this.args.form.addItemToCollection(this.args.fieldName, item);
+ this.args.onAdd?.(item);
+ this.args.onChange?.();
+ }
+
+ @action
+ removeItem(removeFn, index) {
+ this.args.onRemove?.(index);
+ removeFn(index);
+ this.args.onChange?.();
+ }
+
+ <template>
+ <@form.Section @title={{this.label}} @subtitle={{this.description}}>
+ {{#if this.isArrayCollection}}
+ <@form.Collection
+ @name={{@fieldName}}
+ @tagName="div"
+ as |collection index item|
+ >
+ <div class="workflows-property-engine__collection-row">
+ <div class="workflows-property-engine__collection-delete">
+ <DButton
+ @action={{fn this.removeItem collection.remove index}}
+ @icon="trash-can"
+ class="btn-transparent btn-small btn-danger"
+ />
+ </div>
+
+ <collection.Object
+ class="workflows-property-engine__collection-fields"
+ as |object|
+ >
+ {{yield (hash object=object item=item index=index)}}
+ </collection.Object>
+ </div>
+ </@form.Collection>
+
+ {{#if this.showEmptyState}}
+ <WorkflowsEmptyState
+ @description={{@emptyStateDescription}}
+ @onAction={{this.addItem}}
+ @buttonIcon="plus"
+ @translatedButtonLabel={{this.addLabel}}
+ />
+ {{else}}
+ <DButton
+ @action={{this.addItem}}
+ @icon="plus"
+ @translatedLabel={{this.addLabel}}
+ class="btn-default"
+ />
+ {{/if}}
+ {{else}}
+ {{#each this.selectedOptions key="name" as |option|}}
+ <div class="workflows-property-engine__collection-row">
+ <div class="workflows-property-engine__collection-delete">
+ <DButton
+ @action={{fn this.removeOption option}}
+ @icon="trash-can"
+ class="btn-transparent btn-small btn-danger"
+ />
+ </div>
+
+ <div class="workflows-property-engine__collection-fields">
+ <Field
+ @form={{@form}}
+ @formApi={{@formApi}}
+ @configuration={{this.currentValue}}
+ @connections={{@connections}}
+ @credentials={{@credentials}}
+ @fieldName={{this.optionPath option.name}}
+ @label={{this.optionLabel option}}
+ @node={{@node}}
+ @nodeDefinition={{this.nodeDefinition}}
+ @nodeParameters={{@nodeParameters}}
+ @nodeType={{@nodeType}}
+ @nodes={{@nodes}}
+ @nodeTypes={{@nodeTypes}}
+ @schema={{option}}
+ @session={{@session}}
+ />
+ </div>
+ </div>
+ {{/each}}
+
+ {{#if this.hasAvailableOptions}}
+ <DMenu
+ class="btn btn-default workflows-property-engine__add-attrs-btn"
+ @inline={{true}}
+ @modalForwardRecipient={{true}}
+ >
+ <:trigger>
+ {{i18n "discourse_workflows.property_engine.add_option"}}
+ {{dIcon "chevron-down"}}
+ </:trigger>
+ <:content as |menu|>
+ <DDropdownMenu as |dropdown|>
+ {{#each this.availableOptions key="name" as |option|}}
+ <dropdown.item>
+ <DButton
+ class="btn-transparent"
+ @action={{fn this.addOption option menu.close}}
+ @translatedLabel={{this.optionLabel option}}
+ />
+ </dropdown.item>
+ {{/each}}
+ </DDropdownMenu>
+ </:content>
+ </DMenu>
+ {{/if}}
+ {{/if}}
+ </@form.Section>
+ </template>
+}
diff --git a/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/configurators/combo-box.gjs b/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/configurators/combo-box.gjs
new file mode 100644
index 00000000000..2e146edaea7
--- /dev/null
+++ b/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/configurators/combo-box.gjs
@@ -0,0 +1,319 @@
+import Component from "@glimmer/component";
+import { tracked } from "@glimmer/tracking";
+import { hash } from "@ember/helper";
+import { action } from "@ember/object";
+import { service } from "@ember/service";
+import ComboBox from "discourse/select-kit/components/combo-box";
+import DButton from "discourse/ui-kit/d-button";
+import {
+ fieldType,
+ formatOptionValue,
+ normalizeOptions,
+ propertyOptionLabel,
+ propertySelectNoneKey,
+} from "../../../lib/workflows/property-engine";
+import ExpressionWrapper from "./expression-wrapper";
+
+export class DynamicOptionsComboBox extends ComboBox {
+ search(filter) {
+ if (this.loadOptions) {
+ return this.loadOptions(filter);
+ }
+
+ return super.search(filter);
+ }
+}
+
+function optionValue(option, valueProperty) {
+ return option[valueProperty] ?? option.id ?? option.value;
+}
+
+function optionName(option, nameProperty) {
+ return option[nameProperty] ?? option.name ?? option.label;
+}
+
+export default class ComboBoxField extends Component {
+ @service router;
+ @service workflowsNodeTypes;
+
+ @tracked _remoteOptions = [];
+ _remoteOptionsRequestKey = null;
+
+ constructor(owner, args) {
+ super(owner, args);
+ this.ensureRemoteOptions();
+ }
+
+ get methodName() {
+ return this.args.schema?.type_options?.load_options_method;
+ }
+
+ get identifier() {
+ return (
+ this.args.nodeDefinition?.name || this.args.nodeDefinition?.identifier
+ );
+ }
+
+ get typeVersion() {
+ return this.args.nodeDefinition?.version || this.args.node?.typeVersion;
+ }
+
+ get localOptions() {
+ return (
+ this.args.metadata?.[this.methodName] ||
+ this.args.nodeDefinition?.metadata?.[this.methodName]
+ );
+ }
+
+ get usesRemoteOptions() {
+ return Boolean(this.methodName && this.identifier && !this.localOptions);
+ }
+
+ get metadataOptions() {
+ if (!this.methodName) {
+ return null;
+ }
+ if (this.localOptions) {
+ return this.localOptions;
+ }
+ this.ensureRemoteOptions();
+ return this._remoteOptions;
+ }
+
+ get controlOptions() {
+ return this.args.schema?.control_options || {};
+ }
+
+ get none() {
+ return (
+ this.controlOptions.none ||
+ propertySelectNoneKey(this.args.nodeDefinition, this.args.fieldName)
+ );
+ }
+
+ get filterable() {
+ return Boolean(this.controlOptions.filterable);
+ }
+
+ get valueProperty() {
+ return this.controlOptions.value_property || "id";
+ }
+
+ get nameProperty() {
+ return this.controlOptions.name_property || "name";
+ }
+
+ get setFromOption() {
+ return this.controlOptions.set_from_option || {};
+ }
+
+ get resets() {
+ return this.controlOptions.resets || [];
+ }
+
+ get castInteger() {
+ return fieldType(this.args.schema) === "integer";
+ }
+
+ get actionRoute() {
+ return this.controlOptions.action_route;
+ }
+
+ get actionRouteModels() {
+ const models = this.controlOptions.action_route_models;
+
+ if (!models) {
+ return [];
+ }
+
+ return Array.isArray(models) ? models : [models];
+ }
+
+ get actionIcon() {
+ return this.controlOptions.action_icon || "plus";
+ }
+
+ get actionLabel() {
+ return this.controlOptions.action_label;
+ }
+
+ get options() {
+ if (this.metadataOptions) {
+ return this.formatOptions(this.metadataOptions);
+ }
+
+ const optionFormat = this.controlOptions.option_format;
+ return normalizeOptions(this.args.schema.options).map((option) => ({
+ id: option.value,
+ name: optionFormat
+ ? formatOptionValue(option.value, optionFormat)
+ : propertyOptionLabel(
+ this.args.nodeDefinition,
+ this.args.fieldName,
+ option
+ ),
+ original: option,
+ }));
+ }
+
+ formatOptions(options) {
+ return options.map((option) => ({
+ id: optionValue(option, this.valueProperty),
+ name:
+ optionName(option, this.nameProperty) ||
+ optionValue(option, this.valueProperty),
+ original: option,
+ }));
+ }
+
+ remoteOptionsContext(filter = null) {
+ const context = {
+ path: this.args.fieldName,
+ currentNodeParameters:
+ this.args.nodeParameters || this.args.configuration || {},
+ credentials: this.args.credentials || {},
+ node: this.args.node,
+ filter,
+ };
+
+ return this.args.session?.nodeParameterOptionsContext(context) || context;
+ }
+
+ remoteOptionsRequestKey(filter = null) {
+ return JSON.stringify({
+ methodName: this.methodName,
+ identifier: this.identifier,
+ typeVersion: this.typeVersion,
+ context: this.remoteOptionsContext(filter),
+ });
+ }
+
+ ensureRemoteOptions(filter = null) {
+ if (!this.usesRemoteOptions) {
+ return;
+ }
+
+ const requestKey = this.remoteOptionsRequestKey(filter);
+ if (this._remoteOptionsRequestKey === requestKey) {
+ return;
+ }
+
+ this._remoteOptionsRequestKey = requestKey;
+ this.workflowsNodeTypes
+ .loadNodeParameterOptions(
+ this.identifier,
+ this.methodName,
+ this.typeVersion,
+ this.remoteOptionsContext(filter)
+ )
+ .then((options) => {
+ if (this._remoteOptionsRequestKey === requestKey) {
+ this._remoteOptions = options;
+ }
+ });
+ }
+
+ @action
+ async loadRemoteOptions(filter = null) {
+ if (!this.usesRemoteOptions) {
+ return null;
+ }
+
+ // Mutating _remoteOptions here loops via the ComboBox didReceiveAttrs hook.
+ if (!filter) {
+ return this.formatOptions(this._remoteOptions);
+ }
+
+ const options = await this.workflowsNodeTypes.loadNodeParameterOptions(
+ this.identifier,
+ this.methodName,
+ this.typeVersion,
+ this.remoteOptionsContext(filter)
+ );
+
+ return this.formatOptions(options);
+ }
+
+ @action
+ handleChange(value) {
+ this.args.field.set(value);
+
+ const selectedOption = this.options.find(
+ (option) => String(option.id) === String(value)
+ );
+
+ for (const [fieldName, propertyName] of Object.entries(
+ this.setFromOption
+ )) {
+ this.args.formApi?.set(
+ fieldName,
+ selectedOption?.original?.[propertyName] || ""
+ );
+ }
+
+ const schema = this.args.nodeDefinition?.properties || {};
+ for (const fieldName of this.resets) {
+ const type = fieldType(schema[fieldName]);
+ let resetValue = null;
+ if (type === "array" || type === "collection") {
+ resetValue = [];
+ } else if (type === "object") {
+ resetValue = {};
+ }
+ this.args.formApi?.set(fieldName, resetValue);
+ }
+ }
+
+ @action
+ performAction() {
+ this.router.transitionTo(this.actionRoute, ...this.actionRouteModels);
+ }
+
+ <template>
+ <ExpressionWrapper
+ @field={{@field}}
+ @supportsExpression={{@supportsExpression}}
+ @placeholder={{@placeholder}}
+ @dynamicValueHint={{@dynamicValueHint}}
+ @session={{@session}}
+ >
+ {{#if this.actionRoute}}
+ <div class="workflows-property-engine__select-with-action">
+ <DynamicOptionsComboBox
+ @content={{this.options}}
+ @loadOptions={{if this.usesRemoteOptions this.loadRemoteOptions}}
+ @nameProperty="name"
+ @value={{@field.value}}
+ @valueProperty="id"
+ @onChange={{this.handleChange}}
+ @options={{hash
+ filterable=this.filterable
+ none=this.none
+ castInteger=this.castInteger
+ }}
+ />
+ <DButton
+ @action={{this.performAction}}
+ @label={{this.actionLabel}}
+ @icon={{this.actionIcon}}
+ class="btn-default"
+ />
+ </div>
+ {{else}}
+ <DynamicOptionsComboBox
+ @content={{this.options}}
+ @loadOptions={{if this.usesRemoteOptions this.loadRemoteOptions}}
+ @nameProperty="name"
+ @value={{@field.value}}
+ @valueProperty="id"
+ @onChange={{this.handleChange}}
+ @options={{hash
+ filterable=this.filterable
+ none=this.none
+ castInteger=this.castInteger
+ }}
+ />
+ {{/if}}
+ </ExpressionWrapper>
+ </template>
+}
diff --git a/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/configurators/condition-builder.gjs b/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/configurators/condition-builder.gjs
new file mode 100644
index 00000000000..b106b7f70e9
--- /dev/null
+++ b/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/configurators/condition-builder.gjs
@@ -0,0 +1,330 @@
+import Component from "@glimmer/component";
+import { tracked } from "@glimmer/tracking";
+import { fn, get } from "@ember/helper";
+import { action } from "@ember/object";
+import { i18n } from "discourse-i18n";
+import {
+ isSingleValueOperator,
+ operatorsForType,
+} from "../../../lib/workflows/condition-operators";
+import {
+ inputConnectionsForNode,
+ inputFieldPrefixForConnection,
+ inputIndexForConnection,
+ inputSummaryForNode,
+ outputIndexForConnection,
+ previousNodeForConnection,
+ schemaFieldsForNodeInput,
+ schemaFieldsForNodeOutput,
+} from "../../../lib/workflows/data-schema";
+import { isExpression } from "../../../lib/workflows/property-engine";
+import Collection from "./collection";
+import Field from "./field";
+
+function flattenFields(fields, prefix = "", labelPrefix = "") {
+ const result = [];
+ for (const field of fields) {
+ const path = prefix ? `${prefix}.${field.key}` : field.key;
+ if (field.children?.length) {
+ result.push(...flattenFields(field.children, path, labelPrefix));
+ } else {
+ result.push({
+ id: field.id || path,
+ label: labelPrefix ? `${labelPrefix}.${path}` : path,
+ type: field.type,
+ });
+ }
+ }
+ return result;
+}
+
+const CATEGORY_FIELDS = ["category_id", "category"];
+const USER_FIELDS = ["username"];
+
+function leafKey(fieldPath) {
+ if (!fieldPath) {
+ return fieldPath;
+ }
+
+ let path = fieldPath;
+ const exprMatch = path.match(/^=\{\{\s*(.*?)\s*\}\}$/);
+ if (exprMatch) {
+ path = exprMatch[1];
+ }
+
+ const bracketSegments = [
+ ...path.matchAll(/\[((?:"(?:\\.|[^"\\])*")|(?:'(?:\\.|[^'\\])*'))\]/g),
+ ];
+ if (bracketSegments.length) {
+ return unquoteBracketSegment(bracketSegments.at(-1)[1]);
+ }
+
+ const parts = path.split(".");
+ return parts[parts.length - 1];
+}
+
+function unquoteBracketSegment(segment) {
+ if (segment.startsWith('"')) {
+ try {
+ return JSON.parse(segment);
+ } catch {
+ return segment.slice(1, -1);
+ }
+ }
+
+ return segment.slice(1, -1).replace(/\\([\\'])/g, "$1");
+}
+
+const RIGHT_VALUE_SCHEMAS = {
+ category: {
+ type: "string",
+ required: true,
+ ui: { expression: true, control: "category" },
+ },
+ user: {
+ type: "string",
+ required: true,
+ ui: { expression: true, control: "user" },
+ },
+ default: {
+ type: "string",
+ required: true,
+ ui: { expression: true },
+ },
+};
+
+function rightValueSchema(item) {
+ const leaf = leafKey(item?.leftValue);
+
+ if (CATEGORY_FIELDS.includes(leaf)) {
+ return RIGHT_VALUE_SCHEMAS.category;
+ }
+
+ if (USER_FIELDS.includes(leaf)) {
+ return RIGHT_VALUE_SCHEMAS.user;
+ }
+
+ return RIGHT_VALUE_SCHEMAS.default;
+}
+
+function leftValueSchema(fieldOptions) {
+ return {
+ type: "options",
+ required: true,
+ options: fieldOptions.map((f) => ({ value: f.id, label: f.label })),
+ ui: { expression: true },
+ };
+}
+
+const OPERATION_SCHEMAS = {};
+
+function operationSchema(item) {
+ const type = item?.operator?.type || "string";
+ return (OPERATION_SCHEMAS[type] ??= {
+ type: "options",
+ required: true,
+ options: operatorsForType(type),
+ ui: { expression: true },
+ });
+}
+
+export default class ConditionBuilder extends Component {
+ @tracked conditionSchemas = (
+ this.args.formApi?.get(this.args.fieldName) || []
+ ).map((item) => this.#buildConditionSchema(item));
+
+ #buildConditionSchema(item) {
+ return {
+ opSchema: operationSchema(item),
+ singleValue: isSingleValueOperator(item?.operator?.operation),
+ rvSchema: rightValueSchema(item),
+ };
+ }
+
+ #updateSchemaAtIndex(index, schema) {
+ const newSchemas = [...this.conditionSchemas];
+ newSchemas[index] = schema;
+ this.conditionSchemas = newSchemas;
+ }
+
+ get fieldOptions() {
+ if (this.args.fieldOptions) {
+ return this.args.fieldOptions;
+ }
+
+ const graph = {
+ nodes: this.args.nodes || [],
+ connections: this.args.connections || [],
+ nodeTypes: this.args.nodeTypes || [],
+ };
+ const runData = this.args.session?.lastExecutionRunData || {};
+ const inputConnections = inputConnectionsForNode(this.args.node, graph);
+ const primaryConnection = inputConnections[0] || null;
+
+ return inputConnections.flatMap((connection) => {
+ const previousNode = previousNodeForConnection(connection, graph);
+ if (!previousNode) {
+ return [];
+ }
+
+ const inputIndex = inputIndexForConnection(connection);
+ const outputIndex = outputIndexForConnection(connection);
+ const currentInputSummary = this.args.node
+ ? inputSummaryForNode(runData, this.args.node.name, inputIndex)
+ : null;
+ const prefix = inputFieldPrefixForConnection(connection, previousNode, {
+ primaryConnection,
+ });
+ const fields = currentInputSummary
+ ? schemaFieldsForNodeInput(runData, this.args.node.name, {
+ inputIndex,
+ prefix,
+ })
+ : schemaFieldsForNodeOutput(runData, previousNode.name, {
+ outputIndex,
+ prefix,
+ });
+ const labelPrefix =
+ inputConnections.length > 1 ? previousNode.name || null : null;
+
+ return flattenFields(fields, "", labelPrefix);
+ });
+ }
+
+ get fieldLabel() {
+ return this.args.fieldLabel || i18n("discourse_workflows.if.field");
+ }
+
+ @action
+ emptyCondition() {
+ return {
+ id: crypto.randomUUID(),
+ leftValue: "",
+ operator: {
+ operation: "equals",
+ singleValue: false,
+ type: "string",
+ },
+ rightValue: "",
+ };
+ }
+
+ @action
+ onConditionAdded(item) {
+ this.conditionSchemas = [
+ ...this.conditionSchemas,
+ this.#buildConditionSchema(item),
+ ];
+ }
+
+ @action
+ removeCondition(index) {
+ const newSchemas = [...this.conditionSchemas];
+ newSchemas.splice(index, 1);
+ this.conditionSchemas = newSchemas;
+ }
+
+ @action
+ handleLeftValueSet(index, value, { set, name }) {
+ if (isExpression(value)) {
+ set(name, value);
+ return;
+ }
+
+ const field = this.fieldOptions.find((option) => option.id === value);
+ const type = field?.type || "string";
+
+ const storedValue = this.args.fieldOptions
+ ? value
+ : `={{ ${field?.id || value} }}`;
+ set(name, storedValue);
+
+ const operation = operatorsForType(type)[0];
+ const basePath = `${this.args.fieldName}.${index}`;
+
+ set(`${basePath}.operator`, {
+ operation,
+ type,
+ singleValue: isSingleValueOperator(operation),
+ });
+ set(`${basePath}.rightValue`, "");
+
+ const data = this.args.formApi.get(basePath);
+ this.#updateSchemaAtIndex(index, this.#buildConditionSchema(data));
+ }
+
+ @action
+ handleOperatorSet(index, value, { set, name }) {
+ set(name, value);
+
+ if (isExpression(value)) {
+ return;
+ }
+
+ set(
+ `${this.args.fieldName}.${index}.operator.singleValue`,
+ isSingleValueOperator(value)
+ );
+
+ this.#updateSchemaAtIndex(index, {
+ ...this.conditionSchemas[index],
+ singleValue: isSingleValueOperator(value),
+ });
+ }
+
+ <template>
+ <Collection
+ @form={{@form}}
+ @formApi={{@formApi}}
+ @fieldName={{@fieldName}}
+ @label={{@label}}
+ @addLabel={{i18n "discourse_workflows.if.add_condition"}}
+ @emptyItem={{this.emptyCondition}}
+ @onAdd={{this.onConditionAdded}}
+ @onRemove={{this.removeCondition}}
+ @session={{@session}}
+ @emptyStateDescription={{i18n
+ "discourse_workflows.if.no_conditions_body"
+ }}
+ as |ctx|
+ >
+ <Field
+ @form={{ctx.object}}
+ @formApi={{@formApi}}
+ @configuration={{ctx.item}}
+ @fieldName="leftValue"
+ @schema={{leftValueSchema this.fieldOptions}}
+ @label={{this.fieldLabel}}
+ @session={{@session}}
+ @onSet={{fn this.handleLeftValueSet ctx.index}}
+ />
+
+ {{#let (get this.conditionSchemas ctx.index) as |schemas|}}
+ <ctx.object.Object @name="operator" as |operator|>
+ <Field
+ @form={{operator}}
+ @formApi={{@formApi}}
+ @configuration={{ctx.item.operator}}
+ @fieldName="operation"
+ @schema={{schemas.opSchema}}
+ @label={{i18n "discourse_workflows.if.operator"}}
+ @session={{@session}}
+ @onSet={{fn this.handleOperatorSet ctx.index}}
+ />
+ </ctx.object.Object>
+
+ {{#unless schemas.singleValue}}
+ <Field
+ @form={{ctx.object}}
+ @formApi={{@formApi}}
+ @configuration={{ctx.item}}
+ @fieldName="rightValue"
+ @schema={{schemas.rvSchema}}
+ @label={{i18n "discourse_workflows.if.value"}}
+ @session={{@session}}
+ />
+ {{/unless}}
+ {{/let}}
+ </Collection>
+ </template>
+}
diff --git a/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/configurators/credential.gjs b/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/configurators/credential.gjs
new file mode 100644
index 00000000000..cce1bd17180
--- /dev/null
+++ b/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/configurators/credential.gjs
@@ -0,0 +1,133 @@
+import Component from "@glimmer/component";
+import { tracked } from "@glimmer/tracking";
+import { hash } from "@ember/helper";
+import { action } from "@ember/object";
+import { service } from "@ember/service";
+import { ajax } from "discourse/lib/ajax";
+import { popupAjaxError } from "discourse/lib/ajax-error";
+import ComboBox from "discourse/select-kit/components/combo-box";
+import DButton from "discourse/ui-kit/d-button";
+import CredentialModal from "../credential/modal";
+import ExpressionWrapper from "./expression-wrapper";
+
+export default class Credential extends Component {
+ @service modal;
+
+ @tracked credentials = null;
+
+ constructor() {
+ super(...arguments);
+ this.#loadCredentials();
+ }
+
+ async #loadCredentials() {
+ try {
+ const credentialType =
+ this.credentialTypes.length === 1 ? this.credentialTypes[0] : null;
+ const url = credentialType
+ ? `/admin/plugins/discourse-workflows/credentials.json?type=${credentialType}`
+ : "/admin/plugins/discourse-workflows/credentials.json";
+ const result = await ajax(url);
+ this.credentials = result.credentials;
+ } catch (e) {
+ popupAjaxError(e);
+ }
+ }
+
+ get credentialTypes() {
+ return [
+ this.args.credentialTypes ||
+ this.args.schema?.credential_types ||
+ this.args.schema?.credential_type,
+ ]
+ .flat()
+ .filter(Boolean);
+ }
+
+ get value() {
+ return this.args.value?.id || this.args.field?.value || null;
+ }
+
+ get options() {
+ return (this.credentials || [])
+ .filter(
+ (c) =>
+ this.credentialTypes.length === 0 ||
+ this.credentialTypes.includes(c.credential_type)
+ )
+ .map((c) => ({
+ id: c.id?.toString(),
+ name: c.name,
+ credential_type: c.credential_type,
+ }));
+ }
+
+ @action
+ handleChange(value) {
+ if (this.args.onChange) {
+ const selected = this.options.find(
+ (c) => c.id.toString() === value?.toString()
+ );
+ this.args.onChange(
+ value
+ ? {
+ id: value.toString(),
+ credential_type:
+ selected?.credential_type || this.credentialTypes[0] || null,
+ }
+ : null
+ );
+ } else {
+ this.args.field.set(value ? parseInt(value, 10) : null);
+ }
+ }
+
+ @action
+ setupCredential() {
+ this.modal.show(CredentialModal, {
+ model: {
+ credential: null,
+ onSave: async (data) => {
+ const result = await ajax(
+ "/admin/plugins/discourse-workflows/credentials.json",
+ { type: "POST", data }
+ );
+ await this.#loadCredentials();
+ this.handleChange(result.credential.id);
+ },
+ },
+ });
+ }
+
+ <template>
+ <ExpressionWrapper
+ @field={{if @field @field (hash value=this.value)}}
+ @supportsExpression={{@supportsExpression}}
+ @placeholder={{@placeholder}}
+ @dynamicValueHint={{@dynamicValueHint}}
+ @session={{@session}}
+ >
+ {{#if @label}}
+ <label class="workflows-property-engine__label">{{@label}}</label>
+ {{/if}}
+ <div class="workflows-property-engine__select-with-action">
+ <ComboBox
+ @content={{this.options}}
+ @value={{this.value}}
+ @nameProperty="name"
+ @valueProperty="id"
+ @onChange={{this.handleChange}}
+ @options={{hash none="discourse_workflows.credentials.select_type"}}
+ />
+ {{#unless this.value}}
+ <DButton
+ @action={{this.setupCredential}}
+ @label="discourse_workflows.credentials.set_up_credential"
+ @icon="plus"
+ class="btn-default"
+ />
+ {{/unless}}
+ </div>
+ </ExpressionWrapper>
+ </template>
+}
diff --git a/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/configurators/data-table-column-select.gjs b/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/configurators/data-table-column-select.gjs
new file mode 100644
index 00000000000..582da06c392
--- /dev/null
+++ b/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/configurators/data-table-column-select.gjs
@@ -0,0 +1,86 @@
+import Component from "@glimmer/component";
+import { tracked } from "@glimmer/tracking";
+import { hash } from "@ember/helper";
+import { action } from "@ember/object";
+import { service } from "@ember/service";
+import ComboBox from "discourse/select-kit/components/combo-box";
+import { propertySelectNoneKey } from "../../../lib/workflows/property-engine";
+import ExpressionWrapper from "./expression-wrapper";
+
+export default class DataTableColumnSelect extends Component {
+ @service workflowsNodeTypes;
+
+ @tracked _loadedDataTables = null;
+
+ constructor(owner, args) {
+ super(owner, args);
+ const identifier =
+ args.nodeDefinition?.name || args.nodeDefinition?.identifier;
+ if (identifier) {
+ this.workflowsNodeTypes
+ .loadNodeParameterOptions(
+ identifier,
+ "data_tables",
+ args.nodeDefinition?.version,
+ args.session?.nodeParameterOptionsContext({
+ path: "data_table_id",
+ currentNodeParameters: args.configuration || {},
+ }) || {
+ path: "data_table_id",
+ currentNodeParameters: args.configuration || {},
+ }
+ )
+ .then((dataTables) => {
+ this._loadedDataTables = dataTables;
+ });
+ }
+ }
+
+ get none() {
+ return (
+ this.args.schema?.ui?.none ||
+ propertySelectNoneKey(this.args.nodeDefinition, this.args.fieldName)
+ );
+ }
+
+ get options() {
+ const id = parseInt(this.args.configuration?.data_table_id, 10);
+ const dataTables =
+ this.args.metadata?.data_tables || this._loadedDataTables || [];
+ const dataTable = dataTables.find((dt) => dt.id === id) || null;
+
+ return (
+ dataTable?.columns?.map((column) => ({
+ id: column.name,
+ name: column.name,
+ })) ?? []
+ );
+ }
+
+ @action
+ handleChange(value) {
+ this.args.field.set(value || "");
+ }
+
+ <template>
+ <ExpressionWrapper
+ @field={{@field}}
+ @supportsExpression={{@supportsExpression}}
+ @placeholder={{@placeholder}}
+ @dynamicValueHint={{@dynamicValueHint}}
+ @session={{@session}}
+ >
+ {{#if this.options.length}}
+ <ComboBox
+ class="workflows-data-table-column-select"
+ @content={{this.options}}
+ @nameProperty="name"
+ @value={{@field.value}}
+ @valueProperty="id"
+ @onChange={{this.handleChange}}
+ @options={{hash none=this.none}}
+ />
+ {{/if}}
+ </ExpressionWrapper>
+ </template>
+}
diff --git a/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/configurators/data-table-columns.gjs b/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/configurators/data-table-columns.gjs
new file mode 100644
index 00000000000..c2a1dcbb3ce
--- /dev/null
+++ b/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/configurators/data-table-columns.gjs
@@ -0,0 +1,80 @@
+import Component from "@glimmer/component";
+import { tracked } from "@glimmer/tracking";
+import { concat } from "@ember/helper";
+import { service } from "@ember/service";
+import Field from "./field";
+
+function schemaForColumn(column) {
+ switch (column.type) {
+ case "number":
+ return { type: "integer", name: column.name, ui: { expression: true } };
+ case "boolean":
+ return { type: "boolean", name: column.name, ui: { expression: true } };
+ default:
+ return { type: "string", name: column.name, ui: { expression: true } };
+ }
+}
+
+export default class DataTableColumns extends Component {
+ @service workflowsNodeTypes;
+
+ @tracked _loadedDataTables = null;
+
+ constructor(owner, args) {
+ super(owner, args);
+ const identifier =
+ args.nodeDefinition?.name || args.nodeDefinition?.identifier;
+ if (identifier) {
+ this.workflowsNodeTypes
+ .loadNodeParameterOptions(
+ identifier,
+ "data_tables",
+ args.nodeDefinition?.version,
+ args.session?.nodeParameterOptionsContext({
+ path: "data_table_id",
+ currentNodeParameters: args.configuration || {},
+ }) || {
+ path: "data_table_id",
+ currentNodeParameters: args.configuration || {},
+ }
+ )
+ .then((dataTables) => {
+ this._loadedDataTables = dataTables;
+ });
+ }
+ }
+
+ get columns() {
+ const id = parseInt(this.args.configuration?.data_table_id, 10);
+ const dataTables =
+ this.args.metadata?.data_tables || this._loadedDataTables || [];
+ const dataTable = dataTables.find((dt) => dt.id === id) || null;
+
+ return (dataTable?.columns ?? []).filter((c) => !c.reserved);
+ }
+
+ get columnsConfiguration() {
+ return this.args.configuration?.[this.args.fieldName] || {};
+ }
+
+ <template>
+ {{#if this.columns.length}}
+ <@form.Section @title={{@label}}>
+ <@form.Object @name={{@fieldName}} as |object|>
+ {{#each this.columns key="name" as |column|}}
+ <Field
+ @form={{object}}
+ @formApi={{@formApi}}
+ @fieldName={{column.name}}
+ @formApiPath={{concat @fieldName "." column.name}}
+ @configuration={{this.columnsConfiguration}}
+ @label={{column.name}}
+ @schema={{schemaForColumn column}}
+ @session={{@session}}
+ />
+ {{/each}}
+ </@form.Object>
+ </@form.Section>
+ {{/if}}
+ </template>
+}
diff --git a/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/configurators/data-table-condition-builder.gjs b/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/configurators/data-table-condition-builder.gjs
new file mode 100644
index 00000000000..fd0f3bc8522
--- /dev/null
+++ b/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/configurators/data-table-condition-builder.gjs
@@ -0,0 +1,234 @@
+import Component from "@glimmer/component";
+import { tracked } from "@glimmer/tracking";
+import { fn, get } from "@ember/helper";
+import { action } from "@ember/object";
+import { service } from "@ember/service";
+import { i18n } from "discourse-i18n";
+import {
+ implicitValueFor,
+ isSingleValueOperator,
+ operatorsForType,
+} from "../../../lib/workflows/condition-operators";
+import Collection from "./collection";
+import Field from "./field";
+
+const VALUE_SCHEMA = { type: "string", required: true };
+
+function columnTypeToFieldType(columnType) {
+ switch (columnType) {
+ case "number":
+ return "number";
+ case "boolean":
+ return "boolean";
+ case "date":
+ return "date";
+ default:
+ return "string";
+ }
+}
+
+function conditionSchema(type) {
+ return {
+ type: "options",
+ required: true,
+ options: operatorsForType(type, { context: "data_table" }),
+ };
+}
+
+export default class DataTableConditionBuilder extends Component {
+ @service workflowsNodeTypes;
+
+ @tracked schemas = this.#initSchemas();
+ @tracked _loadedDataTables = null;
+
+ constructor(owner, args) {
+ super(owner, args);
+ const identifier =
+ args.nodeDefinition?.name || args.nodeDefinition?.identifier;
+ if (identifier) {
+ this.workflowsNodeTypes
+ .loadNodeParameterOptions(
+ identifier,
+ "data_tables",
+ args.nodeDefinition?.version,
+ args.session?.nodeParameterOptionsContext({
+ path: "data_table_id",
+ currentNodeParameters: args.configuration || {},
+ }) || {
+ path: "data_table_id",
+ currentNodeParameters: args.configuration || {},
+ }
+ )
+ .then((dataTables) => {
+ this._loadedDataTables = dataTables;
+ });
+ }
+ }
+
+ get dataTable() {
+ const id = parseInt(this.args.configuration?.data_table_id, 10);
+ const dataTables =
+ this.args.metadata?.data_tables || this._loadedDataTables || [];
+ return dataTables.find((dt) => dt.id === id) || null;
+ }
+
+ get fieldOptions() {
+ return (this.dataTable?.columns ?? []).map((column) => ({
+ id: column.name,
+ label: `${column.name} (${column.type})`,
+ type: columnTypeToFieldType(column.type),
+ }));
+ }
+
+ get columnSchema() {
+ return {
+ type: "options",
+ required: true,
+ options: this.fieldOptions.map((f) => ({ value: f.id, label: f.label })),
+ };
+ }
+
+ #fieldTypeForColumn(columnName) {
+ const field = this.fieldOptions.find((f) => f.id === columnName);
+ return field?.type || "string";
+ }
+
+ #initSchemas() {
+ const items = this.args.formApi?.get(this.args.fieldName) || [];
+ return items.map((item) => this.#buildSchema(item));
+ }
+
+ #buildSchema(item) {
+ const fieldType = this.#fieldTypeForColumn(item?.columnName);
+ return {
+ conditionSchema: conditionSchema(fieldType),
+ singleValue: isSingleValueOperator(item?.operator?.operation),
+ };
+ }
+
+ #updateSchemaAt(index, schema) {
+ const updated = [...this.schemas];
+ updated[index] = schema;
+ this.schemas = updated;
+ }
+
+ @action
+ emptyItem() {
+ return {
+ columnName: "",
+ operator: { type: "string", operation: "equals", singleValue: false },
+ value: "",
+ };
+ }
+
+ @action
+ onItemAdded(item) {
+ this.schemas = [...this.schemas, this.#buildSchema(item)];
+ }
+
+ @action
+ onItemRemoved(index) {
+ const updated = [...this.schemas];
+ updated.splice(index, 1);
+ this.schemas = updated;
+ }
+
+ @action
+ handleColumnChange(index, value, { set, name }) {
+ set(name, value);
+
+ const fieldType = this.#fieldTypeForColumn(value);
+ const defaultOp = operatorsForType(fieldType, { context: "data_table" })[0];
+ const basePath = `${this.args.fieldName}.${index}`;
+
+ set(`${basePath}.operator`, {
+ operation: defaultOp,
+ type: fieldType,
+ singleValue: isSingleValueOperator(defaultOp),
+ });
+ set(`${basePath}.value`, isSingleValueOperator(defaultOp) ? null : "");
+
+ this.#updateSchemaAt(index, {
+ conditionSchema: conditionSchema(fieldType),
+ singleValue: isSingleValueOperator(defaultOp),
+ });
+ }
+
+ @action
+ handleConditionChange(index, value, { set, name }) {
+ set(name, value);
+
+ if (isSingleValueOperator(value)) {
+ set(`${this.args.fieldName}.${index}.value`, implicitValueFor(value));
+ }
+ set(
+ `${this.args.fieldName}.${index}.operator.singleValue`,
+ isSingleValueOperator(value)
+ );
+
+ this.#updateSchemaAt(index, {
+ ...this.schemas[index],
+ singleValue: isSingleValueOperator(value),
+ });
+ }
+
+ <template>
+ {{#if this.dataTable}}
+ <Collection
+ @form={{@form}}
+ @formApi={{@formApi}}
+ @fieldName={{@fieldName}}
+ @label={{@label}}
+ @addLabel={{i18n "discourse_workflows.if.add_condition"}}
+ @emptyItem={{this.emptyItem}}
+ @onAdd={{this.onItemAdded}}
+ @onRemove={{this.onItemRemoved}}
+ @session={{@session}}
+ @emptyStateDescription={{i18n
+ "discourse_workflows.if.no_conditions_body"
+ }}
+ as |ctx|
+ >
+ <Field
+ @form={{ctx.object}}
+ @formApi={{@formApi}}
+ @configuration={{ctx.item}}
+ @fieldName="columnName"
+ @schema={{this.columnSchema}}
+ @label={{i18n "discourse_workflows.if.column"}}
+ @session={{@session}}
+ @onSet={{fn this.handleColumnChange ctx.index}}
+ />
+
+ {{#let (get this.schemas ctx.index) as |schemas|}}
+ {{#if schemas}}
+ <ctx.object.Object @name="operator" as |operator|>
+ <Field
+ @form={{operator}}
+ @formApi={{@formApi}}
+ @configuration={{ctx.item.operator}}
+ @fieldName="operation"
+ @schema={{schemas.conditionSchema}}
+ @label={{i18n "discourse_workflows.if.operator"}}
+ @session={{@session}}
+ @onSet={{fn this.handleConditionChange ctx.index}}
+ />
+ </ctx.object.Object>
+
+ {{#unless schemas.singleValue}}
+ <Field
+ @form={{ctx.object}}
+ @formApi={{@formApi}}
+ @configuration={{ctx.item}}
+ @fieldName="value"
+ @schema={{VALUE_SCHEMA}}
+ @label={{i18n "discourse_workflows.if.value"}}
+ @session={{@session}}
+ />
+ {{/unless}}
+ {{/if}}
+ {{/let}}
+ </Collection>
+ {{/if}}
+ </template>
+}
diff --git a/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/configurators/data-table-select.gjs b/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/configurators/data-table-select.gjs
new file mode 100644
index 00000000000..06e20b6df5a
--- /dev/null
+++ b/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/configurators/data-table-select.gjs
@@ -0,0 +1,51 @@
+import { hash } from "@ember/helper";
+import { action } from "@ember/object";
+import { service } from "@ember/service";
+import DButton from "discourse/ui-kit/d-button";
+import ComboBoxField, { DynamicOptionsComboBox } from "./combo-box";
+import ExpressionWrapper from "./expression-wrapper";
+
+export default class DataTableSelect extends ComboBoxField {
+ @service router;
+
+ @action
+ manageDataTables() {
+ this.router.transitionTo(
+ "adminPlugins.show.discourse-workflows-data-tables"
+ );
+ }
+
+ <template>
+ <ExpressionWrapper
+ @field={{@field}}
+ @supportsExpression={{@supportsExpression}}
+ @placeholder={{@placeholder}}
+ @dynamicValueHint={{@dynamicValueHint}}
+ @session={{@session}}
+ >
+ <div class="workflows-property-engine__select-with-action">
+ <DynamicOptionsComboBox
+ @content={{this.options}}
+ @loadOptions={{if this.usesRemoteOptions this.loadRemoteOptions}}
+ @nameProperty="name"
+ @value={{@field.value}}
+ @valueProperty="id"
+ @onChange={{this.handleChange}}
+ @options={{hash
+ filterable=this.filterable
+ none=this.none
+ castInteger=this.castInteger
+ }}
+ />
+ {{#unless @field.value}}
+ <DButton
+ @action={{this.manageDataTables}}
+ @label="discourse_workflows.data_tables.manage_data_tables"
+ @icon="plus"
+ class="btn-default"
+ />
+ {{/unless}}
+ </div>
+ </ExpressionWrapper>
+ </template>
+}
diff --git a/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/configurators/default-input-control.gjs b/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/configurators/default-input-control.gjs
new file mode 100644
index 00000000000..61f5d65cee3
--- /dev/null
+++ b/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/configurators/default-input-control.gjs
@@ -0,0 +1,13 @@
+import ExpressionWrapper from "./expression-wrapper";
+
+<template>
+ <ExpressionWrapper
+ @field={{@field}}
+ @supportsExpression={{@supportsExpression}}
+ @placeholder={{@placeholder}}
+ @dynamicValueHint={{@dynamicValueHint}}
+ @session={{@session}}
+ >
+ <@field.Control placeholder={{@placeholder}} />
+ </ExpressionWrapper>
+</template>
diff --git a/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/configurators/expression-input.gjs b/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/configurators/expression-input.gjs
new file mode 100644
index 00000000000..b8d3672b45d
--- /dev/null
+++ b/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/configurators/expression-input.gjs
@@ -0,0 +1,161 @@
+import Component from "@glimmer/component";
+import { tracked } from "@glimmer/tracking";
+import { action } from "@ember/object";
+import didInsert from "@ember/render-modifiers/modifiers/did-insert";
+import { cancel } from "@ember/runloop";
+import { service } from "@ember/service";
+import discourseLater from "discourse/lib/later";
+import buildWorkflowExtension from "../../../lib/workflows/codemirror-extension";
+import {
+ ancestorOutputNodes,
+ inputConnectionsForNode,
+ inputIndexForConnection,
+ inputSummaryForNode,
+ nodeItemJsonPath,
+ outputIndexForConnection,
+ previousNodeForConnection,
+ schemaFieldsForNodeInput,
+ schemaFieldsForNodeOutput,
+} from "../../../lib/workflows/data-schema";
+import ExpressionPreview from "../variable/expression-preview";
+import VariableInput from "../variable/input";
+
+export default class ExpressionInput extends Component {
+ @service siteSettings;
+ @service workflowsNodeTypes;
+
+ @tracked isFocused = false;
+ @tracked segments = [];
+ wrapperElement = null;
+ #focusOutTimer = null;
+
+ willDestroy() {
+ super.willDestroy(...arguments);
+ cancel(this.#focusOutTimer);
+ }
+
+ get displayValue() {
+ const val = this.args.field.value;
+ if (typeof val === "string" && val.startsWith("=")) {
+ return val.slice(1);
+ }
+ return val ?? "";
+ }
+
+ get triggerElement() {
+ return (
+ this.wrapperElement?.querySelector(".workflows-variable-input") ||
+ this.wrapperElement
+ );
+ }
+
+ @action
+ buildExtensions(cmParams) {
+ const session = this.args.session;
+ const node = session?.editingNode;
+ const graph = {
+ nodes: session?.graphNodes || [],
+ connections: session?.graphConnections || [],
+ nodeTypes: this.workflowsNodeTypes.nodeTypes || [],
+ };
+ const itemPrefix =
+ this.workflowsNodeTypes.expressionContext.item_prefix || "$json";
+ const runData = session?.lastExecutionRunData || {};
+ const previousConnection = node
+ ? inputConnectionsForNode(node, graph)[0]
+ : null;
+ const previousNode = previousNodeForConnection(previousConnection, graph);
+ const currentInputIndex = previousConnection
+ ? inputIndexForConnection(previousConnection)
+ : 0;
+ const currentInputSummary = node
+ ? inputSummaryForNode(runData, node.name, currentInputIndex)
+ : null;
+ let inputFields = [];
+ if (currentInputSummary) {
+ inputFields = schemaFieldsForNodeInput(runData, node.name, {
+ inputIndex: currentInputIndex,
+ prefix: itemPrefix,
+ });
+ } else if (previousNode) {
+ inputFields = schemaFieldsForNodeOutput(runData, previousNode.name, {
+ outputIndex: outputIndexForConnection(previousConnection),
+ prefix: itemPrefix,
+ });
+ }
+ const ancestorNodes = node
+ ? ancestorOutputNodes(node, graph).map((ancestor) => ({
+ node: ancestor.node,
+ fields: schemaFieldsForNodeOutput(runData, ancestor.node.name, {
+ outputIndex: ancestor.outputIndex,
+ prefix: nodeItemJsonPath(ancestor.node.name),
+ }),
+ }))
+ : [];
+
+ return buildWorkflowExtension(cmParams, {
+ inputFields,
+ ancestorNodes,
+ siteSettings: this.siteSettings,
+ workflowVars: this.workflowsNodeTypes.workflowVars,
+ nodes: graph.nodes,
+ itemPrefix,
+ workflowId: session?.workflowId,
+ nodeId: node?.id,
+ onSegmentsResolved: (segs) => (this.segments = segs),
+ });
+ }
+
+ @action
+ handleChange(value) {
+ this.args.field.set(`=${value}`);
+ }
+
+ @action
+ handleFocusIn() {
+ cancel(this.#focusOutTimer);
+ this.isFocused = true;
+ }
+
+ @action
+ handleFocusOut() {
+ this.#focusOutTimer = discourseLater(() => {
+ if (this.isDestroying || this.isDestroyed) {
+ return;
+ }
+ const editor = this.wrapperElement?.querySelector(".cm-editor");
+ if (editor?.contains(document.activeElement)) {
+ return;
+ }
+ const tooltip = document.querySelector(
+ '[data-identifier="expression-preview"]'
+ );
+ if (tooltip?.contains(document.activeElement)) {
+ return;
+ }
+ this.isFocused = false;
+ }, 150);
+ }
+
+ @action
+ registerWrapper(element) {
+ this.wrapperElement = element;
+ }
+
+ <template>
+ <div {{didInsert this.registerWrapper}}>
+ <VariableInput
+ @value={{this.displayValue}}
+ @onChange={{this.handleChange}}
+ @extensions={{this.buildExtensions}}
+ @onFocusIn={{this.handleFocusIn}}
+ @onFocusOut={{this.handleFocusOut}}
+ />
+ </div>
+ <ExpressionPreview
+ @segments={{this.segments}}
+ @trigger={{this.triggerElement}}
+ @visible={{this.isFocused}}
+ />
+ </template>
+}
diff --git a/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/configurators/expression-wrapper.gjs b/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/configurators/expression-wrapper.gjs
new file mode 100644
index 00000000000..77d559bf6eb
--- /dev/null
+++ b/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/configurators/expression-wrapper.gjs
@@ -0,0 +1,183 @@
+import Component from "@glimmer/component";
+import { tracked } from "@glimmer/tracking";
+import { on } from "@ember/modifier";
+import { action } from "@ember/object";
+import { service } from "@ember/service";
+import DSegmentedControl from "discourse/components/d-segmented-control";
+import dConcatClass from "discourse/ui-kit/helpers/d-concat-class";
+import { i18n } from "discourse-i18n";
+import {
+ resolveVariableId,
+ WORKFLOW_VARIABLE_MIME,
+} from "../../../lib/workflows/expression-context";
+import { isExpression } from "../../../lib/workflows/property-engine";
+import ExpressionInput from "./expression-input";
+
+const MODE_ITEMS = [
+ {
+ value: "plain",
+ icon: "paragraph",
+ label: i18n("discourse_workflows.parameter_field.plain"),
+ },
+ {
+ value: "dynamic",
+ icon: "code",
+ label: i18n("discourse_workflows.parameter_field.dynamic"),
+ },
+];
+
+function plainValueForModeToggle(value) {
+ if (value === null || value === undefined) {
+ return "";
+ }
+
+ if (typeof value === "string") {
+ return value;
+ }
+
+ if (typeof value === "object") {
+ return JSON.stringify(value, null, 2);
+ }
+
+ return String(value);
+}
+
+export default class ExpressionWrapper extends Component {
+ @service workflowsNodeTypes;
+
+ @tracked isDragOver = false;
+ dragEndHandler = null;
+
+ willDestroy() {
+ super.willDestroy(...arguments);
+ if (this.dragEndHandler) {
+ document.removeEventListener("dragend", this.dragEndHandler);
+ this.dragEndHandler = null;
+ }
+ }
+
+ get expressionMode() {
+ return isExpression(this.args.field?.value);
+ }
+
+ @action
+ toggleMode(value) {
+ const wantsDynamic = value === "dynamic";
+ if (wantsDynamic === this.expressionMode) {
+ return;
+ }
+
+ const currentValue = plainValueForModeToggle(this.args.field.value);
+
+ if (wantsDynamic) {
+ this.args.field.set(
+ currentValue.startsWith("=") ? currentValue : `=${currentValue}`
+ );
+ } else {
+ this.args.field.set(
+ currentValue.startsWith("=") ? currentValue.slice(1) : currentValue
+ );
+ }
+ }
+
+ @action
+ handleDragOver(event) {
+ if (!this.args.supportsExpression) {
+ return;
+ }
+ if (!event.dataTransfer.types.includes(WORKFLOW_VARIABLE_MIME)) {
+ return;
+ }
+ event.preventDefault();
+ event.dataTransfer.dropEffect = "copy";
+ this.isDragOver = true;
+
+ // Safety: clear on next dragend in case dragleave doesn't fire
+ if (!this.dragEndHandler) {
+ this.dragEndHandler = () => {
+ this.isDragOver = false;
+ document.removeEventListener("dragend", this.dragEndHandler);
+ this.dragEndHandler = null;
+ };
+ document.addEventListener("dragend", this.dragEndHandler, {
+ once: true,
+ });
+ }
+ }
+
+ @action
+ handleDragLeave(event) {
+ if (!event.currentTarget.contains(event.relatedTarget)) {
+ this.isDragOver = false;
+ }
+ }
+
+ @action
+ handleDrop(event) {
+ this.isDragOver = false;
+
+ if (!this.args.supportsExpression || this.expressionMode) {
+ return;
+ }
+
+ const data = event.dataTransfer.getData(WORKFLOW_VARIABLE_MIME);
+ if (!data) {
+ return;
+ }
+
+ event.preventDefault();
+ event.stopPropagation();
+
+ let variable;
+ try {
+ variable = JSON.parse(data);
+ } catch {
+ return;
+ }
+
+ const prefix =
+ this.workflowsNodeTypes.expressionContext.item_prefix || "$json";
+ const variableId = resolveVariableId(variable, prefix);
+
+ this.args.field.set(`={{ ${variableId} }}`);
+ }
+
+ <template>
+ <div
+ class={{dConcatClass
+ "workflows-property-engine__control-wrapper"
+ (if this.isDragOver "is-drag-over")
+ }}
+ data-supports-expression={{if @supportsExpression "true"}}
+ {{on "dragover" this.handleDragOver}}
+ {{on "dragleave" this.handleDragLeave}}
+ {{on "drop" this.handleDrop}}
+ >
+ {{#if this.expressionMode}}
+ <ExpressionInput
+ @field={{@field}}
+ @placeholder={{@placeholder}}
+ @session={{@session}}
+ @autofocus={{true}}
+ />
+ {{#if @dynamicValueHint}}
+ <p class="workflows-property-engine__dynamic-hint">
+ {{@dynamicValueHint}}
+ </p>
+ {{/if}}
+ {{else}}
+ {{yield}}
+ {{/if}}
+
+ {{#if @supportsExpression}}
+ <DSegmentedControl
+ @items={{MODE_ITEMS}}
+ @value={{if this.expressionMode "dynamic" "plain"}}
+ @onSelect={{this.toggleMode}}
+ @size="small"
+ class="workflows-property-engine__mode-control"
+ />
+ {{/if}}
+ </div>
+ </template>
+}
diff --git a/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/configurators/field.gjs b/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/configurators/field.gjs
new file mode 100644
index 00000000000..7e2d9c4523d
--- /dev/null
+++ b/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/configurators/field.gjs
@@ -0,0 +1,235 @@
+import Component from "@glimmer/component";
+import { trustHTML } from "@ember/template";
+import { eq } from "discourse/truth-helpers";
+import { i18n } from "discourse-i18n";
+import FIELD_CONTROL_REGISTRY from "../../../lib/workflows/field-control-registry";
+import {
+ fieldControl,
+ fieldFormat,
+ fieldInputType,
+ fieldShowDescription,
+ fieldShowLabel,
+ fieldSupportsExpression,
+ findNodeType,
+ isExpression,
+ propertyDescription,
+ propertyDynamicValueHint,
+ propertyLabel,
+ propertyPlaceholder,
+} from "../../../lib/workflows/property-engine";
+
+const CRON_FIELD_PATTERN =
+ /^(\*|\d+(-\d+)?(\/\d+)?|\*\/\d+)(,(\*|\d+(-\d+)?(\/\d+)?|\*\/\d+))*$/;
+
+function isValidCron(value) {
+ if (!value || typeof value !== "string") {
+ return false;
+ }
+ const fields = value.trim().split(/\s+/);
+ return fields.length === 5 && fields.every((f) => CRON_FIELD_PATTERN.test(f));
+}
+
+const FIELD_VALIDATORS = {
+ cron: (name, value, { addError }) => {
+ if (value && !isExpression(value) && !isValidCron(value)) {
+ addError(name, {
+ title: i18n("discourse_workflows.schedule.cron"),
+ message: i18n("discourse_workflows.schedule.cron_invalid"),
+ });
+ }
+ },
+};
+
+export default class Field extends Component {
+ get control() {
+ return fieldControl(this.args.schema);
+ }
+
+ get entry() {
+ return (
+ FIELD_CONTROL_REGISTRY[this.control] || FIELD_CONTROL_REGISTRY.default
+ );
+ }
+
+ get renderer() {
+ return this.entry.renderer;
+ }
+
+ get resolvedFieldType() {
+ const { type } = this.entry;
+ if (typeof type === "function") {
+ return type({ inputType: this.inputType });
+ }
+ return type;
+ }
+
+ get isCustomType() {
+ return this.resolvedFieldType === "custom";
+ }
+
+ get inputType() {
+ return fieldInputType(this.args.schema);
+ }
+
+ get label() {
+ return (
+ this.args.label || propertyLabel(this.nodeDefinition, this.args.fieldName)
+ );
+ }
+
+ get metadata() {
+ return this.args.metadata || this.nodeDefinition?.metadata || {};
+ }
+
+ get nodeDefinition() {
+ return (
+ this.args.nodeDefinition ||
+ findNodeType(this.args.nodeTypes, this.nodeType)
+ );
+ }
+
+ get nodeType() {
+ return this.args.nodeType || this.args.node?.type;
+ }
+
+ get placeholder() {
+ return propertyPlaceholder(this.nodeDefinition, this.args.fieldName);
+ }
+
+ get showLabel() {
+ return fieldShowLabel(this.args.schema);
+ }
+
+ get format() {
+ return fieldFormat(this.args.schema);
+ }
+
+ get supportsExpression() {
+ return fieldSupportsExpression(this.args.schema);
+ }
+
+ get validation() {
+ const schema = this.args.schema ?? {};
+ const rules = [];
+ if (schema.required) {
+ rules.push("required");
+ }
+ if (schema.min != null || schema.max != null) {
+ const min = schema.min ?? Number.MIN_SAFE_INTEGER;
+ const max = schema.max ?? Number.MAX_SAFE_INTEGER;
+ rules.push(`between:${min},${max}`);
+ }
+ return rules.length > 0 ? rules.join("|") : undefined;
+ }
+
+ get customValidation() {
+ return FIELD_VALIDATORS[this.args.schema?.validate];
+ }
+
+ get fieldDescription() {
+ if (!fieldShowDescription(this.args.schema)) {
+ return undefined;
+ }
+ const description = propertyDescription(
+ this.nodeDefinition,
+ this.args.fieldName
+ );
+ return description ? trustHTML(description) : undefined;
+ }
+
+ get dynamicValueHint() {
+ if (!this.supportsExpression) {
+ return null;
+ }
+
+ return propertyDynamicValueHint(
+ this.nodeDefinition,
+ this.args.fieldName,
+ this.args.schema
+ );
+ }
+
+ get fieldTitle() {
+ return this.label || this.args.fieldName || "-";
+ }
+
+ <template>
+ {{#if (eq this.entry.kind "standalone")}}
+ <this.renderer
+ @form={{@form}}
+ @formApi={{@formApi}}
+ @configuration={{@configuration}}
+ @connections={{@connections}}
+ @credentials={{@credentials}}
+ @fieldName={{@fieldName}}
+ @label={{this.fieldTitle}}
+ @metadata={{this.metadata}}
+ @node={{@node}}
+ @nodeParameters={{@nodeParameters}}
+ @nodes={{@nodes}}
+ @nodeDefinition={{this.nodeDefinition}}
+ @nodeTypes={{@nodeTypes}}
+ @schema={{@schema}}
+ @session={{@session}}
+ @dynamicValueHint={{this.dynamicValueHint}}
+ @onSet={{@onSet}}
+ @onBeforeStartTestSession={{@onBeforeStartTestSession}}
+ />
+ {{else}}
+ <@form.Field
+ @name={{@fieldName}}
+ @title={{this.fieldTitle}}
+ @showTitle={{this.showLabel}}
+ @description={{this.fieldDescription}}
+ @type={{this.resolvedFieldType}}
+ @format={{this.format}}
+ @validation={{this.validation}}
+ @validate={{this.customValidation}}
+ @onSet={{@onSet}}
+ as |field|
+ >
+ {{#if this.isCustomType}}
+ <field.Control>
+ <this.renderer
+ @field={{field}}
+ @fieldName={{@fieldName}}
+ @schema={{@schema}}
+ @configuration={{@configuration}}
+ @credentials={{@credentials}}
+ @metadata={{this.metadata}}
+ @node={{@node}}
+ @nodeDefinition={{this.nodeDefinition}}
+ @nodeParameters={{@nodeParameters}}
+ @nodes={{@nodes}}
+ @formApi={{@formApi}}
+ @session={{@session}}
+ @supportsExpression={{this.supportsExpression}}
+ @placeholder={{this.placeholder}}
+ @dynamicValueHint={{this.dynamicValueHint}}
+ @onBeforeStartTestSession={{@onBeforeStartTestSession}}
+ />
+ </field.Control>
+ {{else}}
+ <this.renderer
+ @field={{field}}
+ @fieldName={{@fieldName}}
+ @schema={{@schema}}
+ @configuration={{@configuration}}
+ @credentials={{@credentials}}
+ @metadata={{this.metadata}}
+ @node={{@node}}
+ @nodeDefinition={{this.nodeDefinition}}
+ @nodeParameters={{@nodeParameters}}
+ @nodes={{@nodes}}
+ @formApi={{@formApi}}
+ @session={{@session}}
+ @supportsExpression={{this.supportsExpression}}
+ @placeholder={{this.placeholder}}
+ @dynamicValueHint={{this.dynamicValueHint}}
+ @onBeforeStartTestSession={{@onBeforeStartTestSession}}
+ />
+ {{/if}}
+ </@form.Field>
+ {{/if}}
+ </template>
+}
diff --git a/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/configurators/filter-query.gjs b/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/configurators/filter-query.gjs
new file mode 100644
index 00000000000..1da99e39ab9
--- /dev/null
+++ b/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/configurators/filter-query.gjs
@@ -0,0 +1,47 @@
+import Component from "@glimmer/component";
+import { tracked } from "@glimmer/tracking";
+import { action } from "@ember/object";
+import FilterNavigationMenu from "discourse/components/discovery/filter-navigation-menu";
+import { ajax } from "discourse/lib/ajax";
+import ExpressionWrapper from "./expression-wrapper";
+
+export default class FilterQuery extends Component {
+ @tracked tips = null;
+
+ constructor() {
+ super(...arguments);
+ this.loadTips();
+ }
+
+ async loadTips() {
+ try {
+ const result = await ajax("/filter.json");
+ this.tips = result.topic_list?.filter_option_info || [];
+ } catch {
+ this.tips = [];
+ }
+ }
+
+ @action
+ handleChange(value) {
+ this.args.field.set(value);
+ }
+
+ <template>
+ <ExpressionWrapper
+ @field={{@field}}
+ @supportsExpression={{@supportsExpression}}
+ @placeholder={{@placeholder}}
+ @dynamicValueHint={{@dynamicValueHint}}
+ @session={{@session}}
+ >
+ {{#if this.tips}}
+ <FilterNavigationMenu
+ @initialInputValue={{@field.value}}
+ @onChange={{this.handleChange}}
+ @tips={{this.tips}}
+ />
+ {{/if}}
+ </ExpressionWrapper>
+ </template>
+}
diff --git a/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/configurators/fixed-collection.gjs b/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/configurators/fixed-collection.gjs
new file mode 100644
index 00000000000..0b08325b492
--- /dev/null
+++ b/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/configurators/fixed-collection.gjs
@@ -0,0 +1,575 @@
+import Component from "@glimmer/component";
+import { tracked } from "@glimmer/tracking";
+import { fn, hash } from "@ember/helper";
+import { action } from "@ember/object";
+import DMenu from "discourse/float-kit/components/d-menu";
+import DButton from "discourse/ui-kit/d-button";
+import DDropdownMenu from "discourse/ui-kit/d-dropdown-menu";
+import dIcon from "discourse/ui-kit/helpers/d-icon";
+import { i18n } from "discourse-i18n";
+import {
+ collectionAddLabel,
+ emptyCollectionItem,
+ emptyFixedCollectionItem,
+ fieldType,
+ fieldVisible,
+ findNodeType,
+ fixedCollectionGroup,
+ fixedCollectionGroupMultiple,
+ fixedCollectionGroups,
+ normalizeSchema,
+ propertyDescription,
+ propertyLabel,
+} from "../../../lib/workflows/property-engine";
+import WorkflowsEmptyState from "../empty-state";
+import Field from "./field";
+
+function isCollection(field) {
+ return fieldType(field) === "fixed_collection";
+}
+
+function isItemFieldVisible(field, item) {
+ return fieldVisible(field, item);
+}
+
+function hasNonDefaultValue(item, field) {
+ const value = item[field.name];
+ if (field.type === "boolean") {
+ return value === true;
+ }
+ return value !== undefined && value !== null && value !== "";
+}
+
+function isExtraFieldShown(field, item, activeAttrs, key) {
+ if (!fieldVisible(field, item)) {
+ return false;
+ }
+ if (field.display_options?.show) {
+ return true;
+ }
+ const explicit = activeAttrs.get(key);
+ if (explicit?.has(field.name)) {
+ return true;
+ }
+ return hasNonDefaultValue(item, field);
+}
+
+export default class FixedCollection extends Component {
+ @tracked activeAttrs = new Map();
+ @tracked itemCounts = new Map();
+
+ get groups() {
+ return fixedCollectionGroups(this.args.schema).length
+ ? fixedCollectionGroups(this.args.schema)
+ : [fixedCollectionGroup(this.args.schema)];
+ }
+
+ get hasMultipleGroups() {
+ return this.groups.length > 1;
+ }
+
+ get addLabel() {
+ return (
+ this.args.addLabel ||
+ collectionAddLabel(
+ this.nodeDefinition,
+ this.args.fieldName,
+ this.args.schema
+ )
+ );
+ }
+
+ get description() {
+ return propertyDescription(this.nodeDefinition, this.args.fieldName);
+ }
+
+ get label() {
+ return (
+ this.args.label || propertyLabel(this.nodeDefinition, this.args.fieldName)
+ );
+ }
+
+ get isFlat() {
+ return this.args.schema?.ui?.flat === true;
+ }
+
+ get hide_optional_fields() {
+ const type_options = this.args.schema.type_options || {};
+ return type_options.hide_optional_fields;
+ }
+
+ get nodeDefinition() {
+ return (
+ this.args.nodeDefinition ||
+ findNodeType(this.args.nodeTypes, this.args.nodeType)
+ );
+ }
+
+ get maxItems() {
+ const type_options = this.args.schema?.type_options || {};
+ return (
+ this.args.schema?.max_items ?? type_options.max_allowed_fields ?? null
+ );
+ }
+
+ get maxItemsReachedTitle() {
+ return i18n("discourse_workflows.property_engine.max_items_reached", {
+ count: this.maxItems,
+ });
+ }
+
+ @action
+ groupPath(group) {
+ return `${this.args.fieldName}.${group.name}`;
+ }
+
+ @action
+ groupLabel(group) {
+ return group.display_name || group.name;
+ }
+
+ @action
+ isMultiple(group) {
+ return fixedCollectionGroupMultiple(group, this.args.schema);
+ }
+
+ @action
+ itemCount(group) {
+ const path = this.groupPath(group);
+ if (this.itemCounts.has(path)) {
+ return this.itemCounts.get(path);
+ }
+
+ const value = this.args.formApi?.get(path);
+ if (Array.isArray(value)) {
+ return value.length;
+ }
+ return value && typeof value === "object" ? 1 : 0;
+ }
+
+ @action
+ atMaxItems(group) {
+ return this.maxItems !== null && this.itemCount(group) >= this.maxItems;
+ }
+
+ @action
+ showEmptyState(group) {
+ return this.args.emptyStateDescription && this.itemCount(group) === 0;
+ }
+
+ @action
+ valuesSchema(group) {
+ return group.values || {};
+ }
+
+ @action
+ allItemFields(group) {
+ return normalizeSchema(this.valuesSchema(group));
+ }
+
+ @action
+ itemFields(group) {
+ const fields = this.allItemFields(group);
+ if (!this.hide_optional_fields) {
+ return fields;
+ }
+
+ return fields.filter(
+ (field) => field.required || field.show_even_when_optional
+ );
+ }
+
+ @action
+ extraItemFields(group) {
+ const explicitExtra = normalizeSchema(
+ this.args.schema.extra_item_schema || {}
+ );
+ if (!this.hide_optional_fields) {
+ return explicitExtra;
+ }
+
+ return [
+ ...explicitExtra,
+ ...this.allItemFields(group).filter(
+ (field) => !field.required && !field.show_even_when_optional
+ ),
+ ];
+ }
+
+ @action
+ hasExtraFieldsFor(group) {
+ return this.extraItemFields(group).length > 0;
+ }
+
+ @action
+ emptyItem(group) {
+ return emptyFixedCollectionItem(group);
+ }
+
+ @action
+ addItem(group) {
+ if (this.atMaxItems(group)) {
+ return;
+ }
+ const path = this.groupPath(group);
+ const item = this.args.emptyItem
+ ? this.args.emptyItem()
+ : this.emptyItem(group);
+ this.args.form.addItemToCollection(path, item);
+ this.args.onAdd?.(item);
+ this.itemCounts = new Map(this.itemCounts).set(
+ path,
+ this.itemCount(group) + 1
+ );
+ this.args.onChange?.();
+ }
+
+ @action
+ fieldLabel(fieldName) {
+ return propertyLabel(this.nodeDefinition, fieldName);
+ }
+
+ @action
+ removeItem(group, removeFn, index) {
+ this.args.onRemove?.(index);
+ const path = this.groupPath(group);
+ const newMap = new Map(this.activeAttrs);
+ newMap.delete(`${group.name}:${index}`);
+ this.activeAttrs = newMap;
+ removeFn(index);
+ this.itemCounts = new Map(this.itemCounts).set(
+ path,
+ Math.max(this.itemCount(group) - 1, 0)
+ );
+ this.args.onChange?.();
+ }
+
+ @action
+ isAttrActive(group, index, field, item) {
+ return isExtraFieldShown(
+ field,
+ item,
+ this.activeAttrs,
+ this.activeAttrKey(group, index)
+ );
+ }
+
+ @action
+ activeAttrKey(group, index) {
+ return `${group.name}:${index}`;
+ }
+
+ @action
+ toggleAttr(group, index, field, item, close) {
+ const key = `${group.name}:${index}`;
+ const active = this.isAttrActive(group, index, field, item);
+ const newMap = new Map(this.activeAttrs);
+ const set = new Set(newMap.get(key) || []);
+
+ if (active) {
+ set.delete(field.name);
+ const defaultVal =
+ field.type === "boolean" ? false : (field.default ?? "");
+ this.args.formApi.set(
+ `${this.groupPath(group)}.${index}.${field.name}`,
+ defaultVal
+ );
+ } else {
+ set.add(field.name);
+ }
+
+ newMap.set(key, set);
+ this.activeAttrs = newMap;
+ close?.();
+ }
+
+ @action
+ nestedItemFields(extraField) {
+ return normalizeSchema(fixedCollectionGroup(extraField).values || {});
+ }
+
+ @action
+ nestedCollectionName(extraField) {
+ return `${extraField.name}.${fixedCollectionGroup(extraField).name}`;
+ }
+
+ @action
+ addNestedItem(group, parentIndex, extraField) {
+ const nestedGroup = fixedCollectionGroup(extraField);
+ const path = `${this.groupPath(group)}.${parentIndex}.${extraField.name}.${nestedGroup.name}`;
+ const current = this.args.formApi.get(path) || [];
+ const newItem = emptyCollectionItem(nestedGroup.values || {});
+ this.args.formApi.set(path, [...current, newItem]);
+ }
+
+ @action
+ removeNestedItem(removeFn, index) {
+ removeFn(index);
+ this.args.onChange?.();
+ }
+
+ @action
+ availableExtraFields(group, item) {
+ return this.extraItemFields(group).filter((field) =>
+ fieldVisible(field, item)
+ );
+ }
+
+ <template>
+ <@form.Section @title={{this.label}} @subtitle={{this.description}}>
+ {{#each this.groups key="name" as |group|}}
+ {{#if this.hasMultipleGroups}}
+ <span class="workflows-property-engine__block-field-label">
+ {{this.groupLabel group}}
+ </span>
+ {{/if}}
+
+ {{#if (this.isMultiple group)}}
+ <@form.Collection
+ @name={{this.groupPath group}}
+ @tagName="div"
+ as |collection index item|
+ >
+ <div class="workflows-property-engine__collection-row">
+ <div class="workflows-property-engine__collection-delete">
+ <DButton
+ @action={{fn this.removeItem group collection.remove index}}
+ @icon="trash-can"
+ class="btn-transparent btn-small btn-danger"
+ />
+ </div>
+
+ <collection.Object
+ class={{if
+ this.isFlat
+ "workflows-property-engine__collection-flat"
+ "workflows-property-engine__collection-fields"
+ }}
+ as |object|
+ >
+ {{#if (has-block)}}
+ {{yield (hash object=object item=item index=index)}}
+ {{else}}
+ {{#each (this.itemFields group) key="name" as |itemField|}}
+ {{#if (isItemFieldVisible itemField item)}}
+ <Field
+ @form={{object}}
+ @formApi={{@formApi}}
+ @configuration={{item}}
+ @connections={{@connections}}
+ @credentials={{@credentials}}
+ @fieldName={{itemField.name}}
+ @node={{@node}}
+ @nodeDefinition={{this.nodeDefinition}}
+ @nodeParameters={{@nodeParameters}}
+ @nodeType={{@nodeType}}
+ @nodes={{@nodes}}
+ @nodeTypes={{@nodeTypes}}
+ @schema={{itemField}}
+ @session={{@session}}
+ />
+ {{/if}}
+ {{/each}}
+
+ {{#each
+ (this.extraItemFields group) key="name"
+ as |extraField|
+ }}
+ {{#if
+ (isExtraFieldShown
+ extraField
+ item
+ this.activeAttrs
+ (this.activeAttrKey group index)
+ )
+ }}
+ {{#if (isCollection extraField)}}
+ <div
+ class="workflows-property-engine__nested-collection"
+ >
+ <span
+ class="workflows-property-engine__block-field-label"
+ >{{this.fieldLabel extraField.name}}</span>
+
+ <object.Collection
+ @name={{this.nestedCollectionName extraField}}
+ @tagName="div"
+ as |subCollection subIndex|
+ >
+ <subCollection.Object
+ class="workflows-property-engine__nested-collection-item"
+ as |subObject|
+ >
+
+ {{#each
+ (this.nestedItemFields extraField) key="name"
+ as |subField|
+ }}
+ <Field
+ @form={{subObject}}
+ @formApi={{@formApi}}
+ @connections={{@connections}}
+ @credentials={{@credentials}}
+ @fieldName={{subField.name}}
+ @node={{@node}}
+ @nodeDefinition={{this.nodeDefinition}}
+ @nodeParameters={{@nodeParameters}}
+ @nodeType={{@nodeType}}
+ @nodes={{@nodes}}
+ @nodeTypes={{@nodeTypes}}
+ @schema={{subField}}
+ @session={{@session}}
+ />
+ {{/each}}
+
+ <DButton
+ @action={{fn
+ this.removeNestedItem
+ subCollection.remove
+ subIndex
+ }}
+ @icon="trash-can"
+ class="btn-flat btn-danger btn-small"
+ />
+ </subCollection.Object>
+ </object.Collection>
+
+ <DButton
+ @action={{fn
+ this.addNestedItem
+ group
+ index
+ extraField
+ }}
+ @icon="plus"
+ @translatedLabel={{i18n
+ "discourse_workflows.property_engine.add_item"
+ }}
+ class="btn-default btn-small"
+ />
+ </div>
+ {{else}}
+ <Field
+ @form={{object}}
+ @formApi={{@formApi}}
+ @connections={{@connections}}
+ @credentials={{@credentials}}
+ @fieldName={{extraField.name}}
+ @node={{@node}}
+ @nodeDefinition={{this.nodeDefinition}}
+ @nodeParameters={{@nodeParameters}}
+ @nodeType={{@nodeType}}
+ @nodes={{@nodes}}
+ @nodeTypes={{@nodeTypes}}
+ @schema={{extraField}}
+ @session={{@session}}
+ />
+ {{/if}}
+ {{/if}}
+ {{/each}}
+
+ {{#if (this.hasExtraFieldsFor group)}}
+ <div class="workflows-property-engine__block-actions">
+ <DMenu
+ class="btn btn-default workflows-property-engine__add-attrs-btn"
+ @inline={{true}}
+ @modalForwardRecipient={{true}}
+ >
+ <:trigger>
+ {{i18n
+ "discourse_workflows.property_engine.add_attributes"
+ }}
+ {{dIcon "chevron-down"}}
+ </:trigger>
+ <:content as |menu|>
+ <DDropdownMenu as |dropdown|>
+ {{#each
+ (this.availableExtraFields group item) key="name"
+ as |extraField|
+ }}
+ <dropdown.item>
+ <DButton
+ class="btn-transparent"
+ @action={{fn
+ this.toggleAttr
+ group
+ index
+ extraField
+ item
+ menu.close
+ }}
+ @translatedLabel={{this.fieldLabel
+ extraField.name
+ }}
+ @icon={{if
+ (this.isAttrActive
+ group index extraField item
+ )
+ "check"
+ }}
+ />
+ </dropdown.item>
+ {{/each}}
+ </DDropdownMenu>
+ </:content>
+ </DMenu>
+ </div>
+ {{/if}}
+ {{/if}}
+ </collection.Object>
+ </div>
+ </@form.Collection>
+
+ {{#if (this.showEmptyState group)}}
+ <WorkflowsEmptyState
+ @description={{@emptyStateDescription}}
+ @onAction={{fn this.addItem group}}
+ @buttonIcon="plus"
+ @translatedButtonLabel={{this.addLabel}}
+ />
+ {{else}}
+ <DButton
+ @action={{fn this.addItem group}}
+ @icon="plus"
+ @translatedLabel={{this.addLabel}}
+ @disabled={{this.atMaxItems group}}
+ @translatedTitle={{this.maxItemsReachedTitle}}
+ class="btn-default"
+ />
+ {{/if}}
+ {{else}}
+ <@form.Object
+ @name={{this.groupPath group}}
+ class={{if
+ this.isFlat
+ "workflows-property-engine__collection-flat"
+ "workflows-property-engine__collection-fields"
+ }}
+ as |object item|
+ >
+ {{#each (this.allItemFields group) key="name" as |itemField|}}
+ {{#if (isItemFieldVisible itemField item)}}
+ <Field
+ @form={{object}}
+ @formApi={{@formApi}}
+ @configuration={{item}}
+ @connections={{@connections}}
+ @credentials={{@credentials}}
+ @fieldName={{itemField.name}}
+ @node={{@node}}
+ @nodeDefinition={{this.nodeDefinition}}
+ @nodeParameters={{@nodeParameters}}
+ @nodeType={{@nodeType}}
+ @nodes={{@nodes}}
+ @nodeTypes={{@nodeTypes}}
+ @schema={{itemField}}
+ @session={{@session}}
+ />
+ {{/if}}
+ {{/each}}
+ </@form.Object>
+ {{/if}}
+ {{/each}}
+ </@form.Section>
+ </template>
+}
diff --git a/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/configurators/group-select.gjs b/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/configurators/group-select.gjs
new file mode 100644
index 00000000000..c10ca37471b
--- /dev/null
+++ b/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/configurators/group-select.gjs
@@ -0,0 +1,49 @@
+import { hash } from "@ember/helper";
+import { action } from "@ember/object";
+import { service } from "@ember/service";
+import DButton from "discourse/ui-kit/d-button";
+import ComboBoxField, { DynamicOptionsComboBox } from "./combo-box";
+import ExpressionWrapper from "./expression-wrapper";
+
+export default class GroupSelect extends ComboBoxField {
+ @service router;
+
+ @action
+ manageGroups() {
+ this.router.transitionTo("groups");
+ }
+
+ <template>
+ <ExpressionWrapper
+ @field={{@field}}
+ @supportsExpression={{@supportsExpression}}
+ @placeholder={{@placeholder}}
+ @dynamicValueHint={{@dynamicValueHint}}
+ @session={{@session}}
+ >
+ <div class="workflows-property-engine__select-with-action">
+ <DynamicOptionsComboBox
+ @content={{this.options}}
+ @loadOptions={{if this.usesRemoteOptions this.loadRemoteOptions}}
+ @nameProperty="name"
+ @value={{@field.value}}
+ @valueProperty="id"
+ @onChange={{this.handleChange}}
+ @options={{hash
+ filterable=this.filterable
+ none=this.none
+ castInteger=this.castInteger
+ }}
+ />
+ {{#unless @field.value}}
+ <DButton
+ @action={{this.manageGroups}}
+ @label="discourse_workflows.group.manage_groups"
+ @icon="plus"
+ class="btn-default"
+ />
+ {{/unless}}
+ </div>
+ </ExpressionWrapper>
+ </template>
+}
diff --git a/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/configurators/icon-control.gjs b/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/configurators/icon-control.gjs
new file mode 100644
index 00000000000..d3a4afd2c06
--- /dev/null
+++ b/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/configurators/icon-control.gjs
@@ -0,0 +1,13 @@
+import ExpressionWrapper from "./expression-wrapper";
+
+<template>
+ <ExpressionWrapper
+ @field={{@field}}
+ @supportsExpression={{@supportsExpression}}
+ @placeholder={{@placeholder}}
+ @dynamicValueHint={{@dynamicValueHint}}
+ @session={{@session}}
+ >
+ <@field.Control />
+ </ExpressionWrapper>
+</template>
diff --git a/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/configurators/multi-combo-box.gjs b/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/configurators/multi-combo-box.gjs
new file mode 100644
index 00000000000..204f9ec3295
--- /dev/null
+++ b/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/configurators/multi-combo-box.gjs
@@ -0,0 +1,45 @@
+import Component from "@glimmer/component";
+import MultiSelect from "discourse/select-kit/components/multi-select";
+import {
+ formatOptionValue,
+ normalizeOptions,
+ propertyOptionLabel,
+} from "../../../lib/workflows/property-engine";
+import ExpressionWrapper from "./expression-wrapper";
+
+export default class MultiComboBox extends Component {
+ get options() {
+ const optionFormat = this.args.schema?.control_options?.option_format;
+ return normalizeOptions(this.args.schema.options).map((option) => ({
+ id: option.value,
+ name: optionFormat
+ ? formatOptionValue(option.value, optionFormat)
+ : propertyOptionLabel(
+ this.args.nodeDefinition,
+ this.args.fieldName,
+ option
+ ),
+ }));
+ }
+
+ get value() {
+ const val = this.args.field.value;
+ return Array.isArray(val) ? val : [];
+ }
+
+ <template>
+ <ExpressionWrapper
+ @field={{@field}}
+ @supportsExpression={{@supportsExpression}}
+ @placeholder={{@placeholder}}
+ @dynamicValueHint={{@dynamicValueHint}}
+ @session={{@session}}
+ >
+ <MultiSelect
+ @content={{this.options}}
+ @value={{this.value}}
+ @onChange={{@field.set}}
+ />
+ </ExpressionWrapper>
+ </template>
+}
diff --git a/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/configurators/notice-control.gjs b/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/configurators/notice-control.gjs
new file mode 100644
index 00000000000..05f1c25cf9d
--- /dev/null
+++ b/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/configurators/notice-control.gjs
@@ -0,0 +1,25 @@
+import Component from "@glimmer/component";
+import { trustHTML } from "@ember/template";
+import {
+ fieldShowDescription,
+ propertyDescription,
+} from "../../../lib/workflows/property-engine";
+
+export default class NoticeControl extends Component {
+ get description() {
+ if (!fieldShowDescription(this.args.schema)) {
+ return undefined;
+ }
+ const desc = propertyDescription(
+ this.args.nodeDefinition,
+ this.args.fieldName
+ );
+ return desc ? trustHTML(desc) : undefined;
+ }
+
+ <template>
+ <@form.Alert @type="info">
+ {{this.description}}
+ </@form.Alert>
+ </template>
+}
diff --git a/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/configurators/property-engine.gjs b/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/configurators/property-engine.gjs
new file mode 100644
index 00000000000..29709d9b2f0
--- /dev/null
+++ b/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/configurators/property-engine.gjs
@@ -0,0 +1,131 @@
+import Component from "@glimmer/component";
+import { fn } from "@ember/helper";
+import { action } from "@ember/object";
+import { eq } from "discourse/truth-helpers";
+import { i18n } from "discourse-i18n";
+import CONTROL_REGISTRY from "../../../lib/workflows/control-registry";
+import { resolveNodeTypeVersion } from "../../../lib/workflows/node-types";
+import {
+ credentialSlotAnchorField,
+ credentialSlotVisible,
+ credentialTypesForSlot,
+ fieldControl,
+ fieldVisible,
+ findNodeType,
+ normalizeSchema,
+} from "../../../lib/workflows/property-engine";
+import CredentialControl from "./credential";
+import Field from "./field";
+
+function credentialSlotLabel(slot) {
+ return i18n(slot.label_key || "discourse_workflows.credentials.type");
+}
+
+export default class PropertyEngineConfigurator extends Component {
+ get allFields() {
+ return normalizeSchema(this.args.schema);
+ }
+
+ get nodeType() {
+ return this.args.nodeType || this.args.node?.type;
+ }
+
+ get nodeDefinition() {
+ const definition =
+ this.args.nodeDefinition ||
+ findNodeType(this.args.nodeTypes, this.nodeType);
+
+ return resolveNodeTypeVersion(definition, this.args.node?.typeVersion);
+ }
+
+ get metadata() {
+ return this.nodeDefinition?.metadata || {};
+ }
+
+ get nodeParameters() {
+ return this.args.nodeParameters || this.args.configuration || {};
+ }
+
+ get credentialSlotsByAnchor() {
+ const map = new Map();
+ for (const slot of this.args.credentialSlots || []) {
+ const anchor = credentialSlotAnchorField(slot);
+ if (!anchor) {
+ continue;
+ }
+ if (!map.has(anchor)) {
+ map.set(anchor, []);
+ }
+ map.get(anchor).push(slot);
+ }
+ return map;
+ }
+
+ @action
+ slotsForField(fieldName) {
+ return this.credentialSlotsByAnchor.get(fieldName) || [];
+ }
+
+ @action
+ controlEntry(field) {
+ return CONTROL_REGISTRY[fieldControl(field)] || CONTROL_REGISTRY.default;
+ }
+
+ <template>
+ {{#each this.allFields key="name" as |field|}}
+ {{#if (fieldVisible field @configuration)}}
+ {{#let (this.controlEntry field) as |entry|}}
+ {{#if (eq entry.kind "structural")}}
+ <entry.renderer
+ @form={{@form}}
+ @formApi={{@formApi}}
+ @configuration={{@configuration}}
+ @connections={{@connections}}
+ @credentials={{@credentials}}
+ @fieldName={{field.name}}
+ @node={{@node}}
+ @nodeDefinition={{this.nodeDefinition}}
+ @nodeParameters={{this.nodeParameters}}
+ @nodeType={{this.nodeType}}
+ @nodes={{@nodes}}
+ @nodeTypes={{@nodeTypes}}
+ @schema={{field}}
+ @session={{@session}}
+ @onChange={{@onChange}}
+ @onBeforeStartTestSession={{@onBeforeStartTestSession}}
+ />
+ {{else}}
+ <Field
+ @form={{@form}}
+ @formApi={{@formApi}}
+ @configuration={{@configuration}}
+ @connections={{@connections}}
+ @credentials={{@credentials}}
+ @fieldName={{field.name}}
+ @metadata={{this.metadata}}
+ @node={{@node}}
+ @nodeDefinition={{this.nodeDefinition}}
+ @nodeParameters={{this.nodeParameters}}
+ @nodes={{@nodes}}
+ @nodeType={{this.nodeType}}
+ @nodeTypes={{@nodeTypes}}
+ @schema={{field}}
+ @session={{@session}}
+ @onBeforeStartTestSession={{@onBeforeStartTestSession}}
+ />
+ {{/if}}
+ {{/let}}
+ {{#each (this.slotsForField field.name) as |slot|}}
+ {{#if (credentialSlotVisible slot @configuration)}}
+ <CredentialControl
+ @credentialTypes={{credentialTypesForSlot slot}}
+ @label={{credentialSlotLabel slot}}
+ @onChange={{fn @onCredentialSet slot.name}}
+ @value={{@credentialValue slot.name}}
+ />
+ {{/if}}
+ {{/each}}
+ {{/if}}
+ {{/each}}
+ </template>
+}
diff --git a/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/configurators/query-params.gjs b/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/configurators/query-params.gjs
new file mode 100644
index 00000000000..66352bfa9c0
--- /dev/null
+++ b/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/configurators/query-params.gjs
@@ -0,0 +1,70 @@
+import Component from "@glimmer/component";
+import { tracked } from "@glimmer/tracking";
+import { concat } from "@ember/helper";
+import { service } from "@ember/service";
+import Field from "./field";
+
+const PARAM_SCHEMA = { type: "string", ui: { expression: true } };
+
+export default class QueryParams extends Component {
+ @service workflowsNodeTypes;
+
+ @tracked _loadedQueries = null;
+
+ constructor(owner, args) {
+ super(owner, args);
+ const identifier =
+ args.nodeDefinition?.name || args.nodeDefinition?.identifier;
+ if (identifier) {
+ this.workflowsNodeTypes
+ .loadNodeParameterOptions(
+ identifier,
+ "queries",
+ args.nodeDefinition?.version,
+ args.session?.nodeParameterOptionsContext({
+ path: "query_id",
+ currentNodeParameters: args.configuration || {},
+ }) || {
+ path: "query_id",
+ currentNodeParameters: args.configuration || {},
+ }
+ )
+ .then((queries) => {
+ this._loadedQueries = queries;
+ });
+ }
+ }
+
+ get params() {
+ const id = parseInt(this.args.configuration?.query_id, 10);
+ const queries = this.args.metadata?.queries || this._loadedQueries || [];
+ const query = queries.find((q) => q.id === id) || null;
+
+ return (query?.params ?? []).filter((p) => !p.internal);
+ }
+
+ get paramsConfiguration() {
+ return this.args.configuration?.[this.args.fieldName] || {};
+ }
+
+ <template>
+ {{#if this.params.length}}
+ <@form.Section @title={{@label}}>
+ <@form.Object @name={{@fieldName}} as |object|>
+ {{#each this.params key="identifier" as |param|}}
+ <Field
+ @form={{object}}
+ @formApi={{@formApi}}
+ @fieldName={{param.identifier}}
+ @formApiPath={{concat @fieldName "." param.identifier}}
+ @configuration={{this.paramsConfiguration}}
+ @label={{param.identifier}}
+ @schema={{PARAM_SCHEMA}}
+ @session={{@session}}
+ />
+ {{/each}}
+ </@form.Object>
+ </@form.Section>
+ {{/if}}
+ </template>
+}
diff --git a/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/configurators/select-control.gjs b/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/configurators/select-control.gjs
new file mode 100644
index 00000000000..5251bc6943f
--- /dev/null
+++ b/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/configurators/select-control.gjs
@@ -0,0 +1,35 @@
+import Component from "@glimmer/component";
+import {
+ normalizeOptions,
+ propertyOptionLabel,
+} from "../../../lib/workflows/property-engine";
+import ExpressionWrapper from "./expression-wrapper";
+
+export default class SelectControl extends Component {
+ get options() {
+ return normalizeOptions(this.args.schema.options).map((option) => ({
+ ...option,
+ label: propertyOptionLabel(
+ this.args.nodeDefinition,
+ this.args.fieldName,
+ option
+ ),
+ }));
+ }
+
+ <template>
+ <ExpressionWrapper
+ @field={{@field}}
+ @supportsExpression={{@supportsExpression}}
+ @placeholder={{@placeholder}}
+ @dynamicValueHint={{@dynamicValueHint}}
+ @session={{@session}}
+ >
+ <@field.Control @includeNone={{false}} as |c|>
+ {{#each this.options as |choice|}}
+ <c.Option @value={{choice.value}}>{{choice.label}}</c.Option>
+ {{/each}}
+ </@field.Control>
+ </ExpressionWrapper>
+ </template>
+}
diff --git a/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/configurators/tags-control.gjs b/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/configurators/tags-control.gjs
new file mode 100644
index 00000000000..8f8db86e3a5
--- /dev/null
+++ b/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/configurators/tags-control.gjs
@@ -0,0 +1,39 @@
+import Component from "@glimmer/component";
+import { action } from "@ember/object";
+import MiniTagChooser from "discourse/select-kit/components/mini-tag-chooser";
+import ExpressionWrapper from "./expression-wrapper";
+
+function tagValue(value) {
+ if (Array.isArray(value)) {
+ return value;
+ }
+ if (typeof value === "string" && value.length > 0) {
+ return value.split(",").map((t) => t.trim());
+ }
+ return [];
+}
+
+export default class TagsControl extends Component {
+ @action
+ handleChange(tags) {
+ const names = (tags || []).map((t) =>
+ typeof t === "string" ? t : t.name || t.id || t
+ );
+ this.args.field.set(names);
+ }
+
+ <template>
+ <ExpressionWrapper
+ @field={{@field}}
+ @supportsExpression={{@supportsExpression}}
+ @placeholder={{@placeholder}}
+ @dynamicValueHint={{@dynamicValueHint}}
+ @session={{@session}}
+ >
+ <MiniTagChooser
+ @value={{tagValue @field.value}}
+ @onChange={{this.handleChange}}
+ />
+ </ExpressionWrapper>
+ </template>
+}
diff --git a/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/configurators/url-preview.gjs b/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/configurators/url-preview.gjs
new file mode 100644
index 00000000000..abfa48a57b4
--- /dev/null
+++ b/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/configurators/url-preview.gjs
@@ -0,0 +1,321 @@
+import Component from "@glimmer/component";
+import { tracked } from "@glimmer/tracking";
+import { fn } from "@ember/helper";
+import { on } from "@ember/modifier";
+import { action } from "@ember/object";
+import { ajax } from "discourse/lib/ajax";
+import { popupAjaxError } from "discourse/lib/ajax-error";
+import { isTesting } from "discourse/lib/environment";
+import { getAbsoluteURL } from "discourse/lib/get-url";
+import { clipboardCopy } from "discourse/lib/utilities";
+import { eq } from "discourse/truth-helpers";
+import dConcatClass from "discourse/ui-kit/helpers/d-concat-class";
+import dIcon from "discourse/ui-kit/helpers/d-icon";
+import { i18n } from "discourse-i18n";
+import ExpressionWrapper from "./expression-wrapper";
+
+export default class UrlPreview extends Component {
+ @tracked copied = false;
+ @tracked mode = "production";
+ @tracked testUrl = null;
+ @tracked isStartingTestSession = false;
+ @tracked now = Date.now();
+ countdownTimer = null;
+
+ willDestroy() {
+ super.willDestroy(...arguments);
+ this.stopCountdown();
+ }
+
+ get isFormTrigger() {
+ return this.args.node?.type === "trigger:form";
+ }
+
+ get isWebhookTrigger() {
+ return this.args.node?.type === "trigger:webhook";
+ }
+
+ get isTestableTrigger() {
+ return this.isFormTrigger || this.isWebhookTrigger;
+ }
+
+ get isTestMode() {
+ return this.isTestableTrigger && this.mode === "test";
+ }
+
+ get displayPath() {
+ const value = this.args.configuration?.path || "";
+
+ if (typeof value === "string" && value.startsWith("=")) {
+ return "<expression>";
+ }
+
+ return value || "<path>";
+ }
+
+ get productionUrl() {
+ const webhookId = this.args.node?.webhookId;
+ if (this.isFormTrigger && webhookId) {
+ return getAbsoluteURL(`/workflows/form/${webhookId}`);
+ }
+
+ return getAbsoluteURL(`/workflows/webhooks/${this.displayPath}`);
+ }
+
+ get webhookTestListener() {
+ if (!this.isWebhookTrigger) {
+ return null;
+ }
+
+ return this.args.session?.webhookTestListenerForNode(
+ this.args.node.clientId
+ );
+ }
+
+ get activeTestUrl() {
+ if (this.isWebhookTrigger) {
+ return this.webhookTestListener?.testUrl;
+ }
+
+ return this.testUrl;
+ }
+
+ get previewUrl() {
+ if (this.isTestMode && this.activeTestUrl) {
+ return getAbsoluteURL(this.activeTestUrl);
+ }
+
+ return this.productionUrl;
+ }
+
+ get previewText() {
+ if (this.isTestMode && !this.activeTestUrl) {
+ return i18n("discourse_workflows.form.listen_for_test_event");
+ }
+
+ return this.previewUrl;
+ }
+
+ get previewIcon() {
+ if (this.isTestMode && !this.activeTestUrl) {
+ return this.isStartingTestSession ? "spinner" : "arrow-pointer";
+ }
+
+ return this.copied ? "check" : "copy";
+ }
+
+ get previewTitle() {
+ if (this.isTestMode && !this.activeTestUrl) {
+ return i18n("discourse_workflows.form.listen_for_test_event");
+ }
+
+ return i18n("discourse_workflows.webhook.click_to_copy");
+ }
+
+ get hint() {
+ if (this.isFormTrigger) {
+ return i18n("discourse_workflows.form.save_for_url");
+ }
+
+ return null;
+ }
+
+ get hasUrl() {
+ if (this.isFormTrigger) {
+ return !!this.args.node?.webhookId;
+ }
+
+ return true;
+ }
+
+ get canStartTestSession() {
+ return this.isTestableTrigger && this.args.session?.workflowId;
+ }
+
+ get isTestSessionUnavailable() {
+ return this.isTestMode && !this.canStartTestSession;
+ }
+
+ @action
+ setMode(mode) {
+ this.mode = mode;
+ if (mode === "test" && this.webhookTestListener) {
+ this.startCountdown();
+ }
+ }
+
+ @action
+ async startTestSession() {
+ if (!this.canStartTestSession || this.isStartingTestSession) {
+ return;
+ }
+
+ this.isStartingTestSession = true;
+ try {
+ await this.args.onBeforeStartTestSession?.();
+
+ if (this.isWebhookTrigger) {
+ await this.args.session.startWebhookTestListener(
+ this.args.node.clientId
+ );
+ this.startCountdown();
+ } else {
+ const result = await ajax(
+ `/admin/plugins/discourse-workflows/workflows/${this.args.session.workflowId}/form-test-sessions.json`,
+ {
+ type: "POST",
+ data: { trigger_node_id: this.args.node.clientId },
+ }
+ );
+ this.testUrl = result.test_url;
+ window.open(getAbsoluteURL(this.testUrl), "_blank");
+ }
+ } catch (e) {
+ popupAjaxError(e);
+ } finally {
+ this.isStartingTestSession = false;
+ }
+ }
+
+ @action
+ async cancelTestSession(event) {
+ event?.stopPropagation();
+ if (!this.isWebhookTrigger || !this.webhookTestListener) {
+ return;
+ }
+
+ try {
+ await this.args.session.cancelWebhookTestListener(
+ this.args.node.clientId
+ );
+ this.stopCountdown();
+ } catch (e) {
+ popupAjaxError(e);
+ }
+ }
+
+ @action
+ async copy() {
+ await clipboardCopy(this.previewUrl);
+ this.copied = true;
+ setTimeout(() => (this.copied = false), 2000);
+ }
+
+ @action
+ async previewAction() {
+ if (this.isTestMode && !this.activeTestUrl) {
+ await this.startTestSession();
+ return;
+ }
+
+ await this.copy();
+ }
+
+ get expiresInSeconds() {
+ const expiresAt = this.webhookTestListener?.expiresAt;
+ if (!expiresAt) {
+ return null;
+ }
+
+ return Math.max(0, Math.ceil((Date.parse(expiresAt) - this.now) / 1000));
+ }
+
+ get statusText() {
+ if (!this.isWebhookTrigger || !this.webhookTestListener) {
+ return null;
+ }
+
+ return i18n("discourse_workflows.webhook.listening_seconds", {
+ seconds: this.expiresInSeconds,
+ });
+ }
+
+ startCountdown() {
+ if (isTesting()) {
+ return;
+ }
+
+ if (this.countdownTimer) {
+ return;
+ }
+
+ this.now = Date.now();
+ this.countdownTimer = setInterval(() => {
+ this.now = Date.now();
+ if (!this.webhookTestListener) {
+ this.stopCountdown();
+ }
+ }, 1000);
+ }
+
+ stopCountdown() {
+ if (!this.countdownTimer) {
+ return;
+ }
+
+ clearInterval(this.countdownTimer);
+ this.countdownTimer = null;
+ }
+
+ <template>
+ <ExpressionWrapper
+ @field={{@field}}
+ @supportsExpression={{@supportsExpression}}
+ @placeholder={{@placeholder}}
+ @dynamicValueHint={{@dynamicValueHint}}
+ @session={{@session}}
+ >
+ {{#if this.isTestableTrigger}}
+ <div class="workflows-url-preview-mode">
+ <button
+ type="button"
+ class={{dConcatClass
+ "workflows-url-preview-mode__button"
+ (if (eq this.mode "test") "is-active")
+ }}
+ {{on "click" (fn this.setMode "test")}}
+ >{{i18n "discourse_workflows.form.test_url"}}</button>
+ <button
+ type="button"
+ class={{dConcatClass
+ "workflows-url-preview-mode__button"
+ (if (eq this.mode "production") "is-active")
+ }}
+ {{on "click" (fn this.setMode "production")}}
+ >{{i18n "discourse_workflows.form.production_url"}}</button>
+ </div>
+ {{/if}}
+
+ {{#if this.hasUrl}}
+ {{! eslint-disable ember/template-no-invalid-interactive }}
+ <div
+ class={{dConcatClass
+ "workflows-url-preview"
+ (if this.copied "is-copied")
+ (if this.isStartingTestSession "is-loading")
+ (if this.isTestSessionUnavailable "is-disabled")
+ }}
+ title={{this.previewTitle}}
+ {{on "click" this.previewAction}}
+ >
+ <code>{{this.previewText}}</code>
+ {{dIcon this.previewIcon}}
+ </div>
+ {{#if this.statusText}}
+ <div class="workflows-url-preview__status">
+ <span>{{this.statusText}}</span>
+ <button
+ type="button"
+ class="btn-link"
+ {{on "click" this.cancelTestSession}}
+ >{{i18n
+ "discourse_workflows.webhook.cancel_test_listener"
+ }}</button>
+ </div>
+ {{/if}}
+ {{else if this.hint}}
+ <p class="workflows-url-preview__hint">{{this.hint}}</p>
+ {{/if}}
+ </ExpressionWrapper>
+ </template>
+}
diff --git a/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/configurators/user-control.gjs b/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/configurators/user-control.gjs
new file mode 100644
index 00000000000..997aaa7ac89
--- /dev/null
+++ b/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/configurators/user-control.gjs
@@ -0,0 +1,28 @@
+import Component from "@glimmer/component";
+import { hash } from "@ember/helper";
+import { action } from "@ember/object";
+import UserChooser from "discourse/select-kit/components/user-chooser";
+import ExpressionWrapper from "./expression-wrapper";
+
+export default class UserControl extends Component {
+ @action
+ handleChange(usernames) {
+ this.args.field.set(usernames[0] || "");
+ }
+
+ <template>
+ <ExpressionWrapper
+ @field={{@field}}
+ @supportsExpression={{@supportsExpression}}
+ @placeholder={{@placeholder}}
+ @dynamicValueHint={{@dynamicValueHint}}
+ @session={{@session}}
+ >
+ <UserChooser
+ @value={{if @field.value @field.value null}}
+ @onChange={{this.handleChange}}
+ @options={{hash maximum=1 excludeCurrentUser=false}}
+ />
+ </ExpressionWrapper>
+ </template>
+}
diff --git a/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/configurators/user-or-group-control.gjs b/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/configurators/user-or-group-control.gjs
new file mode 100644
index 00000000000..ddaccc33db4
--- /dev/null
+++ b/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/configurators/user-or-group-control.gjs
@@ -0,0 +1,28 @@
+import Component from "@glimmer/component";
+import { hash } from "@ember/helper";
+import { action } from "@ember/object";
+import EmailGroupUserChooser from "discourse/select-kit/components/email-group-user-chooser";
+import ExpressionWrapper from "./expression-wrapper";
+
+export default class UserOrGroupControl extends Component {
+ @action
+ handleChange(usernames) {
+ this.args.field.set(usernames[0] || "");
+ }
+
+ <template>
+ <ExpressionWrapper
+ @field={{@field}}
+ @supportsExpression={{@supportsExpression}}
+ @placeholder={{@placeholder}}
+ @dynamicValueHint={{@dynamicValueHint}}
+ @session={{@session}}
+ >
+ <EmailGroupUserChooser
+ @value={{if @field.value @field.value null}}
+ @onChange={{this.handleChange}}
+ @options={{hash maximum=1 includeGroups=true excludeCurrentUser=false}}
+ />
+ </ExpressionWrapper>
+ </template>
+}
diff --git a/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/context/drag-drop-hint.gjs b/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/context/drag-drop-hint.gjs
new file mode 100644
index 00000000000..1c615a60024
--- /dev/null
+++ b/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/context/drag-drop-hint.gjs
@@ -0,0 +1,50 @@
+import Component from "@glimmer/component";
+import { tracked } from "@glimmer/tracking";
+import { on } from "@ember/modifier";
+import { service } from "@ember/service";
+import dIcon from "discourse/ui-kit/helpers/d-icon";
+import { i18n } from "discourse-i18n";
+
+const HINT_DISMISSED_KEY = "workflows-drag-drop-hint-dismissed";
+
+export default class DragDropHint extends Component {
+ @service keyValueStore;
+
+ @tracked dismissed = this.keyValueStore.get(this.dismissedKey) === "true";
+
+ dismiss = () => {
+ this.keyValueStore.set({ key: this.dismissedKey, value: "true" });
+ this.dismissed = true;
+ };
+
+ get dismissedKey() {
+ return this.args.dismissKey || HINT_DISMISSED_KEY;
+ }
+
+ get messageKey() {
+ return (
+ this.args.messageKey || "discourse_workflows.configurator.drag_drop_hint"
+ );
+ }
+
+ <template>
+ {{#unless this.dismissed}}
+ <div class="workflows-context-panel__hint">
+ <h3 class="workflows-context-panel__hint-title">
+ {{dIcon "grip-vertical"}}
+ {{i18n "discourse_workflows.configurator.drag_drop_hint_title"}}
+ <button
+ class="btn-transparent workflows-context-panel__hint-close"
+ type="button"
+ {{on "click" this.dismiss}}
+ >
+ {{dIcon "xmark"}}
+ </button>
+ </h3>
+ <p class="workflows-context-panel__hint-text">
+ {{i18n this.messageKey}}
+ </p>
+ </div>
+ {{/unless}}
+ </template>
+}
diff --git a/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/context/input.gjs b/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/context/input.gjs
new file mode 100644
index 00000000000..c53157c264c
--- /dev/null
+++ b/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/context/input.gjs
@@ -0,0 +1,312 @@
+import Component from "@glimmer/component";
+import { cached } from "@glimmer/tracking";
+import { service } from "@ember/service";
+import { trustHTML } from "@ember/template";
+import dIcon from "discourse/ui-kit/helpers/d-icon";
+import { i18n } from "discourse-i18n";
+import {
+ ancestorOutputNodes,
+ inputConnectionsForNode,
+ inputFieldPrefixForConnection,
+ inputIndexForConnection,
+ inputSummaryForNode,
+ nodeItemJsonPath,
+ outputIndexForConnection,
+ outputSummaryForNode,
+ previousNodeForConnection,
+ schemaFieldsForNodeInput,
+ schemaFieldsForNodeOutput,
+} from "../../../lib/workflows/data-schema";
+import processFields from "../../../lib/workflows/field-processors";
+import { nodeTypeColor, nodeTypeIcon } from "../../../lib/workflows/node-types";
+import DragDropHint from "./drag-drop-hint";
+import SchemaField from "./schema-field";
+
+function ancestorIconStyle(type) {
+ return trustHTML(`color: ${nodeTypeColor(type)}`);
+}
+
+function nodeMatchesCondition(node, condition) {
+ if (condition.type && node.type !== condition.type) {
+ return false;
+ }
+ if (condition.parameters) {
+ for (const [key, value] of Object.entries(condition.parameters)) {
+ if (node.configuration?.[key] !== value) {
+ return false;
+ }
+ }
+ }
+ return true;
+}
+
+function fieldVisible(fieldDef, nodes) {
+ const nodePresentConditions = fieldDef.display_options?.show?.node_present;
+ if (!nodePresentConditions) {
+ return true;
+ }
+ return nodePresentConditions.some((condition) =>
+ (nodes || []).some((n) => nodeMatchesCondition(n, condition))
+ );
+}
+
+function schemaFieldToEntry(key, def, nodes) {
+ const displayKey = key.replace(/^\$/, "");
+ const entry = {
+ key: displayKey,
+ type: def.type || "object",
+ id: key,
+ };
+
+ if (def.fields) {
+ entry.children = Object.entries(def.fields)
+ .filter(([, childDef]) => fieldVisible(childDef, nodes))
+ .map(([childKey, childDef]) => ({
+ key: childKey,
+ type: childDef.type || "string",
+ id: childKey,
+ }));
+ }
+
+ return entry;
+}
+
+function triggerProvidesCurrentUser(nodes, nodeTypesService) {
+ const triggerNode = (nodes || []).find((n) => n.type?.startsWith("trigger:"));
+ if (!triggerNode) {
+ return false;
+ }
+ const nodeType = nodeTypesService.findNodeType(triggerNode.type);
+ return nodeType?.capabilities?.provides_current_user ?? false;
+}
+
+function environmentFields(expressionContext, nodes, nodeTypesService) {
+ const env = expressionContext.environment;
+ if (!env) {
+ return [];
+ }
+
+ const hasCurrentUser = triggerProvidesCurrentUser(nodes, nodeTypesService);
+
+ return Object.entries(env)
+ .filter(([, def]) => {
+ if (def.provided_by_trigger) {
+ return hasCurrentUser;
+ }
+ return true;
+ })
+ .map(([symbol, def]) => schemaFieldToEntry(symbol, def, nodes));
+}
+
+export default class InputContext extends Component {
+ @service workflowsNodeTypes;
+
+ get graph() {
+ return {
+ nodes: this.args.nodes || [],
+ connections: this.args.connections || [],
+ nodeTypes: this.args.nodeTypes || [],
+ };
+ }
+
+ @cached
+ get inputConnections() {
+ return inputConnectionsForNode(this.args.node, this.graph);
+ }
+
+ get primaryInputConnection() {
+ return this.inputConnections[0] || null;
+ }
+
+ get runData() {
+ return this.args.session?.lastExecutionRunData || {};
+ }
+
+ itemCountLabel(summary) {
+ if (!summary?.itemCount) {
+ return null;
+ }
+
+ return i18n("discourse_workflows.configurator.schema_item_count", {
+ count: summary.itemCount,
+ });
+ }
+
+ emptyMessage(summary) {
+ if (summary?.itemCount > 0) {
+ return i18n("discourse_workflows.configurator.no_input_fields");
+ }
+
+ return i18n("discourse_workflows.configurator.no_input_context");
+ }
+
+ get inputSections() {
+ return this.inputConnections
+ .map((connection) => {
+ const previousNode = previousNodeForConnection(connection, this.graph);
+ if (!previousNode) {
+ return null;
+ }
+
+ const inputIndex = inputIndexForConnection(connection);
+ const outputIndex = outputIndexForConnection(connection);
+ const recordedInputSummary = inputSummaryForNode(
+ this.runData,
+ this.args.node.name,
+ inputIndex
+ );
+ const summary =
+ recordedInputSummary ||
+ outputSummaryForNode(this.runData, previousNode.name, outputIndex);
+ const fields = recordedInputSummary
+ ? schemaFieldsForNodeInput(this.runData, this.args.node.name, {
+ inputIndex,
+ prefix: inputFieldPrefixForConnection(connection, previousNode, {
+ primaryConnection: this.primaryInputConnection,
+ }),
+ })
+ : schemaFieldsForNodeOutput(this.runData, previousNode.name, {
+ outputIndex,
+ prefix: inputFieldPrefixForConnection(connection, previousNode, {
+ primaryConnection: this.primaryInputConnection,
+ }),
+ });
+
+ return {
+ node: previousNode,
+ inputIndex,
+ fields: processFields(fields, this.args.node, this.graph),
+ itemCountLabel: this.itemCountLabel(summary),
+ inputLabel: this.inputConnectionLabel(inputIndex),
+ emptyMessage: this.emptyMessage(summary),
+ };
+ })
+ .filter(Boolean);
+ }
+
+ inputConnectionLabel(inputIndex) {
+ if (this.inputConnections.length < 2 && inputIndex === 0) {
+ return null;
+ }
+
+ return i18n("discourse_workflows.configurator.schema_input_label", {
+ number: inputIndex + 1,
+ });
+ }
+
+ get environmentFields() {
+ return environmentFields(
+ this.workflowsNodeTypes.expressionContext,
+ this.args.nodes || [],
+ this.workflowsNodeTypes
+ );
+ }
+
+ get ancestorNodes() {
+ const directNodeIds = new Set(
+ this.inputSections.map((section) => section.node.clientId)
+ );
+
+ return ancestorOutputNodes(this.args.node, this.graph)
+ .filter((ancestor) => !directNodeIds.has(ancestor.node.clientId))
+ .map((ancestor) => {
+ const fields = schemaFieldsForNodeOutput(
+ this.runData,
+ ancestor.node.name,
+ {
+ outputIndex: ancestor.outputIndex,
+ prefix: nodeItemJsonPath(ancestor.node.name),
+ }
+ );
+ return {
+ name: ancestor.node.name,
+ type:
+ this.workflowsNodeTypes.findNodeType(ancestor.node.type) ||
+ ancestor.node.type,
+ fields,
+ itemCountLabel: this.itemCountLabel(
+ outputSummaryForNode(
+ this.runData,
+ ancestor.node.name,
+ ancestor.outputIndex
+ )
+ ),
+ };
+ })
+ .filter((ancestor) => ancestor.fields.length);
+ }
+
+ <template>
+ <div class="workflows-context-panel">
+ {{#if @hasConfiguration}}
+ <DragDropHint />
+ {{/if}}
+
+ {{#each this.inputSections as |section|}}
+ <div class="workflows-context-panel__section">
+ <h3 class="workflows-context-panel__title">
+ {{dIcon "right-to-bracket"}}
+ {{section.node.name}}
+ {{#if section.inputLabel}}
+ <span class="workflows-context-panel__title-info">
+ {{section.inputLabel}}
+ </span>
+ {{/if}}
+ {{#if section.itemCountLabel}}
+ <span class="workflows-context-panel__title-meta">
+ {{section.itemCountLabel}}
+ </span>
+ {{/if}}
+ </h3>
+
+ {{#if section.fields.length}}
+ <ul class="workflows-schema-field-list">
+ {{#each section.fields as |field|}}
+ <SchemaField @field={{field}} @draggable={{true}} />
+ {{/each}}
+ </ul>
+ {{else}}
+ <p class="workflows-context-panel__empty">
+ {{section.emptyMessage}}
+ </p>
+ {{/if}}
+ </div>
+ {{/each}}
+
+ <div class="workflows-context-panel__section">
+ <h3 class="workflows-context-panel__title">
+ {{dIcon "gear"}}
+ {{i18n "discourse_workflows.configurator.environment"}}
+ </h3>
+
+ <ul class="workflows-schema-field-list">
+ {{#each this.environmentFields as |field|}}
+ <SchemaField @field={{field}} @draggable={{true}} />
+ {{/each}}
+ </ul>
+ </div>
+
+ {{#each this.ancestorNodes as |ancestor|}}
+ <div class="workflows-context-panel__section">
+ <h3 class="workflows-context-panel__title">
+ <span style={{ancestorIconStyle ancestor.type}}>
+ {{dIcon (nodeTypeIcon ancestor.type)}}
+ </span>
+ {{ancestor.name}}
+ {{#if ancestor.itemCountLabel}}
+ <span class="workflows-context-panel__title-meta">
+ {{ancestor.itemCountLabel}}
+ </span>
+ {{/if}}
+ </h3>
+
+ <ul class="workflows-schema-field-list">
+ {{#each ancestor.fields as |field|}}
+ <SchemaField @field={{field}} @draggable={{true}} />
+ {{/each}}
+ </ul>
+ </div>
+ {{/each}}
+ </div>
+ </template>
+}
diff --git a/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/context/output.gjs b/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/context/output.gjs
new file mode 100644
index 00000000000..747a1b115c9
--- /dev/null
+++ b/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/context/output.gjs
@@ -0,0 +1,289 @@
+import Component from "@glimmer/component";
+import { tracked } from "@glimmer/tracking";
+import { fn } from "@ember/helper";
+import { on } from "@ember/modifier";
+import { action } from "@ember/object";
+import { popupAjaxError } from "discourse/lib/ajax-error";
+import { eq } from "discourse/truth-helpers";
+import dConcatClass from "discourse/ui-kit/helpers/d-concat-class";
+import dIcon from "discourse/ui-kit/helpers/d-icon";
+import { i18n } from "discourse-i18n";
+import { outputSchemaForNode } from "../../../lib/workflows/data-schema";
+import processFields from "../../../lib/workflows/field-processors";
+import { nodeTypePorts } from "../../../lib/workflows/node-types";
+import DragDropHint from "./drag-drop-hint";
+import PinDataEditor from "./pin-data-editor";
+import SchemaField from "./schema-field";
+
+const VIEW_SCHEMA = "schema";
+const VIEW_JSON = "json";
+
+export default class OutputContext extends Component {
+ @tracked viewMode = VIEW_SCHEMA;
+
+ get nodeName() {
+ return this.args.node?.name;
+ }
+
+ get isPinned() {
+ return this.args.session?.isNodePinned(this.nodeName);
+ }
+
+ get pinnedItems() {
+ return this.args.session?.pinnedItemsForNode(this.nodeName);
+ }
+
+ get singleOutputNode() {
+ return (
+ nodeTypePorts(this.args.node?.type, this.args.node?.typeVersion).length <=
+ 1
+ );
+ }
+
+ get latestRunItems() {
+ return this.args.session?.outputItemsForNode(this.args.node, 0);
+ }
+
+ // Items the JSON view should render: pinned if pinned, otherwise the latest
+ // run's primary output, otherwise undefined.
+ get effectiveItems() {
+ return this.pinnedItems ?? this.latestRunItems;
+ }
+
+ // True when there's nothing to show in either view — no pinned data and no
+ // run output. In that state we render a single full-height empty state
+ // instead of duplicating it in both Schema and JSON views.
+ get hasNoData() {
+ return !this.pinnedItems && !this.latestRunItems;
+ }
+
+ get canPin() {
+ return (
+ this.singleOutputNode &&
+ !this.isPinned &&
+ Array.isArray(this.latestRunItems) &&
+ this.latestRunItems.length > 0
+ );
+ }
+
+ get canUnpin() {
+ return this.isPinned;
+ }
+
+ get canEditPinData() {
+ return this.singleOutputNode;
+ }
+
+ get showPinDataTip() {
+ return this.canPin;
+ }
+
+ get isSchemaView() {
+ return this.viewMode === VIEW_SCHEMA;
+ }
+
+ get isJsonView() {
+ return this.viewMode === VIEW_JSON;
+ }
+
+ get graph() {
+ return {
+ nodes: this.args.nodes || [],
+ connections: this.args.connections || [],
+ nodeTypes: this.args.nodeTypes || [],
+ };
+ }
+
+ get outputSchema() {
+ const currentNode = this.args.node;
+ const schema = outputSchemaForNode(
+ this.args.session?.lastExecutionRunData || {},
+ currentNode.name,
+ { pinnedItems: this.pinnedItems }
+ );
+
+ return {
+ ...schema,
+ itemCountLabel: this.itemCountLabel(schema.summary),
+ emptyMessage: this.emptyMessage(schema.summary),
+ fields: processFields(schema.fields, currentNode, this.graph),
+ };
+ }
+
+ get fields() {
+ return this.outputSchema.fields || [];
+ }
+
+ itemCountLabel(summary) {
+ if (!summary?.itemCount) {
+ return null;
+ }
+
+ return i18n("discourse_workflows.configurator.schema_item_count", {
+ count: summary.itemCount,
+ });
+ }
+
+ get singleItemCountLabel() {
+ return this.outputSchema.itemCountLabel;
+ }
+
+ emptyMessage(summary) {
+ if (!summary) {
+ return i18n(
+ "discourse_workflows.configurator.no_output_context_run_to_discover"
+ );
+ }
+
+ if (summary.itemCount > 0) {
+ return i18n("discourse_workflows.configurator.no_output_fields");
+ }
+
+ return i18n("discourse_workflows.configurator.no_output_context");
+ }
+
+ get emptyOutputMessage() {
+ return this.outputSchema.emptyMessage;
+ }
+
+ @action
+ switchView(viewMode) {
+ this.viewMode = viewMode;
+ }
+
+ @action
+ async togglePin() {
+ try {
+ if (this.isPinned) {
+ await this.args.session.unpinNodeData(this.nodeName);
+ } else if (this.canPin) {
+ await this.args.session.pinNodeData(this.nodeName, this.latestRunItems);
+ }
+ } catch (error) {
+ popupAjaxError(error);
+ }
+ }
+
+ get canTogglePin() {
+ return this.singleOutputNode && (this.isPinned || this.canPin);
+ }
+
+ <template>
+ <div class="workflows-context-panel">
+ {{#if this.isPinned}}
+ <div class="workflows-context-panel__pin-banner">
+ {{dIcon "thumbtack"}}
+ <span class="workflows-context-panel__pin-banner-text">
+ {{i18n "discourse_workflows.pin_data.is_pinned"}}
+ </span>
+ <button
+ type="button"
+ class="btn-link workflows-context-panel__unpin-btn"
+ {{on "click" this.togglePin}}
+ >
+ {{i18n "discourse_workflows.pin_data.unpin"}}
+ </button>
+ </div>
+ {{/if}}
+
+ {{#if this.showPinDataTip}}
+ <DragDropHint
+ @dismissKey="workflows-output-pin-tip-dismissed"
+ @messageKey="discourse_workflows.pin_data.output_available_tip"
+ />
+ {{/if}}
+
+ <div class="workflows-context-panel__section">
+ <div class="workflows-context-panel__header">
+ <h3 class="workflows-context-panel__title">
+ {{i18n "discourse_workflows.configurator.output_context"}}{{dIcon
+ "right-from-bracket"
+ }}
+ {{#if this.singleItemCountLabel}}
+ <span class="workflows-context-panel__title-meta">
+ {{this.singleItemCountLabel}}
+ </span>
+ {{/if}}
+ </h3>
+
+ {{#if this.singleOutputNode}}
+ <div class="workflows-context-panel__header-actions">
+ <div class="workflows-context-panel__tabs" role="tablist">
+ <button
+ type="button"
+ role="tab"
+ aria-selected={{if this.isSchemaView "true" "false"}}
+ class={{dConcatClass
+ "workflows-context-panel__tab"
+ (if (eq this.viewMode "schema") "is-active")
+ }}
+ {{on "click" (fn this.switchView "schema")}}
+ >{{i18n "discourse_workflows.pin_data.schema_view"}}</button>
+ <button
+ type="button"
+ role="tab"
+ aria-selected={{if this.isJsonView "true" "false"}}
+ class={{dConcatClass
+ "workflows-context-panel__tab"
+ (if (eq this.viewMode "json") "is-active")
+ }}
+ {{on "click" (fn this.switchView "json")}}
+ >{{i18n "discourse_workflows.pin_data.json_view"}}</button>
+ </div>
+
+ <button
+ type="button"
+ class={{dConcatClass
+ "workflows-context-panel__icon-btn workflows-context-panel__pin-btn"
+ (if this.isPinned "is-pinned")
+ }}
+ disabled={{if this.canTogglePin false true}}
+ title={{if
+ this.isPinned
+ (i18n "discourse_workflows.pin_data.unpin")
+ (i18n "discourse_workflows.pin_data.pin")
+ }}
+ aria-label={{if
+ this.isPinned
+ (i18n "discourse_workflows.pin_data.unpin")
+ (i18n "discourse_workflows.pin_data.pin")
+ }}
+ {{on "click" this.togglePin}}
+ >
+ {{dIcon "thumbtack"}}
+ </button>
+ </div>
+ {{/if}}
+ </div>
+
+ {{#if this.hasNoData}}
+ <PinDataEditor
+ @nodeName={{this.nodeName}}
+ @initialItems={{this.effectiveItems}}
+ @canEdit={{this.canEditPinData}}
+ @session={{@session}}
+ />
+ {{else if this.isJsonView}}
+ <PinDataEditor
+ @nodeName={{this.nodeName}}
+ @initialItems={{this.effectiveItems}}
+ @canEdit={{this.canEditPinData}}
+ @session={{@session}}
+ />
+ {{else}}
+ {{#if this.fields.length}}
+ <ul class="workflows-schema-field-list">
+ {{#each this.fields as |field|}}
+ <SchemaField @field={{field}} />
+ {{/each}}
+ </ul>
+ {{else}}
+ <p class="workflows-context-panel__empty">
+ {{this.emptyOutputMessage}}
+ </p>
+ {{/if}}
+ {{/if}}
+ </div>
+ </div>
+ </template>
+}
diff --git a/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/context/pin-data-editor.gjs b/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/context/pin-data-editor.gjs
new file mode 100644
index 00000000000..92b6946b56d
--- /dev/null
+++ b/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/context/pin-data-editor.gjs
@@ -0,0 +1,374 @@
+import Component from "@glimmer/component";
+import { tracked } from "@glimmer/tracking";
+import { on } from "@ember/modifier";
+import { action } from "@ember/object";
+import didInsert from "@ember/render-modifiers/modifiers/did-insert";
+import { service } from "@ember/service";
+import { popupAjaxError } from "discourse/lib/ajax-error";
+import loadCodemirrorEditor from "discourse/lib/load-codemirror";
+import dIcon from "discourse/ui-kit/helpers/d-icon";
+import { i18n } from "discourse-i18n";
+import buildJsonEditorExtensions from "../../../lib/workflows/json-editor-extensions";
+
+const EMPTY_SEED = [{}];
+const DEFAULT_MAX_BYTES = 1_048_576;
+
+function prettyPrint(value) {
+ try {
+ return JSON.stringify(value, null, 2);
+ } catch {
+ return "";
+ }
+}
+
+function byteLength(string) {
+ if (typeof TextEncoder === "undefined") {
+ return string.length * 4;
+ }
+ return new TextEncoder().encode(string).length;
+}
+
+// The storage shape on the backend is `[{ json: {...}, pairedItem? }]`.
+// The UI hides that wrapper and shows the inner JSON payload directly.
+function unwrapForDisplay(items) {
+ if (!Array.isArray(items)) {
+ return items;
+ }
+ return items.map((item) =>
+ item && typeof item === "object" && "json" in item ? item.json : item
+ );
+}
+
+// Lenient input normalization: accept either `[{...}]` (unwrapped, what the
+// editor presents) or `[{"json": {...}}]` (wrapped, if the user pasted raw
+// storage shape) and produce the canonical storage shape.
+function wrapForStorage(payloads) {
+ return payloads.map((payload) =>
+ payload && typeof payload === "object" && "json" in payload
+ ? payload
+ : { json: payload }
+ );
+}
+
+function validateUnwrappedShape(value) {
+ if (!Array.isArray(value)) {
+ return "invalid_shape_not_array";
+ }
+ if (value.length === 0) {
+ return "invalid_shape_empty";
+ }
+ for (const payload of value) {
+ if (
+ payload === null ||
+ typeof payload !== "object" ||
+ Array.isArray(payload)
+ ) {
+ return "invalid_shape_item_not_object";
+ }
+ if ("json" in payload) {
+ const inner = payload.json;
+ if (inner === null || typeof inner !== "object" || Array.isArray(inner)) {
+ return "invalid_shape_item_not_object";
+ }
+ }
+ }
+ return null;
+}
+
+export default class PinDataEditor extends Component {
+ @service siteSettings;
+
+ @tracked Editor;
+ @tracked buffer;
+ @tracked bufferBaseline;
+ @tracked enteredFromEmpty = false;
+ @tracked parseError = null;
+ @tracked shapeError = null;
+ @tracked isSaving = false;
+
+ constructor() {
+ super(...arguments);
+ if (this.hasItems) {
+ const initial = prettyPrint(unwrapForDisplay(this.args.initialItems));
+ this.buffer = initial;
+ this.bufferBaseline = initial;
+ } else {
+ this.buffer = "";
+ this.bufferBaseline = "";
+ }
+ this.#recomputeValidity();
+ }
+
+ get hasItems() {
+ return (
+ Array.isArray(this.args.initialItems) && this.args.initialItems.length > 0
+ );
+ }
+
+ // Show the editor when there's data to display or the user has explicitly
+ // opted in from the empty state. Otherwise show the empty-state CTA.
+ get showEditor() {
+ return this.hasItems || this.enteredFromEmpty;
+ }
+
+ get maxBytes() {
+ return (
+ this.args.maxBytes ||
+ this.siteSettings?.discourse_workflows_max_pin_data_bytes ||
+ DEFAULT_MAX_BYTES
+ );
+ }
+
+ get bufferBytes() {
+ return byteLength(this.buffer);
+ }
+
+ get isOverSizeCap() {
+ return this.bufferBytes > this.maxBytes;
+ }
+
+ get isNearSizeCap() {
+ return !this.isOverSizeCap && this.bufferBytes > this.maxBytes * 0.9;
+ }
+
+ get sizeHint() {
+ return i18n("discourse_workflows.pin_data.size_hint", {
+ bytes: this.bufferBytes,
+ max: this.maxBytes,
+ });
+ }
+
+ get parsedPayloads() {
+ if (this.parseError) {
+ return null;
+ }
+ try {
+ return JSON.parse(this.buffer);
+ } catch {
+ return null;
+ }
+ }
+
+ get isDirty() {
+ return this.buffer !== this.bufferBaseline;
+ }
+
+ get canSave() {
+ return (
+ this.isDirty &&
+ !this.parseError &&
+ !this.shapeError &&
+ !this.isOverSizeCap &&
+ !this.isSaving
+ );
+ }
+
+ get saveDisabled() {
+ return !this.canSave;
+ }
+
+ @action
+ async loadEditor() {
+ const Editor = await loadCodemirrorEditor();
+
+ if (this.isDestroying || this.isDestroyed) {
+ return;
+ }
+ this.Editor = Editor;
+ }
+
+ @action
+ buildEditExtensions(cmParams) {
+ return buildJsonEditorExtensions(cmParams, {
+ onChange: (value) => this.updateBuffer(value),
+ });
+ }
+
+ @action
+ updateBuffer(value) {
+ this.buffer = value;
+ this.#recomputeValidity();
+ }
+
+ @action
+ startFromEmpty() {
+ const seed = prettyPrint(EMPTY_SEED);
+ this.buffer = seed;
+ // Baseline stays at "" so the seed counts as dirty and the Save button
+ // is immediately visible. Cancel from this state returns to the empty CTA.
+ this.bufferBaseline = "";
+ this.enteredFromEmpty = true;
+ this.#recomputeValidity();
+ }
+
+ @action
+ cancel() {
+ if (this.enteredFromEmpty && !this.hasItems) {
+ this.enteredFromEmpty = false;
+ this.buffer = "";
+ this.bufferBaseline = "";
+ this.parseError = null;
+ this.shapeError = null;
+ this.args.onCancel?.();
+ return;
+ }
+ this.buffer = this.bufferBaseline;
+ this.parseError = null;
+ this.shapeError = null;
+ this.args.onCancel?.();
+ }
+
+ @action
+ async save() {
+ if (!this.canSave) {
+ return;
+ }
+ const payloads = this.parsedPayloads;
+ if (!payloads) {
+ return;
+ }
+ const items = wrapForStorage(payloads);
+
+ this.isSaving = true;
+ try {
+ await this.args.session.pinNodeData(this.args.nodeName, items);
+ // Update baseline so the Save/Cancel toolbar hides. The parent will
+ // also re-render with the new pinned items flowing in via args.
+ this.bufferBaseline = this.buffer;
+ this.enteredFromEmpty = false;
+ this.args.onSaved?.(items);
+ } catch (error) {
+ popupAjaxError(error);
+ } finally {
+ this.isSaving = false;
+ }
+ }
+
+ #recomputeValidity() {
+ if (this.buffer.trim() === "") {
+ this.parseError = {
+ message: i18n("discourse_workflows.pin_data.invalid_json_empty"),
+ };
+ this.shapeError = null;
+ return;
+ }
+
+ let parsed;
+ try {
+ parsed = JSON.parse(this.buffer);
+ } catch (error) {
+ this.parseError = { message: error.message };
+ this.shapeError = null;
+ return;
+ }
+
+ this.parseError = null;
+ const shapeKey = validateUnwrappedShape(parsed);
+ this.shapeError = shapeKey
+ ? { message: i18n(`discourse_workflows.pin_data.${shapeKey}`) }
+ : null;
+ }
+
+ <template>
+ {{#if this.showEditor}}
+ <div
+ class="workflows-context-panel__editor"
+ {{didInsert this.loadEditor}}
+ >
+ {{#if this.isDirty}}
+ <div class="workflows-context-panel__editor-toolbar">
+ <button
+ type="button"
+ class="btn btn-primary btn-small workflows-context-panel__editor-save"
+ disabled={{this.saveDisabled}}
+ {{on "click" this.save}}
+ >
+ {{dIcon "check"}}
+ {{i18n "discourse_workflows.pin_data.save"}}
+ </button>
+ <button
+ type="button"
+ class="btn btn-default btn-small workflows-context-panel__editor-cancel"
+ {{on "click" this.cancel}}
+ >
+ {{i18n "discourse_workflows.pin_data.cancel"}}
+ </button>
+ <span
+ class="workflows-context-panel__editor-size
+ {{if
+ this.isOverSizeCap
+ 'workflows-context-panel__editor-size--exceeded'
+ }}
+ {{if
+ this.isNearSizeCap
+ 'workflows-context-panel__editor-size--near'
+ }}"
+ >
+ {{this.sizeHint}}
+ </span>
+ </div>
+ {{/if}}
+
+ {{#if this.Editor}}
+ <this.Editor
+ @value={{this.buffer}}
+ @extensions={{this.buildEditExtensions}}
+ @class="workflows-context-panel__editor-codemirror"
+ @lineWrapping={{true}}
+ />
+ {{else}}
+ <div class="workflows-context-panel__editor-loading">
+ {{i18n "discourse_workflows.pin_data.loading_editor"}}
+ </div>
+ {{/if}}
+
+ {{#if this.isDirty}}
+ {{#if this.parseError}}
+ <div
+ class="workflows-context-panel__editor-error alert alert-error"
+ >
+ {{dIcon "circle-exclamation"}}
+ <span>{{i18n "discourse_workflows.pin_data.invalid_json"}}:
+ {{this.parseError.message}}</span>
+ </div>
+ {{else if this.shapeError}}
+ <div
+ class="workflows-context-panel__editor-error alert alert-error"
+ >
+ {{dIcon "circle-exclamation"}}
+ <span>{{this.shapeError.message}}</span>
+ </div>
+ {{/if}}
+
+ {{#if this.isOverSizeCap}}
+ <div
+ class="workflows-context-panel__editor-error alert alert-error"
+ >
+ {{dIcon "circle-exclamation"}}
+ <span>{{i18n "discourse_workflows.pin_data.size_exceeded"}}</span>
+ </div>
+ {{/if}}
+ {{/if}}
+ </div>
+ {{else if @canEdit}}
+ <div class="workflows-context-panel__empty-state">
+ <h4 class="workflows-context-panel__empty-state-title">
+ {{i18n "discourse_workflows.pin_data.empty_title"}}
+ </h4>
+ <button
+ type="button"
+ class="btn btn-primary workflows-context-panel__empty-state-btn"
+ {{on "click" this.startFromEmpty}}
+ >
+ {{i18n "discourse_workflows.pin_data.add_sample_data"}}
+ </button>
+ </div>
+ {{else}}
+ <div class="workflows-context-panel__empty-state">
+ <h4 class="workflows-context-panel__empty-state-title">
+ {{i18n "discourse_workflows.pin_data.no_data_no_edit"}}
+ </h4>
+ </div>
+ {{/if}}
+ </template>
+}
diff --git a/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/context/schema-field.gjs b/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/context/schema-field.gjs
new file mode 100644
index 00000000000..30bfc75aaeb
--- /dev/null
+++ b/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/context/schema-field.gjs
@@ -0,0 +1,108 @@
+import Component from "@glimmer/component";
+import { tracked } from "@glimmer/tracking";
+import { on } from "@ember/modifier";
+import { action } from "@ember/object";
+import { and, not } from "discourse/truth-helpers";
+import dConcatClass from "discourse/ui-kit/helpers/d-concat-class";
+import dIcon from "discourse/ui-kit/helpers/d-icon";
+import { WORKFLOW_VARIABLE_MIME } from "../../../lib/workflows/expression-context";
+
+export default class SchemaField extends Component {
+ @tracked collapsed = true;
+
+ get hasChildren() {
+ return this.args.field.children?.length > 0;
+ }
+
+ typeIcon(type) {
+ let icons = {
+ string: "discourse-text",
+ object: "cube",
+ boolean: "far-square-check",
+ integer: "hashtag",
+ number: "hashtag",
+ array: "layer-group",
+ null: "circle",
+ unknown: "circle-question",
+ };
+ return icons[type];
+ }
+
+ @action
+ toggleChildren(event) {
+ event.preventDefault();
+ this.collapsed = !this.collapsed;
+ }
+
+ get fieldId() {
+ const { field, parentPath } = this.args;
+ if (field.id?.startsWith?.("$")) {
+ return field.id;
+ }
+ return parentPath ? `${parentPath}.${field.id}` : field.id;
+ }
+
+ @action
+ handleDragStart(event) {
+ event.stopPropagation();
+ const field = this.args.field;
+ event.dataTransfer.setData(
+ WORKFLOW_VARIABLE_MIME,
+ JSON.stringify({ id: this.fieldId, key: field.key, type: field.type })
+ );
+ event.dataTransfer.effectAllowed = "copy";
+ document.documentElement.dataset.draggingVariable = "true";
+ }
+
+ @action
+ handleDragEnd() {
+ delete document.documentElement.dataset.draggingVariable;
+ }
+
+ <template>
+ <li
+ class={{dConcatClass
+ "workflows-schema-field"
+ (if this.hasChildren "has-children")
+ (if this.collapsed "is-collapsed")
+ }}
+ >
+ <div
+ class="workflows-schema-field__row"
+ {{(if this.hasChildren (modifier on "click" this.toggleChildren))}}
+ >
+ {{#if this.hasChildren}}
+ <span class="workflows-schema-field__toggle">
+ {{dIcon (if this.collapsed "angle-right" "angle-down")}}
+ </span>
+ {{/if}}
+
+ <span
+ class="workflows-schema-field__key"
+ draggable={{if (and @draggable this.fieldId) "true"}}
+ {{on "dragstart" this.handleDragStart}}
+ {{on "dragend" this.handleDragEnd}}
+ >
+ <span class="workflows-schema-field__key-icon">
+ {{dIcon (this.typeIcon @field.type)}}
+ </span>
+ <span class="workflows-schema-field__key-title">
+ {{@field.key}}
+ </span>
+ </span>
+ </div>
+
+ {{#if (and this.hasChildren (not this.collapsed))}}
+ <ul class="workflows-schema-field-list is-nested">
+ {{#each @field.children as |child|}}
+ <SchemaField
+ @field={{child}}
+ @draggable={{@draggable}}
+ @parentPath={{this.fieldId}}
+ />
+ {{/each}}
+ </ul>
+ {{/if}}
+ </li>
+ </template>
+}
diff --git a/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/credential/manager.gjs b/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/credential/manager.gjs
new file mode 100644
index 00000000000..29a84ee5759
--- /dev/null
+++ b/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/credential/manager.gjs
@@ -0,0 +1,180 @@
+import { fn } from "@ember/helper";
+import { action } from "@ember/object";
+import DMenu from "discourse/float-kit/components/d-menu";
+import { ajax } from "discourse/lib/ajax";
+import { popupAjaxError } from "discourse/lib/ajax-error";
+import DButton from "discourse/ui-kit/d-button";
+import DDropdownMenu from "discourse/ui-kit/d-dropdown-menu";
+import { i18n } from "discourse-i18n";
+import AdminTable from "../admin-table";
+import EmptyState from "../empty-state";
+import InUseDialog from "../in-use-dialog";
+import PaginatedListManager from "../paginated-list-manager";
+import CredentialModal from "./modal";
+
+export default class CredentialsManager extends PaginatedListManager {
+ get collectionKey() {
+ return "credentials";
+ }
+
+ get basePath() {
+ return "/admin/plugins/discourse-workflows/credentials";
+ }
+
+ @action
+ addCredential() {
+ this.modal.show(CredentialModal, {
+ model: {
+ credential: null,
+ onSave: async (data) => {
+ await ajax(this.apiUrl, {
+ type: "POST",
+ data,
+ });
+ await this.loadItems();
+ },
+ },
+ });
+ }
+
+ @action
+ editCredential(credential) {
+ this.modal.show(CredentialModal, {
+ model: {
+ credential,
+ onSave: async (data) => {
+ await ajax(`${this.basePath}/${credential.id}.json`, {
+ type: "PUT",
+ data,
+ });
+ await this.loadItems();
+ },
+ },
+ });
+ }
+
+ @action
+ deleteCredential(credential) {
+ this.dialog.deleteConfirm({
+ message: i18n("discourse_workflows.credentials.delete_confirm", {
+ name: credential.name,
+ }),
+ didConfirm: async () => {
+ try {
+ await ajax(`${this.basePath}/${credential.id}.json`, {
+ type: "DELETE",
+ });
+ await this.loadItems();
+ } catch (e) {
+ const body = e.jqXHR?.responseJSON;
+ if (body?.type === "credential_in_use") {
+ this.dialog.alert({
+ title: i18n("discourse_workflows.credentials.in_use_title"),
+ bodyComponent: InUseDialog,
+ bodyComponentModel: {
+ description: i18n(
+ "discourse_workflows.credentials.in_use_description"
+ ),
+ workflows: body.referencing_workflows,
+ close: () => this.dialog.cancel(),
+ },
+ });
+ } else {
+ popupAjaxError(e);
+ }
+ }
+ },
+ });
+ }
+
+ <template>
+ <AdminTable
+ @items={{this.items}}
+ @isLoading={{this.isLoading}}
+ @canLoadMore={{this.canLoadMore}}
+ @loadMore={{this.loadMore}}
+ @loadingMore={{this.loadingMore}}
+ >
+ <:empty>
+ <EmptyState
+ @emoji="locked_with_key"
+ @title={{i18n
+ "discourse_workflows.credentials.empty_title"
+ username=this.currentUser.displayName
+ }}
+ @description={{i18n
+ "discourse_workflows.credentials.empty_description"
+ }}
+ @buttonLabel="discourse_workflows.credentials.add_first"
+ @onAction={{this.addCredential}}
+ />
+ </:empty>
+ <:toolbar>
+ <DButton
+ @action={{this.addCredential}}
+ @label="discourse_workflows.credentials.add"
+ @icon="plus"
+ class="btn-primary btn-small"
+ />
+ </:toolbar>
+ <:head>
+ <th class="d-table__header-cell">{{i18n
+ "discourse_workflows.credentials.name"
+ }}</th>
+ <th class="d-table__header-cell">{{i18n
+ "discourse_workflows.credentials.type"
+ }}</th>
+ <th class="d-table__header-cell">{{i18n
+ "discourse_workflows.credentials.created"
+ }}</th>
+ <th class="d-table__header-cell"></th>
+ </:head>
+ <:row as |credential|>
+ <td class="d-table__cell --overview">
+ <strong class="d-table__overview-name">{{credential.name}}</strong>
+ </td>
+ <td class="d-table__cell --detail">
+ <div class="d-table__mobile-label">
+ {{i18n "discourse_workflows.credentials.type"}}
+ </div>
+ {{credential.credential_type}}
+ </td>
+ <td class="d-table__cell --detail">
+ <div class="d-table__mobile-label">
+ {{i18n "discourse_workflows.credentials.created"}}
+ </div>
+ {{credential.created_at}}
+ </td>
+ <td class="d-table__cell --controls">
+ <div class="d-table__cell-actions">
+ <DButton
+ @action={{fn this.editCredential credential}}
+ @label="discourse_workflows.edit"
+ @title="discourse_workflows.credentials.edit"
+ class="btn-default btn-small"
+ />
+ <DMenu
+ @identifier="workflows-credential-menu"
+ @title={{i18n "discourse_workflows.more_options"}}
+ @icon="ellipsis-vertical"
+ @triggerClass="btn-default"
+ >
+ <:content>
+ <DDropdownMenu as |dropdown|>
+ <dropdown.item>
+ <DButton
+ @action={{fn this.deleteCredential credential}}
+ @icon="trash-can"
+ @label="discourse_workflows.delete"
+ class="btn-danger"
+ />
+ </dropdown.item>
+ </DDropdownMenu>
+ </:content>
+ </DMenu>
+ </div>
+ </td>
+ </:row>
+ </AdminTable>
+ </template>
+}
diff --git a/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/credential/modal.gjs b/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/credential/modal.gjs
new file mode 100644
index 00000000000..c2b0647cc25
--- /dev/null
+++ b/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/credential/modal.gjs
@@ -0,0 +1,200 @@
+import Component from "@glimmer/component";
+import { tracked } from "@glimmer/tracking";
+import { fn } from "@ember/helper";
+import { action } from "@ember/object";
+import { service } from "@ember/service";
+import Form from "discourse/components/form";
+import { popupAjaxError } from "discourse/lib/ajax-error";
+import { eq } from "discourse/truth-helpers";
+import DModal from "discourse/ui-kit/d-modal";
+import { i18n } from "discourse-i18n";
+import {
+ fieldVisible,
+ normalizeSchema,
+ propertyLabel,
+} from "../../../lib/workflows/property-engine";
+import Field from "../configurators/field";
+
+const CREDENTIAL_DATA_NAME_FIELD = "credential_data_name";
+
+function credentialTypeDefinition(credentialTypes, type) {
+ if (!type || !credentialTypes) {
+ return null;
+ }
+ return credentialTypes.find((ct) => ct.identifier === type);
+}
+
+function credentialTypeSchema(credentialTypes, type) {
+ const def = credentialTypeDefinition(credentialTypes, type);
+ return def ? normalizeSchema(def.property_schema) : [];
+}
+
+export default class CredentialModal extends Component {
+ @service workflowsNodeTypes;
+
+ @tracked credentialTypes = null;
+
+ constructor() {
+ super(...arguments);
+ this.#loadCredentialTypes();
+ }
+
+ async #loadCredentialTypes() {
+ await this.workflowsNodeTypes.load();
+ this.credentialTypes = this.workflowsNodeTypes.credentialTypes || [];
+ }
+
+ get isEditing() {
+ return !!this.args.model.credential;
+ }
+
+ get typeOptions() {
+ return (this.credentialTypes || []).map((ct) => ({
+ value: ct.identifier,
+ label: ct.display_name,
+ }));
+ }
+
+ get formData() {
+ const credential = this.args.model.credential;
+ if (!credential) {
+ return { name: "", credential_type: "" };
+ }
+
+ return {
+ ...(credential.data || {}),
+ name: credential.name,
+ credential_type: credential.credential_type,
+ [CREDENTIAL_DATA_NAME_FIELD]: credential.data?.name,
+ };
+ }
+
+ @action
+ async handleSubmit(credentialTypes, data) {
+ try {
+ const schema = credentialTypeSchema(
+ credentialTypes,
+ data.credential_type
+ );
+ const credentialData = {};
+ for (const field of schema) {
+ const dataFieldName =
+ field.name === "name" ? CREDENTIAL_DATA_NAME_FIELD : field.name;
+ if (data[dataFieldName] !== undefined) {
+ credentialData[field.name] = data[dataFieldName];
+ }
+ }
+
+ await this.args.model.onSave({
+ name: data.name,
+ credential_type: data.credential_type,
+ data: credentialData,
+ });
+ this.args.closeModal();
+ } catch (error) {
+ popupAjaxError(error);
+ }
+ }
+
+ <template>
+ <DModal
+ @title={{if
+ this.isEditing
+ (i18n "discourse_workflows.credentials.edit")
+ (i18n "discourse_workflows.credentials.add")
+ }}
+ @closeModal={{@closeModal}}
+ >
+ <:body>
+ <Form
+ @data={{this.formData}}
+ @onSubmit={{fn this.handleSubmit this.credentialTypes}}
+ class="workflows-configurator-form"
+ as |form transientData|
+ >
+ <form.Field
+ @name="name"
+ @title={{i18n "discourse_workflows.credentials.name"}}
+ @type="input"
+ @format="full"
+ @validation="required"
+ as |field|
+ >
+ <field.Control
+ placeholder={{i18n
+ "discourse_workflows.credentials.name_placeholder"
+ }}
+ />
+ </form.Field>
+
+ {{#if this.isEditing}}
+ <form.Field
+ @name="credential_type"
+ @title={{i18n "discourse_workflows.credentials.type"}}
+ @type="input"
+ @format="full"
+ @disabled={{true}}
+ as |field|
+ >
+ <field.Control @disabled={{true}} />
+ </form.Field>
+ {{else}}
+ <form.Field
+ @name="credential_type"
+ @title={{i18n "discourse_workflows.credentials.type"}}
+ @type="select"
+ @format="full"
+ @validation="required"
+ as |field|
+ >
+ <field.Control
+ @includeNone={{i18n
+ "discourse_workflows.credentials.select_type"
+ }}
+ as |c|
+ >
+ {{#each this.typeOptions as |option|}}
+ <c.Option @value={{option.value}}>{{option.label}}</c.Option>
+ {{/each}}
+ </field.Control>
+ </form.Field>
+ {{/if}}
+
+ {{#each
+ (credentialTypeSchema
+ this.credentialTypes transientData.credential_type
+ )
+ key="name"
+ as |fieldSchema|
+ }}
+ {{#if (fieldVisible fieldSchema transientData)}}
+ <Field
+ @form={{form}}
+ @formApi={{form.api}}
+ @fieldName={{if
+ (eq fieldSchema.name "name")
+ "credential_data_name"
+ fieldSchema.name
+ }}
+ @label={{propertyLabel
+ (credentialTypeDefinition
+ this.credentialTypes transientData.credential_type
+ )
+ fieldSchema.name
+ }}
+ @schema={{fieldSchema}}
+ @configuration={{transientData}}
+ @nodeDefinition={{credentialTypeDefinition
+ this.credentialTypes
+ transientData.credential_type
+ }}
+ />
+ {{/if}}
+ {{/each}}
+
+ <form.Submit />
+ </Form>
+ </:body>
+ </DModal>
+ </template>
+}
diff --git a/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/data-table/add-column-modal.gjs b/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/data-table/add-column-modal.gjs
new file mode 100644
index 00000000000..1d4c8895246
--- /dev/null
+++ b/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/data-table/add-column-modal.gjs
@@ -0,0 +1,87 @@
+import Component from "@glimmer/component";
+import { action } from "@ember/object";
+import Form from "discourse/components/form";
+import { popupAjaxError } from "discourse/lib/ajax-error";
+import DModal from "discourse/ui-kit/d-modal";
+import { i18n } from "discourse-i18n";
+
+const COLUMN_NAME_PATTERN = /^[a-zA-Z_][a-zA-Z0-9_]*$/;
+
+export default class AddColumnModal extends Component {
+ formData = { name: "", type: "string" };
+
+ @action
+ validateColumnName(name, value, { addError }) {
+ if (value && !COLUMN_NAME_PATTERN.test(value)) {
+ addError(name, {
+ title: i18n("discourse_workflows.data_tables.column_name"),
+ message: i18n("discourse_workflows.data_tables.column_name_invalid"),
+ });
+ }
+ }
+
+ @action
+ async handleSubmit(data) {
+ try {
+ await this.args.model.onSave(data);
+ this.args.closeModal();
+ } catch (error) {
+ popupAjaxError(error);
+ }
+ }
+
+ <template>
+ <DModal
+ @title={{i18n "discourse_workflows.data_tables.add_column"}}
+ @closeModal={{@closeModal}}
+ class="data-table-add-column-modal"
+ >
+ <:body>
+ <Form
+ @data={{this.formData}}
+ @onSubmit={{this.handleSubmit}}
+ class="workflows-configurator-form"
+ as |form|
+ >
+ <form.Field
+ @name="name"
+ @title={{i18n "discourse_workflows.data_tables.column_name"}}
+ @type="input"
+ @format="full"
+ @validation="required"
+ @validate={{this.validateColumnName}}
+ as |field|
+ >
+ <field.Control placeholder="column_name" />
+ </form.Field>
+
+ <form.Field
+ @name="type"
+ @title={{i18n "discourse_workflows.data_tables.column_type"}}
+ @type="select"
+ @format="full"
+ @validation="required"
+ as |field|
+ >
+ <field.Control as |select|>
+ <select.Option @value="string">{{i18n
+ "discourse_workflows.data_tables.column_types.string"
+ }}</select.Option>
+ <select.Option @value="number">{{i18n
+ "discourse_workflows.data_tables.column_types.number"
+ }}</select.Option>
+ <select.Option @value="boolean">{{i18n
+ "discourse_workflows.data_tables.column_types.boolean"
+ }}</select.Option>
+ <select.Option @value="date">{{i18n
+ "discourse_workflows.data_tables.column_types.date"
+ }}</select.Option>
+ </field.Control>
+ </form.Field>
+
+ <form.Submit />
+ </Form>
+ </:body>
+ </DModal>
+ </template>
+}
diff --git a/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/data-table/cell-editor.gjs b/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/data-table/cell-editor.gjs
new file mode 100644
index 00000000000..9ab0d913473
--- /dev/null
+++ b/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/data-table/cell-editor.gjs
@@ -0,0 +1,136 @@
+import Component from "@glimmer/component";
+import { tracked } from "@glimmer/tracking";
+import { on } from "@ember/modifier";
+import { action } from "@ember/object";
+import { modifier } from "ember-modifier";
+import { eq } from "discourse/truth-helpers";
+import dConcatClass from "discourse/ui-kit/helpers/d-concat-class";
+
+const autofocus = modifier((element) => element.focus());
+
+export default class CellEditor extends Component {
+ @tracked isEditing = false;
+ @tracked editValue = "";
+
+ get columnType() {
+ return this.args.column.type;
+ }
+
+ get isNull() {
+ return this.args.value === null || this.args.value === undefined;
+ }
+
+ get isEmpty() {
+ return this.args.value === "";
+ }
+
+ get isPlaceholder() {
+ return this.isNull || this.isEmpty;
+ }
+
+ get displayValue() {
+ if (this.isNull) {
+ return "Null";
+ }
+ if (this.isEmpty) {
+ return "Empty";
+ }
+ if (this.columnType === "date") {
+ return this.formatDateValue(this.args.value);
+ }
+ return String(this.args.value);
+ }
+
+ @action
+ startEditing() {
+ if (this.columnType === "boolean") {
+ return;
+ }
+ if (this.isNull) {
+ this.editValue = "";
+ } else if (this.columnType === "date") {
+ this.editValue = this.formatDateValue(this.args.value);
+ } else {
+ this.editValue = String(this.args.value);
+ }
+ this.isEditing = true;
+ }
+
+ @action
+ handleKeydown(event) {
+ if (event.key === "Enter") {
+ this.save();
+ } else if (event.key === "Escape") {
+ this.isEditing = false;
+ }
+ }
+
+ @action
+ save() {
+ this.isEditing = false;
+ this.args.onSave(this.args.column.name, this.editValue);
+ }
+
+ @action
+ toggleBoolean() {
+ const current = this.args.value;
+ this.args.onSave(this.args.column.name, !current);
+ }
+
+ @action
+ onInput(event) {
+ this.editValue = event.target.value;
+ }
+
+ formatDateValue(value) {
+ return String(value).slice(0, 10);
+ }
+
+ get inputType() {
+ if (this.columnType === "number") {
+ return "number";
+ }
+ if (this.columnType === "date") {
+ return "date";
+ }
+ return "text";
+ }
+
+ <template>
+ <td
+ class={{dConcatClass
+ "workflows-data-table-viewer__cell"
+ (if (eq this.columnType "boolean") "--boolean")
+ }}
+ >
+ {{#if (eq this.columnType "boolean")}}
+ <input
+ type="checkbox"
+ checked={{@value}}
+ class="workflows-data-table-viewer__checkbox"
+ {{on "change" this.toggleBoolean}}
+ />
+ {{else if this.isEditing}}
+ <input
+ type={{this.inputType}}
+ value={{this.editValue}}
+ class="workflows-data-table-viewer__cell-input"
+ {{autofocus}}
+ {{on "blur" this.save}}
+ {{on "keydown" this.handleKeydown}}
+ {{on "input" this.onInput}}
+ />
+ {{else}}
+
+ <button
+ type="button"
+ class={{dConcatClass
+ "workflows-data-table-viewer__cell-value"
+ (if this.isPlaceholder "is-null")
+ }}
+ {{on "click" this.startEditing}}
+ >{{this.displayValue}}</button>
+ {{/if}}
+ </td>
+ </template>
+}
diff --git a/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/data-table/manager.gjs b/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/data-table/manager.gjs
new file mode 100644
index 00000000000..3fc586db0a0
--- /dev/null
+++ b/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/data-table/manager.gjs
@@ -0,0 +1,155 @@
+import { fn } from "@ember/helper";
+import { action } from "@ember/object";
+import { LinkTo } from "@ember/routing";
+import { service } from "@ember/service";
+import humanSize from "discourse/admin/helpers/human-size";
+import { ajax } from "discourse/lib/ajax";
+import { popupAjaxError } from "discourse/lib/ajax-error";
+import DButton from "discourse/ui-kit/d-button";
+import { i18n } from "discourse-i18n";
+import AdminTable from "../admin-table";
+import EmptyState from "../empty-state";
+import InUseDialog from "../in-use-dialog";
+import PaginatedListManager from "../paginated-list-manager";
+import DataTableModal from "./modal";
+
+export default class DataTablesManager extends PaginatedListManager {
+ @service router;
+
+ get collectionKey() {
+ return "data_tables";
+ }
+
+ get basePath() {
+ return "/admin/plugins/discourse-workflows/data-tables";
+ }
+
+ @action
+ addDataTable() {
+ this.modal.show(DataTableModal, {
+ model: {
+ dataTable: null,
+ onSave: async (data) => {
+ const result = await ajax(this.apiUrl, {
+ type: "POST",
+ contentType: "application/json",
+ data: JSON.stringify(data),
+ });
+ this.router.transitionTo(
+ "adminPlugins.show.discourse-workflows-data-tables.show",
+ result.data_table.id
+ );
+ },
+ },
+ });
+ }
+
+ @action
+ async deleteDataTable(dataTable) {
+ await this.dialog.deleteConfirm({
+ message: i18n("discourse_workflows.data_tables.delete_confirm"),
+ didConfirm: async () => {
+ try {
+ await ajax(`${this.basePath}/${dataTable.id}.json`, {
+ type: "DELETE",
+ });
+ await this.loadItems();
+ } catch (e) {
+ const body = e.jqXHR?.responseJSON;
+ if (body?.type === "data_table_in_use") {
+ this.dialog.alert({
+ title: i18n("discourse_workflows.data_tables.in_use_title"),
+ bodyComponent: InUseDialog,
+ bodyComponentModel: {
+ description: i18n(
+ "discourse_workflows.data_tables.in_use_description"
+ ),
+ workflows: body.referencing_workflows,
+ close: () => this.dialog.cancel(),
+ },
+ });
+ } else {
+ popupAjaxError(e);
+ }
+ }
+ },
+ });
+ }
+
+ <template>
+ <AdminTable
+ @items={{this.items}}
+ @isLoading={{this.isLoading}}
+ @canLoadMore={{this.canLoadMore}}
+ @loadMore={{this.loadMore}}
+ @loadingMore={{this.loadingMore}}
+ >
+ <:empty>
+ <EmptyState
+ @emoji="wave"
+ @title={{i18n
+ "discourse_workflows.data_tables.empty_title"
+ username=this.currentUser.displayName
+ }}
+ @description={{i18n
+ "discourse_workflows.data_tables.empty_description"
+ }}
+ @buttonLabel="discourse_workflows.data_tables.add_first"
+ @onAction={{this.addDataTable}}
+ />
+ </:empty>
+ <:toolbar>
+ <DButton
+ @action={{this.addDataTable}}
+ @label="discourse_workflows.data_tables.add"
+ @icon="plus"
+ class="btn-primary btn-small"
+ />
+ </:toolbar>
+ <:head>
+ <th class="d-table__header-cell">{{i18n
+ "discourse_workflows.data_tables.name"
+ }}</th>
+ <th class="d-table__header-cell">{{i18n
+ "discourse_workflows.data_tables.columns"
+ }}</th>
+ <th class="d-table__header-cell">{{i18n
+ "discourse_workflows.data_tables.size"
+ }}</th>
+ <th class="d-table__header-cell"></th>
+ </:head>
+ <:row as |dataTable|>
+ <td class="d-table__cell --overview">
+ <LinkTo
+ @route="adminPlugins.show.discourse-workflows-data-tables.show"
+ @model={{dataTable.id}}
+ class="d-table__overview-link"
+ >
+ <strong class="d-table__overview-name">{{dataTable.name}}</strong>
+ </LinkTo>
+ </td>
+ <td class="d-table__cell --detail">
+ <div class="d-table__mobile-label">
+ {{i18n "discourse_workflows.data_tables.columns"}}
+ </div>
+ {{dataTable.columns.length}}
+ </td>
+ <td class="d-table__cell --detail">
+ <div class="d-table__mobile-label">
+ {{i18n "discourse_workflows.data_tables.size"}}
+ </div>
+ {{humanSize dataTable.size}}
+ </td>
+ <td class="d-table__cell --controls">
+ <div class="d-table__cell-actions">
+ <DButton
+ @action={{fn this.deleteDataTable dataTable}}
+ @label="discourse_workflows.delete"
+ class="btn-default btn-small"
+ />
+ </div>
+ </td>
+ </:row>
+ </AdminTable>
+ </template>
+}
diff --git a/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/data-table/modal.gjs b/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/data-table/modal.gjs
new file mode 100644
index 00000000000..68d915901f3
--- /dev/null
+++ b/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/data-table/modal.gjs
@@ -0,0 +1,73 @@
+import Component from "@glimmer/component";
+import { action } from "@ember/object";
+import Form from "discourse/components/form";
+import { popupAjaxError } from "discourse/lib/ajax-error";
+import DModal from "discourse/ui-kit/d-modal";
+import { i18n } from "discourse-i18n";
+
+const NAME_PATTERN = /^[a-zA-Z_][a-zA-Z0-9_ ]*$/;
+
+export default class DataTableModal extends Component {
+ formData = {
+ name: this.args.model.dataTable?.name || "",
+ };
+
+ @action
+ validateName(name, value, { addError }) {
+ if (value && !NAME_PATTERN.test(value)) {
+ addError(name, {
+ title: i18n("discourse_workflows.data_tables.name"),
+ message: i18n("discourse_workflows.data_tables.name_invalid"),
+ });
+ }
+ }
+
+ @action
+ async handleSubmit(data) {
+ try {
+ await this.args.model.onSave(data);
+ this.args.closeModal();
+ } catch (error) {
+ popupAjaxError(error);
+ }
+ }
+
+ <template>
+ <DModal
+ @title={{if
+ @model.dataTable
+ (i18n "discourse_workflows.data_tables.edit")
+ (i18n "discourse_workflows.data_tables.add")
+ }}
+ @closeModal={{@closeModal}}
+ class="data-table-modal"
+ >
+ <:body>
+ <Form
+ @data={{this.formData}}
+ @onSubmit={{this.handleSubmit}}
+ class="workflows-configurator-form"
+ as |form|
+ >
+ <form.Field
+ @name="name"
+ @title={{i18n "discourse_workflows.data_tables.name"}}
+ @type="input"
+ @format="full"
+ @validation="required"
+ @validate={{this.validateName}}
+ as |field|
+ >
+ <field.Control
+ placeholder={{i18n
+ "discourse_workflows.data_tables.name_placeholder"
+ }}
+ />
+ </form.Field>
+
+ <form.Submit />
+ </Form>
+ </:body>
+ </DModal>
+ </template>
+}
diff --git a/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/data-table/viewer.gjs b/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/data-table/viewer.gjs
new file mode 100644
index 00000000000..ca96c915a5a
--- /dev/null
+++ b/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/data-table/viewer.gjs
@@ -0,0 +1,429 @@
+import Component from "@glimmer/component";
+import { tracked } from "@glimmer/tracking";
+import { fn, get } from "@ember/helper";
+import { on } from "@ember/modifier";
+import { action } from "@ember/object";
+import { service } from "@ember/service";
+import { modifier } from "ember-modifier";
+import { ajax } from "discourse/lib/ajax";
+import { popupAjaxError } from "discourse/lib/ajax-error";
+import { eq } from "discourse/truth-helpers";
+import DButton from "discourse/ui-kit/d-button";
+import DConditionalLoadingSpinner from "discourse/ui-kit/d-conditional-loading-spinner";
+import DLoadMore from "discourse/ui-kit/d-load-more";
+import { i18n } from "discourse-i18n";
+import AddColumnModal from "./add-column-modal";
+import CellEditor from "./cell-editor";
+
+const autofocus = modifier((element) => {
+ element.focus();
+ element.select();
+ syncInputWidth(element);
+ const handler = () => syncInputWidth(element);
+ element.addEventListener("input", handler);
+ return () => element.removeEventListener("input", handler);
+});
+
+function syncInputWidth(input) {
+ input.style.setProperty("--col-name-length", input.value.length || 1);
+}
+
+const indeterminate = modifier((element, [value]) => {
+ element.indeterminate = value;
+});
+
+export default class DataTableViewer extends Component {
+ @service modal;
+ @service dialog;
+
+ @tracked rows = null;
+ @tracked dataTable = null;
+ @tracked totalCount = 0;
+ @tracked loadingMore = false;
+ @tracked selectedRowIds = new Set();
+ @tracked editingColumnIndex = null;
+ @tracked editingName = false;
+
+ lastClickedRowIndex = null;
+
+ constructor() {
+ super(...arguments);
+ this.loadTable();
+ }
+
+ get apiBasePath() {
+ return `/admin/plugins/discourse-workflows/data-tables/${this.args.dataTableId}`;
+ }
+
+ async loadTable() {
+ try {
+ const [tableResult, rowsResult] = await Promise.all([
+ ajax(`${this.apiBasePath}.json`),
+ ajax(`${this.apiBasePath}/rows.json`),
+ ]);
+ this.dataTable = tableResult.data_table;
+ this.rows = rowsResult.rows;
+ this.totalCount = rowsResult.count;
+ } catch (e) {
+ popupAjaxError(e);
+ }
+ }
+
+ get canLoadMore() {
+ return this.rows && this.rows.length < this.totalCount;
+ }
+
+ @action
+ async loadMore() {
+ if (!this.canLoadMore || this.loadingMore) {
+ return;
+ }
+
+ this.loadingMore = true;
+ try {
+ const result = await ajax(`${this.apiBasePath}/rows.json`, {
+ data: { offset: this.rows.length },
+ });
+ this.rows = [...this.rows, ...result.rows];
+ this.totalCount = result.count;
+ } catch (e) {
+ popupAjaxError(e);
+ } finally {
+ this.loadingMore = false;
+ }
+ }
+
+ get isLoading() {
+ return this.rows === null || this.dataTable === null;
+ }
+
+ get columns() {
+ const reserved = ["id", "created_at", "updated_at"];
+ return (
+ this.dataTable?.columns?.filter((c) => !reserved.includes(c.name)) ?? []
+ );
+ }
+
+ get hasSelection() {
+ return this.selectedRowIds.size > 0;
+ }
+
+ get allSelected() {
+ return (
+ this.rows?.length > 0 && this.selectedRowIds.size === this.rows.length
+ );
+ }
+
+ get isIndeterminate() {
+ return this.hasSelection && !this.allSelected;
+ }
+
+ @action
+ isRowSelected(rowId) {
+ return this.selectedRowIds.has(rowId);
+ }
+
+ @action
+ toggleRowSelection(rowId, event) {
+ const currentIndex = this.rows.findIndex((r) => r.id === rowId);
+ const next = new Set(this.selectedRowIds);
+
+ if (event?.shiftKey && this.lastClickedRowIndex !== null) {
+ const from = Math.min(this.lastClickedRowIndex, currentIndex);
+ const to = Math.max(this.lastClickedRowIndex, currentIndex);
+ for (let i = from; i <= to; i++) {
+ next.add(this.rows[i].id);
+ }
+ } else if (next.has(rowId)) {
+ next.delete(rowId);
+ } else {
+ next.add(rowId);
+ }
+
+ this.lastClickedRowIndex = currentIndex;
+ this.selectedRowIds = next;
+ }
+
+ @action
+ clearSelection() {
+ this.selectedRowIds = new Set();
+ this.lastClickedRowIndex = null;
+ }
+
+ @action
+ toggleAllSelection() {
+ if (this.allSelected) {
+ this.selectedRowIds = new Set();
+ } else {
+ this.selectedRowIds = new Set(this.rows.map((r) => r.id));
+ }
+ }
+
+ @action
+ deleteSelectedRows() {
+ this.dialog.deleteConfirm({
+ message: i18n("discourse_workflows.data_tables.delete_rows_confirm", {
+ count: this.selectedRowIds.size,
+ }),
+ didConfirm: async () => {
+ try {
+ await ajax(`${this.apiBasePath}/rows.json`, {
+ type: "DELETE",
+ data: { row_ids: [...this.selectedRowIds] },
+ });
+ this.selectedRowIds = new Set();
+ await this.loadTable();
+ } catch (e) {
+ popupAjaxError(e);
+ }
+ },
+ });
+ }
+
+ @action
+ async saveCell(row, columnName, value) {
+ try {
+ const result = await ajax(`${this.apiBasePath}/rows/${row.id}.json`, {
+ type: "PUT",
+ data: { data: { [columnName]: value } },
+ });
+ const idx = this.rows.findIndex((r) => r.id === row.id);
+ if (idx !== -1) {
+ const updated = [...this.rows];
+ updated[idx] = result.row;
+ this.rows = updated;
+ }
+ } catch (e) {
+ popupAjaxError(e);
+ }
+ }
+
+ @action
+ async addRow() {
+ try {
+ const result = await ajax(`${this.apiBasePath}/rows.json`, {
+ type: "POST",
+ data: { data: {} },
+ });
+ this.rows = [...this.rows, result.row];
+ this.totalCount += 1;
+ } catch (e) {
+ popupAjaxError(e);
+ }
+ }
+
+ @action
+ startEditingName() {
+ this.editingName = true;
+ }
+
+ @action
+ handleEditKeydown(originalValue, event) {
+ if (event.key === "Enter") {
+ event.target.blur();
+ } else if (event.key === "Escape") {
+ event.target.value = originalValue;
+ event.target.blur();
+ }
+ }
+
+ @action
+ async saveName(event) {
+ this.editingName = false;
+ const newName = event.target.value.trim();
+ if (!newName || newName === this.dataTable.name) {
+ return;
+ }
+ try {
+ const result = await ajax(`${this.apiBasePath}.json`, {
+ type: "PUT",
+ data: { name: newName },
+ });
+ this.dataTable = result.data_table;
+ } catch (e) {
+ popupAjaxError(e);
+ }
+ }
+
+ @action
+ startEditingColumn(index) {
+ this.editingColumnIndex = index;
+ }
+
+ @action
+ async renameColumn(index, event) {
+ this.editingColumnIndex = null;
+ const newName = event.target.value.trim();
+ const column = this.columns[index];
+ const oldName = column.name;
+ if (!newName || newName === oldName) {
+ return;
+ }
+ try {
+ const result = await ajax(
+ `${this.apiBasePath}/columns/${column.name}/rename.json`,
+ {
+ type: "PATCH",
+ data: { name: newName },
+ }
+ );
+ this.dataTable = result.data_table;
+ await this.loadTable();
+ } catch (e) {
+ popupAjaxError(e);
+ }
+ }
+
+ @action
+ addColumn() {
+ this.modal.show(AddColumnModal, {
+ model: {
+ onSave: async (data) => {
+ const result = await ajax(`${this.apiBasePath}/columns.json`, {
+ type: "POST",
+ data: { name: data.name, column_type: data.type },
+ });
+ this.dataTable = result.data_table;
+ await this.loadTable();
+ },
+ },
+ });
+ }
+
+ <template>
+ <div class="workflows-data-table-viewer">
+ <div class="workflows-data-table-viewer__header">
+ {{#if this.editingName}}
+ <input
+ type="text"
+ value={{this.dataTable.name}}
+ class="workflows-data-table-viewer__title-input"
+ {{autofocus}}
+ {{on "blur" this.saveName}}
+ {{on "keydown" (fn this.handleEditKeydown this.dataTable.name)}}
+ />
+ {{else}}
+ <button
+ type="button"
+ class="workflows-data-table-viewer__title"
+ {{on "click" this.startEditingName}}
+ >{{this.dataTable.name}}</button>
+ {{/if}}
+ <div class="workflows-data-table-viewer__actions">
+ {{#if this.hasSelection}}
+ <DButton
+ @action={{this.deleteSelectedRows}}
+ @icon="trash-can"
+ @label="discourse_workflows.data_tables.delete_selected"
+ class="btn-danger btn-small"
+ />
+ <DButton
+ @action={{this.clearSelection}}
+ @icon="xmark"
+ @label="discourse_workflows.data_tables.clear_selection"
+ class="btn-default btn-small"
+ />
+ {{/if}}
+ </div>
+ </div>
+
+ <DConditionalLoadingSpinner @condition={{this.isLoading}}>
+ <DLoadMore @action={{this.loadMore}} @enabled={{this.canLoadMore}}>
+ <div class="workflows-data-table-viewer__scroll">
+ <table class="workflows-data-table-viewer__table">
+ <thead>
+ <tr>
+ <th class="workflows-data-table-viewer__th --id">
+ <input
+ type="checkbox"
+ checked={{this.allSelected}}
+ class="workflows-data-table-viewer__checkbox"
+ {{indeterminate this.isIndeterminate}}
+ {{on "change" this.toggleAllSelection}}
+ />
+ id
+ </th>
+ {{#each this.columns as |col index|}}
+ <th class="workflows-data-table-viewer__th">
+ <span
+ class="workflows-data-table-viewer__col-type"
+ >{{col.type}}</span>
+ {{#if (eq this.editingColumnIndex index)}}
+ <input
+ type="text"
+ value={{col.name}}
+ class="workflows-data-table-viewer__col-name-input"
+ {{autofocus}}
+ {{on "blur" (fn this.renameColumn index)}}
+ {{on "keydown" (fn this.handleEditKeydown col.name)}}
+ />
+ {{else}}
+ <button
+ type="button"
+ class="workflows-data-table-viewer__col-name"
+ {{on "click" (fn this.startEditingColumn index)}}
+ >{{col.name}}</button>
+ {{/if}}
+ </th>
+ {{/each}}
+ <th
+ class="workflows-data-table-viewer__th --system"
+ >created_at</th>
+ <th
+ class="workflows-data-table-viewer__th --system"
+ >updated_at</th>
+ <th class="workflows-data-table-viewer__th --add-column">
+ <DButton
+ @action={{this.addColumn}}
+ @icon="plus"
+ class="btn-transparent btn-small"
+ />
+ </th>
+ </tr>
+ </thead>
+ <tbody>
+ {{#each this.rows as |row|}}
+ <tr class="workflows-data-table-viewer__row">
+ <td class="workflows-data-table-viewer__cell --id">
+ <input
+ type="checkbox"
+ checked={{this.isRowSelected row.id}}
+ class="workflows-data-table-viewer__checkbox"
+ {{on "click" (fn this.toggleRowSelection row.id)}}
+ />
+ {{row.id}}
+ </td>
+ {{#each this.columns as |col|}}
+ <CellEditor
+ @column={{col}}
+ @value={{get row col.name}}
+ @onSave={{fn this.saveCell row}}
+ />
+ {{/each}}
+ <td
+ class="workflows-data-table-viewer__cell --system"
+ >{{row.created_at}}</td>
+ <td
+ class="workflows-data-table-viewer__cell --system"
+ >{{row.updated_at}}</td>
+ <td class="--add-column"></td>
+ </tr>
+ {{/each}}
+ <tr class="workflows-data-table-viewer__add-row">
+ <td colspan="99">
+ <DButton
+ @action={{this.addRow}}
+ @icon="plus"
+ class="btn-transparent btn-small"
+ />
+ </td>
+ </tr>
+ </tbody>
+ </table>
+ </div>
+ <DConditionalLoadingSpinner @condition={{this.loadingMore}} />
+ </DLoadMore>
+ </DConditionalLoadingSpinner>
+ </div>
+ </template>
+}
diff --git a/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/editable-title.gjs b/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/editable-title.gjs
new file mode 100644
index 00000000000..1f58a5ec2c0
--- /dev/null
+++ b/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/editable-title.gjs
@@ -0,0 +1,106 @@
+import Component from "@glimmer/component";
+import { tracked } from "@glimmer/tracking";
+import { on } from "@ember/modifier";
+import { action } from "@ember/object";
+import { modifier } from "ember-modifier";
+import DButton from "discourse/ui-kit/d-button";
+
+function syncInputWidth(input) {
+ input.style.setProperty(
+ "--title-length",
+ Math.max(input.value.length, 1) + 1
+ );
+}
+
+const autosize = modifier((element) => {
+ syncInputWidth(element);
+ Promise.resolve().then(() => element.focus());
+ const handler = () => syncInputWidth(element);
+ element.addEventListener("input", handler);
+ return () => element.removeEventListener("input", handler);
+});
+
+export default class WorkflowEditableTitle extends Component {
+ @tracked isEditing = false;
+ @tracked editValue = "";
+
+ @action
+ startEditing() {
+ this.editValue = this.args.value;
+ this.isEditing = true;
+ }
+
+ @action
+ cancel() {
+ this.isEditing = false;
+ }
+
+ @action
+ onInput(event) {
+ this.editValue = event.target.value;
+ }
+
+ @action
+ save() {
+ if (!this.isEditing) {
+ return;
+ }
+
+ this.isEditing = false;
+ if (this.editValue.trim() && this.editValue !== this.args.value) {
+ this.args.onSave(this.editValue.trim());
+ }
+ }
+
+ @action
+ handleKeydown(event) {
+ if (event.key === "Enter") {
+ this.save();
+ } else if (event.key === "Escape") {
+ this.cancel();
+ }
+ }
+
+ <template>
+ <div class="workflows-editable-title">
+ {{#if this.isEditing}}
+ <input
+ type="text"
+ value={{this.editValue}}
+ class="workflows-editable-title__input"
+ {{autosize}}
+ {{on "keydown" this.handleKeydown}}
+ {{on "input" this.onInput}}
+ />
+ <div class="workflows-editable-title__actions">
+ <DButton
+ @action={{this.save}}
+ @icon="check"
+ @title="discourse_workflows.save"
+ class="btn-flat workflows-editable-title__save"
+ />
+ <DButton
+ @action={{this.cancel}}
+ @icon="xmark"
+ @title="discourse_workflows.cancel"
+ class="btn-flat workflows-editable-title__cancel"
+ />
+ </div>
+ {{else}}
+ <div class="workflows-editable-title__display">
+ <button
+ type="button"
+ class="workflows-editable-title__text"
+ {{on "click" this.startEditing}}
+ >{{@value}}</button>
+ <DButton
+ @action={{this.startEditing}}
+ @icon="pencil"
+ @title="discourse_workflows.edit"
+ class="btn-flat workflows-editable-title__edit"
+ />
+ </div>
+ {{/if}}
+ </div>
+ </template>
+}
diff --git a/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/editor/graph-utils.js b/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/editor/graph-utils.js
new file mode 100644
index 00000000000..cfe86e24a3e
--- /dev/null
+++ b/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/editor/graph-utils.js
@@ -0,0 +1,299 @@
+import {
+ buildOutgoingIndex,
+ collectLoopBodyNodeIds,
+ graphConnectionKey,
+ LOOP_NODE_TYPE,
+ normalizeSourceOutput,
+ normalizeSourceOutputIndex,
+ normalizeTargetInputIndex,
+ portIndexFromKey,
+} from "../../../lib/workflows/graph-constants";
+
+export {
+ buildOutgoingIndex,
+ LOOP_NODE_TYPE,
+} from "../../../lib/workflows/graph-constants";
+
+function clientConnectionKey(connection) {
+ return graphConnectionKey({
+ source: connection.sourceClientId,
+ sourceOutputIndex: normalizeSourceOutputIndex(connection),
+ target: connection.targetClientId,
+ targetInputIndex: normalizeTargetInputIndex(connection),
+ });
+}
+
+function mergeModeFor(node) {
+ return node?.configuration?.mode || "append";
+}
+
+function cloneConnectionWithTargetInputIndex(connection, targetInputIndex) {
+ return {
+ ...connection,
+ targetInputIndex,
+ targetInput: `input_${targetInputIndex + 1}`,
+ };
+}
+
+function hasExplicitTargetInput(connection) {
+ return (
+ connection.targetInputIndex != null ||
+ (connection.targetInput && connection.targetInput !== "main")
+ );
+}
+
+function nextUnusedInputIndex(used) {
+ let index = 0;
+ while (used.has(index)) {
+ index++;
+ }
+ return index;
+}
+
+export function normalizeConnectionsForNodes(connections, nodes) {
+ const nodeByClientId = new Map(nodes.map((node) => [node.clientId, node]));
+ const usedMergeInputs = new Map();
+
+ for (const connection of connections) {
+ const targetNode = nodeByClientId.get(connection.targetClientId);
+ if (
+ targetNode?.type === "flow:merge" &&
+ hasExplicitTargetInput(connection)
+ ) {
+ const used = usedMergeInputs.get(connection.targetClientId) || new Set();
+ used.add(normalizeTargetInputIndex(connection));
+ usedMergeInputs.set(connection.targetClientId, used);
+ }
+ }
+
+ return connections.flatMap((connection) => {
+ const targetNode = nodeByClientId.get(connection.targetClientId);
+ if (targetNode?.type !== "flow:merge") {
+ return [connection];
+ }
+
+ const mode = mergeModeFor(targetNode);
+ const targetInputIndex = normalizeTargetInputIndex(connection);
+
+ if (mode === "append") {
+ if (!hasExplicitTargetInput(connection)) {
+ const used =
+ usedMergeInputs.get(connection.targetClientId) || new Set();
+ const nextInputIndex = nextUnusedInputIndex(used);
+ used.add(nextInputIndex);
+ usedMergeInputs.set(connection.targetClientId, used);
+ return [
+ cloneConnectionWithTargetInputIndex(connection, nextInputIndex),
+ ];
+ }
+
+ return [
+ cloneConnectionWithTargetInputIndex(connection, targetInputIndex),
+ ];
+ }
+
+ if (hasExplicitTargetInput(connection)) {
+ return targetInputIndex < 2
+ ? [cloneConnectionWithTargetInputIndex(connection, targetInputIndex)]
+ : [];
+ }
+
+ const used = usedMergeInputs.get(connection.targetClientId) || new Set();
+ const nextInputIndex = [0, 1].find((input) => !used.has(input));
+ if (nextInputIndex == null) {
+ return [];
+ }
+
+ used.add(nextInputIndex);
+ usedMergeInputs.set(connection.targetClientId, used);
+
+ return [cloneConnectionWithTargetInputIndex(connection, nextInputIndex)];
+ });
+}
+
+export function normalizeMergeConfiguration(configuration = {}) {
+ const mode = configuration.mode || "append";
+
+ if (mode === "append") {
+ return {
+ mode,
+ number_inputs: Math.max(
+ parseInt(configuration.number_inputs, 10) || 2,
+ 2
+ ),
+ };
+ }
+
+ if (mode === "choose_branch") {
+ return {
+ mode,
+ use_data_of_input: configuration.use_data_of_input || "input_1",
+ use_data_of_input_index:
+ configuration.use_data_of_input_index ??
+ portIndexFromKey(configuration.use_data_of_input),
+ choose_output: configuration.choose_output || "specified_input",
+ };
+ }
+
+ const combineBy = configuration.combine_by || "matching_fields";
+ const normalized = {
+ mode,
+ combine_by: combineBy,
+ resolve_clash: configuration.resolve_clash || "prefer_last",
+ merge_mode: configuration.merge_mode || "deep_merge",
+ override_empty: Boolean(configuration.override_empty),
+ fuzzy_compare: Boolean(configuration.fuzzy_compare),
+ };
+
+ if (combineBy === "matching_fields") {
+ return {
+ ...normalized,
+ fields_to_match: configuration.fields_to_match || [],
+ join_mode: configuration.join_mode || "keep_matches",
+ output_data_from: configuration.output_data_from || "both",
+ multiple_matches: configuration.multiple_matches || "all",
+ };
+ }
+
+ if (combineBy === "position") {
+ return {
+ ...normalized,
+ include_unpaired: Boolean(configuration.include_unpaired),
+ };
+ }
+
+ return normalized;
+}
+
+export function normalizeNodeConfiguration(node) {
+ if (node?.type !== "flow:merge") {
+ return node;
+ }
+
+ return {
+ ...node,
+ configuration: normalizeMergeConfiguration(node.configuration),
+ };
+}
+
+function dedupeConnections(connections) {
+ const seen = new Set();
+
+ return connections.filter((connection) => {
+ if (!connection.sourceClientId || !connection.targetClientId) {
+ return false;
+ }
+
+ const key = clientConnectionKey(connection);
+ if (seen.has(key)) {
+ return false;
+ }
+
+ seen.add(key);
+ return true;
+ });
+}
+
+function getLoopBodyNodeIds(connections, loopNodeClientId) {
+ const outgoing = buildOutgoingIndex(connections, "sourceClientId");
+ return collectLoopBodyNodeIds(loopNodeClientId, outgoing, {
+ targetKey: "targetClientId",
+ outputKey: "sourceOutput",
+ });
+}
+
+function isLoopDoneConnection(connection, loopNodeClientId) {
+ return (
+ connection.sourceClientId === loopNodeClientId &&
+ (connection.sourceOutput === "done" ||
+ normalizeSourceOutputIndex(connection) === 0)
+ );
+}
+
+function reconnectSingleNode(connections, clientId) {
+ const incoming = connections.filter(
+ (connection) => connection.targetClientId === clientId
+ );
+ const outgoing = connections.filter(
+ (connection) => connection.sourceClientId === clientId
+ );
+
+ if (incoming.length !== 1 || outgoing.length !== 1) {
+ return [];
+ }
+
+ return [
+ {
+ sourceClientId: incoming[0].sourceClientId,
+ targetClientId: outgoing[0].targetClientId,
+ sourceOutput: normalizeSourceOutput(incoming[0].sourceOutput),
+ targetInput: outgoing[0].targetInput || "main",
+ },
+ ];
+}
+
+function reconnectLoopNode(connections, loopNodeClientId, idsToRemove) {
+ const bodyNodeIds = getLoopBodyNodeIds(connections, loopNodeClientId);
+ const incoming = connections.filter(
+ (connection) =>
+ connection.targetClientId === loopNodeClientId &&
+ connection.sourceClientId !== loopNodeClientId &&
+ !bodyNodeIds.has(connection.sourceClientId) &&
+ !idsToRemove.has(connection.sourceClientId)
+ );
+ const doneOutgoing = connections.filter(
+ (connection) =>
+ isLoopDoneConnection(connection, loopNodeClientId) &&
+ connection.targetClientId !== loopNodeClientId &&
+ !idsToRemove.has(connection.targetClientId)
+ );
+
+ return incoming.flatMap((src) =>
+ doneOutgoing.map((tgt) => ({
+ sourceClientId: src.sourceClientId,
+ targetClientId: tgt.targetClientId,
+ sourceOutput: normalizeSourceOutput(src.sourceOutput),
+ targetInput: tgt.targetInput || "main",
+ }))
+ );
+}
+
+export function removeNodesFromGraph(nodes, connections, clientIds) {
+ const idsToRemove = new Set(clientIds);
+
+ if (idsToRemove.size === 0) {
+ return { nodes, connections };
+ }
+
+ const reconnects = [];
+
+ for (const node of nodes) {
+ if (idsToRemove.has(node.clientId) && node.type === LOOP_NODE_TYPE) {
+ reconnects.push(
+ ...reconnectLoopNode(connections, node.clientId, idsToRemove)
+ );
+ }
+ }
+
+ if (idsToRemove.size === 1) {
+ const [clientId] = clientIds;
+ const node = nodes.find((n) => n.clientId === clientId);
+ if (node?.type !== LOOP_NODE_TYPE) {
+ reconnects.push(...reconnectSingleNode(connections, clientId));
+ }
+ }
+
+ const remainingNodes = nodes.filter(
+ (node) => !idsToRemove.has(node.clientId)
+ );
+ const remainingConnections = connections.filter(
+ (connection) =>
+ !idsToRemove.has(connection.sourceClientId) &&
+ !idsToRemove.has(connection.targetClientId)
+ );
+
+ return {
+ nodes: remainingNodes,
+ connections: dedupeConnections([...remainingConnections, ...reconnects]),
+ };
+}
diff --git a/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/editor/index.gjs b/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/editor/index.gjs
new file mode 100644
index 00000000000..16aed813f99
--- /dev/null
+++ b/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/editor/index.gjs
@@ -0,0 +1,1458 @@
+import Component from "@glimmer/component";
+import { tracked } from "@glimmer/tracking";
+import { action } from "@ember/object";
+import { service } from "@ember/service";
+import Form from "discourse/components/form";
+import { ajax } from "discourse/lib/ajax";
+import { popupAjaxError } from "discourse/lib/ajax-error";
+import { bind } from "discourse/lib/decorators";
+import { i18n } from "discourse-i18n";
+import WorkflowEditorSession from "../../../lib/workflows/editor-session";
+import {
+ connectionMatchesEndpoint,
+ normalizeSourceOutputIndex,
+ portIndexFromKey,
+} from "../../../lib/workflows/graph-constants";
+import {
+ nodeTypeLabel,
+ nodeTypePrimaryOutputKey,
+ nodeTypeVersion,
+ resolveNodeTypeVersion,
+} from "../../../lib/workflows/node-types";
+import { mergeImportedStaticData } from "../../../lib/workflows/static-data";
+import StickyNote, { STICKY_NOTE_TYPE } from "../../../models/sticky-note";
+import { deserializeConnections } from "../../../models/workflow-connection";
+import WorkflowNode from "../../../models/workflow-node";
+import WorkflowCanvas from "../canvas";
+import NodePanel from "../canvas/node-panel";
+import NodeConfigurator from "../node/configurator";
+import {
+ LOOP_NODE_TYPE,
+ normalizeConnectionsForNodes,
+ normalizeNodeConfiguration,
+ removeNodesFromGraph,
+} from "./graph-utils";
+import { createNode, generateNodeName } from "./node-factory";
+import UndoManager from "./undo-manager";
+
+const MAX_NODES = 50;
+
+function nodeTypeIdentifier(nodeType) {
+ return nodeType?.name || nodeType?.identifier || nodeType?.type || "";
+}
+
+function isTriggerType(type) {
+ return type?.startsWith("trigger:");
+}
+
+export function isNodeUnavailable(workflowsNodeTypes, node) {
+ const nodeType = workflowsNodeTypes.findNodeType(node.type);
+ if (!nodeType) {
+ return true;
+ }
+
+ return (
+ resolveNodeTypeVersion(nodeType, node.typeVersion)?.available === false
+ );
+}
+
+function shouldHideTriggerNodeTypes(context, nodes) {
+ const sourceClientId = context?.sourceClientId || context?.connectionSource;
+
+ if (!sourceClientId) {
+ return false;
+ }
+
+ const sourceNode = nodes?.find((node) => node.clientId === sourceClientId);
+
+ return isTriggerType(sourceNode?.type);
+}
+
+export default class WorkflowsEditor extends Component {
+ @service router;
+ @service dialog;
+ @service modal;
+ @service toasts;
+ @service workflowsNodeTypes;
+ @service messageBus;
+
+ @tracked canUndo = false;
+ @tracked canRedo = false;
+ @tracked nodePanelContext = null;
+ @tracked nodePanelNodeTypes = null;
+ @tracked nodePanelSearchTerm = "";
+ @tracked autoArrangeRequest = 0;
+ formApi = null;
+ ignoreDirty = () => false;
+ undoManager = new UndoManager();
+ allowUnpublishedDraftTransition = false;
+ currentSavePromise = null;
+ pendingGraphSnapshot = null;
+ pendingSaveOptions = null;
+ workflowSession = new WorkflowEditorSession({
+ workflowId: this.args.workflow?.id,
+ lastExecutionRunData: this.args.workflow?.lastExecutionRunData || null,
+ pinData: this.args.workflow?.pinData || {},
+ });
+
+ formData = {
+ name:
+ this.args.workflow.name ||
+ i18n("discourse_workflows.default_workflow_name"),
+ nodes: this.#initNodes(),
+ connections: this.#mapServerConnections(),
+ stickyNotes: this.#initStickyNotes(),
+ };
+ isUndoRedo = false;
+
+ constructor() {
+ super(...arguments);
+ this.#subscribeToExecutions();
+ this.router.on("routeWillChange", this.confirmUnpublishedDraftTransition);
+ window.addEventListener("beforeunload", this.handleBeforeUnload);
+ }
+
+ willDestroy() {
+ super.willDestroy(...arguments);
+ this.undoManager.destroy();
+ this.#unsubscribeFromExecutions();
+ this.router.off("routeWillChange", this.confirmUnpublishedDraftTransition);
+ window.removeEventListener("beforeunload", this.handleBeforeUnload);
+ }
+
+ get hasUnpublishedDraft() {
+ return Boolean(
+ (this.args.workflow?.activeVersionId &&
+ this.args.workflow?.hasUnpublishedChanges) ||
+ this.saving ||
+ this.pendingSave
+ );
+ }
+
+ @bind
+ handleBeforeUnload(event) {
+ if (!this.hasUnpublishedDraft) {
+ return;
+ }
+
+ const message = i18n(
+ "discourse_workflows.unpublished_changes_confirmation"
+ );
+ event.preventDefault();
+ event.returnValue = message;
+ return message;
+ }
+
+ @bind
+ confirmUnpublishedDraftTransition(transition) {
+ const routeChanging = transition.to?.name !== transition.from?.name;
+ const shouldCheck =
+ this.hasUnpublishedDraft &&
+ !this.allowUnpublishedDraftTransition &&
+ !transition.isAborted &&
+ (!transition.queryParamsOnly || routeChanging);
+
+ if (!shouldCheck) {
+ return;
+ }
+
+ transition.abort();
+
+ this.dialog.dialog({
+ class: "workflows-unpublished-draft-dialog",
+ message: i18n("discourse_workflows.unpublished_changes_confirmation"),
+ type: "confirm",
+ buttons: [
+ {
+ label: i18n("discourse_workflows.leave_without_publishing"),
+ class: "btn-primary",
+ action: () => this.leaveWithoutPublishing(transition),
+ },
+ {
+ label: i18n("discourse_workflows.keep_editing"),
+ class: "btn-default",
+ },
+ {
+ label: i18n("discourse_workflows.discard_changes"),
+ class: "btn-default workflows-unpublished-draft-dialog__discard-btn",
+ action: () => this.discardDraftAndRetryTransition(transition),
+ },
+ ],
+ });
+ }
+
+ @action
+ leaveWithoutPublishing(transition) {
+ this.allowUnpublishedDraftTransition = true;
+ transition.retry();
+ }
+
+ @action
+ async discardDraftAndRetryTransition(transition) {
+ const confirmed = await this.confirmDiscardChanges();
+
+ if (!confirmed) {
+ return;
+ }
+
+ await this.discardWorkflowDraft();
+ this.leaveWithoutPublishing(transition);
+ }
+
+ confirmDiscardChanges() {
+ return this.dialog.confirm({
+ message: i18n("discourse_workflows.discard_changes_confirmation"),
+ confirmButtonLabel: "discourse_workflows.discard_changes",
+ cancelButtonLabel: "discourse_workflows.keep_editing",
+ });
+ }
+
+ #subscribeToExecutions() {
+ const workflowId = this.args.workflow?.id;
+ if (!workflowId) {
+ return;
+ }
+ this.executionChannel = `/discourse-workflows/workflow/${workflowId}`;
+ this.messageBus.subscribe(this.executionChannel, (message) => {
+ if (message.type === "execution_completed") {
+ this.workflowSession.lastExecutionRunData =
+ message.lastExecutionRunData;
+ const completedNodeIds = Object.keys(
+ message.lastExecutionRunData || {}
+ );
+ if (message.execution?.trigger_node_id) {
+ completedNodeIds.push(message.execution.trigger_node_id);
+ }
+ const completedWebhookTest = completedNodeIds.some((nodeId) =>
+ this.workflowSession.webhookTestListenerForNode(nodeId)
+ );
+
+ for (const nodeId of completedNodeIds) {
+ this.workflowSession.clearWebhookTestListener(nodeId);
+ }
+
+ if (completedWebhookTest && message.execution) {
+ const toastType =
+ message.execution.status === "error" ? "error" : "success";
+ this.toasts[toastType]({
+ data: {
+ message:
+ message.execution.status === "error"
+ ? i18n("discourse_workflows.manual_trigger.failed")
+ : i18n("discourse_workflows.manual_trigger.triggered"),
+ actions: [
+ {
+ label: i18n(
+ "discourse_workflows.manual_trigger.view_execution"
+ ),
+ class: "btn-primary btn-small",
+ action: ({ close }) => {
+ close();
+ this.router.transitionTo(
+ "adminPlugins.show.discourse-workflows.show.executions.show",
+ message.execution.workflow_id,
+ message.execution.id
+ );
+ },
+ },
+ ],
+ },
+ });
+ }
+ }
+ });
+ }
+
+ #unsubscribeFromExecutions() {
+ if (this.executionChannel) {
+ this.messageBus.unsubscribe(this.executionChannel);
+ this.executionChannel = null;
+ }
+ }
+
+ #mapServerConnections() {
+ const nodes = this.#initNodes();
+ return normalizeConnectionsForNodes(
+ deserializeConnections(this.args.workflow.connections || {}, nodes),
+ nodes
+ );
+ }
+
+ #initNodes() {
+ return (this.args.workflow.nodes || [])
+ .filter((node) => node.type !== STICKY_NOTE_TYPE)
+ .map((node) =>
+ WorkflowNode.create({
+ ...node,
+ position: this.#parsePosition(node.position),
+ })
+ );
+ }
+
+ #initStickyNotes() {
+ const allNodes = this.args.workflow.nodes || [];
+ return allNodes
+ .filter((node) => node.type === STICKY_NOTE_TYPE)
+ .map(StickyNote.fromNode);
+ }
+
+ #parsePosition(pos) {
+ if (pos && typeof pos === "object" && "x" in pos && "y" in pos) {
+ return { x: pos.x, y: pos.y };
+ }
+ return null;
+ }
+
+ @action
+ registerApi(api) {
+ this.formApi = api;
+ }
+
+ #refreshUndoState() {
+ this.canUndo = this.undoManager.canUndo;
+ this.canRedo = this.undoManager.canRedo;
+ }
+
+ #syncFromServer() {
+ const allServerNodes = this.args.workflow.nodes || [];
+ const formNodes = this.formApi.get("nodes");
+
+ const positionsByClientId = new Map(
+ formNodes.map((n) => [n.clientId, n.position])
+ );
+
+ const nodes = allServerNodes
+ .filter((n) => n.type !== STICKY_NOTE_TYPE)
+ .map((serverNode) => {
+ return WorkflowNode.create({
+ ...serverNode,
+ position:
+ positionsByClientId.get(serverNode.clientId) ||
+ this.#parsePosition(serverNode.position),
+ });
+ });
+
+ const stickyNotes = allServerNodes
+ .filter((n) => n.type === STICKY_NOTE_TYPE)
+ .map(StickyNote.fromNode);
+
+ this.formApi.set("nodes", nodes);
+ this.formApi.set("connections", this.#mapServerConnections());
+ this.formApi.set("stickyNotes", stickyNotes);
+ }
+
+ #captureGraphSnapshot() {
+ return {
+ nodes: structuredClone(this.formApi.get("nodes")),
+ connections: structuredClone(this.formApi.get("connections")),
+ stickyNotes: structuredClone(this.formApi.get("stickyNotes")),
+ };
+ }
+
+ #applyGraphSnapshot({ nodes, connections, stickyNotes }) {
+ this.formApi.set("nodes", nodes);
+ this.formApi.set("connections", connections);
+ if (stickyNotes) {
+ this.formApi.set("stickyNotes", stickyNotes);
+ }
+ }
+
+ #captureUndo() {
+ if (this.undoManager.hasPendingCapture) {
+ return;
+ }
+ this.undoManager.captureBeforeState(this.#captureGraphSnapshot());
+ }
+
+ @action
+ applySnapshot({ nodes, connections, stickyNotes }) {
+ this.isUndoRedo = true;
+ this.#applyGraphSnapshot({ nodes, connections, stickyNotes });
+ this.handleSubmit();
+ }
+
+ @action
+ async initializeUndo(area) {
+ await this.undoManager.initialize(area, this.applySnapshot);
+ }
+
+ @action
+ async undo() {
+ await this.#undoRedoAction("undo");
+ }
+
+ @action
+ async redo() {
+ await this.#undoRedoAction("redo");
+ }
+
+ @action
+ browseTemplates() {
+ const nodes = this.formApi.get("nodes") || [];
+ const stickyNotes = this.formApi.get("stickyNotes") || [];
+
+ if (nodes.length === 0 && stickyNotes.length === 0) {
+ this.allowUnpublishedDraftTransition = true;
+ }
+
+ this.router.transitionTo(
+ "adminPlugins.show.discourse-workflows-templates",
+ {
+ queryParams: { workflow_id: this.args.workflow.id },
+ }
+ );
+ }
+
+ async #undoRedoAction(method) {
+ await this.undoManager[method]();
+ this.#refreshUndoState();
+ }
+
+ #isLoopSelfConnection(connection, clientId) {
+ return (
+ connection.sourceClientId === clientId &&
+ connection.targetClientId === clientId &&
+ this.#isLoopOutputConnection(connection, clientId)
+ );
+ }
+
+ #isLoopOutputConnection(connection, loopNodeClientId) {
+ return (
+ connection.sourceClientId === loopNodeClientId &&
+ (connection.sourceOutput === "loop" ||
+ normalizeSourceOutputIndex(connection) === 1)
+ );
+ }
+
+ #ensureLoopSelfConnection(connections, clientId, identifier) {
+ if (identifier !== LOOP_NODE_TYPE) {
+ return;
+ }
+
+ const hasBody = this.#hasLoopBodyConnection(connections, clientId);
+ const selfIdx = connections.findIndex((c) =>
+ this.#isLoopSelfConnection(c, clientId)
+ );
+
+ if (hasBody && selfIdx >= 0) {
+ connections.splice(selfIdx, 1);
+ } else if (!hasBody && selfIdx < 0) {
+ connections.push({
+ sourceClientId: clientId,
+ targetClientId: clientId,
+ sourceOutput: "loop",
+ });
+ }
+ }
+
+ #hasLoopBodyConnection(connections, loopNodeClientId) {
+ return connections.some(
+ (connection) =>
+ this.#isLoopOutputConnection(connection, loopNodeClientId) &&
+ connection.targetClientId !== loopNodeClientId
+ );
+ }
+
+ #addNewNode(nodeType, position, configOverrides, wireConnections) {
+ const existingNodes = this.formApi.get("nodes");
+ if (existingNodes.length >= MAX_NODES) {
+ this.toasts.error({
+ data: {
+ message: i18n("discourse_workflows.canvas.max_nodes_reached", {
+ max: MAX_NODES,
+ }),
+ },
+ });
+ return;
+ }
+ this.#captureUndo();
+ const newNode = createNode(
+ nodeType.name || nodeType.identifier,
+ existingNodes,
+ position,
+ {
+ typeVersion: nodeTypeVersion(nodeType),
+ configOverrides,
+ }
+ );
+
+ this.formApi.set("nodes", [...existingNodes, newNode]);
+
+ const connections = [...this.formApi.get("connections")];
+ const shouldAutoLayout = wireConnections(connections, newNode, nodeType);
+
+ this.#ensureLoopSelfConnection(
+ connections,
+ newNode.clientId,
+ nodeType.name || nodeType.identifier
+ );
+ this.formApi.set("connections", connections);
+
+ if (shouldAutoLayout) {
+ this.autoArrangeRequest++;
+ } else {
+ this.handleSubmit();
+ }
+ }
+
+ @action
+ addNode(sourceClientId, sourceOutput, nodeType, configOverrides = null) {
+ this.#addNewNode(
+ nodeType,
+ null,
+ configOverrides,
+ (connections, newNode) => {
+ if (sourceClientId) {
+ const existingIdx = connections.findIndex(
+ (connection) =>
+ connection.sourceClientId === sourceClientId &&
+ normalizeSourceOutputIndex(connection) ===
+ portIndexFromKey(sourceOutput)
+ );
+
+ if (existingIdx >= 0) {
+ const existing = connections[existingIdx];
+ connections.splice(existingIdx, 1);
+ connections.push({
+ sourceClientId,
+ targetClientId: newNode.clientId,
+ sourceOutput,
+ });
+ connections.push({
+ sourceClientId: newNode.clientId,
+ targetClientId: existing.targetClientId,
+ sourceOutput: nodeTypePrimaryOutputKey(nodeType),
+ });
+ } else {
+ connections.push({
+ sourceClientId,
+ targetClientId: newNode.clientId,
+ sourceOutput,
+ });
+ }
+ }
+ return true;
+ }
+ );
+ }
+
+ @action
+ addNodeAtPosition(
+ sourceClientId,
+ sourceOutput,
+ nodeType,
+ position,
+ configOverrides = null
+ ) {
+ this.#addNewNode(
+ nodeType,
+ position,
+ configOverrides,
+ (connections, newNode) => {
+ if (sourceClientId) {
+ connections.push({
+ sourceClientId,
+ targetClientId: newNode.clientId,
+ sourceOutput,
+ });
+ }
+ return false;
+ }
+ );
+ }
+
+ @action
+ insertNodeOnConnection(
+ sourceClientId,
+ sourceOutput,
+ targetClientId,
+ nodeType,
+ configOverrides = null,
+ targetInput = "main"
+ ) {
+ const existingNodes = this.formApi.get("nodes");
+ const sourceNode = existingNodes.find((n) => n.clientId === sourceClientId);
+ const targetNode = existingNodes.find((n) => n.clientId === targetClientId);
+ const position =
+ sourceNode?.position && targetNode?.position
+ ? {
+ x: (sourceNode.position.x + targetNode.position.x) / 2,
+ y: (sourceNode.position.y + targetNode.position.y) / 2,
+ }
+ : undefined;
+
+ this.#addNewNode(
+ nodeType,
+ position,
+ configOverrides,
+ (connections, newNode) => {
+ const existingIdx = connections.findIndex((connection) =>
+ connectionMatchesEndpoint(connection, {
+ sourceClientId,
+ sourceOutput,
+ targetClientId,
+ targetInput,
+ })
+ );
+ if (existingIdx >= 0) {
+ connections.splice(existingIdx, 1);
+ }
+
+ connections.push({
+ sourceClientId,
+ targetClientId: newNode.clientId,
+ sourceOutput,
+ targetInput: "main",
+ });
+ connections.push({
+ sourceClientId: newNode.clientId,
+ targetClientId,
+ sourceOutput: nodeTypePrimaryOutputKey(nodeType),
+ targetInput,
+ });
+ return true;
+ }
+ );
+ }
+
+ @action
+ addNodeBeforeTarget(
+ targetClientId,
+ nodeType,
+ configOverrides = null,
+ targetInput = "main"
+ ) {
+ const targetNode = this.formApi
+ .get("nodes")
+ .find((n) => n.clientId === targetClientId);
+ const position = targetNode?.position
+ ? { x: targetNode.position.x - 200, y: targetNode.position.y }
+ : null;
+
+ this.#addNewNode(
+ nodeType,
+ position,
+ configOverrides,
+ (connections, newNode, nt) => {
+ connections.push({
+ sourceClientId: newNode.clientId,
+ targetClientId,
+ sourceOutput: nodeTypePrimaryOutputKey(nt),
+ targetInput,
+ });
+ return !position;
+ }
+ );
+ }
+
+ @action
+ updateNodePosition(clientId, position) {
+ this.#captureUndo();
+ const nodes = this.formApi.get("nodes");
+ this.formApi.set(
+ "nodes",
+ nodes.map((n) => (n.clientId === clientId ? { ...n, position } : n))
+ );
+ }
+
+ @action
+ editNode(clientId) {
+ const nodes = this.formApi.get("nodes");
+ const connections = this.formApi.get("connections");
+ const node = nodes.find((n) => n.clientId === clientId);
+ if (!node) {
+ return;
+ }
+
+ if (isNodeUnavailable(this.workflowsNodeTypes, node)) {
+ return;
+ }
+
+ const triggerNode = nodes.find((n) => n.type?.startsWith("trigger:"));
+
+ this.workflowSession.setEditingContext(node, nodes, connections);
+
+ this.modal.show(NodeConfigurator, {
+ model: {
+ node,
+ nodes,
+ connections,
+ session: this.workflowSession,
+ triggerType: triggerNode?.type,
+ onSave: (configuration, name, options) =>
+ this.updateNodeConfiguration(clientId, configuration, name, options),
+ onRemove: () => this.removeNodes([clientId]),
+ },
+ });
+ }
+
+ @action
+ createConnection(
+ sourceClientId,
+ sourceOutput,
+ targetClientId,
+ targetInput = "main"
+ ) {
+ this.#captureUndo();
+ const nodes = this.formApi.get("nodes");
+ const connections = [...this.formApi.get("connections")];
+
+ // Don't create duplicate connections
+ const exists = connections.some((connection) =>
+ connectionMatchesEndpoint(connection, {
+ sourceClientId,
+ sourceOutput,
+ targetClientId,
+ targetInput,
+ })
+ );
+ if (exists) {
+ return;
+ }
+
+ connections.push({
+ sourceClientId,
+ targetClientId,
+ sourceOutput,
+ targetInput,
+ });
+ this.#ensureLoopSelfConnection(
+ connections,
+ sourceClientId,
+ nodes.find((node) => node.clientId === sourceClientId)?.type
+ );
+ this.#ensureLoopSelfConnection(
+ connections,
+ targetClientId,
+ nodes.find((node) => node.clientId === targetClientId)?.type
+ );
+ this.formApi.set("connections", connections);
+ this.handleSubmit();
+ }
+
+ @action
+ deleteConnection(
+ sourceClientId,
+ sourceOutput,
+ targetClientId,
+ targetInput = "main"
+ ) {
+ this.#captureUndo();
+ const nodes = this.formApi.get("nodes");
+ const connections = [...this.formApi.get("connections")];
+ const index = connections.findIndex((connection) =>
+ connectionMatchesEndpoint(connection, {
+ sourceClientId,
+ sourceOutput,
+ targetClientId,
+ targetInput,
+ })
+ );
+
+ if (index < 0) {
+ return;
+ }
+
+ const conn = connections[index];
+ if (conn.sourceClientId === conn.targetClientId) {
+ return;
+ }
+
+ connections.splice(index, 1);
+ this.#ensureLoopSelfConnection(
+ connections,
+ sourceClientId,
+ nodes.find((node) => node.clientId === sourceClientId)?.type
+ );
+ this.#ensureLoopSelfConnection(
+ connections,
+ targetClientId,
+ nodes.find((node) => node.clientId === targetClientId)?.type
+ );
+ this.formApi.set("connections", connections);
+ this.handleSubmit();
+ }
+
+ @action
+ removeNodes(clientIds) {
+ this.#captureUndo();
+ const updatedGraph = removeNodesFromGraph(
+ this.formApi.get("nodes"),
+ this.formApi.get("connections"),
+ clientIds
+ );
+
+ this.formApi.set("nodes", updatedGraph.nodes);
+ this.formApi.set("connections", updatedGraph.connections);
+ this.handleSubmit();
+ }
+
+ @action
+ removeSelected({ nodeIds, stickyNoteIds }) {
+ this.#captureUndo();
+
+ if (nodeIds.length > 0) {
+ const updatedGraph = removeNodesFromGraph(
+ this.formApi.get("nodes"),
+ this.formApi.get("connections"),
+ nodeIds
+ );
+ this.formApi.set("nodes", updatedGraph.nodes);
+ this.formApi.set("connections", updatedGraph.connections);
+ }
+
+ if (stickyNoteIds.length > 0) {
+ const stickyNoteIdSet = new Set(stickyNoteIds);
+ const stickyNotes = this.formApi.get("stickyNotes");
+ this.formApi.set(
+ "stickyNotes",
+ stickyNotes.filter((n) => !stickyNoteIdSet.has(n.clientId))
+ );
+ }
+
+ this.handleSubmit();
+ }
+
+ @action
+ addNodeToLoop(loopNodeClientId, nodeType, configOverrides = null) {
+ const existingNodes = this.formApi.get("nodes");
+ if (existingNodes.length >= MAX_NODES) {
+ this.toasts.error({
+ data: {
+ message: i18n("discourse_workflows.canvas.max_nodes_reached", {
+ max: MAX_NODES,
+ }),
+ },
+ });
+ return;
+ }
+ this.#captureUndo();
+ const loopNode = existingNodes.find((n) => n.clientId === loopNodeClientId);
+ const position = loopNode?.position
+ ? { x: loopNode.position.x, y: loopNode.position.y + 120 }
+ : null;
+
+ const newNode = createNode(
+ nodeType.name || nodeType.identifier,
+ existingNodes,
+ position,
+ {
+ typeVersion: nodeTypeVersion(nodeType),
+ configOverrides,
+ }
+ );
+ const newNodeOutput = nodeTypePrimaryOutputKey(nodeType);
+
+ const connections = [...this.formApi.get("connections")];
+
+ if (!this.#hasLoopBodyConnection(connections, loopNodeClientId)) {
+ connections.push({
+ sourceClientId: loopNodeClientId,
+ targetClientId: newNode.clientId,
+ sourceOutput: "loop",
+ });
+ connections.push({
+ sourceClientId: newNode.clientId,
+ targetClientId: loopNodeClientId,
+ sourceOutput: newNodeOutput,
+ });
+ } else {
+ const loopBodyNodes = new Set();
+ let currentConn = connections.find(
+ (c) =>
+ this.#isLoopOutputConnection(c, loopNodeClientId) &&
+ c.targetClientId !== loopNodeClientId
+ );
+ while (
+ currentConn &&
+ currentConn.targetClientId !== loopNodeClientId &&
+ !loopBodyNodes.has(currentConn.targetClientId)
+ ) {
+ const nextSourceId = currentConn.targetClientId;
+ loopBodyNodes.add(nextSourceId);
+ currentConn = connections.find(
+ (c) => c.sourceClientId === nextSourceId
+ );
+ }
+
+ const loopBackIdx = connections.findIndex(
+ (c) =>
+ c.targetClientId === loopNodeClientId &&
+ loopBodyNodes.has(c.sourceClientId)
+ );
+
+ if (loopBackIdx >= 0) {
+ const loopBack = connections[loopBackIdx];
+ const prevSourceId = loopBack.sourceClientId;
+ const prevSourceOutput = loopBack.sourceOutput;
+ connections.splice(loopBackIdx, 1);
+ connections.push({
+ sourceClientId: prevSourceId,
+ targetClientId: newNode.clientId,
+ sourceOutput: prevSourceOutput,
+ });
+ connections.push({
+ sourceClientId: newNode.clientId,
+ targetClientId: loopNodeClientId,
+ sourceOutput: newNodeOutput,
+ });
+ }
+ }
+
+ this.#ensureLoopSelfConnection(
+ connections,
+ loopNodeClientId,
+ loopNode?.type
+ );
+
+ this.formApi.set("nodes", [...existingNodes, newNode]);
+ this.formApi.set("connections", connections);
+ this.handleSubmit();
+ }
+
+ @action
+ updateNodeConfiguration(clientId, configuration, name, options = {}) {
+ this.#captureUndo();
+ const nodes = this.formApi.get("nodes");
+ const updatedNodes = nodes.map((n) =>
+ n.clientId === clientId
+ ? normalizeNodeConfiguration({
+ ...n,
+ configuration,
+ name: name || n.name,
+ })
+ : n
+ );
+ this.formApi.set("nodes", updatedNodes);
+ this.formApi.set(
+ "connections",
+ normalizeConnectionsForNodes(
+ this.formApi.get("connections"),
+ updatedNodes
+ )
+ );
+ return this.handleSubmit(options);
+ }
+
+ @action
+ replaceTrigger(clientId, nodeType) {
+ this.#captureUndo();
+ const existingNodes = this.formApi.get("nodes");
+ const replacement = createNode(
+ nodeType.name || nodeType.identifier,
+ existingNodes,
+ null,
+ {
+ typeVersion: nodeTypeVersion(nodeType),
+ }
+ );
+
+ const nodes = existingNodes.map((n) =>
+ n.clientId === clientId
+ ? {
+ ...n,
+ type: replacement.type,
+ typeVersion: replacement.typeVersion,
+ name: replacement.name,
+ configuration: replacement.configuration,
+ }
+ : n
+ );
+
+ this.formApi.set("nodes", nodes);
+ this.handleSubmit();
+ }
+
+ @action
+ importNodes(newNodes, newConnections, newStickyNotes, staticData) {
+ const existingNodes = this.formApi.get("nodes");
+ if (existingNodes.length + newNodes.length > MAX_NODES) {
+ this.toasts.error({
+ data: {
+ message: i18n("discourse_workflows.canvas.max_nodes_reached", {
+ max: MAX_NODES,
+ }),
+ },
+ });
+ return;
+ }
+ this.#captureUndo();
+ const existingConnections = this.formApi.get("connections");
+
+ this.formApi.set("nodes", [...existingNodes, ...newNodes]);
+ this.formApi.set("connections", [
+ ...existingConnections,
+ ...newConnections,
+ ]);
+
+ if (newStickyNotes?.length) {
+ const existingStickyNotes = this.formApi.get("stickyNotes");
+ this.formApi.set("stickyNotes", [
+ ...existingStickyNotes,
+ ...newStickyNotes,
+ ]);
+ }
+
+ const saveOptions = {};
+ if (staticData !== undefined) {
+ saveOptions.staticData = mergeImportedStaticData(
+ this.pendingSaveOptions?.staticData || this.args.workflow.staticData,
+ staticData
+ );
+ }
+
+ this.handleSubmit(saveOptions);
+ }
+
+ @action
+ autoLayout(positions) {
+ this.#captureUndo();
+ this.#applyNodePositions(positions);
+ this.handleSubmit();
+ }
+
+ @action
+ hydrateAutoLayout(positions) {
+ this.#applyNodePositions(positions);
+ this.handleSubmit();
+ }
+
+ #applyNodePositions(positions) {
+ const nodes = this.formApi.get("nodes");
+ const updatedNodes = nodes.map((node) => {
+ const pos = positions.get(node.clientId);
+ return pos ? { ...node, position: pos } : node;
+ });
+ this.formApi.set("nodes", updatedNodes);
+ }
+
+ // Sticky notes
+
+ @action
+ addStickyNote(position) {
+ this.#captureUndo();
+ const stickyNotes = [...this.formApi.get("stickyNotes")];
+ stickyNotes.push(
+ StickyNote.create({
+ position: {
+ x: position.canvasX ?? position.x ?? 0,
+ y: position.canvasY ?? position.y ?? 0,
+ },
+ })
+ );
+ this.formApi.set("stickyNotes", stickyNotes);
+ this.handleSubmit();
+ }
+
+ #updateStickyNote(clientId, updates) {
+ const stickyNotes = this.formApi.get("stickyNotes");
+ this.formApi.set(
+ "stickyNotes",
+ stickyNotes.map((n) =>
+ n.clientId === clientId ? { ...n, ...updates } : n
+ )
+ );
+ }
+
+ @action
+ stickyNoteMove(clientId, newPosition) {
+ this.#updateStickyNote(clientId, { position: newPosition });
+ }
+
+ @action
+ stickyNoteResize(clientId, newSize) {
+ this.#updateStickyNote(clientId, { size: newSize });
+ }
+
+ @action
+ stickyNoteUpdateText(clientId, text) {
+ this.#updateStickyNote(clientId, { text });
+ }
+
+ @action
+ stickyNoteBeforeMutation() {
+ this.#captureUndo();
+ }
+
+ @action
+ stickyNoteChangeColor(clientId, color) {
+ this.#captureUndo();
+ this.#updateStickyNote(clientId, { color });
+ }
+
+ @action
+ pasteEntities({ nodes, stickyNotes }) {
+ this.#captureUndo();
+
+ if (nodes.length > 0) {
+ const existingNodes = this.formApi.get("nodes");
+ const newNodes = nodes.map((copiedNode) =>
+ WorkflowNode.create({
+ type: copiedNode.type,
+ typeVersion: copiedNode.typeVersion,
+ name: generateNodeName(copiedNode.type, existingNodes),
+ configuration: structuredClone(copiedNode.configuration || {}),
+ position: copiedNode.position
+ ? { x: copiedNode.position.x, y: copiedNode.position.y }
+ : null,
+ })
+ );
+ this.formApi.set("nodes", [...existingNodes, ...newNodes]);
+ }
+
+ if (stickyNotes.length > 0) {
+ const newNotes = stickyNotes.map((copiedNote) =>
+ StickyNote.create({
+ position: {
+ x: copiedNote.position?.x ?? 0,
+ y: copiedNote.position?.y ?? 0,
+ },
+ size: copiedNote.size,
+ color: copiedNote.color,
+ text: copiedNote.text,
+ })
+ );
+ const existingNotes = this.formApi.get("stickyNotes");
+ this.formApi.set("stickyNotes", [...existingNotes, ...newNotes]);
+ }
+
+ this.handleSubmit();
+ }
+
+ @action
+ async openNodePanel(context) {
+ if (!this.nodePanelNodeTypes) {
+ this.nodePanelNodeTypes = await this.workflowsNodeTypes.load();
+ }
+ this.nodePanelSearchTerm = "";
+ this.nodePanelContext = context || {};
+ }
+
+ @action
+ closeNodePanel() {
+ this.nodePanelContext = null;
+ this.nodePanelSearchTerm = "";
+ }
+
+ @action
+ searchNodePanel(term) {
+ this.nodePanelSearchTerm = term;
+ }
+
+ get filteredNodePanelTypes() {
+ if (!this.nodePanelNodeTypes) {
+ return [];
+ }
+ const term = this.nodePanelSearchTerm?.toLowerCase().trim();
+ const nodeTypes = shouldHideTriggerNodeTypes(
+ this.nodePanelContext,
+ this.formApi?.get("nodes")
+ )
+ ? this.nodePanelNodeTypes.filter(
+ (nodeType) => !isTriggerType(nodeTypeIdentifier(nodeType))
+ )
+ : this.nodePanelNodeTypes;
+
+ if (!term) {
+ return nodeTypes;
+ }
+ return nodeTypes.filter((nt) => {
+ const label = nodeTypeLabel(nt)?.toLowerCase() || "";
+ return label.includes(term);
+ });
+ }
+
+ @action
+ selectNodeFromPanel(nodeType, operationValue = null) {
+ const ctx = this.nodePanelContext;
+ if (!ctx) {
+ return;
+ }
+
+ const configOverrides = operationValue
+ ? { operation: operationValue }
+ : null;
+
+ if (ctx.loopNodeClientId) {
+ this.addNodeToLoop(ctx.loopNodeClientId, nodeType, configOverrides);
+ } else if (ctx.sourceClientId) {
+ const sourceNode = this.formApi
+ .get("nodes")
+ .find((n) => n.clientId === ctx.sourceClientId);
+ const position = sourceNode?.position
+ ? { x: sourceNode.position.x + 200, y: sourceNode.position.y }
+ : null;
+ if (position) {
+ this.addNodeAtPosition(
+ ctx.sourceClientId,
+ ctx.sourceOutput,
+ nodeType,
+ position,
+ configOverrides
+ );
+ } else {
+ this.addNode(
+ ctx.sourceClientId,
+ ctx.sourceOutput,
+ nodeType,
+ configOverrides
+ );
+ }
+ } else if (ctx.targetClientId) {
+ this.addNodeBeforeTarget(
+ ctx.targetClientId,
+ nodeType,
+ configOverrides,
+ ctx.targetInput
+ );
+ } else if (ctx.connectionSource) {
+ this.insertNodeOnConnection(
+ ctx.connectionSource,
+ ctx.connectionSourceOutput,
+ ctx.connectionTarget,
+ nodeType,
+ configOverrides,
+ ctx.connectionTargetInput
+ );
+ } else if (ctx.canvasX != null) {
+ this.addNodeAtPosition(
+ null,
+ "main",
+ nodeType,
+ {
+ x: ctx.canvasX,
+ y: ctx.canvasY,
+ },
+ configOverrides
+ );
+ } else {
+ this.addNode(null, "main", nodeType, configOverrides);
+ }
+
+ this.closeNodePanel();
+ }
+
+ @action
+ async handleSubmit(options = {}) {
+ if (this.saving) {
+ if (options.throwOnError) {
+ await this.currentSavePromise;
+ return this.handleSubmit(options);
+ } else {
+ this.pendingSave = true;
+ this.pendingGraphSnapshot = this.#captureGraphSnapshot();
+ this.pendingSaveOptions = this.#mergePendingSaveOptions(
+ this.pendingSaveOptions,
+ options
+ );
+ }
+ return;
+ }
+
+ const savePromise = this.#saveWorkflow(options);
+ this.currentSavePromise = savePromise;
+ try {
+ await savePromise;
+ } finally {
+ if (this.currentSavePromise === savePromise) {
+ this.currentSavePromise = null;
+ }
+ }
+ }
+
+ @action
+ handleWorkflowDiscarded(workflow) {
+ this.pendingSave = false;
+ this.pendingGraphSnapshot = null;
+ this.pendingSaveOptions = null;
+
+ this.args.workflow.setProperties({
+ name: workflow.name,
+ nodes: workflow.nodes || [],
+ connections: workflow.connections || {},
+ versionId: workflow.version_id,
+ activeVersionId: workflow.active_version_id,
+ versionCounter: workflow.version_counter,
+ hasUnpublishedChanges: workflow.has_unpublished_changes,
+ settings: workflow.settings || {},
+ timezone: workflow.timezone,
+ staticData: workflow.static_data || {},
+ pinData: workflow.pin_data || {},
+ });
+
+ this.formApi.set("name", workflow.name);
+ this.#syncFromServer();
+ this.closeNodePanel();
+ this.undoManager.clear();
+ this.#refreshUndoState();
+ }
+
+ async discardWorkflowDraft() {
+ try {
+ const response = await ajax(
+ `/admin/plugins/discourse-workflows/workflows/${this.args.workflow.id}/discard-draft.json`,
+ {
+ type: "POST",
+ }
+ );
+
+ this.handleWorkflowDiscarded(response.workflow);
+ } catch (e) {
+ popupAjaxError(e);
+ throw e;
+ }
+ }
+
+ async #saveWorkflow(options = {}) {
+ this.saving = true;
+ try {
+ const name = this.formApi.get("name");
+ const nodes = this.formApi.get("nodes");
+ const connections = normalizeConnectionsForNodes(
+ this.formApi.get("connections"),
+ nodes
+ );
+ const stickyNotes = this.formApi.get("stickyNotes");
+ this.formApi.set("connections", connections);
+
+ this.args.workflow.setProperties({
+ name,
+ nodes,
+ connections,
+ stickyNotes: stickyNotes || [],
+ });
+
+ const saveProperties = this.args.workflow.updateProperties();
+ if (options.staticData !== undefined) {
+ saveProperties.static_data = options.staticData;
+ }
+
+ await this.args.workflow.save(saveProperties);
+ this.#syncFromServer();
+
+ if (!this.isUndoRedo) {
+ this.undoManager.commitAction(this.#captureGraphSnapshot());
+ }
+ this.isUndoRedo = false;
+ this.#refreshUndoState();
+
+ if (this.args.isNew) {
+ this.allowUnpublishedDraftTransition = true;
+ this.router.transitionTo(
+ "adminPlugins.show.discourse-workflows.show",
+ this.args.workflow.id
+ );
+ }
+ } catch (e) {
+ popupAjaxError(e);
+ if (options.throwOnError) {
+ throw e;
+ }
+ } finally {
+ this.saving = false;
+ if (this.pendingSave) {
+ const pendingSnapshot = this.pendingGraphSnapshot;
+ const pendingOptions = this.pendingSaveOptions || {};
+ if (
+ options.staticData !== undefined &&
+ pendingOptions.staticData !== undefined
+ ) {
+ pendingOptions.staticData = mergeImportedStaticData(
+ options.staticData,
+ pendingOptions.staticData
+ );
+ }
+ this.pendingSave = false;
+ this.pendingGraphSnapshot = null;
+ this.pendingSaveOptions = null;
+ if (pendingSnapshot) {
+ this.#applyGraphSnapshot(pendingSnapshot);
+ }
+ this.handleSubmit(pendingOptions);
+ }
+ }
+ }
+
+ #mergePendingSaveOptions(existingOptions, nextOptions) {
+ if (nextOptions.staticData === undefined) {
+ return existingOptions || {};
+ }
+
+ return {
+ ...(existingOptions || {}),
+ staticData:
+ existingOptions?.staticData === undefined
+ ? nextOptions.staticData
+ : mergeImportedStaticData(
+ existingOptions.staticData,
+ nextOptions.staticData
+ ),
+ };
+ }
+
+ <template>
+ <Form
+ @data={{this.formData}}
+ @onSubmit={{this.handleSubmit}}
+ @onRegisterApi={{this.registerApi}}
+ @onDirtyCheck={{this.ignoreDirty}}
+ class="workflows-editor"
+ as |form transientData|
+ >
+ <div class="workflows-editor__body">
+ <WorkflowCanvas
+ @nodes={{transientData.nodes}}
+ @connections={{transientData.connections}}
+ @stickyNotes={{transientData.stickyNotes}}
+ @workflowId={{@workflow.id}}
+ @workflowName={{@workflow.name}}
+ @autoArrangeRequest={{this.autoArrangeRequest}}
+ @onUpdateNodePosition={{this.updateNodePosition}}
+ @onEditNode={{this.editNode}}
+ @onRemoveNodes={{this.removeNodes}}
+ @onCreateConnection={{this.createConnection}}
+ @onAddNodeAtPosition={{this.addNodeAtPosition}}
+ @onAddNodeToLoop={{this.addNodeToLoop}}
+ @onInsertNodeOnConnection={{this.insertNodeOnConnection}}
+ @onConnectionDelete={{this.deleteConnection}}
+ @onNodeDragEnd={{this.handleSubmit}}
+ @onAreaReady={{this.initializeUndo}}
+ @onUndo={{this.undo}}
+ @onRedo={{this.redo}}
+ @canUndo={{this.canUndo}}
+ @canRedo={{this.canRedo}}
+ @onAutoLayout={{this.autoLayout}}
+ @onHydrateAutoLayout={{this.hydrateAutoLayout}}
+ @onSyncAutoLayout={{this.hydrateAutoLayout}}
+ @onOpenNodePanel={{this.openNodePanel}}
+ @onCloseNodePanel={{this.closeNodePanel}}
+ @onBrowseTemplates={{this.browseTemplates}}
+ @onDiscardWorkflow={{this.handleWorkflowDiscarded}}
+ @onImportNodes={{this.importNodes}}
+ @onAddStickyNote={{this.addStickyNote}}
+ @onStickyNoteBeforeMutation={{this.stickyNoteBeforeMutation}}
+ @onStickyNoteMove={{this.stickyNoteMove}}
+ @onStickyNoteResize={{this.stickyNoteResize}}
+ @onStickyNoteUpdateText={{this.stickyNoteUpdateText}}
+ @onStickyNoteChangeColor={{this.stickyNoteChangeColor}}
+ @onRemoveSelected={{this.removeSelected}}
+ @onPasteEntities={{this.pasteEntities}}
+ @workflow={{@workflow}}
+ @session={{this.workflowSession}}
+ @workflowPublished={{@workflow.activeVersionId}}
+ @hasUnpublishedChanges={{@workflow.hasUnpublishedChanges}}
+ />
+
+ {{#if this.nodePanelContext}}
+ <NodePanel
+ @nodeTypes={{this.filteredNodePanelTypes}}
+ @searchTerm={{this.nodePanelSearchTerm}}
+ @onSearch={{this.searchNodePanel}}
+ @onSelectNodeType={{this.selectNodeFromPanel}}
+ @onClose={{this.closeNodePanel}}
+ />
+ {{/if}}
+ </div>
+ </Form>
+ </template>
+}
diff --git a/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/editor/node-factory.js b/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/editor/node-factory.js
new file mode 100644
index 00000000000..8aacd9e8432
--- /dev/null
+++ b/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/editor/node-factory.js
@@ -0,0 +1,52 @@
+import { applyValueTransformer } from "discourse/lib/transformer";
+import { i18n } from "discourse-i18n";
+import WorkflowNode from "../../../models/workflow-node";
+
+const NODE_DEFAULTS = {
+ "trigger:webhook": () => ({
+ path: crypto.randomUUID(),
+ http_method: "GET",
+ }),
+ "trigger:schedule": () => ({
+ rule: {
+ interval: [{ field: "hours", hoursInterval: 1, triggerAtMinute: 0 }],
+ },
+ }),
+};
+
+export function generateNodeName(identifier, existingNodes) {
+ const baseName = i18n(`discourse_workflows.nodes.${identifier}`);
+
+ const existingNames = new Set(existingNodes.map((n) => n.name));
+ let name = baseName;
+ let counter = 1;
+ while (existingNames.has(name)) {
+ name = `${baseName} ${counter}`;
+ counter++;
+ }
+ return name;
+}
+
+export function createNode(
+ identifier,
+ existingNodes,
+ position = null,
+ { typeVersion = null, configOverrides = null } = {}
+) {
+ const allDefaults = applyValueTransformer(
+ "workflow-node-defaults",
+ NODE_DEFAULTS
+ );
+ const defaultsFn = allDefaults[identifier];
+
+ return WorkflowNode.create({
+ type: identifier,
+ typeVersion: typeVersion || "1.0",
+ name: generateNodeName(identifier, existingNodes),
+ configuration: {
+ ...(defaultsFn ? defaultsFn() : {}),
+ ...(configOverrides || {}),
+ },
+ position,
+ });
+}
diff --git a/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/editor/undo-manager.js b/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/editor/undo-manager.js
new file mode 100644
index 00000000000..cff97b8791d
--- /dev/null
+++ b/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/editor/undo-manager.js
@@ -0,0 +1,89 @@
+import loadRete from "discourse/lib/load-rete";
+
+const MAX_HISTORY_SIZE = 25;
+
+class SnapshotAction {
+ constructor(before, after, applyFn) {
+ this.before = before;
+ this.after = after;
+ this.applyFn = applyFn;
+ }
+
+ undo() {
+ this.applyFn(this.before);
+ }
+
+ redo() {
+ this.applyFn(this.after);
+ }
+}
+
+export default class UndoManager {
+ #history = null;
+ #pendingBefore = null;
+ #applyFn = null;
+
+ get canUndo() {
+ return this.#history?.getHistorySnapshot().length > 0;
+ }
+
+ get canRedo() {
+ return this.#history?.history.reserved.length > 0;
+ }
+
+ get hasPendingCapture() {
+ return this.#pendingBefore !== null;
+ }
+
+ async initialize(area, applyFn) {
+ const { HistoryPlugin } = await loadRete();
+ this.#history = new HistoryPlugin({ timing: 200 });
+ this.#applyFn = applyFn;
+ area.use(this.#history);
+ }
+
+ captureBeforeState(snapshot) {
+ this.#pendingBefore = structuredClone(snapshot);
+ }
+
+ commitAction(afterSnapshot) {
+ if (!this.#history || !this.#pendingBefore) {
+ return;
+ }
+
+ const before = this.#pendingBefore;
+ const after = structuredClone(afterSnapshot);
+ this.#pendingBefore = null;
+
+ this.#history.add(new SnapshotAction(before, after, this.#applyFn));
+
+ const produced = this.#history.getHistorySnapshot();
+ if (produced.length > MAX_HISTORY_SIZE) {
+ produced.splice(0, produced.length - MAX_HISTORY_SIZE);
+ }
+ }
+
+ async undo() {
+ if (!this.#history) {
+ return;
+ }
+ await this.#history.undo();
+ }
+
+ async redo() {
+ if (!this.#history) {
+ return;
+ }
+ await this.#history.redo();
+ }
+
+ clear() {
+ this.#history?.clear();
+ }
+
+ destroy() {
+ this.#history = null;
+ this.#applyFn = null;
+ this.#pendingBefore = null;
+ }
+}
diff --git a/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/empty-state.gjs b/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/empty-state.gjs
new file mode 100644
index 00000000000..ca781203428
--- /dev/null
+++ b/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/empty-state.gjs
@@ -0,0 +1,21 @@
+import DButton from "discourse/ui-kit/d-button";
+import dEmoji from "discourse/ui-kit/helpers/d-emoji";
+
+<template>
+ <div class="workflows-empty-state">
+ {{#if @emoji}}
+ <span class="workflows-empty-state__icon">{{dEmoji @emoji}}</span>
+ {{/if}}
+ <h2 class="workflows-empty-state__title">{{@title}}</h2>
+ <p class="workflows-empty-state__description">{{@description}}</p>
+ {{#if @onAction}}
+ <DButton
+ @action={{@onAction}}
+ @label={{@buttonLabel}}
+ @translatedLabel={{@translatedButtonLabel}}
+ @icon={{@buttonIcon}}
+ class="btn-primary"
+ />
+ {{/if}}
+ </div>
+</template>
diff --git a/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/error-workflow-chooser.js b/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/error-workflow-chooser.js
new file mode 100644
index 00000000000..a5ce0e8e3c4
--- /dev/null
+++ b/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/error-workflow-chooser.js
@@ -0,0 +1,41 @@
+import { classNames } from "@ember-decorators/component";
+import { ajax } from "discourse/lib/ajax";
+import ComboBoxComponent from "discourse/select-kit/components/combo-box";
+import {
+ pluginApiIdentifiers,
+ selectKitOptions,
+} from "discourse/select-kit/components/select-kit";
+
+@classNames("error-workflow-chooser")
+@pluginApiIdentifiers("error-workflow-chooser")
+@selectKitOptions({
+ filterable: true,
+ allowAny: false,
+})
+export default class ErrorWorkflowChooser extends ComboBoxComponent {
+ nameProperty = "name";
+ valueProperty = "id";
+
+ select(value, item) {
+ this.set("content", [item]);
+ return super.select(value, item);
+ }
+
+ async search(filter) {
+ const result = await ajax(
+ "/admin/plugins/discourse-workflows/workflows.json",
+ {
+ data: {
+ filter,
+ trigger_type: "error",
+ exclude_id: this.selectKit.options.excludeWorkflowId,
+ },
+ }
+ );
+
+ return (result.workflows || []).map((wf) => ({
+ id: wf.id,
+ name: wf.name,
+ }));
+ }
+}
diff --git a/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/execution/manager.gjs b/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/execution/manager.gjs
new file mode 100644
index 00000000000..bb91ed3815b
--- /dev/null
+++ b/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/execution/manager.gjs
@@ -0,0 +1,274 @@
+import Component from "@glimmer/component";
+import { tracked } from "@glimmer/tracking";
+import { concat, fn } from "@ember/helper";
+import { action } from "@ember/object";
+import { service } from "@ember/service";
+import { ajax } from "discourse/lib/ajax";
+import { popupAjaxError } from "discourse/lib/ajax-error";
+import DButton from "discourse/ui-kit/d-button";
+import dIcon from "discourse/ui-kit/helpers/d-icon";
+import { i18n } from "discourse-i18n";
+import AdminTable from "../admin-table";
+import EmptyState from "../empty-state";
+
+const STATUS_ICONS = {
+ success: "circle-check",
+ error: "circle-xmark",
+ running: "spinner",
+ waiting: "clock",
+};
+
+function statusIcon(status) {
+ return STATUS_ICONS[status] || "circle";
+}
+
+function formatTime(timestamp) {
+ if (!timestamp) {
+ return "—";
+ }
+ return new Date(timestamp).toLocaleString();
+}
+
+function runTime(execution) {
+ const ms = execution.run_time_ms;
+ if (ms == null) {
+ return "—";
+ }
+ return ms < 1000 ? `${ms}ms` : `${(ms / 1000).toFixed(1)}s`;
+}
+
+export default class ExecutionsManager extends Component {
+ @service currentUser;
+ @service dialog;
+ @service router;
+
+ @tracked executions = null;
+ @tracked loadMoreUrl = null;
+ @tracked loadingMore = false;
+ @tracked bulkMode = false;
+
+ constructor() {
+ super(...arguments);
+ this.loadExecutions();
+ }
+
+ async loadExecutions() {
+ try {
+ const url = this.args.workflowId
+ ? `/admin/plugins/discourse-workflows/workflows/${this.args.workflowId}/executions.json`
+ : "/admin/plugins/discourse-workflows/executions.json";
+ const result = await ajax(url);
+ this.executions = result.executions;
+ this.loadMoreUrl = result.meta?.load_more_executions;
+ } catch (e) {
+ popupAjaxError(e);
+ }
+ }
+
+ get canLoadMore() {
+ return !!this.loadMoreUrl;
+ }
+
+ @action
+ async loadMore() {
+ if (!this.loadMoreUrl || !this.canLoadMore || this.loadingMore) {
+ return;
+ }
+
+ this.loadingMore = true;
+ try {
+ const result = await ajax(this.loadMoreUrl);
+ this.executions = [...this.executions, ...result.executions];
+ this.loadMoreUrl = result.meta?.load_more_executions;
+ } catch (e) {
+ popupAjaxError(e);
+ } finally {
+ this.loadingMore = false;
+ }
+ }
+
+ get isLoading() {
+ return this.executions === null;
+ }
+
+ @action
+ enableBulkMode() {
+ this.bulkMode = true;
+ }
+
+ @action
+ cancelBulkMode(clearSelection) {
+ clearSelection();
+ this.bulkMode = false;
+ }
+
+ @action
+ showExecution(execution) {
+ this.router.transitionTo(
+ "adminPlugins.show.discourse-workflows.show.executions.show",
+ execution.workflow_id,
+ execution.id
+ );
+ }
+
+ @action
+ async deleteSelected(selectedIds, clearSelection) {
+ const count = selectedIds.size;
+ this.dialog.yesNoConfirm({
+ message: i18n("discourse_workflows.executions.delete_confirm", { count }),
+ didConfirm: async () => {
+ try {
+ await ajax("/admin/plugins/discourse-workflows/executions.json", {
+ type: "DELETE",
+ data: { ids: [...selectedIds] },
+ });
+ clearSelection();
+ this.bulkMode = false;
+ await this.loadExecutions();
+ } catch (e) {
+ popupAjaxError(e);
+ }
+ },
+ });
+ }
+
+ <template>
+ <AdminTable
+ @items={{this.executions}}
+ @isLoading={{this.isLoading}}
+ @canLoadMore={{this.canLoadMore}}
+ @loadMore={{this.loadMore}}
+ @loadingMore={{this.loadingMore}}
+ @selectable={{this.bulkMode}}
+ >
+ <:empty>
+ <EmptyState
+ @emoji="wave"
+ @title={{i18n
+ "discourse_workflows.executions.empty_title"
+ username=this.currentUser.displayName
+ }}
+ @description={{i18n
+ "discourse_workflows.executions.empty_description"
+ }}
+ />
+ </:empty>
+ <:toolbar as |toolbar|>
+ {{#if this.bulkMode}}
+ {{#if toolbar.hasSelection}}
+ <DButton
+ @action={{fn
+ this.deleteSelected
+ toolbar.selectedIds
+ toolbar.clearSelection
+ }}
+ @label="discourse_workflows.executions.delete_selected"
+ @icon="trash-can"
+ class="btn-danger btn-small"
+ />
+ {{/if}}
+ <DButton
+ @action={{fn this.cancelBulkMode toolbar.clearSelection}}
+ @label="discourse_workflows.executions.cancel_select"
+ class="btn-default btn-small"
+ />
+ {{else}}
+ <DButton
+ @action={{this.enableBulkMode}}
+ @label="discourse_workflows.executions.select"
+ @icon="list-check"
+ class="btn-default btn-small"
+ />
+ {{/if}}
+ </:toolbar>
+ <:head>
+ {{#if @workflowId}}
+ <th class="d-table__header-cell">{{i18n
+ "discourse_workflows.executions.started_at"
+ }}</th>
+ <th class="d-table__header-cell">{{i18n
+ "discourse_workflows.executions.status"
+ }}</th>
+ {{else}}
+ <th class="d-table__header-cell">{{i18n
+ "discourse_workflows.executions.workflow"
+ }}</th>
+ <th class="d-table__header-cell">{{i18n
+ "discourse_workflows.executions.status"
+ }}</th>
+ <th class="d-table__header-cell">{{i18n
+ "discourse_workflows.executions.started_at"
+ }}</th>
+ {{/if}}
+ <th class="d-table__header-cell">{{i18n
+ "discourse_workflows.executions.run_time"
+ }}</th>
+ <th class="d-table__header-cell"></th>
+ </:head>
+ <:row as |execution|>
+ {{#if @workflowId}}
+ <td class="d-table__cell --overview">
+ {{formatTime execution.started_at}}
+ </td>
+ <td class="d-table__cell --detail">
+ <div class="d-table__mobile-label">
+ {{i18n "discourse_workflows.executions.status"}}
+ </div>
+ <span
+ class="workflows-executions-manager__status --{{execution.status}}"
+ >
+ {{dIcon (statusIcon execution.status)}}
+ {{i18n
+ (concat
+ "discourse_workflows.executions.statuses." execution.status
+ )
+ }}
+ </span>
+ </td>
+ {{else}}
+ <td class="d-table__cell --overview">
+ <strong
+ class="d-table__overview-name"
+ >{{execution.workflow_name}}</strong>
+ </td>
+ <td class="d-table__cell --detail">
+ <div class="d-table__mobile-label">
+ {{i18n "discourse_workflows.executions.status"}}
+ </div>
+ <span
+ class="workflows-executions-manager__status --{{execution.status}}"
+ >
+ {{dIcon (statusIcon execution.status)}}
+ {{i18n
+ (concat
+ "discourse_workflows.executions.statuses." execution.status
+ )
+ }}
+ </span>
+ </td>
+ <td class="d-table__cell --detail">
+ <div class="d-table__mobile-label">
+ {{i18n "discourse_workflows.executions.started_at"}}
+ </div>
+ {{formatTime execution.started_at}}
+ </td>
+ {{/if}}
+ <td class="d-table__cell --detail">
+ <div class="d-table__mobile-label">
+ {{i18n "discourse_workflows.executions.run_time"}}
+ </div>
+ {{runTime execution}}
+ </td>
+ <td class="d-table__cell --controls">
+ <div class="d-table__cell-actions">
+ <DButton
+ @action={{fn this.showExecution execution}}
+ @label="discourse_workflows.executions.show"
+ class="btn-default btn-small"
+ />
+ </div>
+ </td>
+ </:row>
+ </AdminTable>
+ </template>
+}
diff --git a/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/executions/detail.gjs b/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/executions/detail.gjs
new file mode 100644
index 00000000000..eaae08bd5d2
--- /dev/null
+++ b/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/executions/detail.gjs
@@ -0,0 +1,463 @@
+import Component from "@glimmer/component";
+import { concat } from "@ember/helper";
+import { action } from "@ember/object";
+import didInsert from "@ember/render-modifiers/modifiers/did-insert";
+import { service } from "@ember/service";
+import DButton from "discourse/ui-kit/d-button";
+import dConcatClass from "discourse/ui-kit/helpers/d-concat-class";
+import dIcon from "discourse/ui-kit/helpers/d-icon";
+import { i18n } from "discourse-i18n";
+import {
+ localeKeyPart,
+ propertyOptionLabel,
+} from "../../../lib/workflows/property-engine";
+
+function formatJson(data) {
+ if (!data || Object.keys(data).length === 0) {
+ return "{}";
+ }
+ return JSON.stringify(data, null, 2);
+}
+
+function isTruncationMarker(value) {
+ return value?.__truncated === true && value.__reason;
+}
+
+function truncationLabel(kind) {
+ return i18n(`discourse_workflows.executions.truncated.${kind}`);
+}
+
+function truncationDetails(marker) {
+ const details = [];
+
+ if (marker.__original_bytes) {
+ details.push(
+ i18n("discourse_workflows.executions.truncated.original_bytes", {
+ count: marker.__original_bytes,
+ })
+ );
+ }
+
+ if (marker.__original_size) {
+ details.push(
+ i18n("discourse_workflows.executions.truncated.original_size", {
+ count: marker.__original_size,
+ })
+ );
+ }
+
+ if (marker.__max_bytes) {
+ details.push(
+ i18n("discourse_workflows.executions.truncated.max_bytes", {
+ count: marker.__max_bytes,
+ })
+ );
+ }
+
+ return details.length ? ` (${details.join(", ")})` : "";
+}
+
+function formatTruncationMarker(marker, kind = "value") {
+ return `${truncationLabel(kind)}${truncationDetails(marker)}`;
+}
+
+function replaceTruncationMarkers(value) {
+ if (isTruncationMarker(value)) {
+ return formatTruncationMarker(value);
+ }
+
+ if (Array.isArray(value)) {
+ return value.map(replaceTruncationMarkers);
+ }
+
+ if (value && typeof value === "object") {
+ return Object.fromEntries(
+ Object.entries(value).map(([key, nestedValue]) => [
+ key,
+ replaceTruncationMarkers(nestedValue),
+ ])
+ );
+ }
+
+ return value;
+}
+
+function formatStepData(data, kind = "value") {
+ if (isTruncationMarker(data)) {
+ return formatTruncationMarker(data, kind);
+ }
+
+ data = replaceTruncationMarkers(data);
+
+ if (!Array.isArray(data) || !data.every((i) => i?.json)) {
+ return formatJson(data);
+ }
+ return formatJson(data.length === 1 ? data[0].json : data.map((i) => i.json));
+}
+
+function formatInputData(data) {
+ return formatStepData(data, "input");
+}
+
+function formatOutputData(data) {
+ return formatStepData(data, "output");
+}
+
+function itemCount(data) {
+ return Array.isArray(data) && data.length > 1 && data.every((i) => i?.json)
+ ? data.length
+ : null;
+}
+
+function formatDuration(startedAt, finishedAt) {
+ if (!startedAt || !finishedAt) {
+ return "—";
+ }
+ const ms = new Date(finishedAt) - new Date(startedAt);
+ return ms < 1000 ? `${ms}ms` : `${(ms / 1000).toFixed(1)}s`;
+}
+
+function formatValue(value) {
+ if (Array.isArray(value)) {
+ return JSON.stringify(value);
+ }
+ if (value === null || value === undefined) {
+ return "null";
+ }
+ return String(value);
+}
+
+function conditionOperatorLabel(operator) {
+ return i18n(`discourse_workflows.if.operators.${localeKeyPart(operator)}`);
+}
+
+function formatLogs(logs) {
+ return logs
+ .map((entry) => {
+ if (typeof entry === "string") {
+ return entry;
+ }
+ const prefix =
+ entry.level === "error"
+ ? "[error] "
+ : entry.level === "warn"
+ ? "[warn] "
+ : "";
+ if (entry.key !== undefined) {
+ return `${prefix}${entry.key}: ${entry.value}`;
+ }
+ return `${prefix}${entry.message}`;
+ })
+ .join("\n");
+}
+
+function nodeKind(nodeType) {
+ return nodeType?.split(":")[0] || "action";
+}
+
+const KIND_ICONS = {
+ trigger: "bolt",
+ condition: "arrows-split-up-and-left",
+ action: "gear",
+ flow: "arrows-split-up-and-left",
+};
+
+function kindIcon(nodeType) {
+ return KIND_ICONS[nodeKind(nodeType)] || "gear";
+}
+
+function stepSummary(step) {
+ if (!step.error) {
+ return null;
+ }
+ return String(step.error);
+}
+
+function isFilterStep(step) {
+ return step.node_type === "condition:filter";
+}
+
+function isConditionStep(step) {
+ return step.node_type?.startsWith("condition:");
+}
+
+function conditionPassed(step) {
+ return step.status === "success";
+}
+
+export default class ExecutionDetail extends Component {
+ @service workflowsNodeTypes;
+
+ operationLabel = (step) => {
+ const value = step?.metadata?.operation;
+ if (!value) {
+ return null;
+ }
+
+ // Read tracked state so the template re-renders once node types load.
+ if (!this.workflowsNodeTypes.nodeTypes) {
+ return String(value);
+ }
+
+ const definition = this.workflowsNodeTypes.findNodeType(step.node_type);
+ if (!definition) {
+ return String(value);
+ }
+
+ return propertyOptionLabel(definition, "operation", { value });
+ };
+
+ @action
+ async ensureNodeTypes() {
+ await this.workflowsNodeTypes.load();
+ }
+
+ @action
+ exportAsText() {
+ const execution = this.args.execution;
+ const lines = [];
+
+ lines.push(`Workflow: ${execution.workflow_name ?? "Unknown"}`);
+ lines.push(`Execution ID: ${execution.id}`);
+ lines.push(`Status: ${execution.status}`);
+ lines.push(`Started: ${execution.started_at ?? "—"}`);
+ lines.push(`Finished: ${execution.finished_at ?? "—"}`);
+ lines.push(
+ `Total time: ${formatDuration(execution.started_at, execution.finished_at)}`
+ );
+
+ if (execution.error) {
+ lines.push(`\nError: ${execution.error}`);
+ }
+
+ lines.push("\n" + "=".repeat(60));
+
+ execution.steps?.forEach((step, index) => {
+ lines.push(`\nStep ${index + 1}: ${step.node_name}`);
+ lines.push(` Type: ${step.node_type}`);
+ const operationLabel = this.operationLabel(step);
+ if (operationLabel) {
+ lines.push(` Operation: ${operationLabel}`);
+ }
+ lines.push(` Status: ${step.status}`);
+ lines.push(
+ ` Duration: ${formatDuration(step.started_at, step.finished_at)}${step.metadata?.js_elapsed_ms ? ` (javascript: ${step.metadata.js_elapsed_ms}ms)` : ""}`
+ );
+
+ if (step.metadata?.conditions) {
+ lines.push(" Conditions:");
+ step.metadata.conditions.forEach((c) => {
+ const result = c.passed ? "PASS" : "FAIL";
+ const expr = c.leftExpression ? `${c.leftExpression} ` : "";
+ lines.push(
+ ` [${result}] ${expr}${formatValue(c.left)} ${c.operator} ${c.right != null ? formatValue(c.right) : ""}`
+ );
+ });
+ }
+
+ if (step.metadata?.logs?.length) {
+ lines.push(" Console:");
+ lines.push(
+ ...formatLogs(step.metadata.logs)
+ .split("\n")
+ .map((l) => ` ${l}`)
+ );
+ }
+
+ if (step.input && Object.keys(step.input).length > 0) {
+ lines.push(
+ ` Input: ${formatInputData(step.input).replace(/\n/g, "\n ")}`
+ );
+ }
+
+ if (step.output && Object.keys(step.output).length > 0) {
+ lines.push(
+ ` Output: ${formatOutputData(step.output).replace(/\n/g, "\n ")}`
+ );
+ }
+
+ if (step.error) {
+ const label = step.status === "skipped" ? "Reason" : "Error";
+ lines.push(` ${label}: ${step.error}`);
+ }
+
+ lines.push("-".repeat(60));
+ });
+
+ const text = lines.join("\n");
+ const blob = new Blob([text], { type: "text/plain" });
+ const url = URL.createObjectURL(blob);
+ const a = document.createElement("a");
+ a.href = url;
+ a.download = `discourse-workflows-execution-${execution.id}.txt`;
+ a.click();
+ URL.revokeObjectURL(url);
+ }
+
+ <template>
+ <div class="workflows-execution-detail" {{didInsert this.ensureNodeTypes}}>
+ <div class="workflows-execution-detail__steps">
+ {{#each @execution.steps as |step|}}
+ <div
+ class="workflows-execution-detail__step --{{step.status}}
+ --kind-{{nodeKind step.node_type}}"
+ >
+ <div class="workflows-execution-detail__step-header">
+ <span class="workflows-execution-detail__step-icon">
+ {{dIcon (kindIcon step.node_type)}}
+ </span>
+ <span class="workflows-execution-detail__step-name">
+ {{step.node_name}}
+ </span>
+ {{#let (this.operationLabel step) as |operationLabel|}}
+ {{#if operationLabel}}
+ <span
+ class="workflows-execution-detail__step-operation"
+ >{{operationLabel}}</span>
+ {{/if}}
+ {{/let}}
+ <span
+ class="workflows-execution-detail__kind-badge --{{nodeKind
+ step.node_type
+ }}"
+ >
+ {{i18n
+ (concat
+ "discourse_workflows.executions.kinds."
+ (nodeKind step.node_type)
+ )
+ }}
+ </span>
+ <span
+ class="workflows-execution-detail__step-badge --{{step.status}}"
+ >
+ {{#if (isFilterStep step)}}
+ {{if
+ (conditionPassed step)
+ (i18n "discourse_workflows.executions.statuses.kept")
+ (i18n "discourse_workflows.executions.statuses.rejected")
+ }}
+ {{else if (isConditionStep step)}}
+ {{if
+ (conditionPassed step)
+ (i18n "discourse_workflows.branch.true")
+ (i18n "discourse_workflows.branch.false")
+ }}
+ {{else}}
+ {{i18n
+ (concat
+ "discourse_workflows.executions.statuses." step.status
+ )
+ }}
+ {{/if}}
+ </span>
+ <span class="workflows-execution-detail__step-time">
+ {{formatDuration step.started_at step.finished_at}}
+ {{#if step.metadata.js_elapsed_ms}}
+ <span
+ class="workflows-execution-detail__step-js-time"
+ >(javascript: {{step.metadata.js_elapsed_ms}}ms)</span>
+ {{/if}}
+ </span>
+ </div>
+
+ {{#if (stepSummary step)}}
+ <div class="workflows-execution-detail__step-summary">
+ {{stepSummary step}}
+ </div>
+ {{/if}}
+
+ <div class="workflows-execution-detail__step-body">
+ {{#if step.metadata.conditions}}
+ <div class="workflows-execution-detail__conditions">
+ {{#each step.metadata.conditions as |condition|}}
+ <div
+ class={{dConcatClass
+ "workflows-execution-detail__condition"
+ (if condition.passed "--passed" "--failed")
+ }}
+ >
+ <span
+ class="workflows-execution-detail__condition-result"
+ >{{if condition.passed "✓" "✗"}}</span>
+ <span class="workflows-execution-detail__condition-value">
+ {{#if condition.leftExpression}}
+ <code
+ class="workflows-execution-detail__condition-field"
+ >{{condition.leftExpression}}</code>
+ <span
+ class="workflows-execution-detail__condition-operator"
+ >{{i18n
+ "discourse_workflows.executions.with_value"
+ }}</span>
+ {{/if}}
+ <code>{{formatValue condition.left}}</code>
+ </span>
+ <span
+ class="workflows-execution-detail__condition-operator"
+ >{{conditionOperatorLabel condition.operator}}</span>
+ {{#if condition.right}}
+ <span
+ class="workflows-execution-detail__condition-value"
+ >
+ <code>{{formatValue condition.right}}</code>
+ </span>
+ {{/if}}
+ </div>
+ {{/each}}
+ </div>
+ {{/if}}
+
+ {{#if step.metadata.logs}}
+ <details class="workflows-execution-detail__step-section" open>
+ <summary>{{i18n
+ "discourse_workflows.executions.logs"
+ }}</summary>
+ <pre>{{formatLogs step.metadata.logs}}</pre>
+ </details>
+ {{/if}}
+
+ <details class="workflows-execution-detail__step-section">
+ <summary>
+ {{i18n "discourse_workflows.executions.input"}}
+ {{#if (itemCount step.input)}}
+ <span
+ class="workflows-execution-detail__item-count"
+ >{{itemCount step.input}}
+ {{i18n "discourse_workflows.executions.items"}}</span>
+ {{/if}}
+ </summary>
+ <pre>{{formatInputData step.input}}</pre>
+ </details>
+ <details class="workflows-execution-detail__step-section">
+ <summary>
+ {{i18n "discourse_workflows.executions.output"}}
+ {{#if (itemCount step.output)}}
+ <span
+ class="workflows-execution-detail__item-count"
+ >{{itemCount step.output}}
+ {{i18n "discourse_workflows.executions.items"}}</span>
+ {{/if}}
+ </summary>
+ <pre>{{formatOutputData step.output}}</pre>
+ </details>
+ </div>
+ </div>
+ {{/each}}
+
+ <div class="workflows-execution-detail__footer">
+ <div class="workflows-execution-detail__total">
+ {{i18n "discourse_workflows.executions.total_time"}}
+ {{formatDuration @execution.started_at @execution.finished_at}}
+ </div>
+ <DButton
+ @action={{this.exportAsText}}
+ @icon="download"
+ @label="discourse_workflows.executions.export"
+ class="btn-default btn-small"
+ />
+ </div>
+ </div>
+ </div>
+ </template>
+}
diff --git a/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/in-use-dialog.gjs b/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/in-use-dialog.gjs
new file mode 100644
index 00000000000..b4c50a297f1
--- /dev/null
+++ b/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/in-use-dialog.gjs
@@ -0,0 +1,18 @@
+import { on } from "@ember/modifier";
+import { LinkTo } from "@ember/routing";
+
+<template>
+ <p>{{@model.description}}</p>
+
+ <ul>
+ {{#each @model.workflows as |workflow|}}
+ <li>
+ <LinkTo
+ @route="adminPlugins.show.discourse-workflows.show"
+ @model={{workflow.id}}
+ {{on "click" @model.close}}
+ >{{workflow.name}}</LinkTo>
+ </li>
+ {{/each}}
+ </ul>
+</template>
diff --git a/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/index.gjs b/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/index.gjs
new file mode 100644
index 00000000000..857b5922b50
--- /dev/null
+++ b/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/index.gjs
@@ -0,0 +1,196 @@
+import Component from "@glimmer/component";
+import { tracked } from "@glimmer/tracking";
+import { action } from "@ember/object";
+import { LinkTo } from "@ember/routing";
+import { service } from "@ember/service";
+import { ajax } from "discourse/lib/ajax";
+import { popupAjaxError } from "discourse/lib/ajax-error";
+import { eq } from "discourse/truth-helpers";
+import DButton from "discourse/ui-kit/d-button";
+import dAvatar from "discourse/ui-kit/helpers/d-avatar";
+import dConcatClass from "discourse/ui-kit/helpers/d-concat-class";
+import dFormatDate from "discourse/ui-kit/helpers/d-format-date";
+import dIcon from "discourse/ui-kit/helpers/d-icon";
+import { i18n } from "discourse-i18n";
+import AdminTable from "./admin-table";
+import EmptyState from "./empty-state";
+import Stats from "./stats";
+
+export default class WorkflowsIndex extends Component {
+ @service currentUser;
+ @service router;
+
+ @tracked loading = false;
+
+ @action
+ async loadMore() {
+ if (!this.args.workflows.canLoadMore || this.loading) {
+ return;
+ }
+
+ this.loading = true;
+ try {
+ await this.args.workflows.loadMore();
+ } finally {
+ this.loading = false;
+ }
+ }
+
+ @action
+ async createWorkflow() {
+ try {
+ const result = await ajax(
+ "/admin/plugins/discourse-workflows/workflows.json",
+ {
+ type: "POST",
+ data: {
+ workflow: {
+ name: i18n("discourse_workflows.default_workflow_name"),
+ },
+ },
+ }
+ );
+ this.router.transitionTo(
+ "adminPlugins.show.discourse-workflows.show",
+ result.workflow.id
+ );
+ } catch (e) {
+ popupAjaxError(e);
+ }
+ }
+
+ @action
+ workflowStatusLabel(workflow) {
+ if (workflow.activeVersionId && workflow.hasUnpublishedChanges) {
+ return "discourse_workflows.unpublished_changes";
+ }
+
+ return workflow.activeVersionId
+ ? "discourse_workflows.published"
+ : "discourse_workflows.unpublished";
+ }
+
+ @action
+ workflowStatusClass(workflow) {
+ if (workflow.activeVersionId && workflow.hasUnpublishedChanges) {
+ return "is-unpublished-changes";
+ }
+
+ return workflow.activeVersionId ? "is-published" : "is-unpublished";
+ }
+
+ <template>
+ <Stats @stats={{@stats}} />
+
+ <AdminTable
+ @items={{@workflows.content}}
+ @isLoading={{false}}
+ @canLoadMore={{@workflows.canLoadMore}}
+ @loadMore={{this.loadMore}}
+ @loadingMore={{this.loading}}
+ @rowClass="workflows-index__row"
+ >
+ <:empty>
+ <EmptyState
+ @emoji="wave"
+ @title={{i18n
+ "discourse_workflows.empty_title"
+ username=this.currentUser.displayName
+ }}
+ @description={{i18n "discourse_workflows.empty_description"}}
+ @buttonLabel="discourse_workflows.create_first_workflow"
+ @onAction={{this.createWorkflow}}
+ />
+ </:empty>
+ <:toolbar>
+ <DButton
+ @action={{this.createWorkflow}}
+ @label="discourse_workflows.new_workflow"
+ @icon="plus"
+ class="btn-primary btn-small"
+ />
+ </:toolbar>
+ <:head>
+ <th class="d-table__header-cell">{{i18n
+ "discourse_workflows.workflow_name"
+ }}</th>
+ <th class="d-table__header-cell">{{i18n
+ "discourse_workflows.last_editor"
+ }}</th>
+ <th class="d-table__header-cell">{{i18n
+ "discourse_workflows.last_update"
+ }}</th>
+ <th class="d-table__header-cell">{{i18n
+ "discourse_workflows.last_run"
+ }}</th>
+ <th class="d-table__header-cell">{{i18n
+ "discourse_workflows.status"
+ }}</th>
+ </:head>
+ <:row as |workflow|>
+ <td class="d-table__cell --overview workflows-index__name">
+ <LinkTo
+ @route="adminPlugins.show.discourse-workflows.show"
+ @model={{workflow.id}}
+ class="d-table__overview-link"
+ >
+ <strong class="d-table__overview-name">{{workflow.name}}</strong>
+ {{#if (eq workflow.lastExecutionStatus "error")}}
+ <span
+ class="workflows-index__warning"
+ role="img"
+ aria-label={{i18n "discourse_workflows.last_execution_failed"}}
+ title={{i18n "discourse_workflows.last_execution_failed"}}
+ >
+ {{dIcon "triangle-exclamation"}}
+ </span>
+ {{/if}}
+ </LinkTo>
+ </td>
+ <td class="d-table__cell --detail workflows-index__last-editor">
+ <div class="d-table__mobile-label">
+ {{i18n "discourse_workflows.last_editor"}}
+ </div>
+ {{#if workflow.updatedBy}}
+ <a
+ href={{workflow.updatedBy.path}}
+ class="workflows-index__last-editor-link"
+ >
+ {{dAvatar workflow.updatedBy imageSize="tiny"}}
+ <span>{{workflow.updatedBy.username}}</span>
+ </a>
+ {{/if}}
+ </td>
+ <td class="d-table__cell --detail workflows-index__last-update">
+ <div class="d-table__mobile-label">
+ {{i18n "discourse_workflows.last_update"}}
+ </div>
+ {{dFormatDate workflow.updatedAt format="medium"}}
+ </td>
+ <td class="d-table__cell --detail workflows-index__last-run">
+ <div class="d-table__mobile-label">
+ {{i18n "discourse_workflows.last_run"}}
+ </div>
+ {{#if workflow.lastExecutionAt}}
+ {{dFormatDate workflow.lastExecutionAt format="medium"}}
+ {{else}}
+ {{i18n "discourse_workflows.last_execution_never"}}
+ {{/if}}
+ </td>
+ <td class="d-table__cell --detail">
+ <div class="d-table__mobile-label">
+ {{i18n "discourse_workflows.status"}}
+ </div>
+ <span
+ class={{dConcatClass
+ "workflows-index__badge"
+ (this.workflowStatusClass workflow)
+ }}
+ >
+ {{i18n (this.workflowStatusLabel workflow)}}
+ </span>
+ </td>
+ </:row>
+ </AdminTable>
+ </template>
+}
diff --git a/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/node/configurator.gjs b/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/node/configurator.gjs
new file mode 100644
index 00000000000..25c1691c6fa
--- /dev/null
+++ b/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/node/configurator.gjs
@@ -0,0 +1,715 @@
+import Component from "@glimmer/component";
+import { tracked } from "@glimmer/tracking";
+import { fn } from "@ember/helper";
+import { on } from "@ember/modifier";
+import { action } from "@ember/object";
+import { cancel, later } from "@ember/runloop";
+import { service } from "@ember/service";
+import { modifier } from "ember-modifier";
+import Form from "discourse/components/form";
+import { eq, not, or } from "discourse/truth-helpers";
+import DButton from "discourse/ui-kit/d-button";
+import DConditionalLoadingSpinner from "discourse/ui-kit/d-conditional-loading-spinner";
+import DModal from "discourse/ui-kit/d-modal";
+import dConcatClass from "discourse/ui-kit/helpers/d-concat-class";
+import dIcon from "discourse/ui-kit/helpers/d-icon";
+import { i18n } from "discourse-i18n";
+import { NODE_DIRECT_SETTING_KEYS } from "../../../lib/workflows/node-data-shape";
+import {
+ nodeTypeDescription,
+ nodeTypeIcon,
+ nodeTypeLabel,
+ nodeTypeProducesData,
+ nodeTypeStyle,
+ resolveNodeTypeVersion,
+} from "../../../lib/workflows/node-types";
+import {
+ credentialSlotAnchorField,
+ credentialSlotVisible,
+ credentialTypesForSlot,
+ fieldType,
+ findNodeType,
+ getPropertySchema,
+} from "../../../lib/workflows/property-engine";
+import CredentialControl from "../configurators/credential";
+import PropertyEngineConfigurator from "../configurators/property-engine";
+import InputContext from "../context/input";
+import OutputContext from "../context/output";
+
+function credentialSlotLabel(slot) {
+ return i18n(slot.label_key || "discourse_workflows.credentials.type");
+}
+
+function normalizeCredentials(credentials = {}) {
+ return Object.fromEntries(
+ Object.entries(credentials || {}).filter(([, value]) => value?.id)
+ );
+}
+
+function syncNameInputWidth(input) {
+ input.style.setProperty(
+ "--node-name-length",
+ Math.max(input.value.length, 1) + 1
+ );
+}
+
+const AUTOSAVE_DELAY_MS = 750;
+const SAVED_FADE_DELAY_MS = 2500;
+const SAVED_REMOVE_DELAY_MS = 3000;
+
+export default class NodeConfigurator extends Component {
+ @service workflowsNodeTypes;
+
+ @tracked nodeName = this.args.model.node.name || "";
+ @tracked isEditingName = false;
+ @tracked nodeTypes = null;
+ @tracked activeTab = "parameters";
+ @tracked saveStatus = null;
+ @tracked isSaveStatusFading = false;
+ @tracked
+ settingsFormData = {
+ notes: this.args.model.node.configuration?.notes || "",
+ notesInFlow: this.args.model.node.configuration?.notesInFlow === true,
+ alwaysOutputData:
+ this.args.model.node.configuration?.alwaysOutputData === true,
+ };
+
+ @tracked credentialConfig = structuredClone(
+ normalizeCredentials(
+ this.args.model.node.configuration?.credentials ||
+ this.args.model.node.credentials
+ )
+ );
+ initialConfiguration = structuredClone(
+ this.args.model.node.configuration || {}
+ );
+ initialNodeName = this.args.model.node.name || "";
+ nodeNameBeforeEditing = "";
+ autosaveTimer = null;
+ savedFadeTimer = null;
+ savedRemoveTimer = null;
+
+ parametersApi = null;
+ settingsApi = null;
+
+ focusNameInput = modifier((element) => {
+ syncNameInputWidth(element);
+ element.focus();
+ element.select();
+ const handler = () => syncNameInputWidth(element);
+ element.addEventListener("input", handler);
+ return () => element.removeEventListener("input", handler);
+ });
+
+ focusModal = modifier((element) => {
+ requestAnimationFrame(() => {
+ element.closest(".d-modal")?.querySelector(".btn")?.focus();
+ });
+ });
+
+ constructor() {
+ super(...arguments);
+ this.#loadTypes();
+ }
+
+ willDestroy() {
+ super.willDestroy(...arguments);
+ this.#cancelTimers();
+ }
+
+ get isLoading() {
+ return this.nodeTypes === null;
+ }
+
+ get resolvedNodeType() {
+ return resolveNodeTypeVersion(
+ findNodeType(this.nodeTypes, this.args.model.node.type),
+ this.args.model.node.typeVersion
+ );
+ }
+
+ async #loadTypes() {
+ this.nodeTypes = await this.workflowsNodeTypes.load();
+ this.#applyDefaults();
+ this.#setSavedBaseline(this.configuration, this.initialNodeName);
+ }
+
+ #applyDefaults() {
+ const config = this.initialConfiguration;
+
+ for (const [key, fs] of Object.entries(this.propertySchema)) {
+ if (config[key] != null) {
+ continue;
+ }
+ if (fs.default !== undefined) {
+ config[key] = fs.default;
+ } else if (
+ fieldType(fs) === "collection" ||
+ fieldType(fs) === "fixed_collection"
+ ) {
+ config[key] = {};
+ } else if (fieldType(fs) === "assignment_collection") {
+ config[key] = { assignments: [] };
+ } else if (fieldType(fs) === "array") {
+ config[key] = [];
+ }
+ }
+ }
+
+ get nodeTypeDefaultName() {
+ return nodeTypeLabel(this.resolvedNodeType);
+ }
+
+ get nodeDescription() {
+ return nodeTypeDescription(this.resolvedNodeType);
+ }
+
+ get propertySchema() {
+ return getPropertySchema(
+ this.nodeTypes,
+ this.args.model.node.type,
+ this.args.model.node.typeVersion
+ );
+ }
+
+ get showsOutputContext() {
+ return nodeTypeProducesData(this.resolvedNodeType);
+ }
+
+ get hasConfiguration() {
+ return (
+ Object.keys(this.propertySchema).length > 0 ||
+ this.credentialSlots.length > 0
+ );
+ }
+
+ get credentialSlots() {
+ return this.resolvedNodeType?.credentials || [];
+ }
+
+ get unanchoredCredentialSlots() {
+ return this.credentialSlots.filter(
+ (slot) => !credentialSlotAnchorField(slot)
+ );
+ }
+
+ get isUnavailable() {
+ const nodeType = this.resolvedNodeType;
+ return nodeType?.available === false;
+ }
+
+ get unavailableReasonKey() {
+ return this.resolvedNodeType?.unavailable_reason_key;
+ }
+
+ get trimmedNodeName() {
+ return this.nodeName.trim();
+ }
+
+ get canSaveNodeName() {
+ return this.trimmedNodeName.length > 0;
+ }
+
+ @action
+ switchTab(tab) {
+ if (tab === "settings") {
+ this.settingsFormData = {
+ notes: this.configuration.notes || "",
+ notesInFlow: this.configuration.notesInFlow === true,
+ alwaysOutputData: this.configuration.alwaysOutputData === true,
+ };
+ }
+ this.activeTab = tab;
+ }
+
+ @action
+ registerParametersApi(api) {
+ this.parametersApi = api;
+ }
+
+ @action
+ registerSettingsApi(api) {
+ this.settingsApi = api;
+ }
+
+ @action
+ async handleNotesSet(value, { set, name }) {
+ const notes = value || "";
+ await set(name, notes);
+ await set("notesInFlow", notes.trim().length > 0);
+ }
+
+ @action
+ async handleAlwaysOutputDataSet(value, { set, name }) {
+ await set(name, value);
+ }
+
+ @action
+ handleCredentialSet(slotName, value) {
+ const credentials = { ...this.credentialConfig };
+ if (value?.id) {
+ credentials[slotName] = value;
+ } else {
+ delete credentials[slotName];
+ }
+ this.credentialConfig = credentials;
+ this.scheduleSave();
+ }
+
+ @action
+ credentialValue(slotName) {
+ return this.credentialConfig[slotName];
+ }
+
+ @action
+ startEditingName() {
+ this.nodeNameBeforeEditing = this.nodeName;
+ this.isEditingName = true;
+ }
+
+ @action
+ updateNodeName(event) {
+ this.nodeName = event.target.value;
+ }
+
+ @action
+ async saveNodeName() {
+ if (!this.canSaveNodeName) {
+ return;
+ }
+
+ this.nodeName = this.trimmedNodeName;
+ this.isEditingName = false;
+ await this.saveCurrentConfiguration();
+ }
+
+ @action
+ cancelEditingName() {
+ this.nodeName = this.nodeNameBeforeEditing;
+ this.isEditingName = false;
+ }
+
+ @action
+ handleNameKeydown(event) {
+ if (event.key === "Enter") {
+ event.preventDefault();
+ this.saveNodeName();
+ } else if (event.key === "Escape") {
+ this.cancelEditingName();
+ }
+ }
+
+ get configuration() {
+ if (!this.parametersApi) {
+ return this.configurationWithDirectSettings(this.initialConfiguration);
+ }
+
+ const config = {};
+ for (const key of [
+ ...Object.keys(this.propertySchema),
+ ...NODE_DIRECT_SETTING_KEYS,
+ ]) {
+ let value = this.parametersApi.get(key);
+ if (
+ value === undefined &&
+ Object.hasOwn(this.initialConfiguration, key)
+ ) {
+ value = this.initialConfiguration[key];
+ }
+ if (value !== undefined) {
+ config[key] = value;
+ }
+ }
+
+ return this.configurationWithDirectSettings(config);
+ }
+
+ get settingsConfiguration() {
+ if (!this.settingsApi) {
+ return this.settingsFormData;
+ }
+
+ return {
+ notes: this.settingsApi.get("notes") || "",
+ notesInFlow: this.settingsApi.get("notesInFlow") === true,
+ alwaysOutputData: this.settingsApi.get("alwaysOutputData") === true,
+ };
+ }
+
+ configurationWithDirectSettings(config) {
+ return {
+ ...config,
+ notes: this.settingsConfiguration.notes,
+ notesInFlow: this.settingsConfiguration.notesInFlow,
+ alwaysOutputData: this.settingsConfiguration.alwaysOutputData,
+ credentials: this.credentialConfig,
+ };
+ }
+
+ get isDirty() {
+ const nameDirty = this.nodeName !== this.initialNodeName;
+ const configurationDirty =
+ JSON.stringify(this.configuration) !==
+ JSON.stringify(this.initialConfiguration);
+ return nameDirty || configurationDirty;
+ }
+
+ get showSaveStatus() {
+ return this.saveStatus === "saving" || this.saveStatus === "saved";
+ }
+
+ #cancelTimers() {
+ cancel(this.autosaveTimer);
+ cancel(this.savedFadeTimer);
+ cancel(this.savedRemoveTimer);
+ }
+
+ #cancelSavedTimers() {
+ cancel(this.savedFadeTimer);
+ cancel(this.savedRemoveTimer);
+ }
+
+ #setSavingStatus() {
+ this.#cancelSavedTimers();
+ this.isSaveStatusFading = false;
+ this.saveStatus = "saving";
+ }
+
+ #setSavedStatus() {
+ this.saveStatus = "saved";
+ this.isSaveStatusFading = false;
+
+ this.savedFadeTimer = later(() => {
+ this.isSaveStatusFading = true;
+ }, SAVED_FADE_DELAY_MS);
+
+ this.savedRemoveTimer = later(() => {
+ this.saveStatus = null;
+ this.isSaveStatusFading = false;
+ }, SAVED_REMOVE_DELAY_MS);
+ }
+
+ #setSavedBaseline(configuration, nodeName) {
+ this.initialConfiguration = structuredClone(configuration);
+ this.initialConfiguration.credentials = structuredClone(
+ configuration.credentials
+ );
+ this.initialNodeName = nodeName;
+ }
+
+ async #saveConfiguration(options = {}) {
+ if (!this.isDirty) {
+ return;
+ }
+
+ const configuration = structuredClone(this.configuration);
+ const nodeName = this.trimmedNodeName || this.initialNodeName;
+
+ this.#setSavingStatus();
+ await this.args.model.onSave(configuration, nodeName, options);
+ this.#setSavedBaseline(configuration, nodeName);
+
+ if (!this.isDirty) {
+ this.#setSavedStatus();
+ }
+ }
+
+ @action
+ scheduleSave() {
+ cancel(this.autosaveTimer);
+ this.autosaveTimer = later(() => {
+ this.#saveConfiguration({ throwOnError: true }).catch(() => {
+ this.saveStatus = null;
+ this.isSaveStatusFading = false;
+ });
+ }, AUTOSAVE_DELAY_MS);
+ }
+
+ @action
+ async saveCurrentConfiguration() {
+ cancel(this.autosaveTimer);
+ await this.#saveConfiguration({ throwOnError: true });
+ }
+
+ @action
+ handleClose() {
+ if (this.isDirty) {
+ cancel(this.autosaveTimer);
+ this.args.model.onSave(
+ this.configuration,
+ this.trimmedNodeName || this.initialNodeName
+ );
+ }
+ this.args.closeModal();
+ this.args.model.session.clearEditingContext();
+ }
+
+ <template>
+ <DModal
+ @closeModal={{this.handleClose}}
+ @submitOnEnter={{false}}
+ @hideHeader={{true}}
+ class="workflows-configurator-modal"
+ >
+ <:body>
+ <div class="workflows-configurator-modal__header" {{this.focusModal}}>
+ {{#if (nodeTypeIcon this.resolvedNodeType)}}
+ <span
+ class="workflows-configurator-modal__node-icon"
+ style={{nodeTypeStyle this.resolvedNodeType}}
+ >
+ {{dIcon (nodeTypeIcon this.resolvedNodeType)}}
+ </span>
+ {{/if}}
+ {{#if this.isEditingName}}
+ <input
+ type="text"
+ value={{this.nodeName}}
+ class="workflows-configurator-modal__name-input"
+ {{this.focusNameInput}}
+ {{on "input" this.updateNodeName}}
+ {{on "keydown" this.handleNameKeydown}}
+ />
+ <div class="workflows-configurator-modal__name-actions">
+ <DButton
+ @action={{this.saveNodeName}}
+ @icon="check"
+ @title="discourse_workflows.save"
+ @disabled={{not this.canSaveNodeName}}
+ class="btn-flat workflows-configurator-modal__save-name"
+ />
+ <DButton
+ @action={{this.cancelEditingName}}
+ @icon="xmark"
+ @title="discourse_workflows.cancel"
+ class="btn-flat workflows-configurator-modal__cancel-name"
+ />
+ </div>
+ {{else}}
+ {{! eslint-disable ember/template-no-invalid-interactive }}
+ <div
+ class="workflows-configurator-modal__name"
+ {{on "click" this.startEditingName}}
+ >{{this.nodeName}}</div>
+ <DButton
+ @action={{this.startEditingName}}
+ @icon="pencil"
+ @title="discourse_workflows.edit"
+ class="btn-flat workflows-configurator-modal__edit-name"
+ />
+ {{/if}}
+ {{#if this.showSaveStatus}}
+ <span
+ class={{dConcatClass
+ "workflows-configurator-modal__save-status"
+ (if
+ (eq this.saveStatus "saved")
+ "workflows-configurator-modal__save-status--saved"
+ )
+ (if
+ this.isSaveStatusFading
+ "workflows-configurator-modal__save-status--fading"
+ )
+ }}
+ >
+ {{#if (eq this.saveStatus "saving")}}
+ <span
+ class="spinner workflows-configurator-modal__save-spinner"
+ ></span>
+ {{i18n "discourse_workflows.configurator.saving"}}
+ {{else}}
+ {{dIcon "check"}}
+ {{i18n "discourse_workflows.configurator.saved"}}
+ {{/if}}
+ </span>
+ {{/if}}
+ <DButton
+ @action={{this.handleClose}}
+ @icon="xmark"
+ class="btn-flat workflows-configurator-modal__close"
+ />
+ </div>
+ <DConditionalLoadingSpinner @condition={{this.isLoading}}>
+ {{#if this.isUnavailable}}
+ <div class="workflows-configurator-modal__unavailable-banner">
+ {{dIcon "triangle-exclamation"}}
+ <span>{{i18n
+ (or
+ this.unavailableReasonKey
+ "discourse_workflows.node_unavailable.default"
+ )
+ }}</span>
+ </div>
+ {{/if}}
+ <div
+ class={{dConcatClass
+ "workflows-configurator-modal__columns"
+ (if this.isUnavailable "is-unavailable")
+ }}
+ >
+ <div class="workflows-configurator-modal__column --left">
+ <InputContext
+ @node={{@model.node}}
+ @nodes={{@model.nodes}}
+ @connections={{@model.connections}}
+ @triggerType={{@model.triggerType}}
+ @nodeTypes={{this.nodeTypes}}
+ @session={{@model.session}}
+ @hasConfiguration={{this.hasConfiguration}}
+ />
+ </div>
+
+ <div class="workflows-configurator-modal__column --center">
+ <div class="workflows-configurator__tabs">
+ <button
+ type="button"
+ class={{dConcatClass
+ "workflows-configurator__tab"
+ (if (eq this.activeTab "parameters") "is-active")
+ }}
+ {{on "click" (fn this.switchTab "parameters")}}
+ >{{i18n
+ "discourse_workflows.configurator.tabs.parameters"
+ }}</button>
+ <button
+ type="button"
+ class={{dConcatClass
+ "workflows-configurator__tab"
+ (if (eq this.activeTab "settings") "is-active")
+ }}
+ {{on "click" (fn this.switchTab "settings")}}
+ >{{i18n
+ "discourse_workflows.configurator.tabs.settings"
+ }}</button>
+ </div>
+
+ {{#if this.hasConfiguration}}
+ <Form
+ @data={{this.initialConfiguration}}
+ @onRegisterApi={{this.registerParametersApi}}
+ @onSet={{this.scheduleSave}}
+ @validateOn="change"
+ class="workflows-configurator-form
+ {{unless (eq this.activeTab 'parameters') 'is-hidden'}}"
+ as |form transientData|
+ >
+ <PropertyEngineConfigurator
+ @form={{form}}
+ @formApi={{this.parametersApi}}
+ @configuration={{transientData}}
+ @nodeType={{@model.node.type}}
+ @schema={{this.propertySchema}}
+ @credentials={{this.credentialConfig}}
+ @credentialSlots={{this.credentialSlots}}
+ @credentialValue={{this.credentialValue}}
+ @onCredentialSet={{this.handleCredentialSet}}
+ @triggerType={{@model.triggerType}}
+ @node={{@model.node}}
+ @nodeParameters={{transientData}}
+ @nodes={{@model.nodes}}
+ @connections={{@model.connections}}
+ @nodeTypes={{this.nodeTypes}}
+ @session={{@model.session}}
+ @onChange={{this.scheduleSave}}
+ @onBeforeStartTestSession={{this.saveCurrentConfiguration}}
+ />
+ {{#each this.unanchoredCredentialSlots as |slot|}}
+ {{#if (credentialSlotVisible slot transientData)}}
+ <CredentialControl
+ @credentialTypes={{credentialTypesForSlot slot}}
+ @label={{credentialSlotLabel slot}}
+ @onChange={{fn this.handleCredentialSet slot.name}}
+ @value={{this.credentialValue slot.name}}
+ />
+ {{/if}}
+ {{/each}}
+ </Form>
+ {{else if (eq this.activeTab "parameters")}}
+ <p>{{i18n
+ "discourse_workflows.configurator.no_configuration"
+ }}</p>
+ {{/if}}
+
+ {{#if (eq this.activeTab "settings")}}
+ <Form
+ @data={{this.settingsFormData}}
+ @onRegisterApi={{this.registerSettingsApi}}
+ @onSet={{this.scheduleSave}}
+ class="workflows-configurator-form"
+ as |form|
+ >
+ <form.Field
+ @name="notes"
+ @title={{i18n
+ "discourse_workflows.configurator.description"
+ }}
+ @type="textarea"
+ @format="full"
+ @onSet={{this.handleNotesSet}}
+ as |field|
+ >
+ <field.Control
+ placeholder={{i18n
+ "discourse_workflows.configurator.description_placeholder"
+ }}
+ />
+ </form.Field>
+ <form.Field
+ @name="alwaysOutputData"
+ @title={{i18n
+ "discourse_workflows.configurator.always_output_data"
+ }}
+ @description={{i18n
+ "discourse_workflows.configurator.always_output_data_help"
+ }}
+ @type="toggle"
+ @format="full"
+ @onSet={{this.handleAlwaysOutputDataSet}}
+ class="workflows-configurator-form__setting-toggle"
+ as |field|
+ >
+ <field.Control />
+ </form.Field>
+ </Form>
+ {{#if this.nodeDescription}}
+ <div class="workflows-configurator-modal__node">
+ <span class="workflows-configurator-modal__node-title">
+ {{#if (nodeTypeIcon this.resolvedNodeType)}}
+ <span
+ class="workflows-configurator-modal__node-icon"
+ style={{nodeTypeStyle this.resolvedNodeType}}
+ >
+ {{dIcon (nodeTypeIcon this.resolvedNodeType)}}
+ </span>
+ {{/if}}{{this.nodeTypeDefaultName}}
+ </span>
+ <p class="workflows-configurator-modal__node-description">
+ {{this.nodeDescription}}
+ </p>
+ <span class="workflows-configurator-modal__node-version">
+ v{{@model.node.typeVersion}}
+ </span>
+ </div>
+ {{/if}}
+ {{/if}}
+ </div>
+
+ {{#if this.showsOutputContext}}
+ <div class="workflows-configurator-modal__column --right">
+ <OutputContext
+ @node={{@model.node}}
+ @nodes={{@model.nodes}}
+ @connections={{@model.connections}}
+ @triggerType={{@model.triggerType}}
+ @nodeTypes={{this.nodeTypes}}
+ @session={{@model.session}}
+ @configuration={{this.configuration}}
+ />
+ </div>
+ {{/if}}
+ </div>
+ </DConditionalLoadingSpinner>
+ </:body>
+ </DModal>
+ </template>
+}
diff --git a/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/paginated-list-manager.js b/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/paginated-list-manager.js
new file mode 100644
index 00000000000..d28ffb06465
--- /dev/null
+++ b/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/paginated-list-manager.js
@@ -0,0 +1,67 @@
+import Component from "@glimmer/component";
+import { tracked } from "@glimmer/tracking";
+import { action } from "@ember/object";
+import { service } from "@ember/service";
+import { ajax } from "discourse/lib/ajax";
+import { popupAjaxError } from "discourse/lib/ajax-error";
+
+export default class PaginatedListManager extends Component {
+ // eslint-disable-next-line discourse/no-unused-services -- used by subclasses
+ @service currentUser;
+ // eslint-disable-next-line discourse/no-unused-services -- used by subclasses
+ @service dialog;
+ // eslint-disable-next-line discourse/no-unused-services -- used by subclasses
+ @service modal;
+
+ @tracked items = null;
+ @tracked loadMoreUrl = null;
+ @tracked totalRows = 0;
+ @tracked loadingMore = false;
+
+ constructor() {
+ super(...arguments);
+ this.loadItems();
+ }
+
+ get apiUrl() {
+ return `${this.basePath}.json`;
+ }
+
+ get canLoadMore() {
+ return this.items && this.items.length < this.totalRows;
+ }
+
+ get isLoading() {
+ return this.items === null;
+ }
+
+ async loadItems() {
+ try {
+ const result = await ajax(this.apiUrl);
+ this.items = result[this.collectionKey];
+ this.loadMoreUrl = result.meta?.load_more_url;
+ this.totalRows = result.meta?.total_rows ?? this.items.length;
+ } catch (e) {
+ popupAjaxError(e);
+ }
+ }
+
+ @action
+ async loadMore() {
+ if (!this.loadMoreUrl || !this.canLoadMore || this.loadingMore) {
+ return;
+ }
+
+ this.loadingMore = true;
+ try {
+ const result = await ajax(this.loadMoreUrl);
+ this.items = [...this.items, ...result[this.collectionKey]];
+ this.loadMoreUrl = result.meta?.load_more_url;
+ this.totalRows = result.meta?.total_rows ?? this.totalRows;
+ } catch (e) {
+ popupAjaxError(e);
+ } finally {
+ this.loadingMore = false;
+ }
+ }
+}
diff --git a/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/settings.gjs b/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/settings.gjs
new file mode 100644
index 00000000000..5eb792f59f2
--- /dev/null
+++ b/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/settings.gjs
@@ -0,0 +1,137 @@
+import Component from "@glimmer/component";
+import { hash } from "@ember/helper";
+import { action } from "@ember/object";
+import { service } from "@ember/service";
+import Form from "discourse/components/form";
+import { ajax } from "discourse/lib/ajax";
+import { popupAjaxError } from "discourse/lib/ajax-error";
+import TimezoneInput from "discourse/select-kit/components/timezone-input";
+import { i18n } from "discourse-i18n";
+import ErrorWorkflowChooser from "./error-workflow-chooser";
+
+export default class WorkflowSettings extends Component {
+ @service router;
+ @service dialog;
+ @service toasts;
+
+ formData = {
+ errorWorkflowId: this.args.workflow.errorWorkflowId,
+ timezone: this.args.workflow.timezone || "UTC",
+ };
+
+ errorWorkflowContent =
+ this.args.workflow.errorWorkflowId && this.args.workflow.errorWorkflowName
+ ? [
+ {
+ id: this.args.workflow.errorWorkflowId,
+ name: this.args.workflow.errorWorkflowName,
+ },
+ ]
+ : [];
+
+ @action
+ async deleteWorkflow() {
+ await this.dialog.deleteConfirm({
+ message: i18n("discourse_workflows.delete_confirm", {
+ name: this.args.workflow.name,
+ }),
+ didConfirm: async () => {
+ try {
+ await this.args.workflow.destroyRecord();
+ this.router.transitionTo(
+ "adminPlugins.show.discourse-workflows.index"
+ );
+ } catch (e) {
+ popupAjaxError(e);
+ }
+ },
+ });
+ }
+
+ @action
+ async submitForm(name, value, data) {
+ try {
+ await ajax(
+ `/admin/plugins/discourse-workflows/workflows/${this.args.workflow.id}.json`,
+ {
+ type: "PUT",
+ data: {
+ workflow: {
+ name: this.args.workflow.name,
+ error_workflow_id: data.errorWorkflowId,
+ timezone: data.timezone,
+ },
+ },
+ }
+ );
+
+ this.toasts.success({
+ duration: "short",
+ data: { message: i18n("discourse_workflows.settings.saved") },
+ });
+ } catch (e) {
+ popupAjaxError(e);
+ }
+ }
+
+ <template>
+ <Form
+ @onSet={{this.submitForm}}
+ @data={{this.formData}}
+ class="workflows-settings"
+ as |form|
+ >
+ <form.Field
+ @name="errorWorkflowId"
+ @title={{i18n "discourse_workflows.settings.error_workflow"}}
+ @description={{i18n
+ "discourse_workflows.settings.error_workflow_description"
+ }}
+ @type="custom"
+ @format="full"
+ as |field|
+ >
+ <field.Control>
+ <ErrorWorkflowChooser
+ @content={{this.errorWorkflowContent}}
+ @value={{field.value}}
+ @onChange={{field.set}}
+ @options={{hash
+ none="discourse_workflows.settings.error_workflow_none"
+ }}
+ />
+ </field.Control>
+ </form.Field>
+
+ <form.Field
+ @name="timezone"
+ @title={{i18n "discourse_workflows.settings.timezone"}}
+ @description={{i18n
+ "discourse_workflows.settings.timezone_description"
+ }}
+ @type="custom"
+ @format="full"
+ as |field|
+ >
+ <field.Control>
+ <TimezoneInput @value={{field.value}} @onChange={{field.set}} />
+ </field.Control>
+ </form.Field>
+
+ <form.Emphasis
+ @title={{i18n "discourse_workflows.settings.danger_zone"}}
+ @subtitle={{i18n "discourse_workflows.settings.delete_description"}}
+ @type="error"
+ >
+ <form.Actions>
+ <form.Button
+ @label="discourse_workflows.delete"
+ @action={{this.deleteWorkflow}}
+ class="btn-danger"
+ />
+ </form.Actions>
+ </form.Emphasis>
+ </Form>
+ </template>
+}
diff --git a/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/stats.gjs b/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/stats.gjs
new file mode 100644
index 00000000000..604a8a33397
--- /dev/null
+++ b/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/stats.gjs
@@ -0,0 +1,29 @@
+import DStatTiles from "discourse/ui-kit/d-stat-tiles";
+import { i18n } from "discourse-i18n";
+
+<template>
+ {{#if @stats.total}}
+ <DStatTiles
+ title={{i18n "discourse_workflows.stats.period"}}
+ @format="compact"
+ as |tiles|
+ >
+ <tiles.Tile
+ @label={{i18n "discourse_workflows.stats.executions"}}
+ @formattedValue={{@stats.total}}
+ />
+ <tiles.Tile
+ @label={{i18n "discourse_workflows.stats.failures"}}
+ @formattedValue={{@stats.failed}}
+ />
+ <tiles.Tile
+ @label={{i18n "discourse_workflows.stats.failure_rate"}}
+ @formattedValue={{@stats.failure_rate}}
+ />
+ <tiles.Tile
+ @label={{i18n "discourse_workflows.stats.avg_run_time"}}
+ @formattedValue={{@stats.avg_duration}}
+ />
+ </DStatTiles>
+ {{/if}}
+</template>
diff --git a/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/templates.gjs b/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/templates.gjs
new file mode 100644
index 00000000000..772ed5b9f5f
--- /dev/null
+++ b/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/templates.gjs
@@ -0,0 +1,144 @@
+import Component from "@glimmer/component";
+import { tracked } from "@glimmer/tracking";
+import { fn } from "@ember/helper";
+import { on } from "@ember/modifier";
+import { action } from "@ember/object";
+import didInsert from "@ember/render-modifiers/modifiers/did-insert";
+import { service } from "@ember/service";
+import { trustHTML } from "@ember/template";
+import { ajax } from "discourse/lib/ajax";
+import { popupAjaxError } from "discourse/lib/ajax-error";
+import dIcon from "discourse/ui-kit/helpers/d-icon";
+import { nodeTypeColor, nodeTypeIcon } from "../../lib/workflows/node-types";
+import { workflowFromTemplate } from "../../lib/workflows/template-workflow";
+
+const MAX_VISIBLE_ICONS = 3;
+
+function visibleNodeTypes(nodeTypes) {
+ return (nodeTypes || []).slice(0, MAX_VISIBLE_ICONS);
+}
+
+function hasOverflow(nodeTypes) {
+ return (nodeTypes || []).length > MAX_VISIBLE_ICONS;
+}
+
+function overflowCount(nodeTypes) {
+ return (nodeTypes || []).length - MAX_VISIBLE_ICONS;
+}
+
+function iconFor(nodeType) {
+ return nodeTypeIcon(nodeType) || "cog";
+}
+
+function iconStyle(nodeType) {
+ return trustHTML(`color: ${nodeTypeColor(nodeType)}`);
+}
+
+export default class WorkflowsTemplates extends Component {
+ @service router;
+ @service workflowsNodeTypes;
+
+ @tracked creatingTemplateId = null;
+ @tracked nodeTypesLoaded = false;
+
+ resolveNodeType = (identifier) => {
+ return this.workflowsNodeTypes.findNodeType(identifier) || identifier;
+ };
+
+ get workflowId() {
+ return this.router.currentRoute?.queryParams?.workflow_id;
+ }
+
+ @action
+ async ensureNodeTypes() {
+ await this.workflowsNodeTypes.load();
+ this.nodeTypesLoaded = true;
+ }
+
+ @action
+ async useTemplate(template) {
+ if (this.creatingTemplateId) {
+ return;
+ }
+
+ this.creatingTemplateId = template.id;
+
+ try {
+ const fullTemplate = await ajax(
+ `/admin/plugins/discourse-workflows/templates/${template.id}.json`
+ );
+
+ const workflow = workflowFromTemplate(fullTemplate.template);
+
+ if (this.workflowId) {
+ await ajax(
+ `/admin/plugins/discourse-workflows/workflows/${this.workflowId}.json`,
+ {
+ type: "PUT",
+ contentType: "application/json",
+ data: JSON.stringify({ workflow }),
+ }
+ );
+
+ this.router.transitionTo(
+ "adminPlugins.show.discourse-workflows.show",
+ this.workflowId
+ );
+ return;
+ }
+
+ const result = await ajax(
+ "/admin/plugins/discourse-workflows/workflows.json",
+ {
+ type: "POST",
+ contentType: "application/json",
+ data: JSON.stringify({ workflow }),
+ }
+ );
+
+ this.router.transitionTo(
+ "adminPlugins.show.discourse-workflows.show",
+ result.workflow.id
+ );
+ } catch (e) {
+ popupAjaxError(e);
+ this.creatingTemplateId = null;
+ }
+ }
+
+ <template>
+ <div class="workflows-templates" {{didInsert this.ensureNodeTypes}}>
+ {{#each @templates as |tmpl|}}
+ <button
+ type="button"
+ class="workflows-templates__tile"
+ disabled={{this.creatingTemplateId}}
+ {{on "click" (fn this.useTemplate tmpl)}}
+ >
+ <span class="workflows-templates__description">
+ {{tmpl.description}}
+ </span>
+ {{#if this.nodeTypesLoaded}}
+ <div class="workflows-templates__icons">
+ {{#each (visibleNodeTypes tmpl.node_types) as |nodeTypeId|}}
+ {{#let (this.resolveNodeType nodeTypeId) as |nodeType|}}
+ <span
+ class="workflows-templates__icon"
+ style={{iconStyle nodeType}}
+ >
+ {{dIcon (iconFor nodeType)}}
+ </span>
+ {{/let}}
+ {{/each}}
+ {{#if (hasOverflow tmpl.node_types)}}
+ <span class="workflows-templates__icon --overflow">
+ +{{overflowCount tmpl.node_types}}
+ </span>
+ {{/if}}
+ </div>
+ {{/if}}
+ </button>
+ {{/each}}
+ </div>
+ </template>
+}
diff --git a/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/variable/expression-preview-content.gjs b/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/variable/expression-preview-content.gjs
new file mode 100644
index 00000000000..7c65840b0a0
--- /dev/null
+++ b/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/variable/expression-preview-content.gjs
@@ -0,0 +1,55 @@
+import Component from "@glimmer/component";
+import { i18n } from "discourse-i18n";
+
+const VALID_STATES = new Set([
+ "valid",
+ "invalid",
+ "undefined",
+ "warning",
+ "pending",
+ "empty",
+]);
+
+const I18N_PREFIX = "discourse_workflows.expression_preview";
+
+export default class ExpressionPreviewContent extends Component {
+ get displaySegments() {
+ const segments = this.args.data?.segments;
+ if (!segments?.length) {
+ return [];
+ }
+
+ return segments.map((seg) => {
+ if (seg.kind === "plaintext") {
+ return { className: "expression-preview__plaintext", text: seg.text };
+ }
+
+ const state = VALID_STATES.has(seg.state) ? seg.state : "pending";
+ if (state === "valid" && seg.text.length > 0) {
+ return {
+ className: `expression-preview__resolved --${state}`,
+ text: seg.text,
+ };
+ }
+
+ const labelState = state === "valid" ? "empty" : state;
+ return {
+ className: `expression-preview__resolved --${labelState} --label`,
+ text: i18n(`${I18N_PREFIX}.${labelState}`),
+ };
+ });
+ }
+
+ <template>
+ <div class="expression-preview">
+ <span class="expression-preview__label">
+ {{i18n "discourse_workflows.expression_preview.result"}}
+ </span>
+ <span class="expression-preview__result">
+ {{~#each this.displaySegments as |seg|~}}
+ <span class={{seg.className}}>{{seg.text}}</span>
+ {{~/each~}}
+ </span>
+ </div>
+ </template>
+}
diff --git a/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/variable/expression-preview.gjs b/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/variable/expression-preview.gjs
new file mode 100644
index 00000000000..d01dd95ca77
--- /dev/null
+++ b/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/variable/expression-preview.gjs
@@ -0,0 +1,97 @@
+import Component from "@glimmer/component";
+import didInsert from "@ember/render-modifiers/modifiers/did-insert";
+import didUpdate from "@ember/render-modifiers/modifiers/did-update";
+import { service } from "@ember/service";
+import ExpressionPreviewContent from "./expression-preview-content";
+
+export default class ExpressionPreview extends Component {
+ @service tooltip;
+
+ handleSegmentsChange = () => {
+ if (this.args.visible) {
+ this.#showTooltip();
+ }
+ };
+ handleVisibilityChange = () => {
+ if (this.args.visible) {
+ if (this.args.segments?.length) {
+ this.#showTooltip();
+ }
+ } else {
+ this.#closeTooltip();
+ }
+ };
+ #tooltipInstance = null;
+
+ willDestroy() {
+ super.willDestroy(...arguments);
+ this.#closeTooltip();
+ }
+
+ async #showTooltip() {
+ const trigger = this.args.trigger;
+ if (!trigger || this.isDestroying || this.isDestroyed) {
+ return;
+ }
+
+ const segments = this.args.segments;
+ if (!segments?.length) {
+ this.#closeTooltip();
+ return;
+ }
+
+ if (this.#tooltipInstance) {
+ this.#tooltipInstance.options = {
+ ...this.#tooltipInstance.options,
+ data: { segments },
+ };
+ return;
+ }
+
+ const input = trigger.querySelector(".workflows-variable-input") || trigger;
+ const portalOutletElement = trigger.closest(".d-modal");
+
+ const instance = await this.tooltip.show(input, {
+ identifier: "expression-preview",
+ component: ExpressionPreviewContent,
+ data: { segments },
+ placement: "bottom-start",
+ fallbackPlacements: ["top-start"],
+ interactive: true,
+ arrow: false,
+ animated: false,
+ closeOnEscape: false,
+ closeOnClickOutside: false,
+ closeOnScroll: false,
+ matchTriggerWidth: true,
+ maxWidth: 9999,
+ offset: 4,
+ portalOutletElement,
+ });
+
+ if (this.isDestroying || this.isDestroyed) {
+ if (instance) {
+ this.tooltip.close(instance);
+ }
+ return;
+ }
+
+ this.#tooltipInstance = instance;
+ }
+
+ #closeTooltip() {
+ if (this.#tooltipInstance) {
+ this.tooltip.close(this.#tooltipInstance);
+ this.#tooltipInstance = null;
+ }
+ }
+
+ <template>
+ <span
+ class="expression-preview__anchor"
+ {{didInsert this.handleSegmentsChange}}
+ {{didUpdate this.handleSegmentsChange @segments}}
+ {{didUpdate this.handleVisibilityChange @visible}}
+ ></span>
+ </template>
+}
diff --git a/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/variable/input.gjs b/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/variable/input.gjs
new file mode 100644
index 00000000000..3cea134c2d0
--- /dev/null
+++ b/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/variable/input.gjs
@@ -0,0 +1,46 @@
+import Component from "@glimmer/component";
+import { tracked } from "@glimmer/tracking";
+import { action } from "@ember/object";
+import didInsert from "@ember/render-modifiers/modifiers/did-insert";
+import { service } from "@ember/service";
+import loadCodemirrorEditor from "discourse/lib/load-codemirror";
+
+export default class VariableInput extends Component {
+ @service workflowsNodeTypes;
+
+ @tracked Editor;
+
+ @action
+ async loadEditor() {
+ const [Editor] = await Promise.all([
+ loadCodemirrorEditor(),
+ this.workflowsNodeTypes.loadWorkflowVars(),
+ ]);
+
+ if (this.isDestroying || this.isDestroyed) {
+ return;
+ }
+
+ this.Editor = Editor;
+ }
+
+ <template>
+ <div
+ class="workflows-variable-input__container"
+ {{didInsert this.loadEditor}}
+ >
+ {{#if this.Editor}}
+ <this.Editor
+ @value={{@value}}
+ @change={{@onChange}}
+ @extensions={{@extensions}}
+ @class="workflows-variable-input"
+ @lineWrapping={{true}}
+ @onSetup={{@onSetup}}
+ @focusIn={{@onFocusIn}}
+ @focusOut={{@onFocusOut}}
+ />
+ {{/if}}
+ </div>
+ </template>
+}
diff --git a/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/variable/manager.gjs b/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/variable/manager.gjs
new file mode 100644
index 00000000000..8f21438e954
--- /dev/null
+++ b/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/variable/manager.gjs
@@ -0,0 +1,204 @@
+import { concat, fn } from "@ember/helper";
+import { action } from "@ember/object";
+import { service } from "@ember/service";
+import DMenu from "discourse/float-kit/components/d-menu";
+import { ajax } from "discourse/lib/ajax";
+import { popupAjaxError } from "discourse/lib/ajax-error";
+import { userPath } from "discourse/lib/url";
+import { clipboardCopy } from "discourse/lib/utilities";
+import DButton from "discourse/ui-kit/d-button";
+import DDropdownMenu from "discourse/ui-kit/d-dropdown-menu";
+import dAvatar from "discourse/ui-kit/helpers/d-avatar";
+import { i18n } from "discourse-i18n";
+import AdminTable from "../admin-table";
+import EmptyState from "../empty-state";
+import PaginatedListManager from "../paginated-list-manager";
+import VariableModal from "./modal";
+
+export default class VariablesManager extends PaginatedListManager {
+ @service toasts;
+ @service workflowsNodeTypes;
+
+ get collectionKey() {
+ return "variables";
+ }
+
+ get basePath() {
+ return "/admin/plugins/discourse-workflows/variables";
+ }
+
+ @action
+ addVariable() {
+ this.modal.show(VariableModal, {
+ model: {
+ variable: null,
+ onSave: async (data) => {
+ await ajax(this.apiUrl, {
+ type: "POST",
+ data,
+ });
+ this.workflowsNodeTypes.invalidateWorkflowVars();
+ await this.loadItems();
+ },
+ },
+ });
+ }
+
+ @action
+ editVariable(variable) {
+ this.modal.show(VariableModal, {
+ model: {
+ variable,
+ onSave: async (data) => {
+ await ajax(`${this.basePath}/${variable.id}.json`, {
+ type: "PUT",
+ data,
+ });
+ this.workflowsNodeTypes.invalidateWorkflowVars();
+ await this.loadItems();
+ },
+ },
+ });
+ }
+
+ @action
+ deleteVariable(variable) {
+ this.dialog.deleteConfirm({
+ message: i18n("discourse_workflows.variables.delete_confirm", {
+ key: variable.key,
+ }),
+ didConfirm: async () => {
+ try {
+ await ajax(`${this.basePath}/${variable.id}.json`, {
+ type: "DELETE",
+ });
+ this.workflowsNodeTypes.invalidateWorkflowVars();
+ await this.loadItems();
+ } catch (e) {
+ popupAjaxError(e);
+ }
+ },
+ });
+ }
+
+ @action
+ async copySyntax(key) {
+ await clipboardCopy(`$vars.${key}`);
+ this.toasts.success({
+ duration: "short",
+ data: { message: i18n("discourse_workflows.variables.copied") },
+ });
+ }
+
+ <template>
+ <AdminTable
+ @items={{this.items}}
+ @isLoading={{this.isLoading}}
+ @canLoadMore={{this.canLoadMore}}
+ @loadMore={{this.loadMore}}
+ @loadingMore={{this.loadingMore}}
+ >
+ <:empty>
+ <EmptyState
+ @emoji="wave"
+ @title={{i18n
+ "discourse_workflows.variables.empty_title"
+ username=this.currentUser.displayName
+ }}
+ @description={{i18n
+ "discourse_workflows.variables.empty_description"
+ }}
+ @buttonLabel="discourse_workflows.variables.add_first"
+ @onAction={{this.addVariable}}
+ />
+ </:empty>
+ <:toolbar>
+ <DButton
+ @action={{this.addVariable}}
+ @label="discourse_workflows.variables.add"
+ @icon="plus"
+ class="btn-primary btn-small"
+ />
+ </:toolbar>
+ <:head>
+ <th class="d-table__header-cell">{{i18n
+ "discourse_workflows.variables.key"
+ }}</th>
+ <th class="d-table__header-cell">{{i18n
+ "discourse_workflows.variables.value"
+ }}</th>
+ <th class="d-table__header-cell">{{i18n
+ "discourse_workflows.variables.creator"
+ }}</th>
+ <th class="d-table__header-cell">{{i18n
+ "discourse_workflows.variables.usage_syntax"
+ }}</th>
+ <th class="d-table__header-cell"></th>
+ </:head>
+ <:row as |variable|>
+ <td class="d-table__cell --overview">
+ <strong class="d-table__overview-name">{{variable.key}}</strong>
+ </td>
+ <td class="d-table__cell --detail">
+ <div class="d-table__mobile-label">
+ {{i18n "discourse_workflows.variables.value"}}
+ </div>
+ {{variable.value}}
+ </td>
+ <td class="d-table__cell --detail">
+ <div class="d-table__mobile-label">
+ {{i18n "discourse_workflows.variables.creator"}}
+ </div>
+ <a
+ href={{userPath variable.created_by.username}}
+ class="workflows-variables__creator"
+ >
+ {{dAvatar variable.created_by imageSize="tiny"}}
+ <span>{{variable.created_by.username}}</span>
+ </a>
+ </td>
+ <td class="d-table__cell --detail">
+ <div class="d-table__mobile-label">
+ {{i18n "discourse_workflows.variables.usage_syntax"}}
+ </div>
+ <DButton
+ @action={{fn this.copySyntax variable.key}}
+ @translatedLabel={{concat "$vars." variable.key}}
+ @icon="copy"
+ @title="discourse_workflows.variables.copy_syntax"
+ class="btn-flat btn-small"
+ />
+ </td>
+ <td class="d-table__cell --controls">
+ <div class="d-table__cell-actions">
+ <DButton
+ @action={{fn this.editVariable variable}}
+ @label="discourse_workflows.edit"
+ @title="discourse_workflows.variables.edit"
+ class="btn-default btn-small"
+ />
+ <DMenu
+ @identifier="workflows-variable-menu"
+ @title={{i18n "discourse_workflows.more_options"}}
+ @icon="ellipsis-vertical"
+ @triggerClass="btn-default"
+ >
+ <:content>
+ <DDropdownMenu as |dropdown|>
+ <dropdown.item>
+ <DButton
+ @action={{fn this.deleteVariable variable}}
+ @icon="trash-can"
+ @label="discourse_workflows.delete"
+ class="btn-danger"
+ />
+ </dropdown.item>
+ </DDropdownMenu>
+ </:content>
+ </DMenu>
+ </div>
+ </td>
+ </:row>
+ </AdminTable>
+ </template>
+}
diff --git a/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/variable/modal.gjs b/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/variable/modal.gjs
new file mode 100644
index 00000000000..bb2756e6414
--- /dev/null
+++ b/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/variable/modal.gjs
@@ -0,0 +1,88 @@
+import Component from "@glimmer/component";
+import { action } from "@ember/object";
+import Form from "discourse/components/form";
+import { popupAjaxError } from "discourse/lib/ajax-error";
+import DModal from "discourse/ui-kit/d-modal";
+import { i18n } from "discourse-i18n";
+
+const KEY_PATTERN = /^[a-zA-Z_][a-zA-Z0-9_]*$/;
+
+export default class VariableModal extends Component {
+ formData = {
+ key: this.args.model.variable?.key || "",
+ value: this.args.model.variable?.value || "",
+ };
+
+ @action
+ validateKey(name, value, { addError }) {
+ if (value && !KEY_PATTERN.test(value)) {
+ addError(name, {
+ title: i18n("discourse_workflows.variables.key"),
+ message: i18n("discourse_workflows.variables.key_invalid"),
+ });
+ }
+ }
+
+ @action
+ async handleSubmit(data) {
+ try {
+ await this.args.model.onSave(data);
+ this.args.closeModal();
+ } catch (error) {
+ popupAjaxError(error);
+ }
+ }
+
+ <template>
+ <DModal
+ @title={{if
+ @model.variable
+ (i18n "discourse_workflows.variables.edit")
+ (i18n "discourse_workflows.variables.add")
+ }}
+ @closeModal={{@closeModal}}
+ >
+ <:body>
+ <Form
+ @data={{this.formData}}
+ @onSubmit={{this.handleSubmit}}
+ class="workflows-configurator-form"
+ as |form|
+ >
+ <form.Field
+ @name="key"
+ @title={{i18n "discourse_workflows.variables.key"}}
+ @type="input"
+ @format="full"
+ @validation="required"
+ @validate={{this.validateKey}}
+ as |field|
+ >
+ <field.Control
+ placeholder={{i18n
+ "discourse_workflows.variables.key_placeholder"
+ }}
+ />
+ </form.Field>
+
+ <form.Field
+ @name="value"
+ @title={{i18n "discourse_workflows.variables.value"}}
+ @type="input"
+ @format="full"
+ @validation="required"
+ as |field|
+ >
+ <field.Control
+ placeholder={{i18n
+ "discourse_workflows.variables.value_placeholder"
+ }}
+ />
+ </form.Field>
+
+ <form.Submit />
+ </Form>
+ </:body>
+ </DModal>
+ </template>
+}
diff --git a/plugins/discourse-workflows/admin/assets/javascripts/admin/discourse-workflows-route-map.js b/plugins/discourse-workflows/admin/assets/javascripts/admin/discourse-workflows-route-map.js
new file mode 100644
index 00000000000..15022eb7958
--- /dev/null
+++ b/plugins/discourse-workflows/admin/assets/javascripts/admin/discourse-workflows-route-map.js
@@ -0,0 +1,26 @@
+export default {
+ resource: "admin.adminPlugins.show",
+ path: "/plugins",
+ map() {
+ this.route("discourse-workflows", { path: "workflows" }, function () {
+ this.route("new");
+ this.route("show", { path: "/:id" }, function () {
+ this.route("executions", function () {
+ this.route("show", { path: "/:execution_id" });
+ });
+ this.route("settings");
+ });
+ });
+ this.route("discourse-workflows-templates", { path: "templates" });
+ this.route("discourse-workflows-variables", { path: "variables" });
+ this.route("discourse-workflows-credentials", { path: "credentials" });
+ this.route("discourse-workflows-executions", { path: "executions" });
+ this.route(
+ "discourse-workflows-data-tables",
+ { path: "data-tables" },
+ function () {
+ this.route("show", { path: "/:id" });
+ }
+ );
+ },
+};
diff --git a/plugins/discourse-workflows/admin/assets/javascripts/admin/lib/workflows/codemirror-extension.js b/plugins/discourse-workflows/admin/assets/javascripts/admin/lib/workflows/codemirror-extension.js
new file mode 100644
index 00000000000..da6f7a9723a
--- /dev/null
+++ b/plugins/discourse-workflows/admin/assets/javascripts/admin/lib/workflows/codemirror-extension.js
@@ -0,0 +1,938 @@
+import { ajax } from "discourse/lib/ajax";
+import { i18n } from "discourse-i18n";
+import {
+ buildScope,
+ lookupWorkflowMethodDoc,
+ resolveVariableId,
+ walkScope,
+ WORKFLOW_VARIABLE_MIME,
+} from "./expression-context";
+
+// Extends core's generic analyzePropertyAccess with workflow-specific
+// patterns: $('Node Name') references and $-prefixed variables.
+function buildAnalyzeAtCursor({ cmLanguage, utils }) {
+ const { syntaxTree } = cmLanguage;
+ const { analyzePropertyAccess } = utils;
+
+ return function analyzeAtCursor(state, pos) {
+ const tree = syntaxTree(state);
+ const node = tree.resolveInner(pos, -1);
+ const doc = state.doc;
+
+ // $(' or $(" — node reference
+ const lb = doc.sliceString(Math.max(0, pos - 3), pos);
+ if (lb === "$('" || lb === '$("') {
+ return { kind: "nodeRef", from: pos, pos };
+ }
+
+ // $('NodeName') as a complete CallExpression
+ let cur = node;
+ while (cur) {
+ if (cur.name === "CallExpression") {
+ const callee = cur.firstChild;
+ if (callee && doc.sliceString(callee.from, callee.to) === "$") {
+ const argList = cur.getChild("ArgList");
+ if (argList && pos > argList.from && pos <= argList.to) {
+ return { kind: "nodeRef", from: argList.from + 1, pos };
+ }
+ }
+ }
+ cur = cur.parent;
+ }
+
+ const result = analyzePropertyAccess(state, pos);
+
+ if (result.kind === "identifier" && result.partial?.startsWith("$")) {
+ return { ...result, kind: "dollar" };
+ }
+
+ return result;
+ };
+}
+
+const DOLLAR_VAR_DOCS = {
+ $input: {
+ detail: "object",
+ infoKey: "discourse_workflows.expression_docs.vars.input",
+ },
+ $itemIndex: {
+ detail: "number",
+ infoKey: "discourse_workflows.expression_docs.vars.item_index",
+ },
+ $json: {
+ detail: "object",
+ infoKey: "discourse_workflows.expression_docs.vars.json",
+ },
+ trigger: {
+ detail: "object",
+ infoKey: "discourse_workflows.expression_docs.vars.trigger",
+ },
+ $site_settings: {
+ detail: "object",
+ infoKey: "discourse_workflows.expression_docs.vars.site_settings",
+ },
+ $current_user: {
+ detail: "object",
+ infoKey: "discourse_workflows.expression_docs.vars.current_user",
+ },
+ $vars: {
+ detail: "object",
+ infoKey: "discourse_workflows.expression_docs.vars.workflow_vars",
+ },
+ $execution: {
+ detail: "object",
+ infoKey: "discourse_workflows.expression_docs.vars.execution",
+ },
+};
+
+function lookupDollarVarDoc(name) {
+ const doc = DOLLAR_VAR_DOCS[name];
+ if (!doc) {
+ return null;
+ }
+ return { detail: doc.detail, info: i18n(doc.infoKey) };
+}
+
+function buildDollarVars(scope, sections) {
+ const groups = [
+ {
+ names: ["$input", "$json", "$itemIndex", "trigger"],
+ section: sections.recommended,
+ boost: (name) => (name === "$json" ? 10 : 5),
+ },
+ {
+ names: ["$site_settings", "$current_user", "$vars", "$execution"],
+ section: sections.metadata,
+ },
+ ];
+
+ const dollarVars = [];
+ for (const group of groups) {
+ for (const name of group.names) {
+ if (name in scope) {
+ const docs = lookupDollarVarDoc(name) || {};
+ const isObject =
+ typeof scope[name] === "object" && scope[name] !== null;
+ const entry = {
+ label: name,
+ apply: isObject ? `${name}.` : name,
+ type: "variable",
+ detail: docs.detail || "object",
+ info: docs.info,
+ section: group.section,
+ };
+ if (group.boost) {
+ entry.boost = group.boost(name);
+ }
+ dollarVars.push(entry);
+ }
+ }
+ }
+ dollarVars.push({
+ label: "$(",
+ apply: "$('",
+ type: "function",
+ detail: "node reference",
+ info: i18n("discourse_workflows.expression_docs.vars.node_ref"),
+ section: sections.nodes,
+ });
+ return dollarVars;
+}
+
+const EXPRESSION_TOKEN_NAMES = new Set([
+ "VariableName",
+ "PropertyName",
+ "Number",
+ "String",
+ "BooleanLiteral",
+ ")",
+ "]",
+ "}",
+]);
+
+function applyMethodCompletion(
+ view,
+ completion,
+ from,
+ to,
+ { insertCompletionText, pickedCompletion }
+) {
+ const afterCursor = view.state.doc.sliceString(to, to + 1);
+
+ if (afterCursor === "(") {
+ view.dispatch({
+ ...insertCompletionText(view.state, completion.label, from, to),
+ annotations: pickedCompletion.of(completion),
+ });
+ return;
+ }
+
+ const insert = `${completion.label}()`;
+ const hasArgs = completion.detail && !completion.detail.startsWith("()");
+ const anchor = from + completion.label.length + (hasArgs ? 1 : 2);
+ view.dispatch({
+ ...insertCompletionText(view.state, insert, from, to),
+ selection: { anchor },
+ annotations: pickedCompletion.of(completion),
+ });
+}
+
+function withMethodApply(option, cmAutocomplete) {
+ if (option.type === "method" || option.type === "function") {
+ return {
+ ...option,
+ apply: (view, completion, from, to) =>
+ applyMethodCompletion(view, completion, from, to, cmAutocomplete),
+ };
+ }
+ return option;
+}
+
+function escapeQuotedString(value, quote) {
+ return String(value).replace(/\\/g, "\\\\").replaceAll(quote, `\\${quote}`);
+}
+
+function buildCompletions(
+ cmParams,
+ { scope, ancestorNodes, analyzeAtCursor, sections }
+) {
+ const { cmAutocomplete, cmLanguage, cmView, utils } = cmParams;
+ const { autocompletion, completionKeymap } = cmAutocomplete;
+ const { syntaxTree } = cmLanguage;
+ const { keymap } = cmView;
+ const {
+ isInsideExpression,
+ globalCompletions,
+ globalStaticMethods,
+ methodsForType,
+ } = utils;
+
+ const dollarVars = buildDollarVars(scope, sections);
+ const globalOptions = globalCompletions.map((g) =>
+ withMethodApply({ ...g, section: sections.globals }, cmAutocomplete)
+ );
+
+ const completer = (context) => {
+ if (!isInsideExpression(context)) {
+ return null;
+ }
+
+ const ctx = analyzeAtCursor(context.state, context.pos);
+
+ switch (ctx.kind) {
+ case "property": {
+ const target = walkScope(scope, ctx.object);
+ if (target == null) {
+ return null;
+ }
+
+ const options = [];
+
+ const statics = globalStaticMethods[ctx.object];
+ if (statics) {
+ for (const m of statics) {
+ options.push(
+ withMethodApply(
+ { ...m, section: sections.methods },
+ cmAutocomplete
+ )
+ );
+ }
+ }
+
+ const methods = methodsForType(target);
+ for (const m of methods) {
+ options.push(
+ withMethodApply({ ...m, section: sections.methods }, cmAutocomplete)
+ );
+ }
+
+ if (typeof target === "object" && target !== null) {
+ for (const name of Object.keys(target)) {
+ const value = target[name];
+ if (typeof value === "function") {
+ const methodDoc = lookupWorkflowMethodDoc(ctx.object, name);
+ options.push(
+ withMethodApply(
+ {
+ label: name,
+ type: "method",
+ detail: methodDoc?.detail || "()",
+ info: methodDoc?.info,
+ section: sections.methods,
+ },
+ cmAutocomplete
+ )
+ );
+ continue;
+ }
+ options.push({
+ label: name,
+ type:
+ typeof value === "object" && value !== null
+ ? "property"
+ : "variable",
+ detail: Array.isArray(value) ? "array" : typeof value,
+ section: sections.properties,
+ });
+ }
+ }
+
+ if (!options.length) {
+ return null;
+ }
+ return { from: ctx.from, options, filter: true, validFor: /^[\w$]*$/ };
+ }
+
+ case "nodeRef": {
+ const charBefore = context.state.doc.sliceString(
+ ctx.from - 1,
+ ctx.from
+ );
+ const q = charBefore === '"' ? '"' : "'";
+ const prefix = charBefore === "'" || charBefore === '"' ? "" : q;
+ return {
+ from: ctx.from,
+ options: ancestorNodes.map((a) => ({
+ label: a.node.name,
+ apply: `${prefix}${escapeQuotedString(a.node.name, q)}${q})`,
+ type: "variable",
+ detail: a.node.type,
+ section: sections.nodes,
+ })),
+ filter: true,
+ };
+ }
+
+ case "bracket": {
+ const target = walkScope(scope, ctx.object);
+ if (!target || typeof target !== "object") {
+ return null;
+ }
+ return {
+ from: ctx.from,
+ options: Object.keys(target)
+ .filter((k) => typeof target[k] !== "function")
+ .map((name) => ({
+ label: name,
+ apply: `'${name.replace(/\\/g, "\\\\").replace(/'/g, "\\'")}']`,
+ type: "property",
+ section: sections.properties,
+ })),
+ filter: true,
+ };
+ }
+
+ case "dollar":
+ return { from: ctx.from, options: dollarVars, filter: true };
+
+ case "identifier": {
+ const charBefore = context.state.doc.sliceString(
+ Math.max(0, ctx.from - 1),
+ ctx.from
+ );
+ if (charBefore === ".") {
+ return null;
+ }
+ return { from: ctx.from, options: globalOptions, filter: true };
+ }
+
+ case "blank": {
+ if (!context.explicit) {
+ return null;
+ }
+ const prevNode = syntaxTree(context.state).resolveInner(
+ ctx.from - 1,
+ -1
+ );
+ if (ctx.from > 0 && EXPRESSION_TOKEN_NAMES.has(prevNode.name)) {
+ return null;
+ }
+ return {
+ from: ctx.from,
+ options: [...dollarVars, ...globalOptions],
+ filter: true,
+ };
+ }
+
+ default:
+ return null;
+ }
+ };
+
+ return [
+ autocompletion({
+ override: [completer],
+ activateOnTyping: true,
+ // Re-trigger completions after picking $( or any property that
+ // ends with "." (e.g. "$json.") so the next level shows immediately.
+ // String applies end with "."; function applies (methods) don't match.
+ activateOnCompletion: (completion) =>
+ completion.label === "$(" || completion.apply?.toString().endsWith("."),
+ icons: true,
+ }),
+ keymap.of(completionKeymap),
+ ];
+}
+
+function renderTooltipContent(doc) {
+ if (!doc) {
+ return null;
+ }
+
+ if (typeof doc.info === "function") {
+ const richContent = doc.info(doc);
+ if (richContent) {
+ return richContent;
+ }
+ }
+
+ const el = document.createElement("div");
+ el.className = "cm-wf-hover-tooltip";
+
+ const nameEl = document.createElement("div");
+ nameEl.className = "cm-wf-hover-tooltip__name";
+ nameEl.textContent = doc.label;
+ el.appendChild(nameEl);
+
+ if (typeof doc.info === "string") {
+ const desc = document.createElement("div");
+ desc.className = "cm-wf-hover-tooltip__description";
+ desc.textContent = doc.info;
+ el.appendChild(desc);
+ }
+
+ return el;
+}
+
+function makeTooltip(jsNode, content) {
+ if (!content) {
+ return null;
+ }
+ return {
+ pos: jsNode.from,
+ end: jsNode.to,
+ above: true,
+ create: () => ({ dom: content }),
+ };
+}
+
+function buildHoverTooltip({ cmLanguage, cmView, utils }, { scope }) {
+ const { syntaxTree } = cmLanguage;
+ const { hoverTooltip } = cmView;
+ const {
+ isInsideExpressionAt,
+ resolveNodeValue,
+ lookupMethodDoc,
+ globalDocs,
+ } = utils;
+
+ return hoverTooltip(
+ (view, pos) => {
+ const tree = syntaxTree(view.state);
+ const doc = view.state.doc;
+
+ if (!isInsideExpressionAt(view.state, pos)) {
+ return null;
+ }
+
+ const jsNode = tree.resolveInner(pos, -1);
+ const name = doc.sliceString(jsNode.from, jsNode.to);
+
+ if (
+ jsNode.name !== "VariableName" &&
+ jsNode.name !== "VariableDefinition" &&
+ jsNode.name !== "PropertyName"
+ ) {
+ return null;
+ }
+
+ if (jsNode.name === "PropertyName") {
+ const memberExpr = jsNode.parent;
+ if (memberExpr?.name === "MemberExpression") {
+ const parentPath = resolveNodeValue(memberExpr.firstChild, doc);
+ const parentValue = walkScope(scope, parentPath);
+
+ const methodDoc =
+ lookupWorkflowMethodDoc(parentPath, name) ||
+ lookupMethodDoc(name, parentValue);
+ if (methodDoc) {
+ return makeTooltip(jsNode, renderTooltipContent(methodDoc));
+ }
+
+ const path = resolveNodeValue(memberExpr, doc);
+ const value = walkScope(scope, path);
+ if (value !== undefined) {
+ const typeStr = Array.isArray(value) ? "array" : typeof value;
+ const label =
+ typeStr === "string" && value.length < 60
+ ? `${name}: "${value}"`
+ : `${name}: ${typeStr}`;
+ return makeTooltip(jsNode, renderTooltipContent({ label }));
+ }
+ }
+ }
+
+ const varDoc = lookupDollarVarDoc(name);
+ if (varDoc) {
+ return makeTooltip(
+ jsNode,
+ renderTooltipContent({ ...varDoc, label: name })
+ );
+ }
+
+ const globalDoc = globalDocs.get(name);
+ if (globalDoc) {
+ return makeTooltip(jsNode, renderTooltipContent(globalDoc));
+ }
+
+ return null;
+ },
+ { hoverTime: 400 }
+ );
+}
+
+function buildArgumentInfo(
+ { cmAutocomplete, cmLanguage, cmState, cmView, utils },
+ { scope }
+) {
+ const { completionStatus } = cmAutocomplete;
+ const { syntaxTree } = cmLanguage;
+ const { StateField } = cmState;
+ const { showTooltip } = cmView;
+ const { resolveNodeValue, lookupMethodDoc } = utils;
+
+ function findCallContext(state, pos) {
+ const tree = syntaxTree(state);
+ const doc = state.doc;
+ let node = tree.resolveInner(pos, -1);
+
+ while (node) {
+ if (node.name === "ArgList") {
+ const call = node.parent;
+ if (!call || call.name !== "CallExpression") {
+ return null;
+ }
+
+ const callee = call.firstChild;
+ if (!callee) {
+ return null;
+ }
+
+ if (
+ callee.name === "VariableName" &&
+ doc.sliceString(callee.from, callee.to) === "$"
+ ) {
+ return null;
+ }
+
+ let methodName;
+ let parentPath;
+
+ if (callee.name === "MemberExpression") {
+ const prop = callee.lastChild;
+ if (prop?.name === "PropertyName") {
+ methodName = doc.sliceString(prop.from, prop.to);
+ parentPath = resolveNodeValue(callee.firstChild, doc);
+ }
+ } else if (callee.name === "VariableName") {
+ methodName = doc.sliceString(callee.from, callee.to);
+ }
+
+ if (!methodName) {
+ return null;
+ }
+
+ let argIndex = 0;
+ for (let child = node.firstChild; child; child = child.nextSibling) {
+ if (child.name === "," && child.to <= pos) {
+ argIndex++;
+ }
+ }
+
+ return { methodName, parentPath, argIndex, callFrom: call.from };
+ }
+ node = node.parent;
+ }
+ return null;
+ }
+
+ function buildTooltipForCall(ctx, pos) {
+ const parentValue = ctx.parentPath
+ ? walkScope(scope, ctx.parentPath)
+ : null;
+ const doc =
+ lookupWorkflowMethodDoc(ctx.parentPath, ctx.methodName) ||
+ lookupMethodDoc(ctx.methodName, parentValue);
+ if (!doc?.info) {
+ return null;
+ }
+
+ const content = typeof doc.info === "function" ? doc.info(doc) : null;
+ if (!content) {
+ return null;
+ }
+
+ return {
+ pos,
+ above: true,
+ strictSide: true,
+ create: () => ({ dom: content }),
+ };
+ }
+
+ return StateField.define({
+ create: () => ({ tooltip: null, callFrom: null }),
+ update(prev, tr) {
+ if (!tr.docChanged && !tr.selection) {
+ return prev;
+ }
+
+ if (completionStatus(tr.state) === "active") {
+ return { tooltip: null, callFrom: null };
+ }
+
+ const { head } = tr.state.selection.ranges[0];
+ const ctx = findCallContext(tr.state, head);
+ if (!ctx) {
+ return { tooltip: null, callFrom: null };
+ }
+
+ if (prev.callFrom === ctx.callFrom) {
+ return prev;
+ }
+
+ return {
+ tooltip: buildTooltipForCall(ctx, head),
+ callFrom: ctx.callFrom,
+ };
+ },
+ provide: (f) => showTooltip.compute([f], (state) => state.field(f).tooltip),
+ });
+}
+
+function buildDragDrop({ cmLanguage, cmView }, { itemPrefix }) {
+ const { ensureSyntaxTree } = cmLanguage;
+ const { dropCursor, EditorView } = cmView;
+
+ return [
+ dropCursor(),
+ EditorView.domEventHandlers({
+ dragover(event) {
+ if (event.dataTransfer.types.includes(WORKFLOW_VARIABLE_MIME)) {
+ event.preventDefault();
+ event.dataTransfer.dropEffect = "copy";
+ }
+ },
+ drop(event, view) {
+ const data = event.dataTransfer.getData(WORKFLOW_VARIABLE_MIME);
+ if (!data) {
+ return false;
+ }
+
+ event.preventDefault();
+
+ let variable;
+ try {
+ variable = JSON.parse(data);
+ } catch {
+ return false;
+ }
+
+ const variableId = resolveVariableId(variable, itemPrefix);
+
+ let pos = view.posAtCoords({ x: event.clientX, y: event.clientY });
+ if (pos === null) {
+ pos = view.state.doc.length;
+ }
+
+ let inside = false;
+ const tree = ensureSyntaxTree(view.state, view.state.doc.length, 100);
+ if (tree) {
+ for (const side of [-1, 1]) {
+ let n = tree.resolve(pos, side);
+ while (n) {
+ if (n.name === "Expression") {
+ inside = pos > n.from + 2 && pos < n.to - 2;
+ break;
+ }
+ n = n.parent;
+ }
+ if (inside) {
+ break;
+ }
+ }
+ }
+ const insert = inside ? variableId : `{{ ${variableId} }}`;
+ view.dispatch({
+ changes: { from: pos, insert },
+ selection: { anchor: pos, head: pos + insert.length },
+ });
+ view.focus();
+
+ return true;
+ },
+ }),
+ ];
+}
+
+function buildValidation({ cmLanguage, cmView }) {
+ const { syntaxTree } = cmLanguage;
+ const { Decoration, ViewPlugin } = cmView;
+
+ const errorMark = Decoration.mark({ class: "cm-wf-error" });
+
+ return ViewPlugin.fromClass(
+ class {
+ decorations;
+
+ constructor(view) {
+ this.decorations = this.build(view.state);
+ }
+
+ update(update) {
+ if (update.docChanged || update.startState.tree !== update.state.tree) {
+ this.decorations = this.build(update.state);
+ }
+ }
+
+ build(state) {
+ const widgets = [];
+ const tree = syntaxTree(state);
+ const docLen = state.doc.length;
+
+ tree.iterate({
+ enter(node) {
+ if (node.name === "Expression") {
+ const text = state.doc.sliceString(node.from, node.to);
+ if (!text.endsWith("}}")) {
+ widgets.push(errorMark.range(node.from, docLen));
+ }
+ }
+ },
+ });
+
+ return Decoration.set(widgets, true);
+ }
+ },
+ { decorations: (v) => v.decorations }
+ );
+}
+
+function buildAutoCloseBraces({ cmAutocomplete, cmView }) {
+ const { startCompletion } = cmAutocomplete;
+ const { EditorView } = cmView;
+
+ return EditorView.inputHandler.of((view, from, to, text) => {
+ if (text !== "{") {
+ return false;
+ }
+
+ const before = view.state.doc.sliceString(Math.max(0, from - 1), from);
+ if (before !== "{") {
+ return false;
+ }
+
+ const after = view.state.doc.sliceString(to, to + 2);
+ if (after === "}}") {
+ // Already have closing braces — just insert the space and move cursor in
+ view.dispatch({
+ changes: { from, to, insert: "{ " },
+ selection: { anchor: from + 2 },
+ });
+ } else {
+ view.dispatch({
+ changes: { from, to, insert: "{ }}" },
+ selection: { anchor: from + 2 },
+ });
+ }
+
+ startCompletion(view);
+
+ return true;
+ });
+}
+
+function buildExpressionDecorations({ cmState, cmView }) {
+ const { StateEffect, StateField } = cmState;
+ const { Decoration, EditorView } = cmView;
+
+ const MARKS = {
+ valid: Decoration.mark({ class: "cm-wf-valid-expression" }),
+ invalid: Decoration.mark({ class: "cm-wf-invalid-expression" }),
+ undefined: Decoration.mark({ class: "cm-wf-invalid-expression" }),
+ empty: Decoration.mark({ class: "cm-wf-empty-expression" }),
+ warning: Decoration.mark({ class: "cm-wf-warning-expression" }),
+ pending: Decoration.mark({ class: "cm-wf-pending-expression" }),
+ };
+
+ const setSegmentsEffect = StateEffect.define();
+
+ const field = StateField.define({
+ create() {
+ return Decoration.none;
+ },
+ update(decorations, tr) {
+ decorations = decorations.map(tr.changes);
+
+ for (const effect of tr.effects) {
+ if (effect.is(setSegmentsEffect)) {
+ const ranges = effect.value.filter(
+ (seg) =>
+ seg.kind === "resolved" &&
+ seg.from !== undefined &&
+ seg.to !== undefined
+ );
+ decorations = ranges.length
+ ? Decoration.set(
+ ranges.map(({ from, to, state }) =>
+ (MARKS[state] || MARKS.invalid).range(from, to)
+ ),
+ true
+ )
+ : Decoration.none;
+ }
+ }
+
+ return decorations;
+ },
+ provide: (f) => EditorView.decorations.from(f),
+ });
+
+ return { field, setSegmentsEffect };
+}
+
+function buildTheme({ cmLanguage, lezerHighlight }) {
+ const { HighlightStyle, syntaxHighlighting } = cmLanguage;
+ const { tags } = lezerHighlight;
+
+ return syntaxHighlighting(
+ HighlightStyle.define([
+ { tag: tags.content, class: "cm-wf-text" },
+ { tag: tags.brace, class: "cm-wf-brace" },
+ { tag: tags.keyword, class: "cm-wf-keyword" },
+ { tag: tags.string, class: "cm-wf-string" },
+ { tag: tags.number, class: "cm-wf-number" },
+ { tag: tags.bool, class: "cm-wf-bool" },
+ { tag: tags.null, class: "cm-wf-null" },
+ { tag: tags.variableName, class: "cm-wf-variable" },
+ { tag: tags.propertyName, class: "cm-wf-property" },
+ { tag: tags.function(tags.variableName), class: "cm-wf-function" },
+ { tag: tags.function(tags.propertyName), class: "cm-wf-function" },
+ { tag: tags.operator, class: "cm-wf-operator" },
+ { tag: tags.punctuation, class: "cm-wf-punctuation" },
+ { tag: tags.comment, class: "cm-wf-comment" },
+ ])
+ );
+}
+
+function buildExpressionValidator(
+ { cmView },
+ { setSegmentsEffect, workflowId, nodeId, onSegmentsResolved }
+) {
+ const { ViewPlugin } = cmView;
+
+ return ViewPlugin.fromClass(
+ class {
+ timeout = null;
+ destroyed = false;
+
+ constructor(view) {
+ this.view = view;
+ if (workflowId && nodeId && view.state.doc.toString()) {
+ this.evaluate();
+ }
+ }
+
+ update(update) {
+ if (update.docChanged) {
+ this.scheduleEvaluation();
+ } else if (
+ update.focusChanged &&
+ update.view.hasFocus &&
+ update.view.state.doc.toString()
+ ) {
+ this.evaluate();
+ }
+ }
+
+ scheduleEvaluation() {
+ clearTimeout(this.timeout);
+ const template = this.view.state.doc.toString();
+ if (!template) {
+ this.timeout = setTimeout(() => this.dispatch([]), 0);
+ return;
+ }
+ this.timeout = setTimeout(() => this.evaluate(), 500);
+ }
+
+ async evaluate() {
+ const template = this.view.state.doc.toString();
+ try {
+ const result = await ajax(
+ "/admin/plugins/discourse-workflows/expressions/evaluate.json",
+ {
+ type: "POST",
+ data: { template, workflow_id: workflowId, node_id: nodeId },
+ }
+ );
+
+ if (this.destroyed || template !== this.view.state.doc.toString()) {
+ return;
+ }
+
+ this.dispatch(result.segments || []);
+ } catch {
+ if (this.destroyed) {
+ return;
+ }
+ this.dispatch([]);
+ }
+ }
+
+ dispatch(segments) {
+ this.view.dispatch({
+ effects: setSegmentsEffect.of(segments),
+ });
+ onSegmentsResolved?.(segments);
+ }
+
+ destroy() {
+ clearTimeout(this.timeout);
+ this.destroyed = true;
+ }
+ }
+ );
+}
+
+export default function workflowExtension(cmParams, domainOpts = {}) {
+ const itemPrefix = domainOpts.itemPrefix || "$json";
+ const analyzeAtCursor = buildAnalyzeAtCursor(cmParams);
+ const SECTION_NODES = cmParams.utils.section("Previous nodes", 1);
+ const sections = { ...cmParams.utils.sections, nodes: SECTION_NODES };
+
+ const scope = buildScope(domainOpts);
+ const ancestorNodes = domainOpts.ancestorNodes || [];
+ const completionOpts = { scope, ancestorNodes, analyzeAtCursor, sections };
+
+ const { field: decorationsField, setSegmentsEffect } =
+ buildExpressionDecorations(cmParams);
+
+ return [
+ cmParams.utils.expressionLanguage(),
+ buildTheme(cmParams),
+ buildValidation(cmParams),
+ buildAutoCloseBraces(cmParams),
+ ...buildDragDrop(cmParams, { itemPrefix }),
+ ...buildCompletions(cmParams, completionOpts),
+ buildHoverTooltip(cmParams, completionOpts),
+ buildArgumentInfo(cmParams, completionOpts),
+ decorationsField,
+ buildExpressionValidator(cmParams, {
+ setSegmentsEffect,
+ workflowId: domainOpts.workflowId,
+ nodeId: domainOpts.nodeId,
+ onSegmentsResolved: domainOpts.onSegmentsResolved,
+ }),
+ ];
+}
diff --git a/plugins/discourse-workflows/admin/assets/javascripts/admin/lib/workflows/condition-operators.js b/plugins/discourse-workflows/admin/assets/javascripts/admin/lib/workflows/condition-operators.js
new file mode 100644
index 00000000000..3a820a4a699
--- /dev/null
+++ b/plugins/discourse-workflows/admin/assets/javascripts/admin/lib/workflows/condition-operators.js
@@ -0,0 +1,92 @@
+const OPERATORS = {
+ equals: {
+ contexts: {
+ workflow: ["string", "number", "boolean"],
+ data_table: ["string", "number", "date"],
+ },
+ needsValue: true,
+ },
+ notEquals: {
+ contexts: {
+ workflow: ["string", "number", "boolean"],
+ data_table: ["string", "number", "date"],
+ },
+ needsValue: true,
+ },
+ contains: {
+ contexts: { workflow: ["string", "array"], data_table: ["string"] },
+ needsValue: true,
+ },
+ notContains: {
+ contexts: { workflow: ["string", "array"], data_table: ["string"] },
+ needsValue: true,
+ },
+ empty: {
+ contexts: {
+ workflow: ["string", "array"],
+ data_table: ["string", "number", "boolean", "date"],
+ },
+ needsValue: false,
+ implicitValue: null,
+ },
+ notEmpty: {
+ contexts: {
+ workflow: ["string", "array"],
+ data_table: ["string", "number", "boolean", "date"],
+ },
+ needsValue: false,
+ implicitValue: null,
+ },
+ gt: {
+ contexts: {
+ workflow: ["number"],
+ data_table: ["string", "number", "date"],
+ },
+ needsValue: true,
+ },
+ lt: {
+ contexts: {
+ workflow: ["number"],
+ data_table: ["string", "number", "date"],
+ },
+ needsValue: true,
+ },
+ gte: {
+ contexts: {
+ workflow: ["number"],
+ data_table: ["string", "number", "date"],
+ },
+ needsValue: true,
+ },
+ lte: {
+ contexts: {
+ workflow: ["number"],
+ data_table: ["string", "number", "date"],
+ },
+ needsValue: true,
+ },
+ true: {
+ contexts: { workflow: ["boolean"], data_table: ["boolean"] },
+ needsValue: false,
+ implicitValue: true,
+ },
+ false: {
+ contexts: { workflow: ["boolean"], data_table: ["boolean"] },
+ needsValue: false,
+ implicitValue: false,
+ },
+};
+
+export function operatorsForType(type, { context = "workflow" } = {}) {
+ return Object.keys(OPERATORS).filter((op) =>
+ OPERATORS[op].contexts[context]?.includes(type || "string")
+ );
+}
+
+export function isSingleValueOperator(operation) {
+ return OPERATORS[operation] !== undefined && !OPERATORS[operation].needsValue;
+}
+
+export function implicitValueFor(operation) {
+ return OPERATORS[operation]?.implicitValue;
+}
diff --git a/plugins/discourse-workflows/admin/assets/javascripts/admin/lib/workflows/control-registry.js b/plugins/discourse-workflows/admin/assets/javascripts/admin/lib/workflows/control-registry.js
new file mode 100644
index 00000000000..68ef970aa50
--- /dev/null
+++ b/plugins/discourse-workflows/admin/assets/javascripts/admin/lib/workflows/control-registry.js
@@ -0,0 +1,16 @@
+import AssignmentCollection from "../../components/workflows/configurators/assignment-collection";
+import Collection from "../../components/workflows/configurators/collection";
+import FixedCollection from "../../components/workflows/configurators/fixed-collection";
+import FIELD_CONTROL_REGISTRY from "./field-control-registry";
+
+const CONTROL_REGISTRY = {
+ collection: { kind: "structural", renderer: Collection },
+ fixed_collection: { kind: "structural", renderer: FixedCollection },
+ assignment_collection: {
+ kind: "structural",
+ renderer: AssignmentCollection,
+ },
+ ...FIELD_CONTROL_REGISTRY,
+};
+
+export default CONTROL_REGISTRY;
diff --git a/plugins/discourse-workflows/admin/assets/javascripts/admin/lib/workflows/data-schema.js b/plugins/discourse-workflows/admin/assets/javascripts/admin/lib/workflows/data-schema.js
new file mode 100644
index 00000000000..b6ed9ff4c35
--- /dev/null
+++ b/plugins/discourse-workflows/admin/assets/javascripts/admin/lib/workflows/data-schema.js
@@ -0,0 +1,416 @@
+import {
+ normalizeSourceOutputIndex,
+ normalizeTargetInputIndex,
+} from "./graph-constants";
+
+const TYPE_EXEMPLARS = {
+ string: "",
+ integer: 0,
+ number: 0,
+ boolean: false,
+ array: [],
+ object: {},
+ null: null,
+ unknown: null,
+};
+
+function classifyValue(value) {
+ if (Array.isArray(value)) {
+ return "array";
+ }
+
+ if (value === null || value === undefined) {
+ return value === null ? "null" : "unknown";
+ }
+
+ if (typeof value === "number") {
+ return "number";
+ }
+
+ if (typeof value === "boolean") {
+ return "boolean";
+ }
+
+ if (typeof value === "object") {
+ return "object";
+ }
+
+ return "string";
+}
+
+function propertySegment(key) {
+ return /^[A-Za-z_$][\w$]*$/.test(key)
+ ? `.${key}`
+ : `[${JSON.stringify(key)}]`;
+}
+
+export function nodeItemJsonPath(nodeName) {
+ return `$(${JSON.stringify(nodeName)}).item.json`;
+}
+
+export function nodeOutputItemJsonPath(
+ nodeName,
+ { outputIndex = 0, itemIndex = "$itemIndex" } = {}
+) {
+ return `$(${JSON.stringify(nodeName)}).all(${outputIndex})[${itemIndex}].json`;
+}
+
+export function inputFieldPrefixForConnection(
+ connection,
+ previousNode,
+ { primaryConnection, itemPrefix = "$json" } = {}
+) {
+ if (!connection || connection === primaryConnection || !previousNode?.name) {
+ return itemPrefix;
+ }
+
+ return nodeOutputItemJsonPath(previousNode.name, {
+ outputIndex: outputIndexForConnection(connection),
+ });
+}
+
+export function outputIndexForConnection(connection) {
+ return normalizeSourceOutputIndex(connection);
+}
+
+export function inputIndexForConnection(connection) {
+ return normalizeTargetInputIndex(connection);
+}
+
+function arraySegment(index) {
+ return `[${index}]`;
+}
+
+function compactObject(obj) {
+ return Object.fromEntries(
+ Object.entries(obj).filter(([, value]) => value !== undefined)
+ );
+}
+
+function representativeValue(values) {
+ const presentValue = values.find(
+ (value) => value !== undefined && value !== null
+ );
+ if (presentValue !== undefined) {
+ return presentValue;
+ }
+
+ return values.includes(null) ? null : undefined;
+}
+
+function childValuesForObject(values, childKey) {
+ return values.map((value) =>
+ value && typeof value === "object" && !Array.isArray(value)
+ ? value[childKey]
+ : undefined
+ );
+}
+
+function childValuesForArray(values, index) {
+ return values.map((value) =>
+ Array.isArray(value) ? value[index] : undefined
+ );
+}
+
+function schemaFromValues(values, key, path) {
+ const value = representativeValue(values);
+ const type = classifyValue(value);
+ const field = compactObject({
+ key,
+ id: path,
+ type,
+ value,
+ });
+
+ if (type === "object") {
+ const childKeys = new Set();
+ for (const candidate of values) {
+ if (
+ candidate &&
+ typeof candidate === "object" &&
+ !Array.isArray(candidate)
+ ) {
+ Object.keys(candidate).forEach((childKey) => childKeys.add(childKey));
+ }
+ }
+ field.children = [...childKeys].map((childKey) =>
+ schemaFromValues(
+ childValuesForObject(values, childKey),
+ childKey,
+ `${path}${propertySegment(childKey)}`
+ )
+ );
+ }
+
+ if (type === "array") {
+ const childIndexes = new Set();
+ for (const candidate of values) {
+ if (Array.isArray(candidate)) {
+ candidate.forEach((_, index) => childIndexes.add(index));
+ }
+ }
+ field.children = [...childIndexes].map((index) =>
+ schemaFromValues(
+ childValuesForArray(values, index),
+ index.toString(),
+ `${path}${arraySegment(index)}`
+ )
+ );
+ }
+
+ return field;
+}
+
+export function schemaFieldsForItems(items = [], { prefix = "$json" } = {}) {
+ const jsonItems = items
+ .map((item) => item?.json)
+ .filter((json) => json && typeof json === "object" && !Array.isArray(json));
+
+ const keys = new Set();
+ jsonItems.forEach((json) =>
+ Object.keys(json).forEach((key) => keys.add(key))
+ );
+
+ const jsonFields = [...keys].map((key) =>
+ schemaFromValues(
+ jsonItems.map((json) => json[key]),
+ key,
+ `${prefix}${propertySegment(key)}`
+ )
+ );
+
+ return jsonFields;
+}
+
+export function exemplarFromFields(fields = []) {
+ const obj = Object.create(null);
+
+ for (const field of fields) {
+ if (field.type === "object" && field.children?.length) {
+ obj[field.key] = exemplarFromFields(field.children);
+ } else if (field.type === "array" && field.children?.length) {
+ const child = field.children[0];
+ if (child?.type === "object") {
+ obj[field.key] = [exemplarFromFields(child.children || [])];
+ } else if (child?.value !== undefined) {
+ obj[field.key] = [child.value];
+ } else {
+ obj[field.key] = [TYPE_EXEMPLARS[child?.type] ?? TYPE_EXEMPLARS.string];
+ }
+ } else if (field.value !== undefined) {
+ obj[field.key] = field.value;
+ } else {
+ obj[field.key] = TYPE_EXEMPLARS[field.type] ?? TYPE_EXEMPLARS.string;
+ }
+ }
+
+ return obj;
+}
+
+function latestSuccessfulRun(runData, nodeName) {
+ const runs = (runData?.[nodeName] || []).filter(
+ (run) => run.status === "success"
+ );
+ if (!runs?.length) {
+ return null;
+ }
+
+ return runs[runs.length - 1] || null;
+}
+
+export function latestRunWithOutput(runData, nodeName) {
+ return latestSuccessfulRun(runData, nodeName);
+}
+
+export function latestRunWithInput(runData, nodeName) {
+ return latestSuccessfulRun(runData, nodeName);
+}
+
+function portForRun(run, portKey, portIndex = 0) {
+ if (!run) {
+ return null;
+ }
+
+ return (run[portKey] || []).find((port) => port.index === portIndex) || null;
+}
+
+export function outputForRun(run, outputIndex = 0) {
+ return portForRun(run, "outputs", outputIndex);
+}
+
+export function inputForRun(run, inputIndex = 0) {
+ return portForRun(run, "inputs", inputIndex);
+}
+
+export function schemaFieldsForNodeOutput(
+ runData,
+ nodeName,
+ { outputIndex = 0, prefix = "$json" } = {}
+) {
+ const run = latestRunWithOutput(runData, nodeName, outputIndex);
+ const output = outputForRun(run, outputIndex);
+ return schemaFieldsForItems(output?.items || [], { prefix });
+}
+
+export function schemaFieldsForNodeInput(
+ runData,
+ nodeName,
+ { inputIndex = 0, prefix = "$json" } = {}
+) {
+ const run = latestRunWithInput(runData, nodeName, inputIndex);
+ const input = inputForRun(run, inputIndex);
+ return schemaFieldsForItems(input?.items || [], { prefix });
+}
+
+function portSummary(port, indexKey) {
+ if (!port) {
+ return null;
+ }
+
+ return {
+ [indexKey]: port.index,
+ itemCount: port.item_count ?? port.items?.length ?? 0,
+ truncated: port.truncated === true,
+ };
+}
+
+export function outputSummaryForNode(runData, nodeName, outputIndex = 0) {
+ const run = latestRunWithOutput(runData, nodeName, outputIndex);
+ return portSummary(outputForRun(run, outputIndex), "outputIndex");
+}
+
+export function inputSummaryForNode(runData, nodeName, inputIndex = 0) {
+ const run = latestRunWithInput(runData, nodeName, inputIndex);
+ return portSummary(inputForRun(run, inputIndex), "inputIndex");
+}
+
+function combinedPortSummary(ports, itemCount) {
+ if (!ports) {
+ return null;
+ }
+
+ return {
+ itemCount,
+ truncated: ports.some((port) => port.truncated === true),
+ };
+}
+
+function outputPreviewItems(outputs) {
+ if (outputs.length <= 1) {
+ return outputs[0]?.items || [];
+ }
+
+ return outputs
+ .map((output) => output.items?.find((item) => item))
+ .filter(Boolean);
+}
+
+function outputPreviewItemCount(outputs, items) {
+ if (outputs.length <= 1) {
+ return outputs[0]?.item_count ?? items.length;
+ }
+
+ return items.length ? 1 : 0;
+}
+
+export function outputSchemaForNode(runData, nodeName, { pinnedItems } = {}) {
+ if (Array.isArray(pinnedItems) && pinnedItems.length > 0) {
+ return {
+ summary: {
+ itemCount: pinnedItems.length,
+ truncated: false,
+ pinned: true,
+ },
+ fields: schemaFieldsForItems(pinnedItems, { prefix: "$json" }),
+ };
+ }
+
+ const run = latestRunWithOutput(runData, nodeName);
+ if (!run) {
+ return { summary: null, fields: [] };
+ }
+
+ const outputs = run.outputs || [];
+ const items = outputPreviewItems(outputs);
+
+ return {
+ summary: combinedPortSummary(
+ outputs,
+ outputPreviewItemCount(outputs, items)
+ ),
+ fields: schemaFieldsForItems(items, { prefix: "$json" }),
+ };
+}
+
+export function inputConnectionsForNode(node, graph, visited = new Set()) {
+ if (!node) {
+ return [];
+ }
+
+ return (graph.connections || [])
+ .filter(
+ (connection) =>
+ connection.targetClientId === node.clientId &&
+ connection.sourceClientId !== node.clientId &&
+ !visited.has(connection.sourceClientId)
+ )
+ .sort((left, right) => {
+ return (
+ inputIndexForConnection(left) - inputIndexForConnection(right) ||
+ left.sourceClientId.localeCompare(right.sourceClientId) ||
+ outputIndexForConnection(left) - outputIndexForConnection(right)
+ );
+ });
+}
+
+export function previousConnectionForNode(node, graph, visited = new Set()) {
+ const connections = inputConnectionsForNode(node, graph, visited);
+ return connections[0] || null;
+}
+
+export function previousNodeForConnection(connection, graph) {
+ if (!connection) {
+ return null;
+ }
+
+ return (
+ (graph.nodes || []).find(
+ (node) => node.clientId === connection.sourceClientId
+ ) || null
+ );
+}
+
+export function ancestorOutputNodes(node, graph) {
+ const ancestors = [];
+ const visitedNodes = new Set(node ? [node.clientId] : []);
+ const seenAncestors = new Set();
+ const pendingConnections = inputConnectionsForNode(node, graph);
+
+ while (pendingConnections.length) {
+ const connection = pendingConnections.shift();
+ const previous = previousNodeForConnection(connection, graph);
+ if (!previous) {
+ continue;
+ }
+
+ const outputIndex = normalizeSourceOutputIndex(connection);
+ const key = `${previous.clientId}:${outputIndex}`;
+ if (!seenAncestors.has(key)) {
+ seenAncestors.add(key);
+ ancestors.push({
+ node: previous,
+ outputIndex,
+ });
+ }
+
+ if (visitedNodes.has(previous.clientId)) {
+ continue;
+ }
+ visitedNodes.add(previous.clientId);
+ pendingConnections.push(
+ ...inputConnectionsForNode(previous, graph, visitedNodes)
+ );
+ }
+
+ return ancestors;
+}
diff --git a/plugins/discourse-workflows/admin/assets/javascripts/admin/lib/workflows/editor-session.js b/plugins/discourse-workflows/admin/assets/javascripts/admin/lib/workflows/editor-session.js
new file mode 100644
index 00000000000..b21befa68aa
--- /dev/null
+++ b/plugins/discourse-workflows/admin/assets/javascripts/admin/lib/workflows/editor-session.js
@@ -0,0 +1,308 @@
+import { tracked } from "@glimmer/tracking";
+import { ajax } from "discourse/lib/ajax";
+
+function compactObject(object) {
+ return Object.fromEntries(
+ Object.entries(object).filter(([, value]) => value !== undefined)
+ );
+}
+
+function normalizeNodeForLoadOptions(node, identifier, typeVersion) {
+ return compactObject({
+ id: node?.clientId || node?.id,
+ name: node?.name,
+ type: node?.type || identifier,
+ typeVersion: node?.typeVersion || typeVersion,
+ });
+}
+
+function portIndexFromKey(value) {
+ value = value?.toString();
+ if (!value || value === "main" || value === "true" || value === "done") {
+ return 0;
+ }
+
+ const inputMatch = value.match(/^input_(\d+)$/);
+ if (inputMatch) {
+ return parseInt(inputMatch[1], 10) - 1;
+ }
+
+ if (value === "false" || value === "loop") {
+ return 1;
+ }
+
+ return parseInt(value, 10) || 0;
+}
+
+function sourceOutputIndexForConnection(connection) {
+ return (
+ connection.sourceOutputIndex ?? portIndexFromKey(connection.sourceOutput)
+ );
+}
+
+function targetInputIndexForConnection(connection) {
+ return (
+ connection.targetInputIndex ?? portIndexFromKey(connection.targetInput)
+ );
+}
+
+function latestPortItems(runs, portKey, portIndex) {
+ const run = [...(runs || [])]
+ .reverse()
+ .find(
+ (candidate) =>
+ candidate.status === "success" &&
+ (candidate[portKey] || []).some(
+ (port) => port.index === portIndex && Array.isArray(port.items)
+ )
+ );
+ const port = (run?.[portKey] || []).find(
+ (candidate) => candidate.index === portIndex
+ );
+ return port?.items;
+}
+
+export default class WorkflowEditorSession {
+ @tracked workflowId = null;
+ @tracked editingNode = null;
+ @tracked graphNodes = null;
+ @tracked graphConnections = null;
+ @tracked lastExecutionRunData = null;
+ @tracked pinData = {};
+ @tracked webhookTestListeners = {};
+
+ constructor({
+ workflowId = null,
+ lastExecutionRunData = null,
+ pinData = {},
+ } = {}) {
+ this.workflowId = workflowId;
+ this.lastExecutionRunData = lastExecutionRunData;
+ this.pinData = pinData || {};
+ }
+
+ setEditingContext(node, nodes, connections) {
+ this.editingNode = node;
+ this.graphNodes = nodes;
+ this.graphConnections = connections;
+ }
+
+ clearEditingContext() {
+ this.editingNode = null;
+ this.graphNodes = null;
+ this.graphConnections = null;
+ }
+
+ nodeParameterOptionsContext(context = {}) {
+ const resolvedNode = context.node || this.editingNode;
+ const resolvedVersion = context.typeVersion || resolvedNode?.typeVersion;
+
+ return compactObject({
+ ...context,
+ node: normalizeNodeForLoadOptions(
+ resolvedNode,
+ context.identifier,
+ resolvedVersion
+ ),
+ workflowId: this.workflowId,
+ inputContext:
+ context.inputContext === undefined
+ ? this.inputContextForNode(resolvedNode)
+ : context.inputContext,
+ executionContext:
+ context.executionContext === undefined
+ ? this.executionContextForNode(resolvedNode)
+ : context.executionContext,
+ });
+ }
+
+ inputContextForNode(node = this.editingNode) {
+ if (!node || !this.lastExecutionRunData) {
+ return {
+ available: false,
+ reason: "No editor execution preview is available for this node",
+ };
+ }
+
+ const incomingConnections = (this.graphConnections || []).filter(
+ (connection) => connection.targetClientId === node.clientId
+ );
+ const resolvedInputs = incomingConnections
+ .map((connection) => {
+ const inputIndex = targetInputIndexForConnection(connection);
+ const outputIndex = sourceOutputIndexForConnection(connection);
+ const sourceNode = this.nodeForClientId(connection.sourceClientId);
+ const currentInput = this.inputItemsForNode(node, inputIndex);
+
+ return {
+ sourceNodeId: connection.sourceClientId,
+ inputIndex,
+ items:
+ currentInput ?? this.outputItemsForNode(sourceNode, outputIndex),
+ };
+ })
+ .filter((input) => input.items !== undefined);
+ const sourceNodeOutputs = Object.fromEntries(
+ resolvedInputs.map((input) => [input.sourceNodeId, input.items])
+ );
+
+ if (Object.keys(sourceNodeOutputs).length === 0) {
+ return {
+ available: false,
+ reason:
+ "No upstream execution preview output is available for this node",
+ };
+ }
+
+ const primaryItems = resolvedInputs[0]?.items || [];
+
+ return {
+ available: true,
+ item: primaryItems[0],
+ items: primaryItems,
+ source_node_outputs: sourceNodeOutputs,
+ };
+ }
+
+ executionContextForNode(node = this.editingNode) {
+ const currentNodeOutput = node ? this.outputItemsForNode(node) : undefined;
+
+ return compactObject({
+ last_node_outputs: this.lastExecutionRunData || {},
+ current_node_output: currentNodeOutput,
+ });
+ }
+
+ pinnedItemsForNode(nodeName) {
+ if (!nodeName) {
+ return undefined;
+ }
+ const items = this.pinData?.[nodeName.toString()];
+ return Array.isArray(items) && items.length > 0 ? items : undefined;
+ }
+
+ isNodePinned(nodeName) {
+ return this.pinnedItemsForNode(nodeName) !== undefined;
+ }
+
+ async pinNodeData(nodeName, items) {
+ if (!this.workflowId) {
+ return;
+ }
+ await ajax(
+ `/admin/plugins/discourse-workflows/workflows/${this.workflowId}/pin-data.json`,
+ {
+ type: "PUT",
+ contentType: "application/json",
+ data: JSON.stringify({
+ node_name: nodeName,
+ items,
+ }),
+ }
+ );
+ this.pinData = { ...(this.pinData || {}), [nodeName]: items };
+ }
+
+ async unpinNodeData(nodeName) {
+ if (!this.workflowId) {
+ return;
+ }
+ await ajax(
+ `/admin/plugins/discourse-workflows/workflows/${this.workflowId}/pin-data.json`,
+ {
+ type: "PUT",
+ contentType: "application/json",
+ data: JSON.stringify({ node_name: nodeName }),
+ }
+ );
+ const next = { ...(this.pinData || {}) };
+ delete next[nodeName];
+ this.pinData = next;
+ }
+
+ webhookTestListenerForNode(nodeId) {
+ if (!nodeId) {
+ return null;
+ }
+
+ const listener = this.webhookTestListeners?.[nodeId.toString()];
+ if (!listener) {
+ return null;
+ }
+
+ if (listener.expiresAt && Date.parse(listener.expiresAt) <= Date.now()) {
+ return null;
+ }
+
+ return listener;
+ }
+
+ async startWebhookTestListener(nodeId) {
+ if (!this.workflowId || !nodeId) {
+ return null;
+ }
+
+ const result = await ajax(
+ `/admin/plugins/discourse-workflows/workflows/${this.workflowId}/webhook-test-listeners.json`,
+ {
+ type: "POST",
+ data: { trigger_node_id: nodeId },
+ }
+ );
+
+ const listener = {
+ listenerId: result.listener_id,
+ testUrl: result.test_url,
+ expiresAt: result.expires_at,
+ };
+ this.webhookTestListeners = {
+ ...(this.webhookTestListeners || {}),
+ [nodeId]: listener,
+ };
+ return listener;
+ }
+
+ async cancelWebhookTestListener(nodeId) {
+ const listener = this.webhookTestListenerForNode(nodeId);
+ if (!this.workflowId || !listener) {
+ return;
+ }
+
+ await ajax(
+ `/admin/plugins/discourse-workflows/workflows/${this.workflowId}/webhook-test-listeners/${listener.listenerId}.json`,
+ { type: "DELETE" }
+ );
+
+ this.clearWebhookTestListener(nodeId);
+ }
+
+ clearWebhookTestListener(nodeId) {
+ const next = { ...(this.webhookTestListeners || {}) };
+ delete next[nodeId];
+ this.webhookTestListeners = next;
+ }
+
+ outputItemsForNode(node, outputIndex = 0) {
+ if (outputIndex === 0) {
+ const pinned = this.pinnedItemsForNode(node?.name);
+ if (pinned) {
+ return pinned;
+ }
+ }
+
+ const runs = this.lastExecutionRunData?.[node?.name];
+ return latestPortItems(runs, "outputs", outputIndex);
+ }
+
+ inputItemsForNode(node, inputIndex = 0) {
+ const runs = this.lastExecutionRunData?.[node?.name];
+ return latestPortItems(runs, "inputs", inputIndex);
+ }
+
+ nodeForClientId(clientId) {
+ if (!clientId) {
+ return null;
+ }
+ return (this.graphNodes || []).find((n) => n.clientId === clientId) || null;
+ }
+}
diff --git a/plugins/discourse-workflows/admin/assets/javascripts/admin/lib/workflows/expression-context.js b/plugins/discourse-workflows/admin/assets/javascripts/admin/lib/workflows/expression-context.js
new file mode 100644
index 00000000000..973bd91f2a5
--- /dev/null
+++ b/plugins/discourse-workflows/admin/assets/javascripts/admin/lib/workflows/expression-context.js
@@ -0,0 +1,358 @@
+import { i18n } from "discourse-i18n";
+
+export const WORKFLOW_VARIABLE_MIME = "application/x-workflow-variable";
+
+const WORKFLOW_METHOD_DOCS = Object.freeze({
+ $input: Object.freeze({
+ all: Object.freeze({
+ detail: "()",
+ infoKey: "discourse_workflows.expression_docs.methods.input.all",
+ }),
+ first: Object.freeze({
+ detail: "()",
+ infoKey: "discourse_workflows.expression_docs.methods.input.first",
+ }),
+ last: Object.freeze({
+ detail: "()",
+ infoKey: "discourse_workflows.expression_docs.methods.input.last",
+ }),
+ }),
+});
+
+export function resolveVariableId(variable, itemPrefix = "$json") {
+ return variable.id.startsWith("$")
+ ? variable.id
+ : `${itemPrefix}.${variable.id}`;
+}
+
+// Matches paths like $('Node Name').rest or $("Node Name").rest
+const NODE_REF_RE = /^\$\((?:"((?:\\.|[^"\\])*)"|'((?:\\.|[^'\\])*)')\)/;
+const METHOD_CALL_RE = /^([A-Za-z_$][\w$]*)\((.*)\)$/;
+const METHOD_WITH_SUFFIX_RE = /^([A-Za-z_$][\w$]*)\((.*?)\)(.*)$/;
+const BRACKET_SUFFIX_RE =
+ /^\[((?:"(?:\\.|[^"\\])*")|(?:'(?:\\.|[^'\\])*')|[^\]]+)\](.*)$/;
+
+export function walkScope(scope, path) {
+ if (!path) {
+ return undefined;
+ }
+
+ const nodeRef = NODE_REF_RE.exec(path);
+ if (nodeRef) {
+ const nodeName = parseNodeReferenceName(nodeRef);
+ const rest = path.slice(nodeRef[0].length);
+ const parts = rest ? rest.slice(1).split(".") : []; // skip leading "."
+ let target;
+ try {
+ target = scope.$(nodeName);
+ } catch {
+ return undefined;
+ }
+ for (const part of parts) {
+ if (target == null) {
+ return undefined;
+ }
+ target = resolvePathPart(target, part, scope);
+ }
+ return target;
+ }
+
+ const parts = path.split(".");
+ let target = scope[parts[0]];
+ for (let i = 1; i < parts.length; i++) {
+ if (target == null) {
+ return undefined;
+ }
+ target = resolvePathPart(target, parts[i], scope);
+ }
+ return target;
+}
+
+function parseNodeReferenceName(nodeRef) {
+ const doubleQuoted = nodeRef[1] !== undefined;
+ const raw = doubleQuoted ? nodeRef[1] : nodeRef[2];
+
+ if (doubleQuoted) {
+ try {
+ return JSON.parse(`"${raw}"`);
+ } catch {
+ return raw;
+ }
+ }
+
+ return raw.replace(/\\([\\'])/g, "$1");
+}
+
+function resolvePathPart(target, part, scope) {
+ const methodWithSuffix = METHOD_WITH_SUFFIX_RE.exec(part);
+ if (methodWithSuffix && typeof target[methodWithSuffix[1]] === "function") {
+ return resolveBracketSuffix(
+ target[methodWithSuffix[1]](...parseMethodArgs(methodWithSuffix[2])),
+ methodWithSuffix[3],
+ scope
+ );
+ }
+
+ const methodCall = METHOD_CALL_RE.exec(part);
+ if (methodCall && typeof target[methodCall[1]] === "function") {
+ return target[methodCall[1]](...parseMethodArgs(methodCall[2]));
+ }
+
+ return target[part];
+}
+
+function resolveBracketSuffix(target, suffix, scope) {
+ let rest = suffix;
+ let value = target;
+
+ while (rest) {
+ const match = BRACKET_SUFFIX_RE.exec(rest);
+ if (!match || value == null) {
+ return undefined;
+ }
+
+ value = value[resolveBracketKey(match[1], scope)];
+ rest = match[2];
+ }
+
+ return value;
+}
+
+function resolveBracketKey(source, scope) {
+ const key = source.trim();
+
+ if (/^-?\d+$/.test(key)) {
+ return Number(key);
+ }
+
+ if (key.startsWith('"')) {
+ try {
+ return JSON.parse(key);
+ } catch {
+ return key.slice(1, -1);
+ }
+ }
+
+ if (key.startsWith("'")) {
+ return key.slice(1, -1).replace(/\\([\\'])/g, "$1");
+ }
+
+ return walkScope(scope, key);
+}
+
+function parseMethodArgs(source) {
+ const args = source.trim();
+ if (!args) {
+ return [];
+ }
+
+ return args.split(",").map((arg) => {
+ const value = arg.trim();
+ if (/^-?\d+(\.\d+)?$/.test(value)) {
+ return Number(value);
+ }
+
+ if (
+ (value.startsWith("'") && value.endsWith("'")) ||
+ (value.startsWith('"') && value.endsWith('"'))
+ ) {
+ return value.slice(1, -1);
+ }
+
+ return undefined;
+ });
+}
+
+const TYPE_EXEMPLARS = {
+ string: "",
+ integer: 0,
+ number: 0,
+ boolean: false,
+ array: [],
+ object: {},
+ null: null,
+ unknown: null,
+};
+
+function cleanObject(obj) {
+ const clean = Object.create(null);
+ for (const [key, value] of Object.entries(obj)) {
+ clean[key] = value;
+ }
+ return clean;
+}
+
+function buildItem(json) {
+ return cleanObject({ json });
+}
+
+function buildNodeOutput(json) {
+ const item = buildItem(json);
+ const items = [item];
+
+ return cleanObject({
+ item,
+ all: () => items,
+ first: () => item,
+ last: () => item,
+ itemMatching: () => item,
+ pairedItem: () => item,
+ context: Object.create(null),
+ params: Object.create(null),
+ });
+}
+
+const EMPTY_NODE_OUTPUT = buildNodeOutput(Object.create(null));
+
+export function lookupWorkflowMethodDoc(parentPath, methodName) {
+ const doc = WORKFLOW_METHOD_DOCS[parentPath]?.[methodName];
+ if (!doc) {
+ return null;
+ }
+ return { detail: doc.detail, info: i18n(doc.infoKey) };
+}
+
+function buildScopeFromFields(fields) {
+ if (!fields?.length) {
+ return Object.create(null);
+ }
+
+ const obj = Object.create(null);
+ for (const field of fields) {
+ if (field.type === "array") {
+ const child = field.children?.[0];
+ if (!child) {
+ obj[field.key] = [];
+ } else if (child.type === "object") {
+ obj[field.key] = [buildScopeFromFields(child.children || [])];
+ } else if (child?.value !== undefined) {
+ obj[field.key] = [child.value];
+ } else {
+ obj[field.key] = [TYPE_EXEMPLARS[child?.type] ?? TYPE_EXEMPLARS.string];
+ }
+ } else if (field.children?.length) {
+ obj[field.key] = buildScopeFromFields(field.children);
+ } else if (field.value !== undefined) {
+ obj[field.key] = field.value;
+ } else {
+ obj[field.key] = TYPE_EXEMPLARS[field.type] ?? TYPE_EXEMPLARS.string;
+ }
+ }
+ return obj;
+}
+
+function buildSiteSettingsScope(siteSettings) {
+ if (!siteSettings) {
+ return Object.create(null);
+ }
+
+ const scope = Object.create(null);
+ for (const key of Object.keys(siteSettings)) {
+ if (key.startsWith("_") || key.startsWith("theme")) {
+ continue;
+ }
+
+ const value = siteSettings[key];
+ const type = typeof value;
+
+ if (type === "function" || type === "symbol") {
+ continue;
+ }
+
+ scope[key] = value;
+ }
+ return scope;
+}
+
+function buildVarsScope(workflowVars) {
+ const scope = Object.create(null);
+ if (workflowVars?.length) {
+ for (const v of workflowVars) {
+ scope[v.key] = v.value ?? "";
+ }
+ }
+ return scope;
+}
+
+function buildExecutionScope(nodes) {
+ const scope = cleanObject({
+ id: 0,
+ workflow_id: 0,
+ workflow_name: "",
+ });
+
+ const hasWebhookWait = (nodes || []).some(
+ (n) => n.type === "flow:wait" && n.configuration?.resume === "webhook"
+ );
+
+ if (hasWebhookWait) {
+ scope.resume_url = "";
+ }
+
+ const hasFormPage = (nodes || []).some(
+ (n) =>
+ n.type === "action:form" && n.configuration?.page_type !== "completion"
+ );
+
+ if (hasFormPage) {
+ scope.resumeFormUrl = "";
+ }
+
+ return scope;
+}
+
+function buildInputScope($json) {
+ const currentItem = buildItem($json);
+ const inputItems = [currentItem];
+
+ return cleanObject({
+ item: currentItem,
+ all: () => inputItems,
+ first: () => currentItem,
+ last: () => currentItem,
+ params: Object.create(null),
+ context: Object.create(null),
+ });
+}
+
+export function buildScope({
+ inputFields = [],
+ ancestorNodes = [],
+ siteSettings,
+ workflowVars,
+ nodes,
+}) {
+ const $json = buildScopeFromFields(inputFields);
+ const $input = buildInputScope($json);
+
+ const nodeOutputs = Object.create(null);
+ for (const ancestor of ancestorNodes) {
+ const json = buildScopeFromFields(ancestor.fields);
+ nodeOutputs[ancestor.node.name] = buildNodeOutput(json);
+ }
+
+ return cleanObject({
+ $input,
+ $itemIndex: 0,
+ $json,
+ trigger: $json,
+ $site_settings: buildSiteSettingsScope(siteSettings),
+ $current_user: cleanObject({ id: 0, username: "" }),
+ $vars: buildVarsScope(workflowVars),
+ $execution: buildExecutionScope(nodes),
+ $: (name) => nodeOutputs[name] || EMPTY_NODE_OUTPUT,
+ JSON,
+ Math,
+ Object,
+ Array,
+ String,
+ Number,
+ Date,
+ parseInt,
+ parseFloat,
+ encodeURIComponent,
+ decodeURIComponent,
+ isNaN,
+ isFinite,
+ });
+}
diff --git a/plugins/discourse-workflows/admin/assets/javascripts/admin/lib/workflows/field-control-registry.js b/plugins/discourse-workflows/admin/assets/javascripts/admin/lib/workflows/field-control-registry.js
new file mode 100644
index 00000000000..2e23fe542c3
--- /dev/null
+++ b/plugins/discourse-workflows/admin/assets/javascripts/admin/lib/workflows/field-control-registry.js
@@ -0,0 +1,71 @@
+import BooleanControl from "../../components/workflows/configurators/boolean-control";
+import CategoryControl from "../../components/workflows/configurators/category-control";
+import CodeControl from "../../components/workflows/configurators/code-control";
+import ComboBox from "../../components/workflows/configurators/combo-box";
+import ConditionBuilder from "../../components/workflows/configurators/condition-builder";
+import Credential from "../../components/workflows/configurators/credential";
+import DataTableColumnSelect from "../../components/workflows/configurators/data-table-column-select";
+import DataTableColumns from "../../components/workflows/configurators/data-table-columns";
+import DataTableConditionBuilder from "../../components/workflows/configurators/data-table-condition-builder";
+import DataTableSelect from "../../components/workflows/configurators/data-table-select";
+import DefaultInputControl from "../../components/workflows/configurators/default-input-control";
+import FilterQuery from "../../components/workflows/configurators/filter-query";
+import GroupSelect from "../../components/workflows/configurators/group-select";
+import IconControl from "../../components/workflows/configurators/icon-control";
+import MultiComboBox from "../../components/workflows/configurators/multi-combo-box";
+import NoticeControl from "../../components/workflows/configurators/notice-control";
+import QueryParams from "../../components/workflows/configurators/query-params";
+import SelectControl from "../../components/workflows/configurators/select-control";
+import TagsControl from "../../components/workflows/configurators/tags-control";
+import UrlPreview from "../../components/workflows/configurators/url-preview";
+import UserControl from "../../components/workflows/configurators/user-control";
+import UserOrGroupControl from "../../components/workflows/configurators/user-or-group-control";
+
+const FIELD_CONTROL_REGISTRY = {
+ notice: { kind: "standalone", renderer: NoticeControl },
+ boolean: { kind: "standalone", renderer: BooleanControl },
+ condition_builder: { kind: "standalone", renderer: ConditionBuilder },
+ data_table_condition_builder: {
+ kind: "standalone",
+ renderer: DataTableConditionBuilder,
+ },
+ data_table_columns: { kind: "standalone", renderer: DataTableColumns },
+ query_params: { kind: "standalone", renderer: QueryParams },
+
+ code: { kind: "field", type: "code", renderer: CodeControl },
+ combo_box: { kind: "field", type: "custom", renderer: ComboBox },
+ credential: { kind: "field", type: "custom", renderer: Credential },
+ data_table_select: {
+ kind: "field",
+ type: "custom",
+ renderer: DataTableSelect,
+ },
+ group_select: { kind: "field", type: "custom", renderer: GroupSelect },
+ data_table_column_select: {
+ kind: "field",
+ type: "custom",
+ renderer: DataTableColumnSelect,
+ },
+ multi_combo_box: { kind: "field", type: "custom", renderer: MultiComboBox },
+ filter_query: { kind: "field", type: "custom", renderer: FilterQuery },
+ url_preview: { kind: "field", type: "custom", renderer: UrlPreview },
+ tags: { kind: "field", type: "custom", renderer: TagsControl },
+ category: { kind: "field", type: "custom", renderer: CategoryControl },
+ user: { kind: "field", type: "custom", renderer: UserControl },
+ user_or_group: {
+ kind: "field",
+ type: "custom",
+ renderer: UserOrGroupControl,
+ },
+ select: { kind: "field", type: "select", renderer: SelectControl },
+ icon: { kind: "field", type: "icon", renderer: IconControl },
+ textarea: { kind: "field", type: "textarea", renderer: DefaultInputControl },
+
+ default: {
+ kind: "field",
+ type: ({ inputType }) => `input-${inputType}`,
+ renderer: DefaultInputControl,
+ },
+};
+
+export default FIELD_CONTROL_REGISTRY;
diff --git a/plugins/discourse-workflows/admin/assets/javascripts/admin/lib/workflows/field-processors.js b/plugins/discourse-workflows/admin/assets/javascripts/admin/lib/workflows/field-processors.js
new file mode 100644
index 00000000000..8b247d9f007
--- /dev/null
+++ b/plugins/discourse-workflows/admin/assets/javascripts/admin/lib/workflows/field-processors.js
@@ -0,0 +1,8 @@
+const PROCESSORS = [];
+
+export default function processFields(fields, ...args) {
+ return PROCESSORS.reduce(
+ (result, processor) => processor(result, ...args),
+ fields
+ );
+}
diff --git a/plugins/discourse-workflows/admin/assets/javascripts/admin/lib/workflows/format-node-issue.js b/plugins/discourse-workflows/admin/assets/javascripts/admin/lib/workflows/format-node-issue.js
new file mode 100644
index 00000000000..4c8cd043547
--- /dev/null
+++ b/plugins/discourse-workflows/admin/assets/javascripts/admin/lib/workflows/format-node-issue.js
@@ -0,0 +1,14 @@
+import { i18n } from "discourse-i18n";
+import { propertyLabel } from "./property-engine";
+
+const KNOWN_MESSAGES = new Set(["required"]);
+
+export default function formatNodeIssue(issue, nodeType) {
+ const label = propertyLabel(nodeType, issue.name);
+ const key = KNOWN_MESSAGES.has(issue.message) ? issue.message : "unknown";
+
+ return i18n(`discourse_workflows.node_issues.${key}`, {
+ label,
+ message: issue.message,
+ });
+}
diff --git a/plugins/discourse-workflows/admin/assets/javascripts/admin/lib/workflows/graph-constants.js b/plugins/discourse-workflows/admin/assets/javascripts/admin/lib/workflows/graph-constants.js
new file mode 100644
index 00000000000..c86aa1daba6
--- /dev/null
+++ b/plugins/discourse-workflows/admin/assets/javascripts/admin/lib/workflows/graph-constants.js
@@ -0,0 +1,189 @@
+export const DEFAULT_OUTPUT = "main";
+export const LOOP_NODE_TYPE = "flow:loop_over_items";
+export const LOOP_OUTPUT = "loop";
+
+export function normalizeSourceOutput(sourceOutput) {
+ return sourceOutput || DEFAULT_OUTPUT;
+}
+
+export function normalizeTargetInput(targetInput) {
+ return targetInput || "main";
+}
+
+export function portIndexFromKey(value) {
+ value = value?.toString();
+ if (!value || value === "main" || value === "true" || value === "done") {
+ return 0;
+ }
+
+ const inputMatch = value.match(/^input_(\d+)$/);
+ if (inputMatch) {
+ return parseInt(inputMatch[1], 10) - 1;
+ }
+
+ if (value === "false" || value === "loop") {
+ return 1;
+ }
+
+ return parseInt(value, 10) || 0;
+}
+
+export function normalizeSourceOutputIndex(connection) {
+ return (
+ connection.sourceOutputIndex ?? portIndexFromKey(connection.sourceOutput)
+ );
+}
+
+export function normalizeTargetInputIndex(connection) {
+ return (
+ connection.targetInputIndex ?? portIndexFromKey(connection.targetInput)
+ );
+}
+
+export function graphConnectionKey({
+ source,
+ sourceOutput,
+ sourceOutputIndex,
+ target,
+ targetInput,
+ targetInputIndex,
+}) {
+ const outputIndex =
+ sourceOutputIndex ?? portIndexFromKey(normalizeSourceOutput(sourceOutput));
+ const inputIndex =
+ targetInputIndex ?? portIndexFromKey(normalizeTargetInput(targetInput));
+ return `${source}::${outputIndex}::${target}::${inputIndex}`;
+}
+
+export function connectionMatchesEndpoint(
+ connection,
+ { sourceClientId, sourceOutput, targetClientId, targetInput = "main" }
+) {
+ return (
+ (connection.sourceClientId ?? connection.source) === sourceClientId &&
+ normalizeSourceOutputIndex(connection) === portIndexFromKey(sourceOutput) &&
+ (connection.targetClientId ?? connection.target) === targetClientId &&
+ normalizeTargetInputIndex(connection) === portIndexFromKey(targetInput)
+ );
+}
+
+export function buildOutgoingIndex(connections, sourceKey = "source") {
+ const index = new Map();
+
+ for (const connection of connections) {
+ const key = connection[sourceKey];
+ const list = index.get(key);
+ if (list) {
+ list.push(connection);
+ } else {
+ index.set(key, [connection]);
+ }
+ }
+
+ return index;
+}
+
+export function collectLoopBodyNodeIds(
+ loopNodeId,
+ outgoingBySource,
+ { targetKey = "target", outputKey = "sourceOutput" } = {}
+) {
+ const bodyNodeIds = new Set();
+ const stack = [];
+
+ for (const connection of outgoingBySource.get(loopNodeId) || []) {
+ if (
+ (normalizeSourceOutput(connection[outputKey]) === LOOP_OUTPUT ||
+ normalizeSourceOutputIndex(connection) === 1) &&
+ connection[targetKey] !== loopNodeId
+ ) {
+ stack.push(connection[targetKey]);
+ }
+ }
+
+ while (stack.length > 0) {
+ const nodeId = stack.pop();
+
+ if (nodeId === loopNodeId || bodyNodeIds.has(nodeId)) {
+ continue;
+ }
+
+ bodyNodeIds.add(nodeId);
+
+ for (const connection of outgoingBySource.get(nodeId) || []) {
+ if (connection[targetKey] !== loopNodeId) {
+ stack.push(connection[targetKey]);
+ }
+ }
+ }
+
+ return bodyNodeIds;
+}
+
+export function buildWorkflowGraphIndex(nodes, connections) {
+ const loopNodeIds = new Set(
+ nodes.filter((node) => node.type === LOOP_NODE_TYPE).map((node) => node.id)
+ );
+ const outgoingBySource = buildOutgoingIndex(
+ connections.map((c) => ({
+ ...c,
+ sourceOutput: normalizeSourceOutput(c.sourceOutput),
+ sourceOutputIndex: normalizeSourceOutputIndex(c),
+ }))
+ );
+
+ const loopOwnerByNodeId = new Map();
+
+ for (const loopNodeId of loopNodeIds) {
+ const bodyNodeIds = collectLoopBodyNodeIds(loopNodeId, outgoingBySource);
+ for (const nodeId of bodyNodeIds) {
+ if (!loopOwnerByNodeId.has(nodeId)) {
+ loopOwnerByNodeId.set(nodeId, loopNodeId);
+ }
+ }
+ }
+
+ return { loopNodeIds, loopOwnerByNodeId };
+}
+
+export function getConnectionKind(graphIndex, connection) {
+ const sourceOutputIndex = normalizeSourceOutputIndex(connection);
+
+ if (
+ sourceOutputIndex === 1 &&
+ graphIndex.loopNodeIds.has(connection.source) &&
+ connection.source !== connection.target
+ ) {
+ return "loopBody";
+ }
+
+ if (
+ connection.source !== connection.target &&
+ graphIndex.loopNodeIds.has(connection.target) &&
+ graphIndex.loopOwnerByNodeId.get(connection.source) === connection.target
+ ) {
+ return "loopReturn";
+ }
+
+ const sourceLoopOwner = graphIndex.loopOwnerByNodeId.get(connection.source);
+ if (
+ sourceLoopOwner &&
+ sourceLoopOwner === graphIndex.loopOwnerByNodeId.get(connection.target)
+ ) {
+ return "loopChain";
+ }
+
+ return null;
+}
+
+export function buildConnectedOutputsIndex(connections) {
+ const connected = new Map();
+ for (const conn of connections) {
+ const output = normalizeSourceOutputIndex(conn);
+ if (!connected.has(conn.source)) {
+ connected.set(conn.source, new Set());
+ }
+ connected.get(conn.source).add(output);
+ }
+ return connected;
+}
diff --git a/plugins/discourse-workflows/admin/assets/javascripts/admin/lib/workflows/json-editor-extensions.js b/plugins/discourse-workflows/admin/assets/javascripts/admin/lib/workflows/json-editor-extensions.js
new file mode 100644
index 00000000000..f1946b139a2
--- /dev/null
+++ b/plugins/discourse-workflows/admin/assets/javascripts/admin/lib/workflows/json-editor-extensions.js
@@ -0,0 +1,37 @@
+// Builds the CodeMirror extension list for the pin-data JSON editor.
+//
+// Plugin code can't directly import `@codemirror/lang-json` or
+// `@codemirror/lang-javascript` — only the modules exposed on `cmParams` by
+// core's `buildCmParams()` are available. So we render JSON as plain text
+// with line numbers and bracket matching, which is still a meaningful UX
+// improvement over a textarea.
+export default function buildJsonEditorExtensions(cmParams, options = {}) {
+ const { cmLanguage, cmView, cmState } = cmParams;
+ const { onChange, readOnly = false } = options;
+
+ const extensions = [
+ cmView.lineNumbers(),
+ cmView.EditorView.lineWrapping,
+ cmLanguage.bracketMatching(),
+ cmLanguage.indentOnInput(),
+ ];
+
+ if (readOnly) {
+ extensions.push(
+ cmState.EditorState.readOnly.of(true),
+ cmView.EditorView.editable.of(false)
+ );
+ }
+
+ if (onChange) {
+ extensions.push(
+ cmView.EditorView.updateListener.of((update) => {
+ if (update.docChanged) {
+ onChange(update.state.doc.toString());
+ }
+ })
+ );
+ }
+
+ return extensions;
+}
diff --git a/plugins/discourse-workflows/admin/assets/javascripts/admin/lib/workflows/node-data-shape.js b/plugins/discourse-workflows/admin/assets/javascripts/admin/lib/workflows/node-data-shape.js
new file mode 100644
index 00000000000..aac1859caef
--- /dev/null
+++ b/plugins/discourse-workflows/admin/assets/javascripts/admin/lib/workflows/node-data-shape.js
@@ -0,0 +1,16 @@
+export const NODE_DIRECT_SETTING_KEY_ATTRIBUTES = Object.freeze({
+ notes: "notes",
+ notesInFlow: "notes_in_flow",
+ alwaysOutputData: "always_output_data",
+ onError: "on_error",
+ continueOnFail: "continue_on_fail",
+});
+export const NODE_DIRECT_SETTING_KEYS = Object.freeze(
+ Object.keys(NODE_DIRECT_SETTING_KEY_ATTRIBUTES)
+);
+export const FORM_TRIGGER_TYPE = "trigger:form";
+export const FORM_TRIGGER_WEBHOOK_ID_KEY = "webhookId";
+
+export function isFormTriggerNodeType(nodeType) {
+ return nodeType === FORM_TRIGGER_TYPE;
+}
diff --git a/plugins/discourse-workflows/admin/assets/javascripts/admin/lib/workflows/node-issues.js b/plugins/discourse-workflows/admin/assets/javascripts/admin/lib/workflows/node-issues.js
new file mode 100644
index 00000000000..b57654c3df5
--- /dev/null
+++ b/plugins/discourse-workflows/admin/assets/javascripts/admin/lib/workflows/node-issues.js
@@ -0,0 +1,131 @@
+import {
+ fieldType,
+ fieldVisible,
+ fixedCollectionGroups,
+ fixedCollectionRows,
+ normalizePropertyOptions,
+} from "./property-engine";
+
+function isBlank(value) {
+ if (value === undefined || value === null) {
+ return true;
+ }
+ if (typeof value === "string") {
+ return value.trim() === "";
+ }
+ if (Array.isArray(value)) {
+ return value.length === 0;
+ }
+ return false;
+}
+
+function itemSchemaFor(field) {
+ return {
+ ...(field.item_schema || {}),
+ ...(field.extra_item_schema || {}),
+ };
+}
+
+function fixedCollectionItemSchema(group) {
+ return group.values || {};
+}
+
+function applyDefaults(schema, config) {
+ const effective = { ...(config || {}) };
+ for (const [name, field] of Object.entries(schema)) {
+ if (effective[name] == null && field.default !== undefined) {
+ effective[name] = field.default;
+ }
+ }
+ return effective;
+}
+
+function walk(schema, config, pathPrefix, issues) {
+ const effective = applyDefaults(schema, config);
+
+ for (const [name, field] of Object.entries(schema)) {
+ if (!fieldVisible(field, effective)) {
+ continue;
+ }
+
+ const path = pathPrefix ? `${pathPrefix}.${name}` : name;
+ const value = effective[name];
+
+ if (field.required && isBlank(value)) {
+ issues.push({ path, name, message: "required" });
+ }
+
+ const type = fieldType(field);
+
+ if (
+ type === "collection" &&
+ value &&
+ typeof value === "object" &&
+ !Array.isArray(value)
+ ) {
+ normalizePropertyOptions(field.options || []).forEach((option) => {
+ if (Object.hasOwn(value, option.name)) {
+ walk({ [option.name]: option }, value, path, issues);
+ }
+ });
+ } else if (
+ type === "fixed_collection" &&
+ value &&
+ typeof value === "object"
+ ) {
+ fixedCollectionGroups(field).forEach((group) => {
+ const rows = fixedCollectionRows(value, group.name);
+ if (field.required && isBlank(rows)) {
+ issues.push({
+ path: `${path}.${group.name}`,
+ name,
+ message: "required",
+ });
+ }
+ rows.forEach((item, index) => {
+ walk(
+ fixedCollectionItemSchema(group),
+ item || {},
+ `${path}.${group.name}.${index}`,
+ issues
+ );
+ });
+ });
+ } else if (
+ type === "assignment_collection" &&
+ value &&
+ typeof value === "object"
+ ) {
+ const assignments = fixedCollectionRows(value, "assignments");
+ if (field.required && isBlank(assignments)) {
+ issues.push({ path: `${path}.assignments`, name, message: "required" });
+ }
+ assignments.forEach((item, index) => {
+ walk(
+ {
+ name: { type: "string", required: true },
+ type: { type: "options", required: true },
+ value: { type: "string", required: true },
+ },
+ item || {},
+ `${path}.assignments.${index}`,
+ issues
+ );
+ });
+ } else if (field.type === "collection" && Array.isArray(value)) {
+ const inner = itemSchemaFor(field);
+ value.forEach((item, index) => {
+ walk(inner, item || {}, `${path}.${index}`, issues);
+ });
+ }
+ }
+}
+
+export default function getNodeIssues(configuration, propertySchema) {
+ if (!propertySchema) {
+ return [];
+ }
+ const issues = [];
+ walk(propertySchema, configuration || {}, "", issues);
+ return issues;
+}
diff --git a/plugins/discourse-workflows/admin/assets/javascripts/admin/lib/workflows/node-types.js b/plugins/discourse-workflows/admin/assets/javascripts/admin/lib/workflows/node-types.js
new file mode 100644
index 00000000000..f73b81866a0
--- /dev/null
+++ b/plugins/discourse-workflows/admin/assets/javascripts/admin/lib/workflows/node-types.js
@@ -0,0 +1,370 @@
+import { trustHTML } from "@ember/template";
+import { i18n } from "discourse-i18n";
+
+const DEFAULT_COLOR = "var(--primary-medium)";
+const DEFAULT_I18N_PREFIX = "discourse_workflows";
+const RUN_SCOPE_LABEL_KEYS = {
+ per_item: "discourse_workflows.run_scope.per_item",
+ all_items: "discourse_workflows.run_scope.all_items",
+};
+
+export function missingTranslation(value) {
+ return typeof value === "string" && value.startsWith("[");
+}
+
+export function translatedOrNull(key) {
+ const value = i18n(key);
+ return missingTranslation(value) ? null : value;
+}
+
+function humanizeKey(key) {
+ return key
+ .toString()
+ .replace(/_/g, " ")
+ .replace(/\b\w/g, (char) => char.toUpperCase());
+}
+
+function nodeTypeIdentifier(nodeTypeOrIdentifier) {
+ if (typeof nodeTypeOrIdentifier === "string") {
+ return nodeTypeOrIdentifier;
+ }
+
+ return (
+ nodeTypeOrIdentifier?.name ||
+ nodeTypeOrIdentifier?.identifier ||
+ nodeTypeOrIdentifier?.type ||
+ ""
+ );
+}
+
+function resolveNodeType(nodeTypeOrIdentifier) {
+ if (!nodeTypeOrIdentifier) {
+ return null;
+ }
+
+ if (typeof nodeTypeOrIdentifier !== "string") {
+ return nodeTypeOrIdentifier;
+ }
+
+ return { name: nodeTypeOrIdentifier, identifier: nodeTypeOrIdentifier };
+}
+
+export function resolveNodeTypeVersion(
+ nodeTypeOrIdentifier,
+ typeVersion = null
+) {
+ const nodeType = resolveNodeType(nodeTypeOrIdentifier);
+
+ if (!nodeType || typeof nodeTypeOrIdentifier === "string") {
+ return nodeType;
+ }
+
+ if (typeVersion && nodeType.versions?.[typeVersion]) {
+ return nodeType.versions[typeVersion];
+ }
+
+ if (nodeType.latest) {
+ return nodeType.latest;
+ }
+
+ return nodeType;
+}
+
+export function nodeTypeVersion(nodeTypeOrIdentifier, typeVersion = null) {
+ return resolveNodeTypeVersion(nodeTypeOrIdentifier, typeVersion)?.version;
+}
+
+export function nodeTypeUi(nodeTypeOrIdentifier, typeVersion = null) {
+ const nodeType = resolveNodeTypeVersion(nodeTypeOrIdentifier, typeVersion);
+
+ return {
+ ...(nodeType?.defaults || {}),
+ ...(nodeType?.description?.defaults || {}),
+ ...(nodeType?.ui || {}),
+ };
+}
+
+export function nodeTypeIcon(nodeTypeOrIdentifier, typeVersion = null) {
+ return nodeTypeUi(nodeTypeOrIdentifier, typeVersion).icon || null;
+}
+
+export function nodeTypeColor(nodeTypeOrIdentifier, typeVersion = null) {
+ const color = nodeTypeUi(nodeTypeOrIdentifier, typeVersion).color;
+ return color ? `var(--workflow-node-color-${color})` : DEFAULT_COLOR;
+}
+
+export function nodeTypeStyle(nodeTypeOrIdentifier, typeVersion = null) {
+ return trustHTML(
+ `--node-icon-color: ${nodeTypeColor(nodeTypeOrIdentifier, typeVersion)}`
+ );
+}
+
+export function nodeTypePaletteGroup(nodeTypeOrIdentifier, typeVersion = null) {
+ return nodeTypeUi(nodeTypeOrIdentifier, typeVersion).palette_group || null;
+}
+
+export function nodeTypeI18nPrefix(nodeTypeOrIdentifier, typeVersion = null) {
+ return (
+ nodeTypeUi(nodeTypeOrIdentifier, typeVersion).i18n_prefix ||
+ resolveNodeTypeVersion(nodeTypeOrIdentifier, typeVersion)?.metadata
+ ?.i18n_prefix ||
+ DEFAULT_I18N_PREFIX
+ );
+}
+
+export function nodeTypeI18nScope(nodeTypeOrIdentifier, typeVersion = null) {
+ return (
+ nodeTypeUi(nodeTypeOrIdentifier, typeVersion).i18n_scope ||
+ nodeTypeIdentifier(nodeTypeOrIdentifier)?.split(":").pop() ||
+ ""
+ );
+}
+
+export function nodeTypeLabelKey(nodeTypeOrIdentifier, typeVersion = null) {
+ return (
+ nodeTypeUi(nodeTypeOrIdentifier, typeVersion).label_key ||
+ `discourse_workflows.nodes.${nodeTypeIdentifier(nodeTypeOrIdentifier)}`
+ );
+}
+
+export function nodeTypeLabel(nodeTypeOrIdentifier, typeVersion = null) {
+ return i18n(nodeTypeLabelKey(nodeTypeOrIdentifier, typeVersion));
+}
+
+export function nodeTypeDescriptionKey(
+ nodeTypeOrIdentifier,
+ typeVersion = null
+) {
+ return (
+ nodeTypeUi(nodeTypeOrIdentifier, typeVersion).description_key ||
+ `discourse_workflows.node_descriptions.${nodeTypeIdentifier(nodeTypeOrIdentifier)}`
+ );
+}
+
+export function nodeTypeDescription(nodeTypeOrIdentifier, typeVersion = null) {
+ return translatedOrNull(
+ nodeTypeDescriptionKey(nodeTypeOrIdentifier, typeVersion)
+ );
+}
+
+export function nodeTypeCapabilities(nodeTypeOrIdentifier, typeVersion = null) {
+ const nodeType = resolveNodeTypeVersion(nodeTypeOrIdentifier, typeVersion);
+
+ return {
+ ...(nodeType?.description?.capabilities || {}),
+ ...(nodeType?.capabilities || {}),
+ };
+}
+
+export function nodeTypeIsManuallyTriggerable(
+ nodeTypeOrIdentifier,
+ typeVersion = null
+) {
+ return Boolean(
+ nodeTypeCapabilities(nodeTypeOrIdentifier, typeVersion)
+ .manually_triggerable ||
+ resolveNodeTypeVersion(nodeTypeOrIdentifier, typeVersion)
+ ?.manually_triggerable
+ );
+}
+
+export function nodeTypeProducesData(nodeTypeOrIdentifier, typeVersion = null) {
+ return (
+ nodeTypeCapabilities(nodeTypeOrIdentifier, typeVersion).produces_data !==
+ false
+ );
+}
+
+export function nodeTypePorts(nodeTypeOrIdentifier, typeVersion = null) {
+ const nodeType = resolveNodeTypeVersion(nodeTypeOrIdentifier, typeVersion);
+ const ports = nodeType?.outputs || nodeType?.ports;
+
+ if (Array.isArray(ports) && ports.length > 0) {
+ return ports;
+ }
+
+ return [{ key: "main", primary: true }];
+}
+
+function indexedPort(port, index) {
+ return {
+ ...port,
+ index: port.index ?? index,
+ key: port.key ?? `${index}`,
+ };
+}
+
+function mergeInputs(node) {
+ const mode = node?.configuration?.mode || "append";
+
+ if (mode === "append") {
+ const count = Math.max(
+ parseInt(node?.configuration?.number_inputs, 10) || 2,
+ 2
+ );
+ return Array.from({ length: count }, (_, index) =>
+ indexedPort(
+ {
+ key: `input_${index + 1}`,
+ display_name: `Input ${index + 1}`,
+ label: `Input ${index + 1}`,
+ },
+ index
+ )
+ );
+ }
+
+ return ["input_1", "input_2"].map((key, index) =>
+ indexedPort({ key, label: `Input ${index + 1}` }, index)
+ );
+}
+
+export function nodeTypeInputs(nodeTypeOrIdentifier, node = null) {
+ const nodeType = resolveNodeTypeVersion(
+ nodeTypeOrIdentifier,
+ node?.typeVersion
+ );
+
+ if (nodeTypeIdentifier(nodeType) === "flow:merge") {
+ return mergeInputs(node);
+ }
+
+ const inputs = nodeType?.inputs;
+
+ if (Array.isArray(inputs)) {
+ return inputs.map(indexedPort);
+ }
+
+ return [{ key: "main", index: 0, required: true }];
+}
+
+export function nodeTypeInputLabel(
+ nodeTypeOrIdentifier,
+ keyOrIndex,
+ node = null
+) {
+ const input = nodeTypeInputs(nodeTypeOrIdentifier, node).find(
+ (item) => item.key === keyOrIndex || item.index === keyOrIndex
+ );
+
+ if (input?.label_key) {
+ return (
+ translatedOrNull(input.label_key) ||
+ input.label ||
+ input.display_name ||
+ humanizeKey(keyOrIndex)
+ );
+ }
+
+ return input?.label || input?.display_name || humanizeKey(keyOrIndex);
+}
+
+export function nodeTypePort(nodeTypeOrIdentifier, key, typeVersion = null) {
+ return (
+ nodeTypePorts(nodeTypeOrIdentifier, typeVersion).find(
+ (port) => port.key === key
+ ) || { key }
+ );
+}
+
+export function nodeTypePortLabel(nodeTypeOrIdentifier, key, node = null) {
+ const port = nodeTypePort(nodeTypeOrIdentifier, key, node?.typeVersion);
+
+ if (port.label_key) {
+ return translatedOrNull(port.label_key) || port.label || key;
+ }
+
+ return port.label || key;
+}
+
+export function nodeTypeOutputKeys(nodeTypeOrIdentifier, node = null) {
+ return nodeTypePorts(nodeTypeOrIdentifier, node?.typeVersion).map(
+ (port) => port.key
+ );
+}
+
+export function nodeTypePrimaryPort(nodeTypeOrIdentifier) {
+ const ports = nodeTypePorts(nodeTypeOrIdentifier);
+ return ports.find((port) => port.primary) || ports[0] || { key: "main" };
+}
+
+export function nodeTypePrimaryOutputKey(nodeTypeOrIdentifier) {
+ return nodeTypePrimaryPort(nodeTypeOrIdentifier).key || "main";
+}
+
+function runScopeFromCapability(runScope, node, nodeType) {
+ if (typeof runScope === "string") {
+ return runScope;
+ }
+
+ if (!runScope?.parameter) {
+ return null;
+ }
+
+ const parameterValue =
+ node?.configuration?.[runScope.parameter] ??
+ nodeType?.properties?.[runScope.parameter]?.default;
+
+ return runScope.values?.[parameterValue] || null;
+}
+
+export function nodeTypeRunScopeLabelKey(nodeTypeOrIdentifier, node = null) {
+ const nodeType = resolveNodeTypeVersion(
+ nodeTypeOrIdentifier,
+ node?.typeVersion
+ );
+ const runScope = runScopeFromCapability(
+ nodeTypeCapabilities(nodeType).run_scope,
+ node,
+ nodeType
+ );
+
+ return RUN_SCOPE_LABEL_KEYS[runScope] || null;
+}
+
+export function nodeTypeOperations(nodeTypeOrIdentifier) {
+ const nodeType = resolveNodeTypeVersion(nodeTypeOrIdentifier);
+
+ if (Array.isArray(nodeType?.operations) && nodeType.operations.length > 0) {
+ return nodeType.operations;
+ }
+
+ const operationField = nodeType?.properties?.operation;
+ if (
+ operationField?.type === "options" &&
+ Array.isArray(operationField.options) &&
+ operationField.options.length > 1
+ ) {
+ return operationField.options.map((value) => ({ value }));
+ }
+
+ return [];
+}
+
+export function nodeTypeOperationLabel(nodeTypeOrIdentifier, operation) {
+ const entry = nodeTypeOperations(nodeTypeOrIdentifier).find(
+ (item) => item.value === operation
+ );
+
+ if (entry?.label_key) {
+ return translatedOrNull(entry.label_key) || entry.label || entry.value;
+ }
+
+ return entry?.label || entry?.name || entry?.value || operation;
+}
+
+export function nodeTypePresenter(nodeTypeOrIdentifier) {
+ const operations = nodeTypeOperations(nodeTypeOrIdentifier);
+
+ return {
+ icon: nodeTypeIcon(nodeTypeOrIdentifier),
+ style: nodeTypeStyle(nodeTypeOrIdentifier),
+ label: nodeTypeLabel(nodeTypeOrIdentifier),
+ description: nodeTypeDescription(nodeTypeOrIdentifier),
+ paletteGroup: nodeTypePaletteGroup(nodeTypeOrIdentifier),
+ hasOperations: operations.length > 0,
+ operations,
+ operationLabel: (operation) =>
+ nodeTypeOperationLabel(nodeTypeOrIdentifier, operation),
+ };
+}
diff --git a/plugins/discourse-workflows/admin/assets/javascripts/admin/lib/workflows/node-utils.js b/plugins/discourse-workflows/admin/assets/javascripts/admin/lib/workflows/node-utils.js
new file mode 100644
index 00000000000..40cb7c8c6e4
--- /dev/null
+++ b/plugins/discourse-workflows/admin/assets/javascripts/admin/lib/workflows/node-utils.js
@@ -0,0 +1,95 @@
+import {
+ nodeTypeLabel,
+ nodeTypeOutputKeys,
+ nodeTypePortLabel,
+} from "./node-types";
+import { propertyOptionLabel } from "./property-engine";
+
+const NODE_WIDTH = 130;
+const NODE_HEIGHT_BASE = 90;
+const NODE_HEIGHT_LONG_LABEL = 105;
+const NODE_HEIGHT_WITH_DESC = 110;
+const PORT_PILL_CHAR_WIDTH = 6;
+const PORT_PILL_HORIZONTAL_PADDING = 12;
+const PORT_PILL_OFFSET = 18;
+
+export { NODE_WIDTH };
+
+export function nodeOperationLabel(node, nodeType) {
+ const value = node.configuration?.operation;
+ if (!value) {
+ return null;
+ }
+ if (!nodeType || typeof nodeType === "string") {
+ return null;
+ }
+ return propertyOptionLabel(nodeType, "operation", { value });
+}
+
+export function nodeLabel(node, nodeType = null) {
+ if (
+ node.type === "action:ai_agent" &&
+ typeof node.configuration?.agent_name === "string" &&
+ node.configuration.agent_name.trim()
+ ) {
+ return node.configuration.agent_name.trim();
+ }
+ const baseLabel = node.name || nodeTypeLabel(node.type);
+ const operationLabel = nodeOperationLabel(node, nodeType);
+ return operationLabel ? `${baseLabel} - ${operationLabel}` : baseLabel;
+}
+
+export function nodeDescription(node) {
+ return node.configuration?.notesInFlow ? node.configuration?.notes || "" : "";
+}
+
+function normalizedPortLabel(label) {
+ return (label || "").replaceAll("_", " ");
+}
+
+function estimatePortLabelWidth(label) {
+ return (
+ normalizedPortLabel(label).length * PORT_PILL_CHAR_WIDTH +
+ PORT_PILL_HORIZONTAL_PADDING
+ );
+}
+
+function resolveOutputKeys(nodeTypeOrIdentifier, node, outputKeys) {
+ if (Array.isArray(outputKeys) && outputKeys.length > 0) {
+ return outputKeys;
+ }
+
+ return nodeTypeOutputKeys(nodeTypeOrIdentifier, node);
+}
+
+export function nodeWidth(node, { nodeType = null, outputKeys } = {}) {
+ const nodeTypeOrIdentifier = nodeType || node?.type;
+ const keys = resolveOutputKeys(nodeTypeOrIdentifier, node, outputKeys);
+
+ if (keys.length < 2) {
+ return NODE_WIDTH;
+ }
+
+ const maxPortLabelWidth = Math.max(
+ 0,
+ ...keys.map((key) =>
+ estimatePortLabelWidth(
+ nodeTypePortLabel(nodeTypeOrIdentifier, key, node) || key
+ )
+ )
+ );
+
+ return NODE_WIDTH + PORT_PILL_OFFSET + maxPortLabelWidth;
+}
+
+const LABEL_WRAP_THRESHOLD = 15;
+
+export function nodeHeight(node, nodeType = null) {
+ if (nodeDescription(node)) {
+ return NODE_HEIGHT_WITH_DESC;
+ }
+ const label = nodeLabel(node, nodeType);
+ return label && label.length > LABEL_WRAP_THRESHOLD
+ ? NODE_HEIGHT_LONG_LABEL
+ : NODE_HEIGHT_BASE;
+}
diff --git a/plugins/discourse-workflows/admin/assets/javascripts/admin/lib/workflows/property-engine.js b/plugins/discourse-workflows/admin/assets/javascripts/admin/lib/workflows/property-engine.js
new file mode 100644
index 00000000000..f00548fdb89
--- /dev/null
+++ b/plugins/discourse-workflows/admin/assets/javascripts/admin/lib/workflows/property-engine.js
@@ -0,0 +1,462 @@
+import moment from "moment";
+import { i18n } from "discourse-i18n";
+import {
+ nodeTypeI18nPrefix,
+ nodeTypeI18nScope,
+ resolveNodeTypeVersion,
+ translatedOrNull,
+} from "./node-types";
+
+function cloneValue(value) {
+ return value === undefined ? undefined : structuredClone(value);
+}
+
+function humanize(value) {
+ return value
+ .toString()
+ .replace(/_/g, " ")
+ .replace(/\b\w/g, (char) => char.toUpperCase());
+}
+
+function fieldUi(schema = {}) {
+ return schema.ui || {};
+}
+
+function fallbackValueForType(type) {
+ switch (type) {
+ case "boolean":
+ return false;
+ case "collection":
+ case "fixed_collection":
+ return {};
+ case "assignment_collection":
+ return { assignments: [] };
+ case "array":
+ case "multi_options":
+ return [];
+ default:
+ return "";
+ }
+}
+
+function translationKeyWithFallback(keys = []) {
+ return keys.find((key) => translatedOrNull(key) !== null) || null;
+}
+
+export function localeKeyPart(value) {
+ return String(value)
+ .replace(/([a-z0-9])([A-Z])/g, "$1_$2")
+ .replace(/([A-Z]+)([A-Z][a-z])/g, "$1_$2")
+ .replace(/[\s-]+/g, "_")
+ .toLowerCase();
+}
+
+export function findNodeType(nodeTypes, nodeType) {
+ return (
+ nodeTypes?.find(
+ (definition) =>
+ definition.name === nodeType || definition.identifier === nodeType
+ ) || null
+ );
+}
+
+export function getPropertySchema(nodeTypes, nodeType, typeVersion = null) {
+ const definition = findNodeType(nodeTypes, nodeType);
+
+ if (!definition) {
+ return {};
+ }
+
+ const versionedDefinition = resolveNodeTypeVersion(definition, typeVersion);
+ if (versionedDefinition?.properties) {
+ return versionedDefinition.properties;
+ }
+
+ return definition.properties || {};
+}
+
+export function normalizeSchema(schema = {}) {
+ return Object.entries(schema).map(([name, field]) => ({
+ name,
+ ...field,
+ }));
+}
+
+export function i18nPrefix(nodeDefinitionOrType) {
+ return nodeTypeI18nPrefix(nodeDefinitionOrType);
+}
+
+export function i18nScope(nodeDefinitionOrType) {
+ return nodeTypeI18nScope(nodeDefinitionOrType);
+}
+
+function i18nBase(nodeDefinitionOrType) {
+ return `${i18nPrefix(nodeDefinitionOrType)}.${i18nScope(nodeDefinitionOrType)}`;
+}
+
+export function propertyLabel(nodeDefinitionOrType, fieldName) {
+ const base = i18nBase(nodeDefinitionOrType);
+ const labelKey = localeKeyPart(fieldName);
+
+ return (
+ translatedOrNull(`${base}.${labelKey}`) ||
+ translatedOrNull(`${base}.${labelKey}.title`) ||
+ humanize(fieldName)
+ );
+}
+
+export function propertyDescription(nodeDefinitionOrType, fieldName) {
+ return translatedOrNull(
+ `${i18nBase(nodeDefinitionOrType)}.${localeKeyPart(fieldName)}_description`
+ );
+}
+
+export function propertyPlaceholder(nodeDefinitionOrType, fieldName) {
+ return translatedOrNull(
+ `${i18nBase(nodeDefinitionOrType)}.${localeKeyPart(fieldName)}_placeholder`
+ );
+}
+
+function dynamicValueKey(schema = {}, fieldName) {
+ const ui = fieldUi(schema);
+
+ if (ui.dynamic_value) {
+ return ui.dynamic_value;
+ }
+
+ switch (fieldControl(schema)) {
+ case "category":
+ return "category_id";
+ case "data_table_column_select":
+ return "column_name";
+ case "data_table_select":
+ return "data_table_id";
+ case "group_select":
+ return "group_id";
+ case "tags":
+ return "tag_names";
+ case "user":
+ return "username";
+ case "user_or_group":
+ return "user_or_group_name";
+ case "select":
+ return "option_value";
+ default:
+ break;
+ }
+
+ if (fieldName?.endsWith("_username")) {
+ return "username";
+ }
+
+ if (fieldName?.endsWith("_id")) {
+ return "id";
+ }
+
+ switch (fieldType(schema)) {
+ case "boolean":
+ return "boolean";
+ case "float":
+ case "integer":
+ case "number":
+ return "number";
+ default:
+ break;
+ }
+
+ return null;
+}
+
+export function propertyDynamicValueHint(
+ nodeDefinitionOrType,
+ fieldName,
+ schema = {}
+) {
+ const base = i18nBase(nodeDefinitionOrType);
+ const labelKey = localeKeyPart(fieldName);
+ const fieldHint = translatedOrNull(`${base}.${labelKey}_dynamic_hint`);
+
+ if (fieldHint) {
+ return fieldHint;
+ }
+
+ const valueKey = dynamicValueKey(schema, fieldName);
+
+ if (!valueKey) {
+ return null;
+ }
+
+ const value =
+ translatedOrNull(
+ `discourse_workflows.property_engine.dynamic_values.${localeKeyPart(
+ valueKey
+ )}`
+ ) || humanize(valueKey);
+
+ return i18n("discourse_workflows.property_engine.dynamic_hint", { value });
+}
+
+export function propertySelectNoneKey(nodeDefinitionOrType, fieldName) {
+ const base = i18nBase(nodeDefinitionOrType);
+ const key = localeKeyPart(fieldName);
+ const selectField = key.replace(/_id$/, "");
+
+ return translationKeyWithFallback([
+ `${base}.select_${selectField}`,
+ `${base}.${key}_placeholder`,
+ ]);
+}
+
+export function collectionAddLabel(
+ nodeDefinitionOrType,
+ fieldName,
+ schema = {}
+) {
+ const override = fieldUi(schema).singular_name;
+ const singular =
+ override || (fieldName.endsWith("s") ? fieldName.slice(0, -1) : fieldName);
+
+ return (
+ translatedOrNull(
+ `${i18nBase(nodeDefinitionOrType)}.add_${localeKeyPart(singular)}`
+ ) || i18n("discourse_workflows.property_engine.add_item")
+ );
+}
+
+export function formatOptionValue(value, format) {
+ if (format === "hour_of_day") {
+ return moment().hour(value).minute(0).format("LT");
+ }
+ if (format === "weekday") {
+ return moment().day(value).format("dddd");
+ }
+ return String(value);
+}
+
+export function normalizeOptions(options = []) {
+ return options.map((option) =>
+ typeof option === "object" ? option : { value: option }
+ );
+}
+
+export function normalizePropertyOptions(options = []) {
+ return options.map((option) => ({
+ name: option.name || option.value,
+ ...option,
+ }));
+}
+
+export function fixedCollectionGroups(schema = {}) {
+ return normalizePropertyOptions(schema.options || []);
+}
+
+export function fixedCollectionGroup(schema = {}) {
+ return fixedCollectionGroups(schema)[0] || { name: "values", values: {} };
+}
+
+export function fixedCollectionGroupMultiple(group = {}, schema = {}) {
+ const type_options = schema.type_options || {};
+ if (Object.hasOwn(type_options, "multiple_values")) {
+ return Boolean(type_options.multiple_values);
+ }
+ if (Object.hasOwn(group, "multiple_values")) {
+ return Boolean(group.multiple_values);
+ }
+ return true;
+}
+
+export function fixedCollectionRows(value, groupName = "values") {
+ if (Array.isArray(value)) {
+ return value;
+ }
+ const groupValue = value?.[groupName];
+ if (Array.isArray(groupValue)) {
+ return groupValue;
+ }
+ if (groupValue && typeof groupValue === "object") {
+ return [groupValue];
+ }
+ return [];
+}
+
+export function fieldType(schema = {}) {
+ return schema.type || "string";
+}
+
+export function propertyOptionLabel(nodeDefinitionOrType, fieldName, option) {
+ const base = i18nBase(nodeDefinitionOrType);
+ const key = localeKeyPart(fieldName);
+ const valueKey = localeKeyPart(option.value);
+
+ return (
+ translatedOrNull(`${base}.${key}_${valueKey}`) ||
+ translatedOrNull(`${base}.${key}s.${valueKey}`) ||
+ option.label ||
+ option.name ||
+ option.value
+ );
+}
+
+const TYPE_TO_CONTROL = {
+ boolean: "boolean",
+ icon: "icon",
+ options: "select",
+ multi_options: "multi_combo_box",
+ collection: "collection",
+ fixed_collection: "fixed_collection",
+ assignment_collection: "assignment_collection",
+ notice: "notice",
+ credential: "credential",
+};
+
+export function fieldControl(schema = {}) {
+ return (
+ fieldUi(schema).control || TYPE_TO_CONTROL[fieldType(schema)] || "input"
+ );
+}
+
+export function fieldSupportsExpression(schema = {}) {
+ if (schema.no_data_expression) {
+ return false;
+ }
+
+ const ui = fieldUi(schema);
+
+ if (Object.hasOwn(ui, "expression")) {
+ return Boolean(ui.expression);
+ }
+
+ return ["string", "integer", "number", "float", "icon"].includes(
+ fieldType(schema)
+ );
+}
+
+export function fieldShowDescription(schema = {}) {
+ return fieldUi(schema).show_description !== false;
+}
+
+export function fieldShowLabel(schema = {}) {
+ return fieldUi(schema).show_label !== false;
+}
+
+export function fieldFormat(schema = {}) {
+ return fieldUi(schema).format || schema.format || "full";
+}
+
+export function fieldInputType(schema = {}) {
+ const ui = fieldUi(schema);
+ if (ui.control === "password") {
+ return "password";
+ }
+ return ["integer", "float", "number"].includes(fieldType(schema))
+ ? "number"
+ : "text";
+}
+
+export function fieldValue(schema = {}, value) {
+ return (
+ value ??
+ cloneValue(schema.default ?? fallbackValueForType(fieldType(schema)))
+ );
+}
+
+export function emptyCollectionItem(itemSchema = {}, extraItemSchema = {}) {
+ return Object.fromEntries(
+ Object.entries({ ...itemSchema, ...extraItemSchema }).map(
+ ([name, schema]) => [name, fieldValue(schema)]
+ )
+ );
+}
+
+export function emptyFixedCollectionItem(group = {}) {
+ return emptyCollectionItem(group.values || {});
+}
+
+export function isExpression(value) {
+ return typeof value === "string" && value.startsWith("=");
+}
+
+export function credentialTypesForSlot(slot = {}) {
+ return slot.credential_types || [slot.credential_type].filter(Boolean);
+}
+
+export function credentialSlotVisible(slot = {}, configuration = {}) {
+ return fieldVisible(
+ {
+ display_options: slot.display_options,
+ },
+ configuration
+ );
+}
+
+export function credentialSlotAnchorField(slot = {}) {
+ const displayOptions = slot.display_options;
+ const fields = new Set([
+ ...Object.keys(displayOptions?.show || {}),
+ ...Object.keys(displayOptions?.hide || {}),
+ ]);
+ return fields.size === 1 ? [...fields][0] : null;
+}
+
+export function fieldVisible(schema = {}, configuration = {}) {
+ if (fieldUi(schema).hidden) {
+ return false;
+ }
+
+ const display_options = schema.display_options;
+ if (
+ display_options?.show &&
+ !matchesRules(display_options.show, configuration)
+ ) {
+ return false;
+ }
+ if (
+ display_options?.hide &&
+ matchesRules(display_options.hide, configuration)
+ ) {
+ return false;
+ }
+
+ return true;
+}
+
+function matchesRules(rules, configuration) {
+ return Object.entries(rules).every(([fieldName, expected]) =>
+ matchesRule(expected, configuration[fieldName])
+ );
+}
+
+function matchesRule(expected, value) {
+ if (!Array.isArray(expected)) {
+ return matchesCondition(expected, value);
+ }
+
+ return expected.some((condition) => matchesCondition(condition, value));
+}
+
+function matchesCondition(condition, value) {
+ const operator = condition?._cnd;
+ if (!operator) {
+ return condition === value;
+ }
+
+ if (Object.hasOwn(operator, "not")) {
+ return value !== operator.not;
+ }
+
+ if (Object.hasOwn(operator, "exists")) {
+ return operator.exists ? !isEmptyValue(value) : isEmptyValue(value);
+ }
+
+ return false;
+}
+
+function isEmptyValue(value) {
+ if (value == null || value === "") {
+ return true;
+ }
+ if (Array.isArray(value)) {
+ return value.length === 0;
+ }
+ return false;
+}
diff --git a/plugins/discourse-workflows/admin/assets/javascripts/admin/lib/workflows/static-data.js b/plugins/discourse-workflows/admin/assets/javascripts/admin/lib/workflows/static-data.js
new file mode 100644
index 00000000000..e9a9c72e6e0
--- /dev/null
+++ b/plugins/discourse-workflows/admin/assets/javascripts/admin/lib/workflows/static-data.js
@@ -0,0 +1,40 @@
+export function isStaticDataMap(staticData) {
+ return (
+ staticData &&
+ typeof staticData === "object" &&
+ !Array.isArray(staticData) &&
+ Object.entries(staticData).every(([key, value]) => {
+ return (
+ key !== "node" &&
+ value &&
+ typeof value === "object" &&
+ !Array.isArray(value)
+ );
+ })
+ );
+}
+
+export function mergeImportedStaticData(
+ existingStaticData,
+ importedStaticData
+) {
+ const existing = isStaticDataMap(existingStaticData)
+ ? existingStaticData
+ : {};
+ const imported = isStaticDataMap(importedStaticData)
+ ? importedStaticData
+ : {};
+ const merged = {
+ ...structuredClone(existing),
+ ...structuredClone(imported),
+ };
+
+ if (existing.global || imported.global) {
+ merged.global = {
+ ...(existing.global || {}),
+ ...(imported.global || {}),
+ };
+ }
+
+ return merged;
+}
diff --git a/plugins/discourse-workflows/admin/assets/javascripts/admin/lib/workflows/template-workflow.js b/plugins/discourse-workflows/admin/assets/javascripts/admin/lib/workflows/template-workflow.js
new file mode 100644
index 00000000000..4be6000c661
--- /dev/null
+++ b/plugins/discourse-workflows/admin/assets/javascripts/admin/lib/workflows/template-workflow.js
@@ -0,0 +1,28 @@
+import { NODE_DIRECT_SETTING_KEYS } from "../../models/workflow-node";
+
+export function workflowFromTemplate(template) {
+ return {
+ name: template.name,
+ nodes: template.nodes.map((n) => {
+ const node = {
+ id: n.id,
+ type: n.type,
+ typeVersion: n.typeVersion,
+ name: n.name,
+ parameters: n.parameters || {},
+ credentials: n.credentials || {},
+ webhookId: n.webhookId || null,
+ position: n.position || null,
+ };
+
+ for (const key of NODE_DIRECT_SETTING_KEYS) {
+ if (Object.hasOwn(n, key)) {
+ node[key] = structuredClone(n[key]);
+ }
+ }
+
+ return node;
+ }),
+ connections: template.connections || {},
+ };
+}
diff --git a/plugins/discourse-workflows/admin/assets/javascripts/admin/models/discourse-workflows-workflow.js b/plugins/discourse-workflows/admin/assets/javascripts/admin/models/discourse-workflows-workflow.js
new file mode 100644
index 00000000000..b7033133a42
--- /dev/null
+++ b/plugins/discourse-workflows/admin/assets/javascripts/admin/models/discourse-workflows-workflow.js
@@ -0,0 +1,95 @@
+import { tracked } from "@glimmer/tracking";
+import RestModel from "discourse/models/rest";
+import StickyNote from "./sticky-note";
+import { serializeConnections } from "./workflow-connection";
+import WorkflowNode from "./workflow-node";
+
+export default class DiscourseWorkflowsWorkflow extends RestModel {
+ static munge(json) {
+ const result = { ...json };
+
+ if (Object.hasOwn(json, "error_workflow_id")) {
+ result.errorWorkflowId = json.error_workflow_id;
+ }
+ if (Object.hasOwn(json, "error_workflow_name")) {
+ result.errorWorkflowName = json.error_workflow_name;
+ }
+ if (Object.hasOwn(json, "version_id")) {
+ result.versionId = json.version_id;
+ }
+ if (Object.hasOwn(json, "active_version_id")) {
+ result.activeVersionId = json.active_version_id;
+ }
+ if (Object.hasOwn(json, "version_counter")) {
+ result.versionCounter = json.version_counter;
+ }
+ if (Object.hasOwn(json, "has_unpublished_changes")) {
+ result.hasUnpublishedChanges = json.has_unpublished_changes;
+ }
+ if (Object.hasOwn(json, "last_execution_status")) {
+ result.lastExecutionStatus = json.last_execution_status;
+ }
+ if (Object.hasOwn(json, "last_execution_at")) {
+ result.lastExecutionAt = json.last_execution_at;
+ }
+ if (Object.hasOwn(json, "last_execution_run_data")) {
+ result.lastExecutionRunData = json.last_execution_run_data;
+ }
+ if (Object.hasOwn(json, "created_at")) {
+ result.createdAt = json.created_at;
+ }
+ if (Object.hasOwn(json, "updated_at")) {
+ result.updatedAt = json.updated_at;
+ }
+ if (Object.hasOwn(json, "created_by")) {
+ result.createdBy = json.created_by;
+ }
+ if (Object.hasOwn(json, "updated_by")) {
+ result.updatedBy = json.updated_by;
+ }
+ if (Object.hasOwn(json, "static_data")) {
+ result.staticData = json.static_data;
+ }
+ if (Object.hasOwn(json, "pin_data")) {
+ result.pinData = json.pin_data;
+ }
+
+ return result;
+ }
+
+ @tracked name;
+ @tracked errorWorkflowId;
+ @tracked versionId;
+ @tracked activeVersionId;
+ @tracked versionCounter;
+ @tracked hasUnpublishedChanges;
+ @tracked lastExecutionStatus;
+ @tracked lastExecutionRunData;
+ @tracked timezone;
+ @tracked settings;
+ @tracked staticData;
+ @tracked pinData;
+ @tracked nodes = [];
+ @tracked connections = [];
+ @tracked stickyNotes = [];
+
+ updateProperties() {
+ return {
+ name: this.name,
+ error_workflow_id: this.errorWorkflowId,
+ static_data: this.staticData,
+ nodes: [
+ ...this.nodes.map(WorkflowNode.serialize),
+ ...(this.stickyNotes || []).map(StickyNote.serialize),
+ ],
+ connections: serializeConnections(this.connections, [
+ ...this.nodes,
+ ...(this.stickyNotes || []),
+ ]),
+ };
+ }
+
+ createProperties() {
+ return this.updateProperties();
+ }
+}
diff --git a/plugins/discourse-workflows/admin/assets/javascripts/admin/models/sticky-note.js b/plugins/discourse-workflows/admin/assets/javascripts/admin/models/sticky-note.js
new file mode 100644
index 00000000000..f46d39d3891
--- /dev/null
+++ b/plugins/discourse-workflows/admin/assets/javascripts/admin/models/sticky-note.js
@@ -0,0 +1,52 @@
+export const STICKY_NOTE_TYPE = "flow:sticky_note";
+
+const DEFAULT_WIDTH = 200;
+const DEFAULT_HEIGHT = 150;
+const DEFAULT_COLOR = "yellow";
+
+export default class StickyNote {
+ static create(args = {}) {
+ return new StickyNote(args);
+ }
+
+ static serialize(note) {
+ return {
+ id: note.id || note.clientId,
+ type: STICKY_NOTE_TYPE,
+ typeVersion: "1.0",
+ name: "Sticky Note",
+ parameters: {
+ content: note.text,
+ width: note.size.width,
+ height: note.size.height,
+ color: note.color,
+ },
+ credentials: {},
+ webhookId: null,
+ position: note.position,
+ };
+ }
+
+ static fromNode(node) {
+ const config = node.parameters || {};
+ return new StickyNote({
+ clientId: node.id?.toString() ?? node.clientId,
+ position: node.position ?? { x: 0, y: 0 },
+ size: {
+ width: config.width ?? DEFAULT_WIDTH,
+ height: config.height ?? DEFAULT_HEIGHT,
+ },
+ color: config.color ?? DEFAULT_COLOR,
+ text: config.content ?? "",
+ });
+ }
+
+ constructor(args = {}) {
+ this.id = args.id?.toString() ?? args.clientId ?? crypto.randomUUID();
+ this.clientId = args.clientId ?? this.id;
+ this.position = args.position ?? { x: 0, y: 0 };
+ this.size = args.size ?? { width: DEFAULT_WIDTH, height: DEFAULT_HEIGHT };
+ this.color = args.color ?? DEFAULT_COLOR;
+ this.text = args.text ?? "";
+ }
+}
diff --git a/plugins/discourse-workflows/admin/assets/javascripts/admin/models/workflow-connection.js b/plugins/discourse-workflows/admin/assets/javascripts/admin/models/workflow-connection.js
new file mode 100644
index 00000000000..990aaa2a6f7
--- /dev/null
+++ b/plugins/discourse-workflows/admin/assets/javascripts/admin/models/workflow-connection.js
@@ -0,0 +1,106 @@
+import {
+ normalizeSourceOutputIndex,
+ normalizeTargetInputIndex,
+ portIndexFromKey,
+} from "../lib/workflows/graph-constants";
+
+export default class WorkflowConnection {
+ static create(args = {}) {
+ return new WorkflowConnection(args);
+ }
+
+ static serialize(connection) {
+ return {
+ sourceClientId: connection.sourceClientId,
+ targetClientId: connection.targetClientId,
+ connectionType: connection.connectionType || "main",
+ sourceOutputIndex: normalizeSourceOutputIndex(connection),
+ targetInputIndex: normalizeTargetInputIndex(connection),
+ };
+ }
+
+ constructor(args = {}) {
+ this.sourceClientId = args.sourceClientId;
+ this.targetClientId = args.targetClientId;
+ this.sourceOutput = args.sourceOutput ?? "main";
+ this.targetInput = args.targetInput ?? "main";
+ this.connectionType = args.connectionType ?? "main";
+ this.sourceOutputIndex =
+ args.sourceOutputIndex ?? portIndexFromKey(this.sourceOutput);
+ this.targetInputIndex =
+ args.targetInputIndex ?? portIndexFromKey(this.targetInput);
+ }
+}
+
+export function serializeConnections(connections, nodes) {
+ const nodesByClientId = new Map(nodes.map((node) => [node.clientId, node]));
+
+ return (connections || []).reduce((result, connection) => {
+ const sourceNode = nodesByClientId.get(connection.sourceClientId);
+ const targetNode = nodesByClientId.get(connection.targetClientId);
+
+ if (!sourceNode || !targetNode) {
+ return result;
+ }
+
+ const connectionType = connection.connectionType || "main";
+ const sourceOutputIndex = normalizeSourceOutputIndex(connection);
+ const targetInputIndex = normalizeTargetInputIndex(connection);
+
+ result[sourceNode.name] ||= {};
+ result[sourceNode.name][connectionType] ||= [];
+ while (
+ result[sourceNode.name][connectionType].length <= sourceOutputIndex
+ ) {
+ result[sourceNode.name][connectionType].push([]);
+ }
+ result[sourceNode.name][connectionType][sourceOutputIndex].push({
+ node: targetNode.name,
+ type: connectionType,
+ index: targetInputIndex,
+ });
+
+ return result;
+ }, {});
+}
+
+export function deserializeConnections(connections, nodes) {
+ const nodesByName = new Map(nodes.map((node) => [node.name, node]));
+ const result = [];
+
+ for (const [sourceName, outputsByType] of Object.entries(connections || {})) {
+ const sourceNode = nodesByName.get(sourceName);
+
+ if (!sourceNode || !outputsByType) {
+ continue;
+ }
+
+ for (const [connectionType, outputConnections] of Object.entries(
+ outputsByType
+ )) {
+ (outputConnections || []).forEach(
+ (targetConnections, sourceOutputIndex) => {
+ (targetConnections || []).forEach((targetConnection) => {
+ const targetNode = nodesByName.get(targetConnection.node);
+
+ if (!targetNode) {
+ return;
+ }
+
+ result.push(
+ WorkflowConnection.create({
+ sourceClientId: sourceNode.clientId,
+ targetClientId: targetNode.clientId,
+ connectionType,
+ sourceOutputIndex,
+ targetInputIndex: targetConnection.index || 0,
+ })
+ );
+ });
+ }
+ );
+ }
+ }
+
+ return result;
+}
diff --git a/plugins/discourse-workflows/admin/assets/javascripts/admin/models/workflow-node.js b/plugins/discourse-workflows/admin/assets/javascripts/admin/models/workflow-node.js
new file mode 100644
index 00000000000..ff1692f2ce7
--- /dev/null
+++ b/plugins/discourse-workflows/admin/assets/javascripts/admin/models/workflow-node.js
@@ -0,0 +1,99 @@
+import {
+ FORM_TRIGGER_WEBHOOK_ID_KEY,
+ NODE_DIRECT_SETTING_KEYS,
+} from "../lib/workflows/node-data-shape";
+
+export { NODE_DIRECT_SETTING_KEYS };
+
+function directSettingsFromNodeData(node = {}) {
+ const settings = {};
+
+ for (const key of NODE_DIRECT_SETTING_KEYS) {
+ if (Object.hasOwn(node, key)) {
+ settings[key] = structuredClone(node[key]);
+ }
+ }
+
+ return settings;
+}
+
+function splitConfiguration(configuration = {}, existing = {}) {
+ const parameters = structuredClone(configuration || {});
+ const directSettings = directSettingsFromNodeData(existing);
+ const credentials = Object.hasOwn(parameters, "credentials")
+ ? structuredClone(parameters.credentials || {})
+ : structuredClone(existing.credentials || {});
+ let webhookId = existing.webhookId || null;
+
+ delete parameters.credentials;
+
+ for (const key of NODE_DIRECT_SETTING_KEYS) {
+ if (Object.hasOwn(parameters, key)) {
+ directSettings[key] = parameters[key];
+ delete parameters[key];
+ }
+ }
+
+ return { parameters, credentials, directSettings, webhookId };
+}
+
+function configurationFromNodeData({
+ parameters = {},
+ credentials = {},
+ directSettings = {},
+}) {
+ const configuration = {
+ ...structuredClone(parameters || {}),
+ ...structuredClone(directSettings || {}),
+ };
+
+ if (credentials && Object.keys(credentials).length > 0) {
+ configuration.credentials = structuredClone(credentials);
+ }
+
+ return configuration;
+}
+
+export default class WorkflowNode {
+ static create(args = {}) {
+ return new WorkflowNode(args);
+ }
+
+ static serialize(node) {
+ const split = splitConfiguration(node.configuration, node);
+
+ return {
+ id: node.id || node.clientId,
+ type: node.type,
+ typeVersion: node.typeVersion,
+ name: node.name,
+ parameters: split.parameters,
+ credentials: split.credentials,
+ [FORM_TRIGGER_WEBHOOK_ID_KEY]: split.webhookId,
+ position: node.position || null,
+ ...split.directSettings,
+ };
+ }
+
+ constructor(args = {}) {
+ this.id = args.id?.toString() ?? args.clientId ?? crypto.randomUUID();
+ this.clientId = args.clientId ?? this.id;
+ this.type = args.type;
+ this.typeVersion = args.typeVersion ?? "1.0";
+ this.name = args.name;
+ this.parameters = args.parameters ?? {};
+ this.credentials = args.credentials ?? {};
+ this.directSettings = directSettingsFromNodeData(args);
+ this.webhookId = args.webhookId ?? null;
+ this.configuration =
+ args.configuration ??
+ configurationFromNodeData({
+ parameters: this.parameters,
+ credentials: this.credentials,
+ directSettings: this.directSettings,
+ });
+ this.position = args.position ?? null;
+
+ Object.assign(this, this.directSettings);
+ }
+}
diff --git a/plugins/discourse-workflows/admin/assets/javascripts/discourse/routes/admin-plugins/show/discourse-workflows-credentials.js b/plugins/discourse-workflows/admin/assets/javascripts/discourse/routes/admin-plugins/show/discourse-workflows-credentials.js
new file mode 100644
index 00000000000..f0632861164
--- /dev/null
+++ b/plugins/discourse-workflows/admin/assets/javascripts/discourse/routes/admin-plugins/show/discourse-workflows-credentials.js
@@ -0,0 +1,3 @@
+import DiscourseRoute from "discourse/routes/discourse";
+
+export default class DiscourseWorkflowsCredentialsRoute extends DiscourseRoute {}
diff --git a/plugins/discourse-workflows/admin/assets/javascripts/discourse/routes/admin-plugins/show/discourse-workflows-data-tables.js b/plugins/discourse-workflows/admin/assets/javascripts/discourse/routes/admin-plugins/show/discourse-workflows-data-tables.js
new file mode 100644
index 00000000000..33ac0bc8c71
--- /dev/null
+++ b/plugins/discourse-workflows/admin/assets/javascripts/discourse/routes/admin-plugins/show/discourse-workflows-data-tables.js
@@ -0,0 +1,3 @@
+import DiscourseRoute from "discourse/routes/discourse";
+
+export default class DiscourseWorkflowsDataTablesRoute extends DiscourseRoute {}
diff --git a/plugins/discourse-workflows/admin/assets/javascripts/discourse/routes/admin-plugins/show/discourse-workflows-data-tables/show.js b/plugins/discourse-workflows/admin/assets/javascripts/discourse/routes/admin-plugins/show/discourse-workflows-data-tables/show.js
new file mode 100644
index 00000000000..00d47d50e49
--- /dev/null
+++ b/plugins/discourse-workflows/admin/assets/javascripts/discourse/routes/admin-plugins/show/discourse-workflows-data-tables/show.js
@@ -0,0 +1,7 @@
+import DiscourseRoute from "discourse/routes/discourse";
+
+export default class DiscourseWorkflowsDataTablesShowRoute extends DiscourseRoute {
+ model(params) {
+ return parseInt(params.id, 10);
+ }
+}
diff --git a/plugins/discourse-workflows/admin/assets/javascripts/discourse/routes/admin-plugins/show/discourse-workflows-executions.js b/plugins/discourse-workflows/admin/assets/javascripts/discourse/routes/admin-plugins/show/discourse-workflows-executions.js
new file mode 100644
index 00000000000..5d6060d752b
--- /dev/null
+++ b/plugins/discourse-workflows/admin/assets/javascripts/discourse/routes/admin-plugins/show/discourse-workflows-executions.js
@@ -0,0 +1,3 @@
+import DiscourseRoute from "discourse/routes/discourse";
+
+export default class DiscourseWorkflowsExecutionsRoute extends DiscourseRoute {}
diff --git a/plugins/discourse-workflows/admin/assets/javascripts/discourse/routes/admin-plugins/show/discourse-workflows-templates.js b/plugins/discourse-workflows/admin/assets/javascripts/discourse/routes/admin-plugins/show/discourse-workflows-templates.js
new file mode 100644
index 00000000000..c2024b4123b
--- /dev/null
+++ b/plugins/discourse-workflows/admin/assets/javascripts/discourse/routes/admin-plugins/show/discourse-workflows-templates.js
@@ -0,0 +1,8 @@
+import { ajax } from "discourse/lib/ajax";
+import DiscourseRoute from "discourse/routes/discourse";
+
+export default class DiscourseWorkflowsTemplatesRoute extends DiscourseRoute {
+ async model() {
+ return ajax("/admin/plugins/discourse-workflows/templates.json");
+ }
+}
diff --git a/plugins/discourse-workflows/admin/assets/javascripts/discourse/routes/admin-plugins/show/discourse-workflows-variables.js b/plugins/discourse-workflows/admin/assets/javascripts/discourse/routes/admin-plugins/show/discourse-workflows-variables.js
new file mode 100644
index 00000000000..eb99f9844b1
--- /dev/null
+++ b/plugins/discourse-workflows/admin/assets/javascripts/discourse/routes/admin-plugins/show/discourse-workflows-variables.js
@@ -0,0 +1,3 @@
+import DiscourseRoute from "discourse/routes/discourse";
+
+export default class DiscourseWorkflowsVariablesRoute extends DiscourseRoute {}
diff --git a/plugins/discourse-workflows/admin/assets/javascripts/discourse/routes/admin-plugins/show/discourse-workflows.js b/plugins/discourse-workflows/admin/assets/javascripts/discourse/routes/admin-plugins/show/discourse-workflows.js
new file mode 100644
index 00000000000..57afbfcba99
--- /dev/null
+++ b/plugins/discourse-workflows/admin/assets/javascripts/discourse/routes/admin-plugins/show/discourse-workflows.js
@@ -0,0 +1,3 @@
+import Route from "@ember/routing/route";
+
+export default class extends Route {}
diff --git a/plugins/discourse-workflows/admin/assets/javascripts/discourse/routes/admin-plugins/show/discourse-workflows/index.js b/plugins/discourse-workflows/admin/assets/javascripts/discourse/routes/admin-plugins/show/discourse-workflows/index.js
new file mode 100644
index 00000000000..4a18b5aca01
--- /dev/null
+++ b/plugins/discourse-workflows/admin/assets/javascripts/discourse/routes/admin-plugins/show/discourse-workflows/index.js
@@ -0,0 +1,15 @@
+import { service } from "@ember/service";
+import { ajax } from "discourse/lib/ajax";
+import DiscourseRoute from "discourse/routes/discourse";
+
+export default class DiscourseWorkflowsIndexRoute extends DiscourseRoute {
+ @service store;
+
+ async model() {
+ const [workflows, stats] = await Promise.all([
+ this.store.findAll("discourse-workflows-workflow"),
+ ajax("/admin/plugins/discourse-workflows/stats.json"),
+ ]);
+ return { workflows, stats };
+ }
+}
diff --git a/plugins/discourse-workflows/admin/assets/javascripts/discourse/routes/admin-plugins/show/discourse-workflows/new.js b/plugins/discourse-workflows/admin/assets/javascripts/discourse/routes/admin-plugins/show/discourse-workflows/new.js
new file mode 100644
index 00000000000..4c337030795
--- /dev/null
+++ b/plugins/discourse-workflows/admin/assets/javascripts/discourse/routes/admin-plugins/show/discourse-workflows/new.js
@@ -0,0 +1,14 @@
+import { service } from "@ember/service";
+import DiscourseRoute from "discourse/routes/discourse";
+
+export default class DiscourseWorkflowsNewRoute extends DiscourseRoute {
+ @service store;
+
+ model() {
+ return this.store.createRecord("discourse-workflows-workflow", {
+ name: "",
+ nodes: [],
+ connections: [],
+ });
+ }
+}
diff --git a/plugins/discourse-workflows/admin/assets/javascripts/discourse/routes/admin-plugins/show/discourse-workflows/show.js b/plugins/discourse-workflows/admin/assets/javascripts/discourse/routes/admin-plugins/show/discourse-workflows/show.js
new file mode 100644
index 00000000000..d61e12a2e25
--- /dev/null
+++ b/plugins/discourse-workflows/admin/assets/javascripts/discourse/routes/admin-plugins/show/discourse-workflows/show.js
@@ -0,0 +1,15 @@
+import { service } from "@ember/service";
+import { ajax } from "discourse/lib/ajax";
+import DiscourseRoute from "discourse/routes/discourse";
+
+export default class DiscourseWorkflowsShowRoute extends DiscourseRoute {
+ @service store;
+
+ async model(params) {
+ const [workflow, stats] = await Promise.all([
+ this.store.find("discourse-workflows-workflow", params.id),
+ ajax(`/admin/plugins/discourse-workflows/stats/${params.id}.json`),
+ ]);
+ return { workflow, stats };
+ }
+}
diff --git a/plugins/discourse-workflows/admin/assets/javascripts/discourse/routes/admin-plugins/show/discourse-workflows/show/executions.js b/plugins/discourse-workflows/admin/assets/javascripts/discourse/routes/admin-plugins/show/discourse-workflows/show/executions.js
new file mode 100644
index 00000000000..607be2be165
--- /dev/null
+++ b/plugins/discourse-workflows/admin/assets/javascripts/discourse/routes/admin-plugins/show/discourse-workflows/show/executions.js
@@ -0,0 +1,3 @@
+import DiscourseRoute from "discourse/routes/discourse";
+
+export default class DiscourseWorkflowsShowExecutionsRoute extends DiscourseRoute {}
diff --git a/plugins/discourse-workflows/admin/assets/javascripts/discourse/routes/admin-plugins/show/discourse-workflows/show/executions/index.js b/plugins/discourse-workflows/admin/assets/javascripts/discourse/routes/admin-plugins/show/discourse-workflows/show/executions/index.js
new file mode 100644
index 00000000000..08b13eed895
--- /dev/null
+++ b/plugins/discourse-workflows/admin/assets/javascripts/discourse/routes/admin-plugins/show/discourse-workflows/show/executions/index.js
@@ -0,0 +1,7 @@
+import DiscourseRoute from "discourse/routes/discourse";
+
+export default class DiscourseWorkflowsShowExecutionsIndexRoute extends DiscourseRoute {
+ model() {
+ return this.modelFor("adminPlugins.show.discourse-workflows.show");
+ }
+}
diff --git a/plugins/discourse-workflows/admin/assets/javascripts/discourse/routes/admin-plugins/show/discourse-workflows/show/executions/show.js b/plugins/discourse-workflows/admin/assets/javascripts/discourse/routes/admin-plugins/show/discourse-workflows/show/executions/show.js
new file mode 100644
index 00000000000..e9acd941ce3
--- /dev/null
+++ b/plugins/discourse-workflows/admin/assets/javascripts/discourse/routes/admin-plugins/show/discourse-workflows/show/executions/show.js
@@ -0,0 +1,11 @@
+import { ajax } from "discourse/lib/ajax";
+import DiscourseRoute from "discourse/routes/discourse";
+
+export default class DiscourseWorkflowsShowExecutionsShowRoute extends DiscourseRoute {
+ async model(params) {
+ const result = await ajax(
+ `/admin/plugins/discourse-workflows/executions/${params.execution_id}`
+ );
+ return result.execution;
+ }
+}
diff --git a/plugins/discourse-workflows/admin/assets/javascripts/discourse/templates/admin-plugins/show/discourse-workflows-credentials.gjs b/plugins/discourse-workflows/admin/assets/javascripts/discourse/templates/admin-plugins/show/discourse-workflows-credentials.gjs
new file mode 100644
index 00000000000..57c66f4b3b8
--- /dev/null
+++ b/plugins/discourse-workflows/admin/assets/javascripts/discourse/templates/admin-plugins/show/discourse-workflows-credentials.gjs
@@ -0,0 +1,12 @@
+import htmlClass from "discourse/helpers/html-class";
+import DBreadcrumbsItem from "discourse/ui-kit/d-breadcrumbs-item";
+import { i18n } from "discourse-i18n";
+import CredentialsManager from "discourse/plugins/discourse-workflows/admin/components/workflows/credential/manager";
+
+export default <template>
+ {{htmlClass "workflows-page"}}
+ <div class="admin-config-page__main-area">
+ <DBreadcrumbsItem @label={{i18n "discourse_workflows.tabs.credentials"}} />
+ <CredentialsManager />
+ </div>
+</template>
diff --git a/plugins/discourse-workflows/admin/assets/javascripts/discourse/templates/admin-plugins/show/discourse-workflows-data-tables.gjs b/plugins/discourse-workflows/admin/assets/javascripts/discourse/templates/admin-plugins/show/discourse-workflows-data-tables.gjs
new file mode 100644
index 00000000000..16378c7d9a4
--- /dev/null
+++ b/plugins/discourse-workflows/admin/assets/javascripts/discourse/templates/admin-plugins/show/discourse-workflows-data-tables.gjs
@@ -0,0 +1,3 @@
+import htmlClass from "discourse/helpers/html-class";
+
+export default <template>{{htmlClass "workflows-page"}}{{outlet}}</template>
diff --git a/plugins/discourse-workflows/admin/assets/javascripts/discourse/templates/admin-plugins/show/discourse-workflows-data-tables/index.gjs b/plugins/discourse-workflows/admin/assets/javascripts/discourse/templates/admin-plugins/show/discourse-workflows-data-tables/index.gjs
new file mode 100644
index 00000000000..9bc288b7b1b
--- /dev/null
+++ b/plugins/discourse-workflows/admin/assets/javascripts/discourse/templates/admin-plugins/show/discourse-workflows-data-tables/index.gjs
@@ -0,0 +1,10 @@
+import DBreadcrumbsItem from "discourse/ui-kit/d-breadcrumbs-item";
+import { i18n } from "discourse-i18n";
+import DataTablesManager from "discourse/plugins/discourse-workflows/admin/components/workflows/data-table/manager";
+
+export default <template>
+ <div class="admin-config-page__main-area">
+ <DBreadcrumbsItem @label={{i18n "discourse_workflows.tabs.data_tables"}} />
+ <DataTablesManager />
+ </div>
+</template>
diff --git a/plugins/discourse-workflows/admin/assets/javascripts/discourse/templates/admin-plugins/show/discourse-workflows-data-tables/show.gjs b/plugins/discourse-workflows/admin/assets/javascripts/discourse/templates/admin-plugins/show/discourse-workflows-data-tables/show.gjs
new file mode 100644
index 00000000000..d96f609d7ff
--- /dev/null
+++ b/plugins/discourse-workflows/admin/assets/javascripts/discourse/templates/admin-plugins/show/discourse-workflows-data-tables/show.gjs
@@ -0,0 +1,13 @@
+import DBreadcrumbsItem from "discourse/ui-kit/d-breadcrumbs-item";
+import { i18n } from "discourse-i18n";
+import DataTableViewer from "discourse/plugins/discourse-workflows/admin/components/workflows/data-table/viewer";
+
+export default <template>
+ <div class="admin-config-page__main-area">
+ <DBreadcrumbsItem
+ @label={{i18n "discourse_workflows.tabs.data_tables"}}
+ @path="/admin/plugins/discourse-workflows/data-tables"
+ />
+ <DataTableViewer @dataTableId={{@controller.model}} />
+ </div>
+</template>
diff --git a/plugins/discourse-workflows/admin/assets/javascripts/discourse/templates/admin-plugins/show/discourse-workflows-executions.gjs b/plugins/discourse-workflows/admin/assets/javascripts/discourse/templates/admin-plugins/show/discourse-workflows-executions.gjs
new file mode 100644
index 00000000000..5bbb633561b
--- /dev/null
+++ b/plugins/discourse-workflows/admin/assets/javascripts/discourse/templates/admin-plugins/show/discourse-workflows-executions.gjs
@@ -0,0 +1,12 @@
+import htmlClass from "discourse/helpers/html-class";
+import DBreadcrumbsItem from "discourse/ui-kit/d-breadcrumbs-item";
+import { i18n } from "discourse-i18n";
+import ExecutionsManager from "discourse/plugins/discourse-workflows/admin/components/workflows/execution/manager";
+
+export default <template>
+ {{htmlClass "workflows-page"}}
+ <div class="admin-config-page__main-area">
+ <DBreadcrumbsItem @label={{i18n "discourse_workflows.tabs.executions"}} />
+ <ExecutionsManager />
+ </div>
+</template>
diff --git a/plugins/discourse-workflows/admin/assets/javascripts/discourse/templates/admin-plugins/show/discourse-workflows-templates.gjs b/plugins/discourse-workflows/admin/assets/javascripts/discourse/templates/admin-plugins/show/discourse-workflows-templates.gjs
new file mode 100644
index 00000000000..128da04d2e2
--- /dev/null
+++ b/plugins/discourse-workflows/admin/assets/javascripts/discourse/templates/admin-plugins/show/discourse-workflows-templates.gjs
@@ -0,0 +1,12 @@
+import htmlClass from "discourse/helpers/html-class";
+import DBreadcrumbsItem from "discourse/ui-kit/d-breadcrumbs-item";
+import { i18n } from "discourse-i18n";
+import WorkflowsTemplates from "discourse/plugins/discourse-workflows/admin/components/workflows/templates";
+
+export default <template>
+ {{htmlClass "workflows-page"}}
+ <div class="admin-config-page__main-area">
+ <DBreadcrumbsItem @label={{i18n "discourse_workflows.tabs.templates"}} />
+ <WorkflowsTemplates @templates={{@controller.model.templates}} />
+ </div>
+</template>
diff --git a/plugins/discourse-workflows/admin/assets/javascripts/discourse/templates/admin-plugins/show/discourse-workflows-variables.gjs b/plugins/discourse-workflows/admin/assets/javascripts/discourse/templates/admin-plugins/show/discourse-workflows-variables.gjs
new file mode 100644
index 00000000000..41f61f6a859
--- /dev/null
+++ b/plugins/discourse-workflows/admin/assets/javascripts/discourse/templates/admin-plugins/show/discourse-workflows-variables.gjs
@@ -0,0 +1,12 @@
+import htmlClass from "discourse/helpers/html-class";
+import DBreadcrumbsItem from "discourse/ui-kit/d-breadcrumbs-item";
+import { i18n } from "discourse-i18n";
+import VariablesManager from "discourse/plugins/discourse-workflows/admin/components/workflows/variable/manager";
+
+export default <template>
+ {{htmlClass "workflows-page"}}
+ <div class="admin-config-page__main-area">
+ <DBreadcrumbsItem @label={{i18n "discourse_workflows.tabs.variables"}} />
+ <VariablesManager />
+ </div>
+</template>
diff --git a/plugins/discourse-workflows/admin/assets/javascripts/discourse/templates/admin-plugins/show/discourse-workflows.gjs b/plugins/discourse-workflows/admin/assets/javascripts/discourse/templates/admin-plugins/show/discourse-workflows.gjs
new file mode 100644
index 00000000000..a087a33dfcb
--- /dev/null
+++ b/plugins/discourse-workflows/admin/assets/javascripts/discourse/templates/admin-plugins/show/discourse-workflows.gjs
@@ -0,0 +1 @@
+export default <template>{{outlet}}</template>
diff --git a/plugins/discourse-workflows/admin/assets/javascripts/discourse/templates/admin-plugins/show/discourse-workflows/index.gjs b/plugins/discourse-workflows/admin/assets/javascripts/discourse/templates/admin-plugins/show/discourse-workflows/index.gjs
new file mode 100644
index 00000000000..3ce09f196af
--- /dev/null
+++ b/plugins/discourse-workflows/admin/assets/javascripts/discourse/templates/admin-plugins/show/discourse-workflows/index.gjs
@@ -0,0 +1,15 @@
+import DBreadcrumbsItem from "discourse/ui-kit/d-breadcrumbs-item";
+import { i18n } from "discourse-i18n";
+import WorkflowsIndex from "discourse/plugins/discourse-workflows/admin/components/workflows/index";
+
+export default <template>
+ <div class="admin-config-page__main-area">
+ <DBreadcrumbsItem
+ @label={{i18n "discourse_workflows.tabs.all_workflows"}}
+ />
+ <WorkflowsIndex
+ @workflows={{@controller.model.workflows}}
+ @stats={{@controller.model.stats}}
+ />
+ </div>
+</template>
diff --git a/plugins/discourse-workflows/admin/assets/javascripts/discourse/templates/admin-plugins/show/discourse-workflows/new.gjs b/plugins/discourse-workflows/admin/assets/javascripts/discourse/templates/admin-plugins/show/discourse-workflows/new.gjs
new file mode 100644
index 00000000000..c6c697cb163
--- /dev/null
+++ b/plugins/discourse-workflows/admin/assets/javascripts/discourse/templates/admin-plugins/show/discourse-workflows/new.gjs
@@ -0,0 +1,13 @@
+import htmlClass from "discourse/helpers/html-class";
+import DBreadcrumbsItem from "discourse/ui-kit/d-breadcrumbs-item";
+import { i18n } from "discourse-i18n";
+import WorkflowsEditor from "discourse/plugins/discourse-workflows/admin/components/workflows/editor";
+
+export default <template>
+ {{htmlClass "workflows-page"}}
+ <DBreadcrumbsItem @label={{i18n "discourse_workflows.new_workflow"}} />
+
+ <div class="admin-config-page__main-area">
+ <WorkflowsEditor @workflow={{@controller.model}} @isNew={{true}} />
+ </div>
+</template>
diff --git a/plugins/discourse-workflows/admin/assets/javascripts/discourse/templates/admin-plugins/show/discourse-workflows/show.gjs b/plugins/discourse-workflows/admin/assets/javascripts/discourse/templates/admin-plugins/show/discourse-workflows/show.gjs
new file mode 100644
index 00000000000..52f36533fcb
--- /dev/null
+++ b/plugins/discourse-workflows/admin/assets/javascripts/discourse/templates/admin-plugins/show/discourse-workflows/show.gjs
@@ -0,0 +1,74 @@
+import Component from "@glimmer/component";
+import { action } from "@ember/object";
+import htmlClass from "discourse/helpers/html-class";
+import { ajax } from "discourse/lib/ajax";
+import { popupAjaxError } from "discourse/lib/ajax-error";
+import DBreadcrumbsItem from "discourse/ui-kit/d-breadcrumbs-item";
+import DHorizontalOverflowNav from "discourse/ui-kit/d-horizontal-overflow-nav";
+import DNavItem from "discourse/ui-kit/d-nav-item";
+import WorkflowEditableTitle from "discourse/plugins/discourse-workflows/admin/components/workflows/editable-title";
+import Stats from "discourse/plugins/discourse-workflows/admin/components/workflows/stats";
+
+class WorkflowShowPage extends Component {
+ get workflow() {
+ return this.args.controller.model.workflow;
+ }
+
+ get stats() {
+ return this.args.controller.model.stats;
+ }
+
+ @action
+ async updateName(name) {
+ try {
+ await ajax(
+ `/admin/plugins/discourse-workflows/workflows/${this.workflow.id}.json`,
+ { type: "PUT", data: { workflow: { name } } }
+ );
+ this.workflow.set("name", name);
+ } catch (e) {
+ popupAjaxError(e);
+ }
+ }
+
+ <template>
+ {{htmlClass "workflows-page"}}
+ <DBreadcrumbsItem
+ @path="/admin/plugins/discourse-workflows/workflows/{{this.workflow.id}}"
+ @label={{this.workflow.name}}
+ />
+
+ <div class="admin-config-page__main-area">
+ <div class="workflows-header">
+ <WorkflowEditableTitle
+ @value={{this.workflow.name}}
+ @onSave={{this.updateName}}
+ />
+
+ <Stats @stats={{this.stats}} />
+ </div>
+
+ <div class="workflows-show-nav">
+ <DHorizontalOverflowNav>
+ <DNavItem
+ @route="adminPlugins.show.discourse-workflows.show.index"
+ @label="discourse_workflows.tabs.workflow"
+ />
+ <DNavItem
+ @route="adminPlugins.show.discourse-workflows.show.executions"
+ @label="discourse_workflows.tabs.executions"
+ />
+ <DNavItem
+ @route="adminPlugins.show.discourse-workflows.show.settings"
+ @label="discourse_workflows.tabs.settings"
+ />
+ </DHorizontalOverflowNav>
+
+ </div>
+
+ {{outlet}}
+ </div>
+ </template>
+}
+
+export default WorkflowShowPage;
diff --git a/plugins/discourse-workflows/admin/assets/javascripts/discourse/templates/admin-plugins/show/discourse-workflows/show/executions.gjs b/plugins/discourse-workflows/admin/assets/javascripts/discourse/templates/admin-plugins/show/discourse-workflows/show/executions.gjs
new file mode 100644
index 00000000000..a087a33dfcb
--- /dev/null
+++ b/plugins/discourse-workflows/admin/assets/javascripts/discourse/templates/admin-plugins/show/discourse-workflows/show/executions.gjs
@@ -0,0 +1 @@
+export default <template>{{outlet}}</template>
diff --git a/plugins/discourse-workflows/admin/assets/javascripts/discourse/templates/admin-plugins/show/discourse-workflows/show/executions/index.gjs b/plugins/discourse-workflows/admin/assets/javascripts/discourse/templates/admin-plugins/show/discourse-workflows/show/executions/index.gjs
new file mode 100644
index 00000000000..f979f7527d1
--- /dev/null
+++ b/plugins/discourse-workflows/admin/assets/javascripts/discourse/templates/admin-plugins/show/discourse-workflows/show/executions/index.gjs
@@ -0,0 +1,8 @@
+import DBreadcrumbsItem from "discourse/ui-kit/d-breadcrumbs-item";
+import { i18n } from "discourse-i18n";
+import ExecutionsManager from "discourse/plugins/discourse-workflows/admin/components/workflows/execution/manager";
+
+export default <template>
+ <DBreadcrumbsItem @label={{i18n "discourse_workflows.tabs.executions"}} />
+ <ExecutionsManager @workflowId={{@controller.model.workflow.id}} />
+</template>
diff --git a/plugins/discourse-workflows/admin/assets/javascripts/discourse/templates/admin-plugins/show/discourse-workflows/show/executions/show.gjs b/plugins/discourse-workflows/admin/assets/javascripts/discourse/templates/admin-plugins/show/discourse-workflows/show/executions/show.gjs
new file mode 100644
index 00000000000..cee40a7a002
--- /dev/null
+++ b/plugins/discourse-workflows/admin/assets/javascripts/discourse/templates/admin-plugins/show/discourse-workflows/show/executions/show.gjs
@@ -0,0 +1,12 @@
+import DBreadcrumbsItem from "discourse/ui-kit/d-breadcrumbs-item";
+import { i18n } from "discourse-i18n";
+import ExecutionDetail from "discourse/plugins/discourse-workflows/admin/components/workflows/executions/detail";
+
+export default <template>
+ <DBreadcrumbsItem
+ @path="/admin/plugins/discourse-workflows/workflows/{{@controller.model.workflow_id}}/executions"
+ @label={{i18n "discourse_workflows.tabs.executions"}}
+ />
+ <DBreadcrumbsItem @label="#{{@controller.model.id}}" />
+ <ExecutionDetail @execution={{@controller.model}} />
+</template>
diff --git a/plugins/discourse-workflows/admin/assets/javascripts/discourse/templates/admin-plugins/show/discourse-workflows/show/index.gjs b/plugins/discourse-workflows/admin/assets/javascripts/discourse/templates/admin-plugins/show/discourse-workflows/show/index.gjs
new file mode 100644
index 00000000000..d455434ca76
--- /dev/null
+++ b/plugins/discourse-workflows/admin/assets/javascripts/discourse/templates/admin-plugins/show/discourse-workflows/show/index.gjs
@@ -0,0 +1,5 @@
+import WorkflowsEditor from "discourse/plugins/discourse-workflows/admin/components/workflows/editor";
+
+export default <template>
+ <WorkflowsEditor @workflow={{@controller.model.workflow}} />
+</template>
diff --git a/plugins/discourse-workflows/admin/assets/javascripts/discourse/templates/admin-plugins/show/discourse-workflows/show/settings.gjs b/plugins/discourse-workflows/admin/assets/javascripts/discourse/templates/admin-plugins/show/discourse-workflows/show/settings.gjs
new file mode 100644
index 00000000000..58a8accbda0
--- /dev/null
+++ b/plugins/discourse-workflows/admin/assets/javascripts/discourse/templates/admin-plugins/show/discourse-workflows/show/settings.gjs
@@ -0,0 +1,8 @@
+import DBreadcrumbsItem from "discourse/ui-kit/d-breadcrumbs-item";
+import { i18n } from "discourse-i18n";
+import WorkflowSettings from "discourse/plugins/discourse-workflows/admin/components/workflows/settings";
+
+export default <template>
+ <DBreadcrumbsItem @label={{i18n "discourse_workflows.tabs.settings"}} />
+ <WorkflowSettings @workflow={{@controller.model.workflow}} />
+</template>
diff --git a/plugins/discourse-workflows/app/controllers/discourse_workflows/admin_controller.rb b/plugins/discourse-workflows/app/controllers/discourse_workflows/admin_controller.rb
new file mode 100644
index 00000000000..379bd46893b
--- /dev/null
+++ b/plugins/discourse-workflows/app/controllers/discourse_workflows/admin_controller.rb
@@ -0,0 +1,11 @@
+# frozen_string_literal: true
+
+module DiscourseWorkflows
+ class AdminController < ::Admin::AdminController
+ requires_plugin DiscourseWorkflows::PLUGIN_NAME
+
+ def index
+ render html: "", layout: "admin"
+ end
+ end
+end
diff --git a/plugins/discourse-workflows/app/controllers/discourse_workflows/credentials_controller.rb b/plugins/discourse-workflows/app/controllers/discourse_workflows/credentials_controller.rb
new file mode 100644
index 00000000000..dc24f2250ea
--- /dev/null
+++ b/plugins/discourse-workflows/app/controllers/discourse_workflows/credentials_controller.rb
@@ -0,0 +1,101 @@
+# frozen_string_literal: true
+
+module DiscourseWorkflows
+ class CredentialsController < ::Admin::AdminController
+ requires_plugin DiscourseWorkflows::PLUGIN_NAME
+
+ def index
+ DiscourseWorkflows::Credential::List.call(service_params) do |result|
+ on_success do |credentials:, load_more_url:, total_rows:|
+ render json: {
+ credentials:
+ serialize_data(credentials, DiscourseWorkflows::CredentialSerializer),
+ meta: { total_rows: total_rows, load_more_url: load_more_url }.compact,
+ }
+ end
+ on_failure { render(json: failed_json, status: :unprocessable_entity) }
+ on_failed_policy(:can_manage_workflows) { raise Discourse::InvalidAccess }
+ end
+ end
+
+ def create
+ DiscourseWorkflows::Credential::Create.call(service_params) do |result|
+ on_success do |credential:|
+ render_serialized(
+ credential,
+ DiscourseWorkflows::CredentialSerializer,
+ root: "credential",
+ status: :created,
+ )
+ end
+ on_failure { render(json: failed_json, status: :unprocessable_entity) }
+ on_failed_policy(:can_manage_workflows) { raise Discourse::InvalidAccess }
+ on_failed_policy(:valid_credential_type) do
+ render(json: failed_json.merge(errors: ["Invalid credential type"]), status: :bad_request)
+ end
+ on_failed_contract do |contract|
+ render(
+ json: failed_json.merge(errors: contract.errors.full_messages),
+ status: :bad_request,
+ )
+ end
+ on_model_errors(:credential) do |model|
+ render(
+ json: failed_json.merge(errors: model.errors.full_messages),
+ status: :unprocessable_entity,
+ )
+ end
+ end
+ end
+
+ def update
+ DiscourseWorkflows::Credential::Update.call(
+ service_params.deep_merge(params: { credential_id: params[:id] }),
+ ) do |result|
+ on_success do |credential:|
+ render_serialized(
+ credential,
+ DiscourseWorkflows::CredentialSerializer,
+ root: "credential",
+ )
+ end
+ on_failure { render(json: failed_json, status: :unprocessable_entity) }
+ on_failed_policy(:can_manage_workflows) { raise Discourse::InvalidAccess }
+ on_failed_contract do |contract|
+ render(
+ json: failed_json.merge(errors: contract.errors.full_messages),
+ status: :bad_request,
+ )
+ end
+ on_model_not_found(:credential) { raise Discourse::NotFound }
+ on_model_errors(:credential) do |model|
+ render(
+ json: failed_json.merge(errors: model.errors.full_messages),
+ status: :unprocessable_entity,
+ )
+ end
+ end
+ end
+
+ def destroy
+ DiscourseWorkflows::Credential::Destroy.call(
+ service_params.deep_merge(params: { credential_id: params[:id] }),
+ ) do |result|
+ on_success { head :no_content }
+ on_failure { render(json: failed_json, status: :unprocessable_entity) }
+ on_failed_policy(:can_manage_workflows) { raise Discourse::InvalidAccess }
+ on_failed_policy(:credential_not_in_use) do
+ render(
+ json:
+ failed_json.merge(
+ type: "credential_in_use",
+ referencing_workflows: result[:referencing_workflows],
+ ),
+ status: :unprocessable_entity,
+ )
+ end
+ on_model_not_found(:credential) { raise Discourse::NotFound }
+ end
+ end
+ end
+end
diff --git a/plugins/discourse-workflows/app/controllers/discourse_workflows/data_table_columns_controller.rb b/plugins/discourse-workflows/app/controllers/discourse_workflows/data_table_columns_controller.rb
new file mode 100644
index 00000000000..7d4d7ad92dc
--- /dev/null
+++ b/plugins/discourse-workflows/app/controllers/discourse_workflows/data_table_columns_controller.rb
@@ -0,0 +1,61 @@
+# frozen_string_literal: true
+
+module DiscourseWorkflows
+ class DataTableColumnsController < ::Admin::AdminController
+ requires_plugin DiscourseWorkflows::PLUGIN_NAME
+
+ def create
+ DiscourseWorkflows::DataTableColumn::Create.call(service_params) do |result|
+ on_success do |data_table:|
+ render_serialized(
+ data_table,
+ DiscourseWorkflows::DataTableSerializer,
+ root: "data_table",
+ status: :created,
+ )
+ end
+ on_failure { render(json: failed_json, status: :unprocessable_entity) }
+ on_failed_contract do |contract|
+ render(
+ json: failed_json.merge(errors: contract.errors.full_messages),
+ status: :bad_request,
+ )
+ end
+ on_model_not_found(:data_table) { raise Discourse::NotFound }
+ on_failed_policy(:can_manage_workflows) { raise Discourse::InvalidAccess }
+ end
+ end
+
+ def rename
+ DiscourseWorkflows::DataTableColumn::Rename.call(service_params) do |result|
+ on_success do |data_table:|
+ render_serialized(data_table, DiscourseWorkflows::DataTableSerializer, root: "data_table")
+ end
+ on_failure { render(json: failed_json, status: :unprocessable_entity) }
+ on_failed_contract do |contract|
+ render(
+ json: failed_json.merge(errors: contract.errors.full_messages),
+ status: :bad_request,
+ )
+ end
+ on_model_not_found(:data_table) { raise Discourse::NotFound }
+ on_failed_policy(:can_manage_workflows) { raise Discourse::InvalidAccess }
+ end
+ end
+
+ def destroy
+ DiscourseWorkflows::DataTableColumn::Destroy.call(service_params) do |result|
+ on_success { head :no_content }
+ on_failure { render(json: failed_json, status: :unprocessable_entity) }
+ on_failed_contract do |contract|
+ render(
+ json: failed_json.merge(errors: contract.errors.full_messages),
+ status: :bad_request,
+ )
+ end
+ on_model_not_found(:data_table) { raise Discourse::NotFound }
+ on_failed_policy(:can_manage_workflows) { raise Discourse::InvalidAccess }
+ end
+ end
+ end
+end
diff --git a/plugins/discourse-workflows/app/controllers/discourse_workflows/data_table_rows_controller.rb b/plugins/discourse-workflows/app/controllers/discourse_workflows/data_table_rows_controller.rb
new file mode 100644
index 00000000000..4e078810638
--- /dev/null
+++ b/plugins/discourse-workflows/app/controllers/discourse_workflows/data_table_rows_controller.rb
@@ -0,0 +1,146 @@
+# frozen_string_literal: true
+
+module DiscourseWorkflows
+ class DataTableRowsController < ::Admin::AdminController
+ requires_plugin DiscourseWorkflows::PLUGIN_NAME
+
+ def index
+ DiscourseWorkflows::DataTableRow::Get.call(
+ service_params.deep_merge(params: { data_table_id: params[:data_table_id] }),
+ ) do |result|
+ on_success do |query_result:|
+ render json: { rows: query_result[:rows], count: query_result[:count] }
+ end
+ on_failure { render(json: failed_json, status: :unprocessable_entity) }
+ on_failed_contract do |contract|
+ render(
+ json: failed_json.merge(errors: contract.errors.full_messages),
+ status: :bad_request,
+ )
+ end
+ on_model_not_found(:data_table) { raise Discourse::NotFound }
+ on_failed_policy(:can_manage_workflows) { raise Discourse::InvalidAccess }
+ on_model_errors(:query) { |model| render_invalid_model(model) }
+ end
+ end
+
+ def create
+ DiscourseWorkflows::DataTableRow::Insert.call(
+ service_params.deep_merge(params: { data_table_id: params[:data_table_id] }),
+ ) do |result|
+ on_success { |row:| render json: { row: row }, status: :created }
+ on_failure { render(json: failed_json, status: :unprocessable_entity) }
+ on_failed_contract do |contract|
+ render(
+ json: failed_json.merge(errors: contract.errors.full_messages),
+ status: :bad_request,
+ )
+ end
+ on_model_not_found(:data_table) { raise Discourse::NotFound }
+ on_failed_policy(:can_manage_workflows) { raise Discourse::InvalidAccess }
+ on_failed_policy(:within_storage_limit) { render_storage_limit_exceeded }
+ on_model_errors(:row_input) { |model| render_invalid_model(model) }
+ end
+ end
+
+ def update_bulk
+ DiscourseWorkflows::DataTableRow::Update.call(
+ service_params.deep_merge(params: { data_table_id: params[:data_table_id] }),
+ ) do |result|
+ on_success { |updated_count:| render json: { updated_count: updated_count } }
+ on_failure { render(json: failed_json, status: :unprocessable_entity) }
+ on_failed_contract do |contract|
+ render(
+ json: failed_json.merge(errors: contract.errors.full_messages),
+ status: :bad_request,
+ )
+ end
+ on_model_not_found(:data_table) { raise Discourse::NotFound }
+ on_failed_policy(:can_manage_workflows) { raise Discourse::InvalidAccess }
+ on_failed_policy(:within_storage_limit) { render_storage_limit_exceeded }
+ on_model_errors(:query) { |model| render_invalid_model(model) }
+ on_model_errors(:row_input) { |model| render_invalid_model(model) }
+ end
+ end
+
+ def update
+ DiscourseWorkflows::DataTableRow::UpdateSingle.call(
+ service_params.deep_merge(
+ params: {
+ data_table_id: params[:data_table_id],
+ row_id: params[:id],
+ },
+ ),
+ ) do |result|
+ on_success { |row:| render json: { row: row } }
+ on_failure { render(json: failed_json, status: :unprocessable_entity) }
+ on_failed_contract do |contract|
+ render(
+ json: failed_json.merge(errors: contract.errors.full_messages),
+ status: :bad_request,
+ )
+ end
+ on_model_not_found(:data_table) { raise Discourse::NotFound }
+ on_model_not_found(:existing_row) { raise Discourse::NotFound }
+ on_failed_policy(:can_manage_workflows) { raise Discourse::InvalidAccess }
+ on_failed_policy(:within_storage_limit) { render_storage_limit_exceeded }
+ on_model_errors(:row_input) { |model| render_invalid_model(model) }
+ end
+ end
+
+ def destroy
+ DiscourseWorkflows::DataTableRow::Destroy.call(
+ service_params.deep_merge(
+ params: {
+ data_table_id: params[:data_table_id],
+ row_id: params[:id],
+ },
+ ),
+ ) do |result|
+ on_success { head :no_content }
+ on_failure { render(json: failed_json, status: :unprocessable_entity) }
+ on_failed_contract do |contract|
+ render(
+ json: failed_json.merge(errors: contract.errors.full_messages),
+ status: :bad_request,
+ )
+ end
+ on_model_not_found(:data_table) { raise Discourse::NotFound }
+ on_model_not_found(:row) { raise Discourse::NotFound }
+ on_failed_policy(:can_manage_workflows) { raise Discourse::InvalidAccess }
+ end
+ end
+
+ def destroy_bulk
+ DiscourseWorkflows::DataTableRow::Destroy.call(
+ service_params.deep_merge(params: { data_table_id: params[:data_table_id] }),
+ ) do |result|
+ on_success { |deleted_count:| render json: { deleted_count: deleted_count } }
+ on_failure { render(json: failed_json, status: :unprocessable_entity) }
+ on_failed_contract do |contract|
+ render(
+ json: failed_json.merge(errors: contract.errors.full_messages),
+ status: :bad_request,
+ )
+ end
+ on_model_not_found(:data_table) { raise Discourse::NotFound }
+ on_failed_policy(:can_manage_workflows) { raise Discourse::InvalidAccess }
+ on_model_errors(:query) { |model| render_invalid_model(model) }
+ end
+ end
+
+ private
+
+ def render_storage_limit_exceeded
+ render json:
+ failed_json.merge(
+ errors: [I18n.t("discourse_workflows.errors.storage_limit_exceeded")],
+ ),
+ status: :bad_request
+ end
+
+ def render_invalid_model(model)
+ render json: failed_json.merge(errors: model.errors.full_messages), status: :bad_request
+ end
+ end
+end
diff --git a/plugins/discourse-workflows/app/controllers/discourse_workflows/data_tables_controller.rb b/plugins/discourse-workflows/app/controllers/discourse_workflows/data_tables_controller.rb
new file mode 100644
index 00000000000..a55e8b5f21e
--- /dev/null
+++ b/plugins/discourse-workflows/app/controllers/discourse_workflows/data_tables_controller.rb
@@ -0,0 +1,114 @@
+# frozen_string_literal: true
+
+module DiscourseWorkflows
+ class DataTablesController < ::Admin::AdminController
+ requires_plugin DiscourseWorkflows::PLUGIN_NAME
+
+ def index
+ DiscourseWorkflows::DataTable::List.call(service_params) do |result|
+ on_success do |data_tables:, total_rows:, table_sizes: {}, load_more_url:|
+ render json: {
+ data_tables:
+ serialize_data(
+ data_tables,
+ DiscourseWorkflows::DataTableSerializer,
+ table_sizes: table_sizes,
+ ),
+ meta: { total_rows: total_rows, load_more_url: load_more_url }.compact,
+ }
+ end
+ on_failure { render(json: failed_json, status: :unprocessable_entity) }
+ on_failed_policy(:can_manage_workflows) { raise Discourse::InvalidAccess }
+ end
+ end
+
+ def show
+ DiscourseWorkflows::DataTable::Show.call(
+ service_params.deep_merge(params: { data_table_id: params[:id] }),
+ ) do |result|
+ on_success do |data_table:|
+ render_serialized(data_table, DiscourseWorkflows::DataTableSerializer, root: "data_table")
+ end
+ on_failure { render(json: failed_json, status: :unprocessable_entity) }
+ on_model_not_found(:data_table) { raise Discourse::NotFound }
+ on_failed_policy(:can_manage_workflows) { raise Discourse::InvalidAccess }
+ end
+ end
+
+ def create
+ DiscourseWorkflows::DataTable::Create.call(service_params) do |result|
+ on_success do |data_table:|
+ render_serialized(
+ data_table,
+ DiscourseWorkflows::DataTableSerializer,
+ root: "data_table",
+ status: :created,
+ )
+ end
+ on_failure { render(json: failed_json, status: :unprocessable_entity) }
+ on_failed_contract do |contract|
+ render(
+ json: failed_json.merge(errors: contract.errors.full_messages),
+ status: :bad_request,
+ )
+ end
+ on_failed_policy(:can_manage_workflows) { raise Discourse::InvalidAccess }
+ on_model_errors(:data_table) do |model|
+ render(
+ json: failed_json.merge(errors: model.errors.full_messages),
+ status: :unprocessable_entity,
+ )
+ end
+ end
+ end
+
+ def update
+ DiscourseWorkflows::DataTable::Update.call(
+ service_params.deep_merge(params: { data_table_id: params[:id] }),
+ ) do |result|
+ on_success do |data_table:|
+ render_serialized(data_table, DiscourseWorkflows::DataTableSerializer, root: "data_table")
+ end
+ on_failure { render(json: failed_json, status: :unprocessable_entity) }
+ on_failed_contract do |contract|
+ render(
+ json: failed_json.merge(errors: contract.errors.full_messages),
+ status: :bad_request,
+ )
+ end
+ on_model_not_found(:data_table) { raise Discourse::NotFound }
+ on_failed_policy(:can_manage_workflows) { raise Discourse::InvalidAccess }
+ on_model_errors(:data_table) do |model|
+ render(
+ json: failed_json.merge(errors: model.errors.full_messages),
+ status: :unprocessable_entity,
+ )
+ end
+ end
+ end
+
+ def destroy
+ DiscourseWorkflows::DataTable::Destroy.call(
+ service_params.deep_merge(params: { data_table_id: params[:id] }),
+ ) do |result|
+ on_success { head :no_content }
+ on_failure { render(json: failed_json, status: :unprocessable_entity) }
+ on_failed_policy(:can_manage_workflows) { raise Discourse::InvalidAccess }
+ on_failed_policy(:data_table_not_in_use) do
+ render(
+ json:
+ failed_json.merge(
+ type: "data_table_in_use",
+ referencing_workflows:
+ result[:referencing_workflows]
+ .pluck(:id, :name)
+ .map { |id, name| { id:, name: } },
+ ),
+ status: :unprocessable_entity,
+ )
+ end
+ on_model_not_found(:data_table) { raise Discourse::NotFound }
+ end
+ end
+ end
+end
diff --git a/plugins/discourse-workflows/app/controllers/discourse_workflows/dynamic_node_parameters_controller.rb b/plugins/discourse-workflows/app/controllers/discourse_workflows/dynamic_node_parameters_controller.rb
new file mode 100644
index 00000000000..8122d15b441
--- /dev/null
+++ b/plugins/discourse-workflows/app/controllers/discourse_workflows/dynamic_node_parameters_controller.rb
@@ -0,0 +1,50 @@
+# frozen_string_literal: true
+
+module DiscourseWorkflows
+ class DynamicNodeParametersController < ::Admin::AdminController
+ requires_plugin DiscourseWorkflows::PLUGIN_NAME
+
+ def options
+ node_type = hash_param(:nodeTypeAndVersion)
+ identifier = node_type["name"].presence
+ raise Discourse::NotFound if identifier.blank?
+
+ version = node_type["version"].presence&.to_s
+ node_class = DiscourseWorkflows::Registry.find_node_type(identifier, version: version)
+ raise Discourse::NotFound unless node_class.respond_to?(:load_options_context)
+
+ context =
+ DiscourseWorkflows::LoadOptionsContext.new(
+ method_name: params[:methodName],
+ property_name: params[:path],
+ node_identifier: identifier,
+ node_version: version,
+ node_id: hash_param(:node).dig("id"),
+ node_name: hash_param(:node).dig("name"),
+ workflow_id: params[:workflowId],
+ parameters: hash_param(:currentNodeParameters),
+ credentials: hash_param(:credentials),
+ filter: params[:filter],
+ input_context: hash_param(:inputContext),
+ execution_context: hash_param(:executionContext),
+ user: current_user,
+ guardian: guardian,
+ node_class: node_class,
+ )
+
+ options = node_class.load_options_context(context)
+ raise Discourse::NotFound if options.nil?
+
+ render_json_dump options
+ end
+
+ private
+
+ def hash_param(key)
+ value = params[key]
+ value = JSON.parse(value) if value.is_a?(String) && value.start_with?("{")
+ value = value.to_unsafe_h if value.respond_to?(:to_unsafe_h)
+ value.is_a?(Hash) ? value : {}
+ end
+ end
+end
diff --git a/plugins/discourse-workflows/app/controllers/discourse_workflows/executions_controller.rb b/plugins/discourse-workflows/app/controllers/discourse_workflows/executions_controller.rb
new file mode 100644
index 00000000000..cf96ea172e0
--- /dev/null
+++ b/plugins/discourse-workflows/app/controllers/discourse_workflows/executions_controller.rb
@@ -0,0 +1,64 @@
+# frozen_string_literal: true
+
+module DiscourseWorkflows
+ class ExecutionsController < ::Admin::AdminController
+ requires_plugin DiscourseWorkflows::PLUGIN_NAME
+
+ def create
+ DiscourseWorkflows::Workflow::ManualExecute.call(
+ service_params.deep_merge(params: { user_id: current_user.id }),
+ ) do |result|
+ on_success do |execution:|
+ render json: {
+ execution: {
+ id: execution.id,
+ workflow_id: execution.workflow_id,
+ },
+ },
+ status: :created
+ end
+ on_failure { render(json: failed_json, status: :unprocessable_entity) }
+ on_failed_policy(:can_manage_workflows) { raise Discourse::InvalidAccess }
+ on_model_not_found(:trigger_node) { raise Discourse::NotFound }
+ on_model_not_found(:workflow) { raise Discourse::NotFound }
+ end
+ end
+
+ def index
+ DiscourseWorkflows::Execution::List.call(service_params) do |result|
+ on_success do |executions:, load_more_url: nil|
+ render json: {
+ executions:
+ serialize_data(executions, DiscourseWorkflows::ExecutionListSerializer),
+ meta: { load_more_executions: load_more_url }.compact,
+ }
+ end
+ on_failure { render(json: failed_json, status: :unprocessable_entity) }
+ on_failed_policy(:can_manage_workflows) { raise Discourse::InvalidAccess }
+ end
+ end
+
+ def destroy
+ DiscourseWorkflows::Execution::Destroy.call(
+ service_params.deep_merge(params: { execution_ids: params[:ids] }),
+ ) do |result|
+ on_success { head :no_content }
+ on_failure { render(json: failed_json, status: :unprocessable_entity) }
+ on_failed_policy(:can_manage_workflows) { raise Discourse::InvalidAccess }
+ end
+ end
+
+ def show
+ DiscourseWorkflows::Execution::Show.call(
+ service_params.deep_merge(params: { execution_id: params[:id] }),
+ ) do |result|
+ on_success do |execution:|
+ render_serialized(execution, DiscourseWorkflows::ExecutionSerializer, root: "execution")
+ end
+ on_failure { render(json: failed_json, status: :unprocessable_entity) }
+ on_model_not_found(:execution) { raise Discourse::NotFound }
+ on_failed_policy(:can_manage_workflows) { raise Discourse::InvalidAccess }
+ end
+ end
+ end
+end
diff --git a/plugins/discourse-workflows/app/controllers/discourse_workflows/expressions_controller.rb b/plugins/discourse-workflows/app/controllers/discourse_workflows/expressions_controller.rb
new file mode 100644
index 00000000000..3453b9aa4e1
--- /dev/null
+++ b/plugins/discourse-workflows/app/controllers/discourse_workflows/expressions_controller.rb
@@ -0,0 +1,38 @@
+# frozen_string_literal: true
+
+module DiscourseWorkflows
+ class ExpressionsController < ::Admin::AdminController
+ requires_plugin DiscourseWorkflows::PLUGIN_NAME
+
+ RATE_LIMIT = 30
+ RATE_PERIOD = 60
+
+ before_action :rate_limit_evaluation, only: :evaluate
+
+ def evaluate
+ Expression::Evaluate.call(service_params) do |result|
+ on_success { |segments:| render json: { segments: } }
+ on_failed_policy(:can_manage_workflows) { raise Discourse::InvalidAccess }
+ on_failed_contract do |contract|
+ render(
+ json: failed_json.merge(errors: contract.errors.full_messages),
+ status: :bad_request,
+ )
+ end
+ on_failure { render(json: failed_json, status: :unprocessable_entity) }
+ end
+ end
+
+ private
+
+ def rate_limit_evaluation
+ RateLimiter.new(
+ current_user,
+ "expression-evaluate",
+ RATE_LIMIT,
+ RATE_PERIOD,
+ apply_limit_to_staff: true,
+ ).performed!
+ end
+ end
+end
diff --git a/plugins/discourse-workflows/app/controllers/discourse_workflows/form_test_sessions_controller.rb b/plugins/discourse-workflows/app/controllers/discourse_workflows/form_test_sessions_controller.rb
new file mode 100644
index 00000000000..e3500d7cece
--- /dev/null
+++ b/plugins/discourse-workflows/app/controllers/discourse_workflows/form_test_sessions_controller.rb
@@ -0,0 +1,33 @@
+# frozen_string_literal: true
+
+module DiscourseWorkflows
+ class FormTestSessionsController < ::Admin::AdminController
+ requires_plugin DiscourseWorkflows::PLUGIN_NAME
+
+ def create
+ DiscourseWorkflows::FormTestSession::Create.call(
+ service_params.deep_merge(
+ params: {
+ workflow_id: params[:id],
+ trigger_node_id: params[:trigger_node_id],
+ },
+ ),
+ ) do |result|
+ on_success do |token:|
+ render json: { test_url: "/workflows/form-test/#{token}" }, status: :created
+ end
+ on_failure { render(json: failed_json, status: :unprocessable_entity) }
+ on_failed_contract do |contract|
+ render(
+ json: failed_json.merge(errors: contract.errors.full_messages),
+ status: :bad_request,
+ )
+ end
+ on_failed_policy(:can_manage_workflows) { raise Discourse::InvalidAccess }
+ on_failed_policy(:form_trigger_node) { raise Discourse::NotFound }
+ on_model_not_found(:workflow) { raise Discourse::NotFound }
+ on_model_not_found(:trigger_node) { raise Discourse::NotFound }
+ end
+ end
+ end
+end
diff --git a/plugins/discourse-workflows/app/controllers/discourse_workflows/forms_controller.rb b/plugins/discourse-workflows/app/controllers/discourse_workflows/forms_controller.rb
new file mode 100644
index 00000000000..e4f96eb0734
--- /dev/null
+++ b/plugins/discourse-workflows/app/controllers/discourse_workflows/forms_controller.rb
@@ -0,0 +1,198 @@
+# frozen_string_literal: true
+
+module DiscourseWorkflows
+ class FormsController < ::ApplicationController
+ requires_plugin DiscourseWorkflows::PLUGIN_NAME
+
+ FORM_SHOW_RATE_LIMIT = 30
+ FORM_SHOW_RATE_PERIOD = 60
+
+ skip_before_action :verify_authenticity_token
+ skip_before_action :redirect_to_login_if_required
+ skip_before_action :check_xhr
+
+ before_action :check_form_show_rate_limit, only: %i[show test_show waiting_show waiting_status]
+ before_action :check_form_submit_rate_limit, only: %i[create test_create]
+ before_action :check_form_resume_rate_limit, only: :waiting_create
+ before_action :verify_request_origin, only: %i[create test_create waiting_create]
+
+ def show
+ if request.format.json?
+ DiscourseWorkflows::Form::Show.call(
+ service_params.deep_merge(params: { form_query_parameters: form_query_parameters }),
+ ) do
+ on_success { |form_data:| render json: form_data }
+ on_failed_policy(:authenticated_if_required) { raise Discourse::NotLoggedIn }
+ on_failed_policy(:action_form) { raise Discourse::NotFound }
+ on_failure { render(json: failed_json, status: :unprocessable_entity) }
+ on_model_not_found(:published_trigger) { raise Discourse::NotFound }
+ on_model_not_found(:form_node) { raise Discourse::NotFound }
+ end
+ else
+ render html: "", layout: "application"
+ end
+ end
+
+ def create
+ DiscourseWorkflows::Form::Submit.call(service_params) do
+ on_success do |execution:, response_metadata:|
+ body = DiscourseWorkflows::FormResponse.initial_submission(execution, response_metadata)
+ status =
+ DiscourseWorkflows::FormResponse.initial_submission_status(execution, response_metadata)
+ render_form_response(body, status)
+ end
+ on_failed_policy(:authenticated_if_required) { raise Discourse::NotLoggedIn }
+ on_failed_policy(:valid_initial_submission_token) do
+ render_form_response(
+ failed_json.merge(errors: [I18n.t("discourse_workflows.errors.invalid_form_token")]),
+ :unprocessable_entity,
+ )
+ end
+ on_failed_step(:ensure_form_valid) do |form_validation:|
+ render json: { errors: form_validation.errors.map(&:to_h) }, status: :unprocessable_entity
+ end
+ on_failure do
+ render_form_response(
+ failed_json.merge(
+ errors: [I18n.t("discourse_workflows.errors.invalid_form_submission")],
+ ),
+ :unprocessable_entity,
+ )
+ end
+ on_model_not_found(:published_trigger) { raise Discourse::NotFound }
+ end
+ end
+
+ def test_show
+ unless request.format.json?
+ render html: "", layout: "application"
+ return
+ end
+
+ DiscourseWorkflows::FormTestSession::Show.call(service_params) do
+ on_success { |form_data:| render json: form_data }
+ on_failed_policy(:owns_form_test_session) { raise Discourse::InvalidAccess }
+ on_failure { render(json: failed_json, status: :unprocessable_entity) }
+ on_model_not_found(:form_test_session) { raise Discourse::NotFound }
+ on_model_not_found(:workflow) { raise Discourse::NotFound }
+ on_model_not_found(:form_node) { raise Discourse::NotFound }
+ end
+ end
+
+ def test_create
+ DiscourseWorkflows::FormTestSession::Submit.call(service_params) do
+ on_success do |execution:, response_metadata:|
+ body = DiscourseWorkflows::FormResponse.initial_submission(execution, response_metadata)
+ status =
+ DiscourseWorkflows::FormResponse.initial_submission_status(execution, response_metadata)
+ render_form_response(body, status)
+ end
+ on_failed_policy(:owns_form_test_session) { raise Discourse::InvalidAccess }
+ on_failed_step(:ensure_form_valid) do |form_validation:|
+ render json: { errors: form_validation.errors.map(&:to_h) }, status: :unprocessable_entity
+ end
+ on_failure do
+ render_form_response(
+ failed_json.merge(
+ errors: [I18n.t("discourse_workflows.errors.invalid_form_submission")],
+ ),
+ :unprocessable_entity,
+ )
+ end
+ on_model_not_found(:form_test_session) { raise Discourse::NotFound }
+ on_model_not_found(:workflow) { raise Discourse::NotFound }
+ on_model_not_found(:form_node) { raise Discourse::NotFound }
+ end
+ end
+
+ def waiting_status
+ render_waiting_webhook(path: "status")
+ end
+
+ def waiting_show
+ render_waiting_webhook(path: "")
+ end
+
+ def waiting_create
+ render_waiting_webhook(path: "", dispatch_params: { form_data: submitted_form_data })
+ end
+
+ private
+
+ def check_form_show_rate_limit
+ RateLimiter.new(
+ nil,
+ "workflow_form_show:#{request.remote_ip}",
+ FORM_SHOW_RATE_LIMIT,
+ FORM_SHOW_RATE_PERIOD,
+ ).performed!
+ end
+
+ def check_form_submit_rate_limit
+ RateLimiter.new(current_user, "workflow_form_submit:#{request.remote_ip}", 10, 60).performed!
+ end
+
+ def check_form_resume_rate_limit
+ RateLimiter.new(current_user, "workflow_form_resume:#{request.remote_ip}", 10, 60).performed!
+ end
+
+ def verify_request_origin
+ origin = request.origin || request.headers["Origin"]
+ raise Discourse::InvalidAccess if origin.blank?
+ raise Discourse::InvalidAccess if URI.parse(origin).host != Discourse.current_hostname
+ rescue URI::InvalidURIError
+ raise Discourse::InvalidAccess
+ end
+
+ def form_query_parameters
+ request.query_parameters.except(
+ "resume_token",
+ DiscourseWorkflows::WaitingExecution::SIGNATURE_PARAM,
+ )
+ end
+
+ def waiting_signature
+ request.query_parameters[DiscourseWorkflows::WaitingExecution::SIGNATURE_PARAM].presence
+ end
+
+ def submitted_form_data
+ form_data = params[:form_data] || {}
+ return form_data.to_unsafe_h if form_data.respond_to?(:to_unsafe_h)
+
+ form_data
+ end
+
+ def render_waiting_webhook(path:, dispatch_params: {})
+ result =
+ DiscourseWorkflows::WaitingWebhookRunner.call(
+ execution_id: params[:execution_id].to_i,
+ signature: waiting_signature,
+ http_method: request.method,
+ path: path,
+ node_type: "form",
+ params: dispatch_params,
+ service_params: service_params,
+ )
+
+ render_form_response(result.body, result.status)
+ end
+
+ def render_form_response(body, status)
+ return head status if body.nil?
+
+ render json: normalize_form_response(body), status: status
+ end
+
+ def normalize_form_response(body)
+ return body unless body.is_a?(Hash)
+
+ normalized = body.deep_dup
+ error = normalized.delete(:error)
+ error = normalized.delete("error") if error.nil?
+ has_errors = normalized.key?(:errors) || normalized.key?("errors")
+ normalized[:errors] = Array(error) if error.present? && !has_errors
+
+ normalized
+ end
+ end
+end
diff --git a/plugins/discourse-workflows/app/controllers/discourse_workflows/node_types_controller.rb b/plugins/discourse-workflows/app/controllers/discourse_workflows/node_types_controller.rb
new file mode 100644
index 00000000000..f06c65f136c
--- /dev/null
+++ b/plugins/discourse-workflows/app/controllers/discourse_workflows/node_types_controller.rb
@@ -0,0 +1,21 @@
+# frozen_string_literal: true
+
+module DiscourseWorkflows
+ class NodeTypesController < ::Admin::AdminController
+ requires_plugin DiscourseWorkflows::PLUGIN_NAME
+
+ def index
+ DiscourseWorkflows::NodeType::List.call(service_params) do |result|
+ on_success do |node_types:, credential_types:, expression_context:|
+ render json: {
+ node_types: node_types,
+ credential_types: credential_types,
+ expression_context: expression_context,
+ }
+ end
+ on_failure { render(json: failed_json, status: :unprocessable_entity) }
+ on_failed_policy(:can_manage_workflows) { raise Discourse::InvalidAccess }
+ end
+ end
+ end
+end
diff --git a/plugins/discourse-workflows/app/controllers/discourse_workflows/stats_controller.rb b/plugins/discourse-workflows/app/controllers/discourse_workflows/stats_controller.rb
new file mode 100644
index 00000000000..72a94c47c15
--- /dev/null
+++ b/plugins/discourse-workflows/app/controllers/discourse_workflows/stats_controller.rb
@@ -0,0 +1,15 @@
+# frozen_string_literal: true
+
+module DiscourseWorkflows
+ class StatsController < ::Admin::AdminController
+ requires_plugin DiscourseWorkflows::PLUGIN_NAME
+
+ def index
+ DiscourseWorkflows::Stats::Summary.call(service_params) do |result|
+ on_success { |stats:| render json: stats }
+ on_failure { render(json: failed_json, status: :unprocessable_entity) }
+ on_failed_policy(:can_manage_workflows) { raise Discourse::InvalidAccess }
+ end
+ end
+ end
+end
diff --git a/plugins/discourse-workflows/app/controllers/discourse_workflows/templates_controller.rb b/plugins/discourse-workflows/app/controllers/discourse_workflows/templates_controller.rb
new file mode 100644
index 00000000000..96949d4c1bd
--- /dev/null
+++ b/plugins/discourse-workflows/app/controllers/discourse_workflows/templates_controller.rb
@@ -0,0 +1,26 @@
+# frozen_string_literal: true
+
+module DiscourseWorkflows
+ class TemplatesController < ::Admin::AdminController
+ requires_plugin DiscourseWorkflows::PLUGIN_NAME
+
+ def index
+ DiscourseWorkflows::Template::List.call(service_params) do
+ on_success { |templates:| render json: { templates: } }
+ on_failed_policy(:can_manage_workflows) { raise Discourse::InvalidAccess }
+ on_failure { render(json: failed_json, status: :unprocessable_entity) }
+ end
+ end
+
+ def show
+ DiscourseWorkflows::Template::Show.call(
+ service_params.deep_merge(params: { template_id: params[:id] }),
+ ) do
+ on_success { |template:| render json: { template: } }
+ on_failure { render(json: failed_json, status: :unprocessable_entity) }
+ on_model_not_found(:template) { raise Discourse::NotFound }
+ on_failed_policy(:can_manage_workflows) { raise Discourse::InvalidAccess }
+ end
+ end
+ end
+end
diff --git a/plugins/discourse-workflows/app/controllers/discourse_workflows/topic_admin_button_controller.rb b/plugins/discourse-workflows/app/controllers/discourse_workflows/topic_admin_button_controller.rb
new file mode 100644
index 00000000000..a14d4805ff7
--- /dev/null
+++ b/plugins/discourse-workflows/app/controllers/discourse_workflows/topic_admin_button_controller.rb
@@ -0,0 +1,25 @@
+# frozen_string_literal: true
+
+module DiscourseWorkflows
+ class TopicAdminButtonController < ::ApplicationController
+ requires_plugin DiscourseWorkflows::PLUGIN_NAME
+
+ before_action :ensure_logged_in
+
+ def create
+ DiscourseWorkflows::Workflow::TriggerTopicAdminButton.call(service_params) do
+ on_success { head :no_content }
+ on_failure { render(json: failed_json, status: :unprocessable_entity) }
+ on_failed_contract do |contract|
+ render(
+ json: failed_json.merge(errors: contract.errors.full_messages),
+ status: :bad_request,
+ )
+ end
+ on_model_not_found(:published_trigger) { raise Discourse::NotFound }
+ on_model_not_found(:topic) { raise Discourse::NotFound }
+ on_failed_policy(:can_manage_workflows) { raise Discourse::InvalidAccess }
+ end
+ end
+ end
+end
diff --git a/plugins/discourse-workflows/app/controllers/discourse_workflows/variables_controller.rb b/plugins/discourse-workflows/app/controllers/discourse_workflows/variables_controller.rb
new file mode 100644
index 00000000000..64a84e26218
--- /dev/null
+++ b/plugins/discourse-workflows/app/controllers/discourse_workflows/variables_controller.rb
@@ -0,0 +1,83 @@
+# frozen_string_literal: true
+
+module DiscourseWorkflows
+ class VariablesController < ::Admin::AdminController
+ requires_plugin DiscourseWorkflows::PLUGIN_NAME
+
+ def index
+ DiscourseWorkflows::Variable::List.call(service_params) do |result|
+ on_success do |variables:, total_rows:, load_more_url:|
+ render json: {
+ variables: serialize_data(variables, DiscourseWorkflows::VariableSerializer),
+ meta: { total_rows: total_rows, load_more_url: load_more_url }.compact,
+ }
+ end
+ on_failure { render(json: failed_json, status: :unprocessable_entity) }
+ on_failed_policy(:can_manage_workflows) { raise Discourse::InvalidAccess }
+ end
+ end
+
+ def create
+ DiscourseWorkflows::Variable::Create.call(service_params) do |result|
+ on_success do |variable:|
+ render_serialized(
+ variable,
+ DiscourseWorkflows::VariableSerializer,
+ root: "variable",
+ status: :created,
+ )
+ end
+ on_failure { render(json: failed_json, status: :unprocessable_entity) }
+ on_failed_policy(:can_manage_workflows) { raise Discourse::InvalidAccess }
+ on_failed_contract do |contract|
+ render(
+ json: failed_json.merge(errors: contract.errors.full_messages),
+ status: :bad_request,
+ )
+ end
+ on_model_errors(:variable) do |model|
+ render(
+ json: failed_json.merge(errors: model.errors.full_messages),
+ status: :unprocessable_entity,
+ )
+ end
+ end
+ end
+
+ def update
+ DiscourseWorkflows::Variable::Update.call(
+ service_params.deep_merge(params: { variable_id: params[:id] }),
+ ) do |result|
+ on_success do |variable:|
+ render_serialized(variable, DiscourseWorkflows::VariableSerializer, root: "variable")
+ end
+ on_failure { render(json: failed_json, status: :unprocessable_entity) }
+ on_failed_policy(:can_manage_workflows) { raise Discourse::InvalidAccess }
+ on_failed_contract do |contract|
+ render(
+ json: failed_json.merge(errors: contract.errors.full_messages),
+ status: :bad_request,
+ )
+ end
+ on_model_not_found(:variable) { raise Discourse::NotFound }
+ on_model_errors(:variable) do |model|
+ render(
+ json: failed_json.merge(errors: model.errors.full_messages),
+ status: :unprocessable_entity,
+ )
+ end
+ end
+ end
+
+ def destroy
+ DiscourseWorkflows::Variable::Destroy.call(
+ service_params.deep_merge(params: { variable_id: params[:id] }),
+ ) do |result|
+ on_success { head :no_content }
+ on_failure { render(json: failed_json, status: :unprocessable_entity) }
+ on_failed_policy(:can_manage_workflows) { raise Discourse::InvalidAccess }
+ on_model_not_found(:variable) { raise Discourse::NotFound }
+ end
+ end
+ end
+end
diff --git a/plugins/discourse-workflows/app/controllers/discourse_workflows/webhook_test_listeners_controller.rb b/plugins/discourse-workflows/app/controllers/discourse_workflows/webhook_test_listeners_controller.rb
new file mode 100644
index 00000000000..3ea2c0ebc12
--- /dev/null
+++ b/plugins/discourse-workflows/app/controllers/discourse_workflows/webhook_test_listeners_controller.rb
@@ -0,0 +1,65 @@
+# frozen_string_literal: true
+
+module DiscourseWorkflows
+ class WebhookTestListenersController < ::Admin::AdminController
+ requires_plugin DiscourseWorkflows::PLUGIN_NAME
+
+ def create
+ DiscourseWorkflows::WebhookTestListener::Start.call(
+ service_params.deep_merge(
+ params: {
+ workflow_id: params[:id],
+ trigger_node_id: params[:trigger_node_id],
+ },
+ ),
+ ) do |result|
+ on_success do |listener:|
+ render(
+ json: {
+ listener_id: listener.listener_id,
+ test_url: listener.test_url,
+ expires_at: listener.expires_at.iso8601,
+ },
+ status: :created,
+ )
+ end
+ on_failure { render(json: failed_json, status: :unprocessable_entity) }
+ on_failed_contract do |contract|
+ render(
+ json: failed_json.merge(errors: contract.errors.full_messages),
+ status: :bad_request,
+ )
+ end
+ on_failed_policy(:can_manage_workflows) { raise Discourse::InvalidAccess }
+ on_failed_policy(:webhook_trigger_node) { raise Discourse::NotFound }
+ on_model_not_found(:workflow) { raise Discourse::NotFound }
+ on_model_not_found(:trigger_node) { raise Discourse::NotFound }
+ end
+ end
+
+ def destroy
+ DiscourseWorkflows::WebhookTestListener::Cancel.call(
+ service_params.deep_merge(
+ params: {
+ workflow_id: params[:id],
+ listener_id: params[:listener_id],
+ },
+ ),
+ ) do
+ on_success { head :no_content }
+ on_failure { render(json: failed_json, status: :unprocessable_entity) }
+ on_failed_contract do |contract|
+ render(
+ json: failed_json.merge(errors: contract.errors.full_messages),
+ status: :bad_request,
+ )
+ end
+ on_failed_policy(:can_manage_workflows) { raise Discourse::InvalidAccess }
+ on_failed_policy(:listener_belongs_to_workflow) { raise Discourse::NotFound }
+ on_failed_policy(:owns_webhook_test_listener) { raise Discourse::InvalidAccess }
+ on_model_not_found(:workflow) { raise Discourse::NotFound }
+ on_model_not_found(:listener) { raise Discourse::NotFound }
+ end
+ end
+ end
+end
diff --git a/plugins/discourse-workflows/app/controllers/discourse_workflows/webhooks_controller.rb b/plugins/discourse-workflows/app/controllers/discourse_workflows/webhooks_controller.rb
new file mode 100644
index 00000000000..430a22a48fa
--- /dev/null
+++ b/plugins/discourse-workflows/app/controllers/discourse_workflows/webhooks_controller.rb
@@ -0,0 +1,112 @@
+# frozen_string_literal: true
+
+module DiscourseWorkflows
+ class WebhooksController < ::ApplicationController
+ requires_plugin DiscourseWorkflows::PLUGIN_NAME
+
+ skip_before_action :verify_authenticity_token
+ skip_before_action :redirect_to_login_if_required
+ skip_before_action :check_xhr
+
+ WEBHOOK_RATE_LIMIT = 20
+ WEBHOOK_RATE_PERIOD = 10
+
+ before_action :check_webhook_rate_limit, only: %i[receive receive_test]
+
+ def receive
+ receive_webhook(test_webhook: false)
+ end
+
+ def receive_test
+ receive_webhook(test_webhook: true)
+ end
+
+ private
+
+ def receive_webhook(test_webhook:)
+ DiscourseWorkflows::Webhook::Receive.call(
+ service_params.deep_merge(params: webhook_params(test_webhook: test_webhook)),
+ ) do |result|
+ on_success do
+ DiscourseWorkflows::WebhookResponseRenderer.render(self, result[:webhook_response])
+ end
+ on_model_not_found(:webhook_test_listener) do
+ render json: { error: "not_found" }, status: :not_found
+ end
+ on_model_not_found(:claimed_webhook_test_listener) do
+ render json: { error: "not_found" }, status: :not_found
+ end
+ on_model_not_found(:webhook_nodes) do
+ render json: { error: "not_found" }, status: :not_found
+ end
+ on_failed_policy(:valid_resume_request) do
+ render json: { error: "not_found" }, status: :not_found
+ end
+ on_failed_policy(:valid_http_method) do
+ render json: { error: "not_found" }, status: :not_found
+ end
+ on_model_not_found(:authenticated_nodes) do
+ render_auth_failure(result[:auth_failure_reason], result[:auth_failure_mode])
+ end
+ on_model_not_found(:request_allowed_nodes) do
+ render json: { error: "forbidden" }, status: :forbidden
+ end
+ on_model_not_found(:claimed_execution) do
+ render json: {
+ error: I18n.t("discourse_workflows.errors.already_resumed"),
+ },
+ status: :conflict
+ end
+ on_failure { render(json: failed_json, status: :unprocessable_entity) }
+ end
+ end
+
+ def render_auth_failure(reason, auth_mode)
+ if auth_mode == Webhook::Action::AuthenticateNode::BASIC_AUTH &&
+ reason != Webhook::Action::AuthenticateNode::MISCONFIGURED
+ response.headers["WWW-Authenticate"] = 'Basic realm="Webhook"'
+ end
+
+ case reason
+ when Webhook::Action::AuthenticateNode::CHALLENGE
+ render plain: "Authorization is required!", status: :unauthorized
+ when Webhook::Action::AuthenticateNode::DENIED
+ render plain: "Authorization data is wrong!", status: :forbidden
+ else
+ render plain: "No authentication data defined on node!", status: :internal_server_error
+ end
+ end
+
+ def check_webhook_rate_limit
+ key = "workflow_webhook:#{request.remote_ip}"
+ limiter = RateLimiter.new(nil, key, WEBHOOK_RATE_LIMIT, WEBHOOK_RATE_PERIOD)
+ unless limiter.performed!(raise_error: false)
+ render json: { error: "rate_limit" }, status: :too_many_requests
+ end
+ end
+
+ def webhook_params(test_webhook:)
+ parser = WebhookRequestParser.new(request, params)
+ is_resume = params[:execution_id].present?
+ query = request.query_parameters
+ {
+ execution_id: params[:execution_id]&.to_i,
+ token: is_resume ? query["signature"] : query["token"],
+ webhook_suffix: params[:suffix].to_s,
+ path: params[:path].to_s,
+ test_listener_id: params[:listener_id].to_s,
+ http_method: request.method,
+ body: parser.parse_body,
+ headers: parser.extract_headers,
+ path_params: {
+ },
+ query_params: is_resume ? query.except("signature") : query,
+ raw_body: request.raw_post,
+ remote_ip: request.remote_ip,
+ ips: request.respond_to?(:ips) ? request.ips : [],
+ raw_authorization: request.headers["Authorization"],
+ test_webhook: test_webhook,
+ }
+ end
+ end
+end
diff --git a/plugins/discourse-workflows/app/controllers/discourse_workflows/workflows_controller.rb b/plugins/discourse-workflows/app/controllers/discourse_workflows/workflows_controller.rb
new file mode 100644
index 00000000000..c4cc1e6d14a
--- /dev/null
+++ b/plugins/discourse-workflows/app/controllers/discourse_workflows/workflows_controller.rb
@@ -0,0 +1,247 @@
+# frozen_string_literal: true
+
+module DiscourseWorkflows
+ class WorkflowsController < ::Admin::AdminController
+ requires_plugin DiscourseWorkflows::PLUGIN_NAME
+
+ def index
+ DiscourseWorkflows::Workflow::List.call(service_params) do |result|
+ on_success do |workflows:, total_rows:, load_more_url:|
+ render json: {
+ workflows: serialize_data(workflows, DiscourseWorkflows::WorkflowSerializer),
+ meta: {
+ total_rows_workflows: total_rows,
+ load_more_workflows: load_more_url,
+ }.compact,
+ }
+ end
+ on_failure { render(json: failed_json, status: :unprocessable_entity) }
+ on_failed_policy(:can_manage_workflows) { raise Discourse::InvalidAccess }
+ end
+ end
+
+ def show
+ DiscourseWorkflows::Workflow::Show.call(
+ service_params.deep_merge(params: { workflow_id: params[:id] }),
+ ) do |result|
+ on_success do |workflow:|
+ render_serialized(workflow, DiscourseWorkflows::WorkflowSerializer, root: "workflow")
+ end
+ on_failure { render(json: failed_json, status: :unprocessable_entity) }
+ on_model_not_found(:workflow) { raise Discourse::NotFound }
+ on_failed_policy(:can_manage_workflows) { raise Discourse::InvalidAccess }
+ end
+ end
+
+ def create
+ DiscourseWorkflows::Workflow::Create.call(
+ service_params.deep_merge(params: workflow_params),
+ ) do |result|
+ on_success do |workflow:|
+ render_serialized(
+ workflow,
+ DiscourseWorkflows::WorkflowSerializer,
+ root: "workflow",
+ status: :created,
+ )
+ end
+ on_failure { render(json: failed_json, status: :unprocessable_entity) }
+ on_failed_contract do |contract|
+ render(
+ json: failed_json.merge(errors: contract.errors.full_messages),
+ status: :bad_request,
+ )
+ end
+ on_failed_step(:populate_graph) do |step_result|
+ render(
+ json: failed_json.merge(errors: Array(step_result.error)),
+ status: :unprocessable_entity,
+ )
+ end
+ on_failed_policy(:can_manage_workflows) { raise Discourse::InvalidAccess }
+ on_model_errors(:workflow) do |model|
+ render(
+ json: failed_json.merge(errors: model.errors.full_messages),
+ status: :unprocessable_entity,
+ )
+ end
+ end
+ end
+
+ def update
+ workflow_attrs = workflow_params
+
+ if workflow_attrs.key?("published") &&
+ workflow_attrs.keys.all? { |key| %w[name published].include?(key) }
+ return update_published_state(workflow_attrs["published"])
+ end
+
+ DiscourseWorkflows::Workflow::Update.call(
+ service_params.deep_merge(params: workflow_attrs.merge(workflow_id: params[:id])),
+ ) do |result|
+ on_success do |workflow:|
+ render_serialized(workflow, DiscourseWorkflows::WorkflowSerializer, root: "workflow")
+ end
+ on_failure { render(json: failed_json, status: :unprocessable_entity) }
+ on_failed_contract do |contract|
+ render(
+ json: failed_json.merge(errors: contract.errors.full_messages),
+ status: :bad_request,
+ )
+ end
+ on_failed_step(:populate_graph) do |step_result|
+ render(
+ json: failed_json.merge(errors: Array(step_result.error)),
+ status: :unprocessable_entity,
+ )
+ end
+ on_model_not_found(:workflow) { raise Discourse::NotFound }
+ on_failed_policy(:can_manage_workflows) { raise Discourse::InvalidAccess }
+ on_model_errors(:workflow) do |model|
+ render(
+ json: failed_json.merge(errors: model.errors.full_messages),
+ status: :unprocessable_entity,
+ )
+ end
+ end
+ end
+
+ def destroy
+ DiscourseWorkflows::Workflow::Destroy.call(
+ service_params.deep_merge(params: { workflow_id: params[:id] }),
+ ) do |result|
+ on_success { head :no_content }
+ on_failure { render(json: failed_json, status: :unprocessable_entity) }
+ on_model_not_found(:workflow) { raise Discourse::NotFound }
+ on_failed_policy(:can_manage_workflows) { raise Discourse::InvalidAccess }
+ end
+ end
+
+ def update_pin_data
+ service_input = { workflow_id: params[:id], node_name: params[:node_name] }
+ service_input[:items] = unwrap_pin_data_items(params[:items]) if params.key?(:items)
+
+ DiscourseWorkflows::Workflow::UpdatePinData.call(
+ service_params.deep_merge(params: service_input),
+ ) do |result|
+ on_success { head :no_content }
+ on_model_not_found(:workflow) { raise Discourse::NotFound }
+ on_model_not_found(:node) { raise Discourse::NotFound }
+ on_failed_policy(:can_manage_workflows) { raise Discourse::InvalidAccess }
+ on_failed_policy(:node_supports_pinning) do
+ render(
+ json:
+ failed_json.merge(
+ errors: [I18n.t("discourse_workflows.pin_data.errors.unsupported_node")],
+ ),
+ status: :unprocessable_entity,
+ )
+ end
+ on_failed_policy(:within_size_cap) do
+ render(
+ json:
+ failed_json.merge(
+ errors: [
+ I18n.t(
+ "discourse_workflows.pin_data.errors.size_limit_exceeded",
+ limit: SiteSetting.discourse_workflows_max_pin_data_bytes,
+ ),
+ ],
+ ),
+ status: :unprocessable_entity,
+ )
+ end
+ on_failed_policy(:items_are_valid) do
+ render(
+ json:
+ failed_json.merge(
+ errors: [I18n.t("discourse_workflows.pin_data.errors.invalid_items")],
+ ),
+ status: :unprocessable_entity,
+ )
+ end
+ on_failure { render(json: failed_json, status: :unprocessable_entity) }
+ end
+ end
+
+ def discard_draft
+ DiscourseWorkflows::Workflow::DiscardDraft.call(
+ service_params.deep_merge(params: { workflow_id: params[:id] }),
+ ) do |result|
+ on_success do |workflow:|
+ render_serialized(workflow, DiscourseWorkflows::WorkflowSerializer, root: "workflow")
+ end
+ on_failure { render(json: failed_json, status: :unprocessable_entity) }
+ on_failed_contract do |contract|
+ render(
+ json: failed_json.merge(errors: contract.errors.full_messages),
+ status: :bad_request,
+ )
+ end
+ on_model_not_found(:workflow) { raise Discourse::NotFound }
+ on_model_not_found(:active_version) do
+ render(json: failed_json, status: :unprocessable_entity)
+ end
+ on_failed_policy(:can_manage_workflows) { raise Discourse::InvalidAccess }
+ on_model_errors(:workflow) do |model|
+ render(
+ json: failed_json.merge(errors: model.errors.full_messages),
+ status: :unprocessable_entity,
+ )
+ end
+ end
+ end
+
+ private
+
+ def workflow_params
+ params.require(:workflow).to_unsafe_h
+ end
+
+ def unwrap_pin_data_items(raw)
+ case raw
+ when ActionController::Parameters
+ raw.to_unsafe_h
+ when Array
+ raw.map { |item| unwrap_pin_data_items(item) }
+ else
+ raw
+ end
+ end
+
+ def update_published_state(published)
+ service_class =
+ ActiveModel::Type::Boolean.new.cast(published) ? Workflow::Publish : Workflow::Unpublish
+
+ service_class.call(service_params.deep_merge(params: { workflow_id: params[:id] })) do
+ on_success do |workflow:|
+ render_serialized(workflow, DiscourseWorkflows::WorkflowSerializer, root: "workflow")
+ end
+ on_failed_step(:activate_triggers) do |step_result|
+ render(
+ json: failed_json.merge(errors: Array(step_result.error)),
+ status: :unprocessable_entity,
+ )
+ end
+ on_failure { render(json: failed_json, status: :unprocessable_entity) }
+ on_failed_contract do |contract|
+ render(
+ json: failed_json.merge(errors: contract.errors.full_messages),
+ status: :bad_request,
+ )
+ end
+ on_model_not_found(:workflow) { raise Discourse::NotFound }
+ on_model_not_found(:workflow_version) do
+ render(json: failed_json, status: :unprocessable_entity)
+ end
+ on_failed_policy(:can_manage_workflows) { raise Discourse::InvalidAccess }
+ on_model_errors(:workflow) do |model|
+ render(
+ json: failed_json.merge(errors: model.errors.full_messages),
+ status: :unprocessable_entity,
+ )
+ end
+ end
+ end
+ end
+end
diff --git a/plugins/discourse-workflows/app/jobs/regular/discourse_workflows/execute_workflow.rb b/plugins/discourse-workflows/app/jobs/regular/discourse_workflows/execute_workflow.rb
new file mode 100644
index 00000000000..9d1ff60ac5d
--- /dev/null
+++ b/plugins/discourse-workflows/app/jobs/regular/discourse_workflows/execute_workflow.rb
@@ -0,0 +1,21 @@
+# frozen_string_literal: true
+
+module Jobs
+ module DiscourseWorkflows
+ class ExecuteWorkflow < ::Jobs::Base
+ def execute(args)
+ ::DiscourseWorkflows::Workflow::Execute.call(
+ params:
+ args.slice(
+ :workflow_id,
+ :workflow_version_id,
+ :trigger_node_id,
+ :trigger_data,
+ :execution_mode,
+ :user_id,
+ ).compact,
+ )
+ end
+ end
+ end
+end
diff --git a/plugins/discourse-workflows/app/jobs/regular/discourse_workflows/resume_waiting_execution.rb b/plugins/discourse-workflows/app/jobs/regular/discourse_workflows/resume_waiting_execution.rb
new file mode 100644
index 00000000000..e41cba33ecd
--- /dev/null
+++ b/plugins/discourse-workflows/app/jobs/regular/discourse_workflows/resume_waiting_execution.rb
@@ -0,0 +1,24 @@
+# frozen_string_literal: true
+
+module Jobs
+ module DiscourseWorkflows
+ class ResumeWaitingExecution < ::Jobs::Base
+ def execute(args)
+ return unless SiteSetting.discourse_workflows_enabled
+
+ execution = ::DiscourseWorkflows::Execution.find_by(id: args[:execution_id])
+ return if execution.nil? || !execution.waiting?
+ return if execution.waiting_until.present? && execution.waiting_until > Time.current
+
+ if execution.timeout_action == "fail"
+ execution.fail_with_timeout!
+ else
+ claimed = ::DiscourseWorkflows::Execution.claim_for_resume(execution)
+ return if claimed.nil?
+
+ ::DiscourseWorkflows::Executor.resume(claimed, claimed.waiting_step_input_items)
+ end
+ end
+ end
+ end
+end
diff --git a/plugins/discourse-workflows/app/jobs/regular/discourse_workflows/resume_webhook_waiting.rb b/plugins/discourse-workflows/app/jobs/regular/discourse_workflows/resume_webhook_waiting.rb
new file mode 100644
index 00000000000..c5db7987d06
--- /dev/null
+++ b/plugins/discourse-workflows/app/jobs/regular/discourse_workflows/resume_webhook_waiting.rb
@@ -0,0 +1,21 @@
+# frozen_string_literal: true
+
+module Jobs
+ module DiscourseWorkflows
+ class ResumeWebhookWaiting < ::Jobs::Base
+ def execute(args)
+ return unless SiteSetting.discourse_workflows_enabled
+
+ execution =
+ ::DiscourseWorkflows::Execution.find_by(id: args[:execution_id], status: :waiting)
+ return if execution.nil?
+
+ claimed = ::DiscourseWorkflows::Execution.claim_for_resume(execution)
+ return if claimed.nil?
+
+ response_items = args[:response_items] || [{ "json" => {} }]
+ ::DiscourseWorkflows::Executor.resume(claimed, response_items)
+ end
+ end
+ end
+end
diff --git a/plugins/discourse-workflows/app/jobs/scheduled/discourse_workflows/check_schedules.rb b/plugins/discourse-workflows/app/jobs/scheduled/discourse_workflows/check_schedules.rb
new file mode 100644
index 00000000000..64daebc1e20
--- /dev/null
+++ b/plugins/discourse-workflows/app/jobs/scheduled/discourse_workflows/check_schedules.rb
@@ -0,0 +1,13 @@
+# frozen_string_literal: true
+
+module Jobs
+ module DiscourseWorkflows
+ class CheckSchedules < ::Jobs::Scheduled
+ every 1.minute
+
+ def execute(_args = nil)
+ ::DiscourseWorkflows::Execution::CheckSchedules.call
+ end
+ end
+ end
+end
diff --git a/plugins/discourse-workflows/app/jobs/scheduled/discourse_workflows/check_stale_topics.rb b/plugins/discourse-workflows/app/jobs/scheduled/discourse_workflows/check_stale_topics.rb
new file mode 100644
index 00000000000..eb9a4b14708
--- /dev/null
+++ b/plugins/discourse-workflows/app/jobs/scheduled/discourse_workflows/check_stale_topics.rb
@@ -0,0 +1,13 @@
+# frozen_string_literal: true
+
+module Jobs
+ module DiscourseWorkflows
+ class CheckStaleTopics < ::Jobs::Scheduled
+ every 30.minutes
+
+ def execute(_args = nil)
+ ::DiscourseWorkflows::Execution::CheckStaleTopics.call
+ end
+ end
+ end
+end
diff --git a/plugins/discourse-workflows/app/jobs/scheduled/discourse_workflows/expire_waiting_executions.rb b/plugins/discourse-workflows/app/jobs/scheduled/discourse_workflows/expire_waiting_executions.rb
new file mode 100644
index 00000000000..6c67d23933a
--- /dev/null
+++ b/plugins/discourse-workflows/app/jobs/scheduled/discourse_workflows/expire_waiting_executions.rb
@@ -0,0 +1,13 @@
+# frozen_string_literal: true
+
+module Jobs
+ module DiscourseWorkflows
+ class ExpireWaitingExecutions < ::Jobs::Scheduled
+ every 1.minute
+
+ def execute(_args = nil)
+ ::DiscourseWorkflows::Execution::ExpireWaiting.call
+ end
+ end
+ end
+end
diff --git a/plugins/discourse-workflows/app/jobs/scheduled/discourse_workflows/purge_expired_webhook_test_listeners.rb b/plugins/discourse-workflows/app/jobs/scheduled/discourse_workflows/purge_expired_webhook_test_listeners.rb
new file mode 100644
index 00000000000..3512f3d8cd5
--- /dev/null
+++ b/plugins/discourse-workflows/app/jobs/scheduled/discourse_workflows/purge_expired_webhook_test_listeners.rb
@@ -0,0 +1,13 @@
+# frozen_string_literal: true
+
+module Jobs
+ module DiscourseWorkflows
+ class PurgeExpiredWebhookTestListeners < ::Jobs::Scheduled
+ every 5.minutes
+
+ def execute(_args = nil)
+ ::DiscourseWorkflows::WebhookTestListener.purge_expired!
+ end
+ end
+ end
+end
diff --git a/plugins/discourse-workflows/app/jobs/scheduled/discourse_workflows/purge_old_executions.rb b/plugins/discourse-workflows/app/jobs/scheduled/discourse_workflows/purge_old_executions.rb
new file mode 100644
index 00000000000..d61979f4ed0
--- /dev/null
+++ b/plugins/discourse-workflows/app/jobs/scheduled/discourse_workflows/purge_old_executions.rb
@@ -0,0 +1,13 @@
+# frozen_string_literal: true
+
+module Jobs
+ module DiscourseWorkflows
+ class PurgeOldExecutions < ::Jobs::Scheduled
+ every 1.day
+
+ def execute(_args = nil)
+ ::DiscourseWorkflows::Execution.purge_old
+ end
+ end
+ end
+end
diff --git a/plugins/discourse-workflows/app/models/discourse_workflows/credential.rb b/plugins/discourse-workflows/app/models/discourse_workflows/credential.rb
new file mode 100644
index 00000000000..84cf27da156
--- /dev/null
+++ b/plugins/discourse-workflows/app/models/discourse_workflows/credential.rb
@@ -0,0 +1,62 @@
+# frozen_string_literal: true
+
+module DiscourseWorkflows
+ class Credential < ActiveRecord::Base
+ self.table_name = "discourse_workflows_credentials"
+
+ # Wire-format placeholder sent in JSON responses for password fields.
+ # Must remain a string since it round-trips through JSON serialization.
+ REDACTED_VALUE = "__REDACTED__"
+
+ validates :name, presence: true, length: { maximum: 128 }
+ validates :credential_type, presence: true, length: { maximum: 64 }
+ validate :data_matches_schema
+
+ def merge_data(incoming)
+ original = data || {}
+ self.data =
+ original.merge(incoming.stringify_keys) do |_key, orig_val, new_val|
+ new_val == REDACTED_VALUE ? orig_val : new_val
+ end
+ end
+
+ private
+
+ def data_matches_schema
+ return if credential_type.blank?
+
+ type_class = Registry.find_credential_type(credential_type)
+ return if type_class.nil?
+
+ CredentialDataValidator
+ .call(credential_type: type_class, data: data)
+ .each do |field|
+ errors.add(
+ :data,
+ I18n.t("discourse_workflows.errors.credential.missing_required_field", field: field),
+ )
+ end
+ end
+ end
+end
+
+# == Schema Information
+#
+# Table name: discourse_workflows_credentials
+#
+# id :bigint not null, primary key
+# credential_type :string(64) not null
+# data :jsonb not null
+# name :string(128) not null
+# created_at :datetime not null
+# updated_at :datetime not null
+# created_by_id :integer
+# updated_by_id :integer
+#
+# Indexes
+#
+# idx_dwf_credentials_on_created_by_id (created_by_id)
+# idx_dwf_credentials_on_credential_type (credential_type)
+# idx_dwf_credentials_on_name_credential_type (name,credential_type) UNIQUE
+# idx_dwf_credentials_on_updated_by_id (updated_by_id)
+#
diff --git a/plugins/discourse-workflows/app/models/discourse_workflows/data_table.rb b/plugins/discourse-workflows/app/models/discourse_workflows/data_table.rb
new file mode 100644
index 00000000000..3425722cc15
--- /dev/null
+++ b/plugins/discourse-workflows/app/models/discourse_workflows/data_table.rb
@@ -0,0 +1,61 @@
+# frozen_string_literal: true
+
+module DiscourseWorkflows
+ class DataTable < ActiveRecord::Base
+ self.table_name = "discourse_workflows_data_tables"
+
+ VALID_COLUMN_TYPES = %w[string number boolean date].freeze
+ MAX_COLUMN_NAME_LENGTH = 63
+ COLUMN_NAME_FORMAT = /\A[a-zA-Z_][a-zA-Z0-9_]*\z/
+
+ validates :name,
+ presence: true,
+ uniqueness: true,
+ length: {
+ maximum: 100,
+ },
+ format: {
+ with: /\A[a-zA-Z_][a-zA-Z0-9_ ]*\z/,
+ }
+
+ before_destroy :drop_storage_table
+
+ def columns
+ DataTables::Storage.columns(id)
+ end
+
+ class << self
+ def column_name(column)
+ column.respond_to?(:name) ? column.name.to_s : column.fetch("name").to_s
+ end
+
+ def column_type(column)
+ column.respond_to?(:column_type) ? column.column_type.to_s : column.fetch("type").to_s
+ end
+ end
+
+ private
+
+ def drop_storage_table
+ DiscourseWorkflows::DataTables::Facade.drop_table!(id)
+ end
+ end
+end
+
+# == Schema Information
+#
+# Table name: discourse_workflows_data_tables
+#
+# id :bigint not null, primary key
+# name :string(100) not null
+# created_at :datetime not null
+# updated_at :datetime not null
+# created_by_id :integer
+# updated_by_id :integer
+#
+# Indexes
+#
+# idx_dwf_data_tables_on_created_by_id (created_by_id)
+# idx_dwf_data_tables_on_name (name) UNIQUE
+# idx_dwf_data_tables_on_updated_by_id (updated_by_id)
+#
diff --git a/plugins/discourse-workflows/app/models/discourse_workflows/data_table_row.rb b/plugins/discourse-workflows/app/models/discourse_workflows/data_table_row.rb
new file mode 100644
index 00000000000..3d165bc3608
--- /dev/null
+++ b/plugins/discourse-workflows/app/models/discourse_workflows/data_table_row.rb
@@ -0,0 +1,106 @@
+# frozen_string_literal: true
+
+module DiscourseWorkflows
+ class DataTableRow
+ MAX_CELL_LENGTH = 10_000
+
+ class << self
+ def column_map(data_table)
+ data_table
+ .columns
+ .index_by { |column| DataTable.column_name(column) }
+ .except(*DataTables::Types::SYSTEM_COLUMN_NAMES)
+ end
+
+ def normalize_row_data(data_table, data, fill_missing:)
+ raise ArgumentError, "Row data must be an object" unless data.is_a?(Hash)
+
+ normalized_data = data.stringify_keys
+ columns = column_map(data_table)
+ unknown_column = normalized_data.keys.find { |name| !columns.key?(name) }
+ raise ArgumentError, "Unknown column name '#{unknown_column}'" if unknown_column
+
+ values =
+ fill_missing ? columns.keys.index_with { |name| normalized_data[name] } : normalized_data
+ values.each_with_object({}) do |(name, value), result|
+ result[name] = normalize_value(
+ value,
+ DiscourseWorkflows::DataTable.column_type(columns.fetch(name)),
+ )
+ end
+ end
+
+ def normalize_value(value, type)
+ case type.to_s
+ when "number"
+ normalize_number(value)
+ when "boolean"
+ normalize_boolean(value)
+ when "date"
+ normalize_date(value)
+ else
+ normalize_text(value)
+ end
+ end
+
+ private
+
+ def normalize_number(value)
+ return nil if value.nil? || value == ""
+
+ if value.is_a?(Numeric)
+ raise ArgumentError, "Value '#{value}' is not a finite number" unless value.finite?
+ return value
+ end
+
+ value.to_s.match?(/\A-?\d+\z/) ? Integer(value, 10) : Float(value)
+ rescue ArgumentError, TypeError
+ raise ArgumentError, "Value '#{value}' does not match column type 'number'"
+ end
+
+ def normalize_boolean(value)
+ return nil if value.nil?
+ return value if value.in?([true, false])
+
+ case value.to_s.downcase
+ when "true", "1"
+ true
+ when "false", "0"
+ false
+ else
+ raise ArgumentError, "Value '#{value}' does not match column type 'boolean'"
+ end
+ end
+
+ def normalize_date(value)
+ return nil if value.nil? || value == ""
+
+ time =
+ case value
+ when Time
+ value
+ when ::Date
+ value.to_time
+ else
+ Time.zone.parse(value.to_s)
+ end
+
+ raise ArgumentError, "Value '#{value}' does not match column type 'date'" if time.nil?
+
+ time.utc
+ rescue ArgumentError, TypeError
+ raise ArgumentError, "Value '#{value}' does not match column type 'date'"
+ end
+
+ def normalize_text(value)
+ return nil if value.nil?
+
+ str = value.to_s
+ if str.length > MAX_CELL_LENGTH
+ raise ArgumentError, "Value exceeds maximum cell length of #{MAX_CELL_LENGTH} characters"
+ end
+ str
+ end
+ end
+ end
+end
diff --git a/plugins/discourse-workflows/app/models/discourse_workflows/execution.rb b/plugins/discourse-workflows/app/models/discourse_workflows/execution.rb
new file mode 100644
index 00000000000..05c7eff8e2d
--- /dev/null
+++ b/plugins/discourse-workflows/app/models/discourse_workflows/execution.rb
@@ -0,0 +1,212 @@
+# frozen_string_literal: true
+
+module DiscourseWorkflows
+ class Execution < ActiveRecord::Base
+ self.table_name = "discourse_workflows_executions"
+
+ belongs_to :workflow, class_name: "DiscourseWorkflows::Workflow", foreign_key: "workflow_id"
+
+ has_one :execution_data,
+ class_name: "DiscourseWorkflows::ExecutionData",
+ foreign_key: "execution_id",
+ dependent: :destroy
+
+ enum :status,
+ { pending: 0, running: 1, success: 2, error: 3, waiting: 4, rate_limited: 5, skipped: 6 }
+ enum :execution_mode, { normal: 0, error_mode: 1, manual: 2 }
+
+ scope :for_workflow, ->(workflow_id) { workflow_id ? where(workflow_id: workflow_id) : all }
+ scope :recent, ->(period = 7.days) { where("created_at >= ?", period.ago) }
+ scope :successful, -> { where(status: :success) }
+ scope :with_duration,
+ -> { where.not(started_at: nil, finished_at: nil).where(status: %i[success error]) }
+
+ scope :expired_waiting, -> { where(status: :waiting).where("waiting_until < ?", Time.current) }
+
+ TERMINAL_STATUSES_FOR_PURGE = %i[success error rate_limited skipped].freeze
+ PURGE_BATCH_SIZE = 5_000
+
+ def self.purge_old
+ retention_days = SiteSetting.workflow_executions_retention_days
+ return if retention_days <= 0
+
+ cutoff = retention_days.days.ago
+ terminal_ids = statuses.values_at(*TERMINAL_STATUSES_FOR_PURGE)
+
+ loop do
+ ids =
+ where(status: terminal_ids)
+ .where("created_at < ?", cutoff)
+ .limit(PURGE_BATCH_SIZE)
+ .pluck(:id)
+ break if ids.empty?
+
+ ExecutionData.where(execution_id: ids).delete_all
+ where(id: ids).delete_all
+ end
+ end
+
+ def self.claim_for_resume(execution, resume_token: nil)
+ scope = where(id: execution.id, status: :waiting)
+ scope = scope.where(resume_token: resume_token) if resume_token
+
+ now = Time.current
+ affected = scope.update_all(status: statuses[:running], updated_at: now)
+ return nil if affected.zero?
+
+ execution.status = :running
+ execution.updated_at = now
+ execution
+ end
+
+ def self.compute_run_time_ms(steps)
+ waiting_types = NodeType.waiting_identifiers
+ timed =
+ steps.select do |s|
+ step_field(s, :started_at) && step_field(s, :finished_at) &&
+ waiting_types.exclude?(step_field(s, :node_type))
+ end
+ return if timed.empty?
+ total =
+ timed.sum do |s|
+ Time.parse(step_field(s, :finished_at).to_s) - Time.parse(step_field(s, :started_at).to_s)
+ end
+ (total * 1000).round
+ end
+
+ def self.step_field(step, key)
+ step.is_a?(Hash) ? step[key.to_s] : step.public_send(key)
+ end
+ private_class_method :step_field
+
+ def fail_with_timeout!
+ message = I18n.t("discourse_workflows.errors.approval_timed_out")
+ node_id = waiting_node_id
+ claimed = false
+
+ transaction do
+ run_time_ms = execution_data && self.class.compute_run_time_ms(execution_data.steps_array)
+
+ affected =
+ self
+ .class
+ .where(id: id, status: :waiting)
+ .update_all(
+ status: self.class.statuses[:error],
+ error: message,
+ finished_at: Time.current,
+ run_time_ms: run_time_ms,
+ waiting_node_id: nil,
+ waiting_until: nil,
+ resume_token: nil,
+ timeout_action: nil,
+ updated_at: Time.current,
+ )
+
+ next if affected.zero?
+
+ claimed = true
+ update_step_status_in_data!(
+ node_id,
+ Executor::Step::WAITING,
+ Executor::Step::ERROR,
+ message,
+ )
+ end
+
+ claimed
+ end
+
+ def waiting_step_input_items
+ return [{ "json" => {} }] unless execution_data
+
+ entries = execution_data.entries || {}
+ steps = entries[waiting_node_id.to_s] || []
+ waiting_step = steps.find { |s| s["status"] == "waiting" }
+ waiting_step&.dig("input") || [{ "json" => {} }]
+ end
+
+ def find_waiting_node
+ workflow_node(waiting_node_id)
+ end
+
+ def workflow_node(node_id)
+ return workflow.find_published_node(node_id) if workflow_data.blank?
+
+ WorkflowSnapshot.new(workflow_data).to_h["nodes"].find { |node| node["id"] == node_id.to_s }
+ end
+
+ def node_has_reachable_downstream_of_type?(node_id, type)
+ if workflow_data.present?
+ return(
+ WorkflowSnapshot.new(workflow_data).node_has_reachable_downstream_of_type?(node_id, type)
+ )
+ end
+
+ workflow.node_has_reachable_downstream_of_type?(node_id, type, published: true)
+ end
+
+ def workflow_snapshot_name
+ if workflow_data.present?
+ snapshot_name = WorkflowSnapshot.new(workflow_data).workflow_name
+ return snapshot_name if snapshot_name.present?
+ end
+
+ workflow.active_version&.name || workflow.name
+ end
+
+ private
+
+ def workflow_data
+ execution_data&.workflow_data
+ end
+
+ def update_step_status_in_data!(node_id, from_status, to_status, error_msg = nil)
+ return unless execution_data
+
+ full_data = execution_data.data.deep_dup
+ (full_data["entries"] || {}).each_value do |steps|
+ Array(steps).each do |step|
+ if step["node_id"] == node_id.to_s && step["status"] == from_status.to_s
+ step["status"] = to_status.to_s
+ step["error"] = error_msg if error_msg
+ step["finished_at"] = Time.current.iso8601
+ end
+ end
+ end
+ execution_data.update!(data: full_data)
+ end
+ end
+end
+
+# == Schema Information
+#
+# Table name: discourse_workflows_executions
+#
+# id :bigint not null, primary key
+# error :text
+# execution_mode :integer default("normal"), not null
+# finished_at :datetime
+# resume_token :string(64)
+# run_time_ms :integer
+# started_at :datetime
+# status :integer default("pending"), not null
+# timeout_action :string(32)
+# trigger_data :jsonb
+# waiting_until :datetime
+# created_at :datetime not null
+# updated_at :datetime not null
+# trigger_node_id :string(100)
+# waiting_node_id :string(100)
+# workflow_id :bigint not null
+# workflow_version_id :string(36) not null
+#
+# Indexes
+#
+# idx_dwf_executions_on_resume_token (resume_token) WHERE (resume_token IS NOT NULL)
+# idx_dwf_executions_on_retention (created_at) WHERE (status = ANY (ARRAY[2, 3, 5, 6]))
+# idx_dwf_executions_on_status_waiting_until (status,waiting_until)
+# idx_dwf_executions_on_waiting_until (waiting_until) WHERE ((waiting_until IS NOT NULL) AND (status = 4))
+# idx_dwf_executions_on_workflow_created_at_id_desc (workflow_id,created_at DESC,id DESC)
+# idx_dwf_executions_on_workflow_version_id (workflow_version_id)
+#
diff --git a/plugins/discourse-workflows/app/models/discourse_workflows/execution_data.rb b/plugins/discourse-workflows/app/models/discourse_workflows/execution_data.rb
new file mode 100644
index 00000000000..0446a617a96
--- /dev/null
+++ b/plugins/discourse-workflows/app/models/discourse_workflows/execution_data.rb
@@ -0,0 +1,61 @@
+# frozen_string_literal: true
+
+module DiscourseWorkflows
+ class ExecutionData < ActiveRecord::Base
+ self.table_name = "discourse_workflows_execution_data"
+ self.primary_key = "execution_id"
+
+ belongs_to :execution, class_name: "DiscourseWorkflows::Execution", foreign_key: "execution_id"
+
+ def entries
+ data["entries"] || {}
+ end
+
+ def context_data
+ data["context"] || {}
+ end
+
+ def node_contexts
+ data["node_contexts"] || {}
+ end
+
+ def run_data
+ data["run_data"] || {}
+ end
+
+ def steps_array
+ all_steps.sort_by { |s| s["position"] || 0 }
+ end
+
+ def find_step(node_id:, status: nil)
+ node_id_str = node_id.to_s
+ all_steps.find do |step|
+ step["node_id"] == node_id_str && (!status || step["status"] == status.to_s)
+ end
+ end
+
+ def last_step_with_status(status)
+ status_str = status.to_s
+ all_steps.reverse_each.find { |step| step["status"] == status_str }
+ end
+
+ private
+
+ def all_steps
+ entries.values.flatten
+ end
+ end
+end
+
+# == Schema Information
+#
+# Table name: discourse_workflows_execution_data
+#
+# data :jsonb not null
+# workflow_data :jsonb not null
+# execution_id :bigint not null, primary key
+#
+# Indexes
+#
+# idx_dwf_execution_data_on_execution_id (execution_id) UNIQUE
+#
diff --git a/plugins/discourse-workflows/app/models/discourse_workflows/normalized_filter.rb b/plugins/discourse-workflows/app/models/discourse_workflows/normalized_filter.rb
new file mode 100644
index 00000000000..c8904658529
--- /dev/null
+++ b/plugins/discourse-workflows/app/models/discourse_workflows/normalized_filter.rb
@@ -0,0 +1,117 @@
+# frozen_string_literal: true
+
+module DiscourseWorkflows
+ class NormalizedFilter
+ include ActiveModel::Validations
+
+ VALID_TYPES = %w[and or].freeze
+ VALID_CONDITIONS = %w[eq neq like ilike not_ilike gt gte lt lte].freeze
+ LIKE_CONDITIONS = %w[like ilike not_ilike].freeze
+ COMPARISON_CONDITIONS = %w[gt gte lt lte].freeze
+ MAX_FILTER_CONDITIONS = 50
+
+ attr_reader :value
+
+ validate :check_normalization_error
+
+ def initialize(data_table:, filter:, optional: false)
+ @column_map = data_table.columns.index_by { |column| DataTable.column_name(column) }
+ @value = normalize(filter, optional)
+ rescue ArgumentError => e
+ @normalization_error = e.message
+ @value = nil
+ end
+
+ def has_changes_to_save?
+ true
+ end
+
+ private
+
+ def check_normalization_error
+ errors.add(:base, @normalization_error) if @normalization_error.present?
+ end
+
+ def normalize(filter, optional)
+ return nil if filter.blank? && optional
+ validate_filter_structure!(filter)
+
+ normalized = filter.with_indifferent_access
+ type = validated_type(normalized[:type])
+ filters = validated_filters_array(normalized[:filters], optional)
+
+ { "type" => type, "filters" => filters.map.with_index { |f, i| normalize_single(f, i) } }
+ end
+
+ def validate_filter_structure!(filter)
+ raise ArgumentError, "Filter must not be empty" if filter.blank?
+ raise ArgumentError, "Filter must be an object" unless filter.is_a?(Hash)
+ end
+
+ def validated_type(type)
+ type ||= "and"
+ raise ArgumentError, "Unsupported filter type '#{type}'" if VALID_TYPES.exclude?(type)
+ type
+ end
+
+ def validated_filters_array(filters, optional)
+ filters ||= []
+ raise ArgumentError, "Filter filters must be an array" unless filters.is_a?(Array)
+ raise ArgumentError, "Filter must not be empty" if filters.empty? && !optional
+ if filters.size > MAX_FILTER_CONDITIONS
+ raise ArgumentError, "Filter must not have more than #{MAX_FILTER_CONDITIONS} conditions"
+ end
+ filters
+ end
+
+ def normalize_single(filter, index)
+ raise ArgumentError, "Filter #{index + 1} must be an object" unless filter.is_a?(Hash)
+
+ filter = filter.with_indifferent_access
+ column_name = validated_column_name(filter[:columnName], index)
+ condition = validated_condition(filter[:condition])
+
+ {
+ "columnName" => column_name,
+ "condition" => condition,
+ "value" => normalize_value(column_name, condition, filter[:value]),
+ }
+ end
+
+ def validated_column_name(column_name, index)
+ raise ArgumentError, "Filter #{index + 1} is missing columnName" if column_name.blank?
+ raise ArgumentError, "Unknown column name '#{column_name}'" if @column_map[column_name].nil?
+ column_name
+ end
+
+ def validated_condition(condition)
+ condition ||= "eq"
+ if VALID_CONDITIONS.exclude?(condition)
+ raise ArgumentError, "Unsupported filter condition '#{condition}'"
+ end
+ condition
+ end
+
+ def normalize_value(column_name, condition, value)
+ column = @column_map.fetch(column_name)
+ normalized = DataTableRow.normalize_value(value, DataTable.column_type(column))
+
+ return normalize_like_value(normalized, condition) if LIKE_CONDITIONS.include?(condition)
+ if COMPARISON_CONDITIONS.include?(condition) && normalized.nil?
+ raise ArgumentError, "#{condition.upcase} filter value cannot be null or undefined"
+ end
+
+ normalized
+ end
+
+ def normalize_like_value(normalized, condition)
+ if normalized.nil?
+ raise ArgumentError, "#{condition.upcase} filter value cannot be null or undefined"
+ end
+ unless normalized.is_a?(String)
+ raise ArgumentError, "#{condition.upcase} filter value must be a string"
+ end
+ normalized
+ end
+ end
+end
diff --git a/plugins/discourse-workflows/app/models/discourse_workflows/template_store.rb b/plugins/discourse-workflows/app/models/discourse_workflows/template_store.rb
new file mode 100644
index 00000000000..cc852b758e6
--- /dev/null
+++ b/plugins/discourse-workflows/app/models/discourse_workflows/template_store.rb
@@ -0,0 +1,45 @@
+# frozen_string_literal: true
+
+module DiscourseWorkflows
+ class TemplateStore
+ def self.summaries
+ templates_by_id.map { |id, template| summary_for(id, template) }
+ end
+
+ def self.find(id)
+ templates_by_id[id]&.deep_dup
+ end
+
+ def self.reset_cache!
+ remove_instance_variable(:@templates_by_id) if defined?(@templates_by_id)
+ end
+
+ def self.templates_by_id
+ @templates_by_id ||= load_templates
+ end
+ private_class_method :templates_by_id
+
+ def self.load_templates
+ Dir
+ .glob(File.join(DiscourseWorkflows::TEMPLATES_PATH, "*.json"))
+ .sort
+ .each_with_object({}) do |path, templates|
+ id = File.basename(path, ".json")
+ templates[id] = JSON.parse(File.read(path))
+ rescue JSON::ParserError
+ next
+ end
+ end
+ private_class_method :load_templates
+
+ def self.summary_for(id, template)
+ {
+ id: id,
+ name: template["name"],
+ description: template["description"],
+ node_types: template["nodes"].map { |node| node["type"] }.uniq,
+ }.deep_dup
+ end
+ private_class_method :summary_for
+ end
+end
diff --git a/plugins/discourse-workflows/app/models/discourse_workflows/variable.rb b/plugins/discourse-workflows/app/models/discourse_workflows/variable.rb
new file mode 100644
index 00000000000..b419b149948
--- /dev/null
+++ b/plugins/discourse-workflows/app/models/discourse_workflows/variable.rb
@@ -0,0 +1,39 @@
+# frozen_string_literal: true
+
+module DiscourseWorkflows
+ class Variable < ActiveRecord::Base
+ self.table_name = "discourse_workflows_variables"
+
+ belongs_to :created_by, class_name: "User", foreign_key: "created_by_id"
+
+ validates :key,
+ presence: true,
+ uniqueness: true,
+ length: {
+ maximum: 100,
+ },
+ format: {
+ with: /\A[a-zA-Z_][a-zA-Z0-9_]*\z/,
+ }
+ validates :value, length: { maximum: 1000 }
+ validates :description, length: { maximum: 500 }, allow_nil: true
+ end
+end
+
+# == Schema Information
+#
+# Table name: discourse_workflows_variables
+#
+# id :bigint not null, primary key
+# description :text
+# key :string(100) not null
+# value :string(1000) default(""), not null
+# created_at :datetime not null
+# updated_at :datetime not null
+# created_by_id :integer not null
+#
+# Indexes
+#
+# idx_dwf_variables_on_created_by_id (created_by_id)
+# idx_dwf_variables_on_key (key) UNIQUE
+#
diff --git a/plugins/discourse-workflows/app/models/discourse_workflows/webhook.rb b/plugins/discourse-workflows/app/models/discourse_workflows/webhook.rb
new file mode 100644
index 00000000000..c6d8606cf7e
--- /dev/null
+++ b/plugins/discourse-workflows/app/models/discourse_workflows/webhook.rb
@@ -0,0 +1,84 @@
+# frozen_string_literal: true
+
+module DiscourseWorkflows
+ class Webhook < ActiveRecord::Base
+ self.table_name = "discourse_workflows_webhooks"
+
+ DYNAMIC_SEGMENT_PATTERN = /\A:([\w\-]+)\z/
+
+ belongs_to :workflow, class_name: "DiscourseWorkflows::Workflow"
+
+ scope :production, -> { where(test_webhook: false) }
+ scope :test_listeners, -> { where(test_webhook: true) }
+ scope :live, -> { where("expires_at IS NULL OR expires_at > ?", Time.current) }
+ scope :expired, -> { where("expires_at IS NOT NULL AND expires_at <= ?", Time.current) }
+ scope :dynamic, -> { where.not(webhook_id: nil) }
+ scope :static, -> { where(webhook_id: nil) }
+
+ def self.normalize_method(value)
+ value.to_s.upcase
+ end
+
+ def self.normalize_path(value)
+ value.to_s.delete_prefix("/")
+ end
+
+ def self.segments_for(path)
+ normalize_path(path).split("/").reject(&:empty?)
+ end
+
+ def self.dynamic_path?(path)
+ segments_for(path).any? { |segment| segment.match?(DYNAMIC_SEGMENT_PATTERN) }
+ end
+
+ def self.path_length_for(path)
+ segments_for(path).size
+ end
+
+ def self.match_dynamic_path(template:, segments:)
+ template_segments = segments_for(template)
+ return nil unless template_segments.size == segments.size
+
+ params = {}
+ template_segments.zip(segments) do |template_segment, segment|
+ if (match = template_segment.match(DYNAMIC_SEGMENT_PATTERN))
+ params[match[1]] = segment
+ elsif template_segment != segment
+ return nil
+ end
+ end
+ params
+ end
+
+ def dynamic?
+ webhook_id.present?
+ end
+ end
+end
+
+# == Schema Information
+#
+# Table name: discourse_workflows_webhooks
+#
+# id :bigint not null, primary key
+# expires_at :datetime
+# http_method :string(10) not null
+# node_name :string(100) not null
+# path_length :integer
+# test_webhook :boolean default(FALSE), not null
+# webhook_path :string(500) not null
+# workflow_snapshot :jsonb
+# created_at :datetime not null
+# user_id :integer
+# webhook_id :string(36)
+# workflow_id :bigint not null
+# workflow_version_id :string(36)
+#
+# Indexes
+#
+# idx_dwf_webhooks_on_expires_at (expires_at) WHERE (expires_at IS NOT NULL)
+# idx_dwf_webhooks_on_method_path_test (http_method,webhook_path,test_webhook) UNIQUE
+# idx_dwf_webhooks_on_webhook_id_method_test (webhook_id,http_method,test_webhook) WHERE (webhook_id IS NOT NULL)
+# idx_dwf_webhooks_on_workflow_id (workflow_id)
+# idx_dwf_webhooks_on_workflow_version_id (workflow_version_id)
+#
diff --git a/plugins/discourse-workflows/app/models/discourse_workflows/workflow.rb b/plugins/discourse-workflows/app/models/discourse_workflows/workflow.rb
new file mode 100644
index 00000000000..e97d344a3d8
--- /dev/null
+++ b/plugins/discourse-workflows/app/models/discourse_workflows/workflow.rb
@@ -0,0 +1,376 @@
+# frozen_string_literal: true
+
+module DiscourseWorkflows
+ class Workflow < ActiveRecord::Base
+ self.table_name = "discourse_workflows_workflows"
+
+ PUBLISH_EVENT_ACTIVATED = "activated"
+ PUBLISH_EVENT_DEACTIVATED = "deactivated"
+
+ has_many :executions,
+ class_name: "DiscourseWorkflows::Execution",
+ foreign_key: "workflow_id",
+ dependent: :destroy
+
+ has_many :workflow_dependencies,
+ class_name: "DiscourseWorkflows::WorkflowDependency",
+ foreign_key: "workflow_id",
+ dependent: :delete_all
+ has_many :webhooks,
+ class_name: "DiscourseWorkflows::Webhook",
+ foreign_key: "workflow_id",
+ dependent: :delete_all
+ has_many :workflow_versions,
+ class_name: "DiscourseWorkflows::WorkflowVersion",
+ foreign_key: "workflow_id",
+ dependent: :delete_all
+ has_many :publish_history,
+ -> { order(created_at: :desc) },
+ class_name: "DiscourseWorkflows::WorkflowPublishHistory",
+ foreign_key: "workflow_id",
+ dependent: :delete_all
+
+ belongs_to :created_by, class_name: "User", foreign_key: "created_by_id"
+ belongs_to :updated_by, class_name: "User", foreign_key: "updated_by_id", optional: true
+ belongs_to :active_version,
+ class_name: "DiscourseWorkflows::WorkflowVersion",
+ foreign_key: "active_version_id",
+ primary_key: "version_id",
+ optional: true
+ belongs_to :error_workflow,
+ class_name: "DiscourseWorkflows::Workflow",
+ foreign_key: "error_workflow_id",
+ optional: true
+
+ before_validation :assign_version_id, on: :create
+
+ STATIC_DATA_GLOBAL_KEY = "global"
+ STATIC_DATA_NODE_PREFIX = "node:"
+ EMPTY_STATIC_DATA = {}.freeze
+
+ attribute :nodes, default: -> { [] }
+ attribute :connections, default: -> { {} }
+ attribute :static_data, default: -> { Marshal.load(Marshal.dump(EMPTY_STATIC_DATA)) }
+ attribute :trigger_state, default: -> { {} }
+ attribute :settings, default: -> { {} }
+ attribute :pin_data, default: -> { {} }
+
+ validates :name, presence: true, length: { maximum: 100 }
+ validates :version_id, presence: true, length: { maximum: 36 }
+ validate :error_workflow_must_exist
+ validate :error_workflow_cannot_be_self
+
+ before_destroy :nullify_error_workflow_back_references
+
+ scope :published, -> { where.not(active_version_id: nil) }
+ scope :filter_by_name,
+ ->(name) do
+ where("discourse_workflows_workflows.name ILIKE ?", "%#{sanitize_sql_like(name)}%")
+ end
+ scope :filter_by_trigger_type,
+ ->(type) do
+ where(
+ "discourse_workflows_workflows.nodes @> ?",
+ [{ "type" => "trigger:#{type}" }].to_json,
+ )
+ end
+
+ def self.filtered(name: nil, trigger_type: nil, exclude_id: nil)
+ scope = all
+ scope = scope.filter_by_name(name) if name.present?
+ scope = scope.filter_by_trigger_type(trigger_type) if trigger_type.present?
+ scope = scope.where.not(id: exclude_id) if exclude_id
+ scope
+ end
+
+ def find_node(node_id)
+ find_node_in(nodes, node_id)
+ end
+
+ def find_published_node(node_id)
+ find_node_in(published_nodes, node_id)
+ end
+
+ def published_nodes
+ active_version&.nodes || []
+ end
+
+ def published_connections
+ active_version&.connections || {}
+ end
+
+ def snapshot!(user:, autosaved: false, authors: nil)
+ new_version_id = SecureRandom.uuid
+ new_counter = version_counter.to_i + 1
+
+ update!(version_id: new_version_id, version_counter: new_counter, updated_by: user)
+
+ workflow_versions.create!(
+ version_id: new_version_id,
+ version_number: new_counter,
+ name: name,
+ nodes: nodes,
+ connections: connections,
+ settings: settings || {},
+ autosaved: autosaved,
+ authors: authors,
+ created_by: user,
+ updated_by: user,
+ )
+ end
+
+ def initial_snapshot!(user:, authors: nil)
+ workflow_versions.create!(
+ version_id: version_id,
+ version_number: version_counter,
+ name: name,
+ nodes: nodes,
+ connections: connections,
+ settings: settings || {},
+ autosaved: false,
+ authors: authors,
+ created_by: user,
+ updated_by: user,
+ )
+ end
+
+ def publish!(user: nil)
+ published_node_ids = active_version_target&.nodes&.map { |n| n["id"].to_s } || []
+
+ transaction do
+ update!(
+ active_version_id: version_id,
+ trigger_state: (trigger_state || {}).slice(*published_node_ids),
+ )
+ publish_history.create!(
+ version_id: version_id,
+ event: PUBLISH_EVENT_ACTIVATED,
+ user_id: user&.id,
+ )
+ end
+ end
+
+ def unpublish!(user: nil)
+ previous_active_version_id = active_version_id
+
+ transaction do
+ update!(active_version_id: nil)
+ publish_history.create!(
+ version_id: previous_active_version_id,
+ event: PUBLISH_EVENT_DEACTIVATED,
+ user_id: user&.id,
+ )
+ end
+ end
+
+ def restore_from_version!(version, user:)
+ update!(
+ name: version.name,
+ nodes: version.nodes || [],
+ connections: version.connections || {},
+ settings: version.settings || {},
+ version_id: version.version_id,
+ updated_by: user,
+ )
+ end
+
+ def published?
+ active_version_id.present?
+ end
+
+ def has_unpublished_changes?
+ published? && version_id != active_version_id
+ end
+
+ def versioned_payload
+ JSON.parse(
+ {
+ name: name,
+ nodes: nodes || [],
+ connections: connections || {},
+ settings: settings || {},
+ }.to_json,
+ )
+ end
+
+ def find_node_in(node_collection, node_id)
+ node_id_str = node_id.to_s
+ node_collection.find { |n| n["id"] == node_id_str }
+ end
+
+ def trigger_node
+ nodes.find { |n| n["type"]&.start_with?("trigger:") }
+ end
+
+ def normalized_static_data
+ static_data.presence || {}
+ end
+
+ def global_static_data
+ self.class.static_data_slot(normalized_static_data[STATIC_DATA_GLOBAL_KEY])
+ end
+
+ def node_static_data(node_name)
+ self.class.static_data_slot(normalized_static_data[static_data_node_key(node_name)])
+ end
+
+ def node_static_data_entries
+ normalized_static_data.each_with_object({}) do |(key, value), entries|
+ key = key.to_s
+ next unless key.start_with?(STATIC_DATA_NODE_PREFIX)
+
+ entries[key.delete_prefix(STATIC_DATA_NODE_PREFIX)] = self.class.static_data_slot(value)
+ end
+ end
+
+ def update_global_static_data!(data)
+ next_data = normalized_static_data
+ next_data[STATIC_DATA_GLOBAL_KEY] = self.class.static_data_slot(data)
+ update!(static_data: next_data)
+ end
+
+ def update_node_static_data!(node_name, data)
+ next_data = normalized_static_data
+ next_data[static_data_node_key(node_name)] = self.class.static_data_slot(data)
+ update!(static_data: next_data)
+ end
+
+ def commit_static_data!(global:, node:)
+ current_data = normalized_static_data
+ next_data =
+ current_data.reject do |key, _|
+ key = key.to_s
+ key == STATIC_DATA_GLOBAL_KEY || key.start_with?(STATIC_DATA_NODE_PREFIX)
+ end
+
+ if global.present? || current_data.key?(STATIC_DATA_GLOBAL_KEY)
+ next_data[STATIC_DATA_GLOBAL_KEY] = self.class.static_data_slot(global)
+ end
+
+ (node || {}).each do |node_name, data|
+ next_data[static_data_node_key(node_name)] = self.class.static_data_slot(data)
+ end
+
+ update!(static_data: next_data)
+ end
+
+ def static_data_node_key(node_name)
+ self.class.static_data_node_key(node_name)
+ end
+
+ def self.static_data_node_key(node_name)
+ "#{STATIC_DATA_NODE_PREFIX}#{node_name}"
+ end
+
+ def self.static_data_slot(value)
+ value.is_a?(Hash) ? value : {}
+ end
+
+ def self.valid_static_data_map?(value)
+ value.is_a?(Hash) &&
+ value.all? { |key, slot| key.to_s != "node" && static_data_slot(slot) == slot }
+ end
+
+ def node_trigger_state(node_id)
+ (trigger_state || {}).fetch(node_id.to_s, {})
+ end
+
+ def update_node_trigger_state!(node_id, data)
+ update!(trigger_state: (trigger_state || {}).merge(node_id.to_s => data))
+ end
+
+ def node_pin_data(node_name)
+ pin_data&.fetch(node_name.to_s, nil)
+ end
+
+ def node_pinned?(node_name)
+ node_pin_data(node_name).present?
+ end
+
+ def update_node_pin_data!(node_name, items)
+ key = node_name.to_s
+ next_pin_data = (pin_data || {}).dup
+ if items.nil?
+ next_pin_data.delete(key)
+ else
+ next_pin_data[key] = items
+ end
+ update!(pin_data: next_pin_data)
+ end
+
+ def pinned_node_names
+ (pin_data || {}).keys
+ end
+
+ def last_successful_execution
+ executions.successful.includes(:execution_data).order(created_at: :desc).first
+ end
+
+ def node_has_reachable_downstream_of_type?(node_id, type, published: false)
+ graph_nodes = published ? published_nodes : nodes
+ graph_connections = published ? published_connections : connections
+ DiscourseWorkflows::WorkflowSnapshot.new(
+ "name" => name,
+ "nodes" => graph_nodes,
+ "connections" => graph_connections,
+ ).node_has_reachable_downstream_of_type?(node_id, type)
+ end
+
+ private
+
+ def assign_version_id
+ self.version_id ||= SecureRandom.uuid
+ end
+
+ def active_version_target
+ workflow_versions.find_by(version_id: version_id) || active_version
+ end
+
+ def error_workflow_must_exist
+ return if error_workflow_id.nil?
+ errors.add(:error_workflow_id, :invalid) unless Workflow.exists?(error_workflow_id)
+ end
+
+ def error_workflow_cannot_be_self
+ return if error_workflow_id.nil? || id.nil?
+ errors.add(:error_workflow_id, :cannot_be_self) if error_workflow_id == id
+ end
+
+ def nullify_error_workflow_back_references
+ Workflow.where(error_workflow_id: id).update_all(
+ error_workflow_id: nil,
+ updated_at: Time.current,
+ )
+ end
+ end
+end
+
+# == Schema Information
+#
+# Table name: discourse_workflows_workflows
+#
+# id :bigint not null, primary key
+# connections :jsonb not null
+# name :string(100) not null
+# nodes :jsonb not null
+# pin_data :jsonb not null
+# settings :jsonb not null
+# static_data :jsonb not null
+# trigger_state :jsonb not null
+# version_counter :integer default(1), not null
+# created_at :datetime not null
+# updated_at :datetime not null
+# active_version_id :string(36)
+# created_by_id :integer not null
+# error_workflow_id :bigint
+# updated_by_id :integer
+# version_id :string(36) not null
+#
+# Indexes
+#
+# idx_dwf_workflows_on_active_version_id (active_version_id)
+# idx_dwf_workflows_on_created_by_id (created_by_id)
+# idx_dwf_workflows_on_error_workflow_id (error_workflow_id)
+# idx_dwf_workflows_on_updated_by_id (updated_by_id)
+# idx_dwf_workflows_on_version_id (version_id) UNIQUE
+#
diff --git a/plugins/discourse-workflows/app/models/discourse_workflows/workflow_dependency.rb b/plugins/discourse-workflows/app/models/discourse_workflows/workflow_dependency.rb
new file mode 100644
index 00000000000..4eff582f791
--- /dev/null
+++ b/plugins/discourse-workflows/app/models/discourse_workflows/workflow_dependency.rb
@@ -0,0 +1,75 @@
+# frozen_string_literal: true
+
+module DiscourseWorkflows
+ class WorkflowDependency < ActiveRecord::Base
+ self.table_name = "discourse_workflows_workflow_dependencies"
+
+ TOPIC_ADMIN_BUTTON_CACHE_KEY = "topic_admin_buttons"
+
+ belongs_to :workflow, class_name: "DiscourseWorkflows::Workflow"
+ belongs_to :workflow_version,
+ class_name: "DiscourseWorkflows::WorkflowVersion",
+ foreign_key: "workflow_version_id",
+ primary_key: "version_id",
+ optional: true
+
+ TYPES = %w[credential_id data_table_id node_type workflow_call error_workflow].freeze
+
+ validates :dependency_type, inclusion: { in: TYPES }
+
+ scope :of_type, ->(type) { where(dependency_type: type) }
+
+ def self.cache
+ @cache ||= DistributedCache.new("discourse_workflows_dependencies")
+ end
+
+ def self.clear_cache!
+ cache.clear
+ end
+
+ def self.cached_topic_admin_buttons
+ cache.defer_get_set(TOPIC_ADMIN_BUTTON_CACHE_KEY) do
+ Workflow::Action::FindPublishedTriggers
+ .call(trigger_type: "trigger:topic_admin_button")
+ .map do |published_trigger|
+ {
+ trigger_node_id: published_trigger.trigger_node_id,
+ workflow_id: published_trigger.workflow_id,
+ label: NodeData.parameters(published_trigger.trigger_node)["label"],
+ icon: NodeData.parameters(published_trigger.trigger_node)["icon"],
+ }
+ end
+ end
+ end
+
+ def self.workflows_referencing(type, key)
+ joins(:workflow)
+ .where(dependency_type: type, dependency_key: key.to_s)
+ .where(
+ "discourse_workflows_workflow_dependencies.workflow_version_id IN " \
+ "(discourse_workflows_workflows.version_id, " \
+ "discourse_workflows_workflows.active_version_id)",
+ )
+ .select(:workflow_id)
+ end
+ end
+end
+
+# == Schema Information
+#
+# Table name: discourse_workflows_workflow_dependencies
+#
+# id :bigint not null, primary key
+# dependency_key :string(500) not null
+# dependency_type :string(50) not null
+# created_at :datetime not null
+# node_id :string(100)
+# workflow_id :bigint not null
+# workflow_version_id :string(36)
+#
+# Indexes
+#
+# idx_dwf_deps_on_type_key (dependency_type,dependency_key)
+# idx_dwf_deps_on_workflow_id (workflow_id)
+# idx_dwf_deps_on_workflow_version_id (workflow_version_id)
+#
diff --git a/plugins/discourse-workflows/app/models/discourse_workflows/workflow_publish_history.rb b/plugins/discourse-workflows/app/models/discourse_workflows/workflow_publish_history.rb
new file mode 100644
index 00000000000..aa2a2cd7511
--- /dev/null
+++ b/plugins/discourse-workflows/app/models/discourse_workflows/workflow_publish_history.rb
@@ -0,0 +1,38 @@
+# frozen_string_literal: true
+
+module DiscourseWorkflows
+ class WorkflowPublishHistory < ActiveRecord::Base
+ self.table_name = "discourse_workflows_workflow_publish_history"
+
+ EVENT_ACTIVATED = "activated"
+ EVENT_DEACTIVATED = "deactivated"
+ EVENTS = [EVENT_ACTIVATED, EVENT_DEACTIVATED].freeze
+
+ belongs_to :workflow, class_name: "DiscourseWorkflows::Workflow"
+ belongs_to :workflow_version,
+ class_name: "DiscourseWorkflows::WorkflowVersion",
+ foreign_key: "version_id",
+ primary_key: "version_id",
+ optional: true
+ belongs_to :user, optional: true
+
+ validates :workflow_id, presence: true
+ validates :event, presence: true, inclusion: { in: EVENTS }
+ end
+end
+
+# == Schema Information
+#
+# Table name: discourse_workflows_workflow_publish_history
+#
+# id :bigint not null, primary key
+# event :string(32) not null
+# created_at :datetime not null
+# user_id :integer
+# version_id :string(36)
+# workflow_id :bigint not null
+#
+# Indexes
+#
+# idx_dwf_publish_history_on_workflow_created_at_id_desc (workflow_id,created_at DESC,id DESC)
+#
diff --git a/plugins/discourse-workflows/app/models/discourse_workflows/workflow_version.rb b/plugins/discourse-workflows/app/models/discourse_workflows/workflow_version.rb
new file mode 100644
index 00000000000..c1ae15ccbcb
--- /dev/null
+++ b/plugins/discourse-workflows/app/models/discourse_workflows/workflow_version.rb
@@ -0,0 +1,66 @@
+# frozen_string_literal: true
+
+module DiscourseWorkflows
+ class WorkflowVersion < ActiveRecord::Base
+ self.table_name = "discourse_workflows_workflow_versions"
+ self.primary_key = :version_id
+
+ belongs_to :workflow, class_name: "DiscourseWorkflows::Workflow"
+ belongs_to :created_by, class_name: "User", foreign_key: "created_by_id"
+ belongs_to :updated_by, class_name: "User", foreign_key: "updated_by_id", optional: true
+
+ before_validation :assign_version_id, on: :create
+
+ attribute :nodes, default: -> { [] }
+ attribute :connections, default: -> { {} }
+ attribute :settings, default: -> { {} }
+
+ validates :version_id, presence: true, length: { maximum: 36 }
+ validates :workflow_id, :version_number, :name, :created_by_id, presence: true
+ validates :name, length: { maximum: 100 }
+
+ before_destroy :prevent_destroy_if_referenced
+
+ private
+
+ def assign_version_id
+ self.version_id ||= SecureRandom.uuid
+ end
+
+ def prevent_destroy_if_referenced
+ return unless workflow
+ return unless workflow.version_id == version_id || workflow.active_version_id == version_id
+
+ errors.add(
+ :base,
+ I18n.t("discourse_workflows.errors.workflow_version.referenced_by_workflow"),
+ )
+ throw :abort
+ end
+ end
+end
+
+# == Schema Information
+#
+# Table name: discourse_workflows_workflow_versions
+#
+# authors :text
+# autosaved :boolean default(FALSE), not null
+# connections :jsonb not null
+# name :string(100) not null
+# nodes :jsonb not null
+# settings :jsonb not null
+# version_number :integer not null
+# created_at :datetime not null
+# updated_at :datetime not null
+# created_by_id :integer not null
+# updated_by_id :integer
+# version_id :string(36) not null, primary key
+# workflow_id :bigint not null
+#
+# Indexes
+#
+# idx_dwf_versions_on_workflow_created_at (workflow_id,created_at DESC)
+# idx_dwf_versions_on_workflow_id (workflow_id)
+# idx_dwf_versions_on_workflow_version_number (workflow_id,version_number) UNIQUE
+#
diff --git a/plugins/discourse-workflows/app/serializers/discourse_workflows/credential_serializer.rb b/plugins/discourse-workflows/app/serializers/discourse_workflows/credential_serializer.rb
new file mode 100644
index 00000000000..ac0e3b3fcc8
--- /dev/null
+++ b/plugins/discourse-workflows/app/serializers/discourse_workflows/credential_serializer.rb
@@ -0,0 +1,29 @@
+# frozen_string_literal: true
+
+module DiscourseWorkflows
+ class CredentialSerializer < ApplicationSerializer
+ attributes :id, :name, :credential_type, :data, :data_modes, :created_at, :updated_at
+
+ def data
+ schema = Registry.find_credential_type(object.credential_type)&.property_schema || {}
+ credential_data.to_h do |key, value|
+ [
+ key,
+ schema.dig(key.to_sym, :ui, :control) == :password ? Credential::REDACTED_VALUE : value,
+ ]
+ end
+ end
+
+ def data_modes
+ credential_data.transform_values do |value|
+ value.is_a?(String) && value.start_with?("=") ? "expression" : "fixed"
+ end
+ end
+
+ private
+
+ def credential_data
+ @credential_data ||= object.data || {}
+ end
+ end
+end
diff --git a/plugins/discourse-workflows/app/serializers/discourse_workflows/data_table_serializer.rb b/plugins/discourse-workflows/app/serializers/discourse_workflows/data_table_serializer.rb
new file mode 100644
index 00000000000..ba0289f6c67
--- /dev/null
+++ b/plugins/discourse-workflows/app/serializers/discourse_workflows/data_table_serializer.rb
@@ -0,0 +1,19 @@
+# frozen_string_literal: true
+
+module DiscourseWorkflows
+ class DataTableSerializer < ApplicationSerializer
+ attributes :id, :name, :size, :columns, :created_at, :updated_at
+
+ def columns
+ object.columns.map { |c| { name: c["name"], type: c["type"] } }
+ end
+
+ def size
+ if @options[:table_sizes]
+ @options[:table_sizes].fetch(object.id, 0)
+ else
+ DiscourseWorkflows::DataTables::Facade.size_bytes(object.id)
+ end
+ end
+ end
+end
diff --git a/plugins/discourse-workflows/app/serializers/discourse_workflows/execution_list_serializer.rb b/plugins/discourse-workflows/app/serializers/discourse_workflows/execution_list_serializer.rb
new file mode 100644
index 00000000000..c7c3ae33022
--- /dev/null
+++ b/plugins/discourse-workflows/app/serializers/discourse_workflows/execution_list_serializer.rb
@@ -0,0 +1,19 @@
+# frozen_string_literal: true
+
+module DiscourseWorkflows
+ class ExecutionListSerializer < ApplicationSerializer
+ attributes :id,
+ :workflow_id,
+ :workflow_name,
+ :status,
+ :error,
+ :run_time_ms,
+ :started_at,
+ :finished_at,
+ :created_at
+
+ def workflow_name
+ object.workflow_snapshot_name
+ end
+ end
+end
diff --git a/plugins/discourse-workflows/app/serializers/discourse_workflows/execution_serializer.rb b/plugins/discourse-workflows/app/serializers/discourse_workflows/execution_serializer.rb
new file mode 100644
index 00000000000..5ea92f55e51
--- /dev/null
+++ b/plugins/discourse-workflows/app/serializers/discourse_workflows/execution_serializer.rb
@@ -0,0 +1,41 @@
+# frozen_string_literal: true
+
+module DiscourseWorkflows
+ class ExecutionSerializer < ApplicationSerializer
+ attributes :id,
+ :workflow_id,
+ :workflow_name,
+ :status,
+ :trigger_data,
+ :error,
+ :run_time_ms,
+ :started_at,
+ :finished_at,
+ :created_at
+
+ attribute :steps
+
+ def workflow_name
+ object.workflow_snapshot_name
+ end
+
+ STEP_FIELDS = %w[
+ node_id
+ node_name
+ node_type
+ position
+ status
+ input
+ output
+ error
+ metadata
+ started_at
+ finished_at
+ ].freeze
+
+ def steps
+ return [] unless object.execution_data
+ object.execution_data.steps_array.map { |step| step.slice(*STEP_FIELDS).symbolize_keys }
+ end
+ end
+end
diff --git a/plugins/discourse-workflows/app/serializers/discourse_workflows/variable_serializer.rb b/plugins/discourse-workflows/app/serializers/discourse_workflows/variable_serializer.rb
new file mode 100644
index 00000000000..fae42bcae51
--- /dev/null
+++ b/plugins/discourse-workflows/app/serializers/discourse_workflows/variable_serializer.rb
@@ -0,0 +1,11 @@
+# frozen_string_literal: true
+
+module DiscourseWorkflows
+ class VariableSerializer < ApplicationSerializer
+ attributes :id, :key, :value, :description, :created_by, :created_at, :updated_at
+
+ def created_by
+ BasicUserSerializer.new(object.created_by, root: false).as_json
+ end
+ end
+end
diff --git a/plugins/discourse-workflows/app/serializers/discourse_workflows/workflow_serializer.rb b/plugins/discourse-workflows/app/serializers/discourse_workflows/workflow_serializer.rb
new file mode 100644
index 00000000000..16e5a6536e9
--- /dev/null
+++ b/plugins/discourse-workflows/app/serializers/discourse_workflows/workflow_serializer.rb
@@ -0,0 +1,122 @@
+# frozen_string_literal: true
+
+module DiscourseWorkflows
+ class WorkflowSerializer < ApplicationSerializer
+ attributes :id,
+ :name,
+ :nodes,
+ :connections,
+ :version_id,
+ :active_version_id,
+ :version_counter,
+ :has_unpublished_changes,
+ :error_workflow_id,
+ :error_workflow_name,
+ :settings,
+ :static_data,
+ :timezone,
+ :created_at,
+ :updated_at,
+ :last_execution_status,
+ :last_execution_at,
+ :last_execution_run_data,
+ :pin_data
+
+ attribute :created_by
+ attribute :updated_by
+
+ def id
+ object.id.to_s
+ end
+
+ def nodes
+ object.nodes || []
+ end
+
+ def connections
+ object.connections || {}
+ end
+
+ def version_id
+ object.version_id
+ end
+
+ def active_version_id
+ object.active_version_id
+ end
+
+ def version_counter
+ object.version_counter
+ end
+
+ def has_unpublished_changes
+ object.has_unpublished_changes?
+ end
+
+ def error_workflow_id
+ object.error_workflow_id
+ end
+
+ def settings
+ object.settings || {}
+ end
+
+ def static_data
+ object.normalized_static_data
+ end
+
+ def created_by
+ BasicUserSerializer.new(object.created_by, root: false).as_json
+ end
+
+ def updated_by
+ return if object.updated_by.blank?
+ BasicUserSerializer.new(object.updated_by, root: false).as_json
+ end
+
+ def error_workflow_name
+ object.error_workflow&.name
+ end
+
+ def timezone
+ object.settings&.dig("timezone") || DiscourseWorkflows::WorkflowTimezone.default
+ end
+
+ def include_error_workflow_name?
+ object.error_workflow_id.present?
+ end
+
+ def last_execution_at
+ return unless object.attributes.key?("last_execution_at")
+ object.attributes["last_execution_at"]
+ end
+
+ def last_execution_status
+ return unless object.attributes.key?("last_execution_status_value")
+ DiscourseWorkflows::Execution.statuses.key(object.attributes["last_execution_status_value"])
+ end
+
+ def include_last_execution_run_data?
+ !object.attributes.key?("last_execution_status_value")
+ end
+
+ def last_execution_run_data
+ execution =
+ object
+ .executions
+ .includes(:execution_data)
+ .where(status: :success)
+ .order(created_at: :desc)
+ .first
+ execution&.execution_data&.run_data
+ end
+
+ def pin_data
+ object.pin_data || {}
+ end
+
+ def include_pin_data?
+ !object.attributes.key?("last_execution_status_value")
+ end
+ end
+end
diff --git a/plugins/discourse-workflows/app/services/discourse_workflows/concerns/data_table_service_helpers.rb b/plugins/discourse-workflows/app/services/discourse_workflows/concerns/data_table_service_helpers.rb
new file mode 100644
index 00000000000..330e90c003f
--- /dev/null
+++ b/plugins/discourse-workflows/app/services/discourse_workflows/concerns/data_table_service_helpers.rb
@@ -0,0 +1,23 @@
+# frozen_string_literal: true
+
+module DiscourseWorkflows
+ module Concerns
+ module DataTableServiceHelpers
+ extend ActiveSupport::Concern
+
+ private
+
+ def fetch_data_table(params:)
+ DiscourseWorkflows::DataTable.find_by(id: params.data_table_id)
+ end
+
+ def build_facade(data_table:)
+ DataTables::Facade.new(data_table)
+ end
+
+ def within_storage_limit
+ DataTables::Facade.within_storage_limit?
+ end
+ end
+ end
+end
diff --git a/plugins/discourse-workflows/app/services/discourse_workflows/credential/create.rb b/plugins/discourse-workflows/app/services/discourse_workflows/credential/create.rb
new file mode 100644
index 00000000000..8ad57fd389f
--- /dev/null
+++ b/plugins/discourse-workflows/app/services/discourse_workflows/credential/create.rb
@@ -0,0 +1,55 @@
+# frozen_string_literal: true
+
+module DiscourseWorkflows
+ class Credential::Create
+ include Service::Base
+
+ policy :can_manage_workflows, class_name: Policy::CanManageWorkflows
+
+ params do
+ attribute :name, :string
+ attribute :credential_type, :string
+ attribute :data
+
+ validates :name, presence: true, length: { maximum: 128 }
+ validates :credential_type, presence: true, length: { maximum: 64 }
+ validate :data_must_be_hash
+
+ def data_must_be_hash
+ return if data.nil?
+ errors.add(:data, :invalid) unless data.is_a?(Hash)
+ end
+
+ def normalized_data
+ (data || {}).stringify_keys
+ end
+ end
+
+ policy :valid_credential_type
+
+ model :credential, :create_credential
+
+ step :log_credential_creation
+
+ private
+
+ def valid_credential_type(params:)
+ Registry.find_credential_type(params.credential_type).present?
+ end
+
+ def create_credential(params:)
+ DiscourseWorkflows::Credential.create(
+ name: params.name,
+ credential_type: params.credential_type,
+ data: params.normalized_data,
+ )
+ end
+
+ def log_credential_creation(credential:, guardian:)
+ StaffActionLogger.new(guardian.user).log_custom(
+ "discourse_workflows_credential_created",
+ subject: credential.name,
+ )
+ end
+ end
+end
diff --git a/plugins/discourse-workflows/app/services/discourse_workflows/credential/destroy.rb b/plugins/discourse-workflows/app/services/discourse_workflows/credential/destroy.rb
new file mode 100644
index 00000000000..34baf61a7bf
--- /dev/null
+++ b/plugins/discourse-workflows/app/services/discourse_workflows/credential/destroy.rb
@@ -0,0 +1,55 @@
+# frozen_string_literal: true
+
+module DiscourseWorkflows
+ class Credential::Destroy
+ include Service::Base
+
+ params do
+ attribute :credential_id, :integer
+ validates :credential_id, presence: true
+ end
+
+ policy :can_manage_workflows, class_name: Policy::CanManageWorkflows
+ model :credential
+ model :referencing_workflows, optional: true
+ policy :credential_not_in_use
+
+ step :remove_credential
+
+ step :log
+
+ private
+
+ def fetch_credential(params:)
+ DiscourseWorkflows::Credential.find_by(id: params.credential_id)
+ end
+
+ def fetch_referencing_workflows(credential:)
+ workflow_ids =
+ DiscourseWorkflows::WorkflowDependency.workflows_referencing(
+ "credential_id",
+ credential.id,
+ ).pluck(:workflow_id)
+ DiscourseWorkflows::Workflow
+ .where(id: workflow_ids)
+ .order(:name)
+ .pluck(:id, :name)
+ .map { |id, name| { id:, name: } }
+ end
+
+ def credential_not_in_use(referencing_workflows:)
+ referencing_workflows.blank?
+ end
+
+ def remove_credential(credential:)
+ credential.destroy!
+ end
+
+ def log(credential:, guardian:)
+ StaffActionLogger.new(guardian.user).log_custom(
+ "discourse_workflows_credential_destroyed",
+ subject: credential.name,
+ )
+ end
+ end
+end
diff --git a/plugins/discourse-workflows/app/services/discourse_workflows/credential/list.rb b/plugins/discourse-workflows/app/services/discourse_workflows/credential/list.rb
new file mode 100644
index 00000000000..3f53c3ab5f9
--- /dev/null
+++ b/plugins/discourse-workflows/app/services/discourse_workflows/credential/list.rb
@@ -0,0 +1,46 @@
+# frozen_string_literal: true
+
+module DiscourseWorkflows
+ class Credential::List
+ include Service::Base
+
+ policy :can_manage_workflows, class_name: Policy::CanManageWorkflows
+
+ params do
+ attribute :cursor, :integer
+ attribute :limit, :integer
+ attribute :type, :string
+
+ after_validation { self.limit = DiscourseWorkflows::Pagination.normalize_limit(limit) }
+ end
+
+ model :credentials, optional: true
+ model :total_rows, :count_total_rows
+ model :load_more_url, :build_load_more_url, optional: true
+
+ private
+
+ def fetch_credentials(params:)
+ scope = DiscourseWorkflows::Credential.order(id: :desc)
+ scope = scope.where(credential_type: params.type) if params.type.present?
+ context[:page] = DiscourseWorkflows::Pagination.cursor_page(
+ scope: scope,
+ cursor: params.cursor,
+ limit: params.limit,
+ path: "/admin/plugins/discourse-workflows/credentials.json",
+ query: {
+ type: params.type,
+ },
+ )
+ context[:page].records
+ end
+
+ def count_total_rows
+ context[:page].total_rows
+ end
+
+ def build_load_more_url
+ context[:page].load_more_url
+ end
+ end
+end
diff --git a/plugins/discourse-workflows/app/services/discourse_workflows/credential/update.rb b/plugins/discourse-workflows/app/services/discourse_workflows/credential/update.rb
new file mode 100644
index 00000000000..478ab2dc8fc
--- /dev/null
+++ b/plugins/discourse-workflows/app/services/discourse_workflows/credential/update.rb
@@ -0,0 +1,48 @@
+# frozen_string_literal: true
+
+module DiscourseWorkflows
+ class Credential::Update
+ include Service::Base
+
+ params do
+ attribute :credential_id, :integer
+ attribute :name, :string
+ attribute :data
+
+ validates :credential_id, presence: true
+ validates :name, presence: true, length: { maximum: 128 }
+ validate :data_must_be_hash
+
+ def data_must_be_hash
+ return if data.nil?
+ errors.add(:data, :invalid) unless data.is_a?(Hash)
+ end
+ end
+
+ policy :can_manage_workflows, class_name: Policy::CanManageWorkflows
+ model :credential
+
+ model :credential, :save_credential
+ step :log_credential_update
+
+ private
+
+ def fetch_credential(params:)
+ DiscourseWorkflows::Credential.find_by(id: params.credential_id)
+ end
+
+ def save_credential(credential:, params:)
+ credential.name = params.name
+ credential.merge_data(params.data) if params.data.present?
+ credential.save
+ credential
+ end
+
+ def log_credential_update(credential:, guardian:)
+ StaffActionLogger.new(guardian.user).log_custom(
+ "discourse_workflows_credential_updated",
+ subject: credential.name,
+ )
+ end
+ end
+end
diff --git a/plugins/discourse-workflows/app/services/discourse_workflows/data_table/create.rb b/plugins/discourse-workflows/app/services/discourse_workflows/data_table/create.rb
new file mode 100644
index 00000000000..1d10ed4eda9
--- /dev/null
+++ b/plugins/discourse-workflows/app/services/discourse_workflows/data_table/create.rb
@@ -0,0 +1,65 @@
+# frozen_string_literal: true
+
+module DiscourseWorkflows
+ class DataTable::Create
+ include Service::Base
+
+ policy :can_manage_workflows, class_name: Policy::CanManageWorkflows
+
+ params do
+ attribute :name, :string
+ attribute :columns, :array, default: []
+
+ validates :name,
+ presence: true,
+ length: {
+ maximum: 100,
+ },
+ format: {
+ with: /\A[a-zA-Z_][a-zA-Z0-9_ ]*\z/,
+ }
+
+ def normalized_columns
+ columns.filter_map do |column|
+ column = column.respond_to?(:to_h) ? column.to_h.deep_stringify_keys : column
+ name = column["name"].to_s
+ type = column["type"].to_s
+ next if name.blank? || type.blank?
+ next unless DiscourseWorkflows::DataTable::COLUMN_NAME_FORMAT.match?(name)
+ next if DiscourseWorkflows::DataTable::VALID_COLUMN_TYPES.exclude?(type)
+ next if DiscourseWorkflows::DataTables::Types.system_column?(name)
+ next if name.length > DiscourseWorkflows::DataTable::MAX_COLUMN_NAME_LENGTH
+
+ { "name" => name, "type" => type }
+ end
+ end
+ end
+
+ transaction do
+ model :data_table, :build_data_table
+ step :create_storage_table
+ end
+
+ step :log
+
+ private
+
+ def build_data_table(params:)
+ DiscourseWorkflows::DataTable.create(name: params.name)
+ end
+
+ def create_storage_table(data_table:, params:)
+ DiscourseWorkflows::DataTables::Facade.create_table!(
+ data_table,
+ columns: params.normalized_columns,
+ )
+ end
+
+ def log(data_table:, guardian:)
+ StaffActionLogger.new(guardian.user).log_custom(
+ "discourse_workflows_data_table_created",
+ subject: data_table.name,
+ )
+ end
+ end
+end
diff --git a/plugins/discourse-workflows/app/services/discourse_workflows/data_table/destroy.rb b/plugins/discourse-workflows/app/services/discourse_workflows/data_table/destroy.rb
new file mode 100644
index 00000000000..f92e145fe8a
--- /dev/null
+++ b/plugins/discourse-workflows/app/services/discourse_workflows/data_table/destroy.rb
@@ -0,0 +1,47 @@
+# frozen_string_literal: true
+
+module DiscourseWorkflows
+ class DataTable::Destroy
+ include Service::Base
+ include Concerns::DataTableServiceHelpers
+
+ params do
+ attribute :data_table_id, :integer
+ validates :data_table_id, presence: true
+ end
+
+ policy :can_manage_workflows, class_name: Policy::CanManageWorkflows
+ model :data_table
+ model :referencing_workflows, optional: true
+ policy :data_table_not_in_use
+
+ step :delete_data_table
+ step :log
+
+ private
+
+ def fetch_referencing_workflows(data_table:)
+ workflow_ids =
+ DiscourseWorkflows::WorkflowDependency.workflows_referencing(
+ "data_table_id",
+ data_table.id,
+ ).pluck(:workflow_id)
+ DiscourseWorkflows::Workflow.where(id: workflow_ids).to_a
+ end
+
+ def data_table_not_in_use(referencing_workflows:)
+ referencing_workflows.blank?
+ end
+
+ def delete_data_table(data_table:)
+ data_table.destroy!
+ end
+
+ def log(data_table:, guardian:)
+ StaffActionLogger.new(guardian.user).log_custom(
+ "discourse_workflows_data_table_destroyed",
+ subject: data_table.name,
+ )
+ end
+ end
+end
diff --git a/plugins/discourse-workflows/app/services/discourse_workflows/data_table/list.rb b/plugins/discourse-workflows/app/services/discourse_workflows/data_table/list.rb
new file mode 100644
index 00000000000..ed4a8295d9d
--- /dev/null
+++ b/plugins/discourse-workflows/app/services/discourse_workflows/data_table/list.rb
@@ -0,0 +1,46 @@
+# frozen_string_literal: true
+
+module DiscourseWorkflows
+ class DataTable::List
+ include Service::Base
+
+ policy :can_manage_workflows, class_name: Policy::CanManageWorkflows
+
+ params do
+ attribute :cursor, :integer
+ attribute :limit, :integer
+
+ after_validation { self.limit = DiscourseWorkflows::Pagination.normalize_limit(limit) }
+ end
+
+ model :data_tables, optional: true
+ model :table_sizes, :compute_table_sizes, optional: true
+ model :total_rows, :compute_total_rows
+ model :load_more_url, :compute_load_more_url, optional: true
+
+ private
+
+ def fetch_data_tables(params:)
+ scope = DiscourseWorkflows::DataTable.order(id: :desc)
+ context[:page] = DiscourseWorkflows::Pagination.cursor_page(
+ scope: scope,
+ cursor: params.cursor,
+ limit: params.limit,
+ path: "/admin/plugins/discourse-workflows/data-tables.json",
+ )
+ context[:page].records
+ end
+
+ def compute_table_sizes(data_tables:)
+ DiscourseWorkflows::DataTables::Facade.batch_size_bytes(data_tables.map(&:id))
+ end
+
+ def compute_total_rows
+ context[:page].total_rows
+ end
+
+ def compute_load_more_url
+ context[:page].load_more_url
+ end
+ end
+end
diff --git a/plugins/discourse-workflows/app/services/discourse_workflows/data_table/show.rb b/plugins/discourse-workflows/app/services/discourse_workflows/data_table/show.rb
new file mode 100644
index 00000000000..b088f91b746
--- /dev/null
+++ b/plugins/discourse-workflows/app/services/discourse_workflows/data_table/show.rb
@@ -0,0 +1,17 @@
+# frozen_string_literal: true
+
+module DiscourseWorkflows
+ class DataTable::Show
+ include Service::Base
+ include Concerns::DataTableServiceHelpers
+
+ params do
+ attribute :data_table_id, :integer
+
+ validates :data_table_id, presence: true
+ end
+
+ policy :can_manage_workflows, class_name: Policy::CanManageWorkflows
+ model :data_table
+ end
+end
diff --git a/plugins/discourse-workflows/app/services/discourse_workflows/data_table/update.rb b/plugins/discourse-workflows/app/services/discourse_workflows/data_table/update.rb
new file mode 100644
index 00000000000..aa9e95ea8db
--- /dev/null
+++ b/plugins/discourse-workflows/app/services/discourse_workflows/data_table/update.rb
@@ -0,0 +1,43 @@
+# frozen_string_literal: true
+
+module DiscourseWorkflows
+ class DataTable::Update
+ include Service::Base
+ include Concerns::DataTableServiceHelpers
+
+ params do
+ attribute :data_table_id, :integer
+ attribute :name, :string
+
+ validates :data_table_id, presence: true
+ validates :name,
+ presence: true,
+ length: {
+ maximum: 100,
+ },
+ format: {
+ with: /\A[a-zA-Z_][a-zA-Z0-9_ ]*\z/,
+ }
+ end
+
+ policy :can_manage_workflows, class_name: Policy::CanManageWorkflows
+ model :data_table
+ model :data_table, :update_data_table
+
+ step :log
+
+ private
+
+ def update_data_table(data_table:, params:)
+ data_table.update(name: params.name)
+ data_table
+ end
+
+ def log(guardian:, data_table:)
+ StaffActionLogger.new(guardian.user).log_custom(
+ "discourse_workflows_data_table_updated",
+ subject: data_table.name,
+ )
+ end
+ end
+end
diff --git a/plugins/discourse-workflows/app/services/discourse_workflows/data_table_column/create.rb b/plugins/discourse-workflows/app/services/discourse_workflows/data_table_column/create.rb
new file mode 100644
index 00000000000..e19c75b83b5
--- /dev/null
+++ b/plugins/discourse-workflows/app/services/discourse_workflows/data_table_column/create.rb
@@ -0,0 +1,66 @@
+# frozen_string_literal: true
+
+module DiscourseWorkflows
+ class DataTableColumn::Create
+ include Service::Base
+ include Concerns::DataTableServiceHelpers
+
+ MAX_COLUMNS = 30
+
+ params do
+ attribute :data_table_id, :integer
+ attribute :name, :string
+ attribute :column_type, :string
+
+ validates :data_table_id, presence: true
+ validates :name,
+ presence: true,
+ length: {
+ maximum: DiscourseWorkflows::DataTable::MAX_COLUMN_NAME_LENGTH,
+ },
+ format: {
+ with: DiscourseWorkflows::DataTable::COLUMN_NAME_FORMAT,
+ message:
+ "must start with a letter or underscore and contain only letters, numbers, and underscores",
+ },
+ exclusion: {
+ in: DataTables::Types::SYSTEM_COLUMN_NAMES,
+ message: "is reserved",
+ }
+ validates :column_type,
+ presence: true,
+ inclusion: {
+ in: DiscourseWorkflows::DataTable::VALID_COLUMN_TYPES,
+ }
+ end
+
+ policy :can_manage_workflows, class_name: Policy::CanManageWorkflows
+ model :data_table
+ policy :column_limit_not_reached
+
+ step :add_storage_column
+ step :log
+
+ private
+
+ def column_limit_not_reached(data_table:)
+ data_table.columns.size < MAX_COLUMNS
+ end
+
+ def add_storage_column(data_table:, params:)
+ DiscourseWorkflows::DataTables::Facade.new(data_table).add_column!(
+ params.name,
+ params.column_type,
+ )
+ end
+
+ def log(guardian:, data_table:, params:)
+ StaffActionLogger.new(guardian.user).log_custom(
+ "discourse_workflows_data_table_column_created",
+ subject: data_table.name,
+ column_name: params.name,
+ column_type: params.column_type,
+ )
+ end
+ end
+end
diff --git a/plugins/discourse-workflows/app/services/discourse_workflows/data_table_column/destroy.rb b/plugins/discourse-workflows/app/services/discourse_workflows/data_table_column/destroy.rb
new file mode 100644
index 00000000000..6d462c696f7
--- /dev/null
+++ b/plugins/discourse-workflows/app/services/discourse_workflows/data_table_column/destroy.rb
@@ -0,0 +1,46 @@
+# frozen_string_literal: true
+
+module DiscourseWorkflows
+ class DataTableColumn::Destroy
+ include Service::Base
+ include Concerns::DataTableServiceHelpers
+
+ params do
+ attribute :data_table_id, :integer
+ attribute :column_name, :string
+
+ validates :data_table_id, presence: true
+ validates :column_name, presence: true
+ end
+
+ policy :can_manage_workflows, class_name: Policy::CanManageWorkflows
+ model :data_table
+ policy :column_exists
+ policy :not_reserved_column
+
+ step :drop_storage_column
+ step :log
+
+ private
+
+ def column_exists(data_table:, params:)
+ data_table.columns.any? { |c| c["name"] == params.column_name }
+ end
+
+ def not_reserved_column(params:)
+ DataTables::Types::SYSTEM_COLUMN_NAMES.exclude?(params.column_name)
+ end
+
+ def drop_storage_column(data_table:, params:)
+ DiscourseWorkflows::DataTables::Facade.new(data_table).drop_column!(params.column_name)
+ end
+
+ def log(guardian:, data_table:, params:)
+ StaffActionLogger.new(guardian.user).log_custom(
+ "discourse_workflows_data_table_column_destroyed",
+ subject: data_table.name,
+ column_name: params.column_name,
+ )
+ end
+ end
+end
diff --git a/plugins/discourse-workflows/app/services/discourse_workflows/data_table_column/rename.rb b/plugins/discourse-workflows/app/services/discourse_workflows/data_table_column/rename.rb
new file mode 100644
index 00000000000..82e68b0d59a
--- /dev/null
+++ b/plugins/discourse-workflows/app/services/discourse_workflows/data_table_column/rename.rb
@@ -0,0 +1,75 @@
+# frozen_string_literal: true
+
+module DiscourseWorkflows
+ class DataTableColumn::Rename
+ include Service::Base
+ include Concerns::DataTableServiceHelpers
+
+ params do
+ attribute :data_table_id, :integer
+ attribute :column_name, :string
+ attribute :name, :string
+
+ validates :data_table_id, presence: true
+ validates :column_name, presence: true
+ validates :name,
+ presence: true,
+ length: {
+ maximum: DiscourseWorkflows::DataTable::MAX_COLUMN_NAME_LENGTH,
+ },
+ format: {
+ with: DiscourseWorkflows::DataTable::COLUMN_NAME_FORMAT,
+ message:
+ "must start with a letter or underscore and contain only letters, numbers, and underscores",
+ },
+ exclusion: {
+ in: DataTables::Types::SYSTEM_COLUMN_NAMES,
+ message: "is reserved",
+ }
+ end
+
+ policy :can_manage_workflows, class_name: Policy::CanManageWorkflows
+ model :data_table
+ policy :column_exists
+ policy :not_reserved_column
+ policy :name_differs
+ policy :name_available
+
+ step :rename_storage_column
+ step :log
+
+ private
+
+ def column_exists(data_table:, params:)
+ data_table.columns.any? { |c| c["name"] == params.column_name }
+ end
+
+ def not_reserved_column(params:)
+ DataTables::Types::SYSTEM_COLUMN_NAMES.exclude?(params.column_name)
+ end
+
+ def name_available(data_table:, params:)
+ data_table.columns.none? { |c| c["name"] == params.name }
+ end
+
+ def name_differs(params:)
+ params.column_name != params.name
+ end
+
+ def rename_storage_column(data_table:, params:)
+ DiscourseWorkflows::DataTables::Facade.new(data_table).rename_column!(
+ old_name: params.column_name,
+ new_name: params.name,
+ )
+ end
+
+ def log(guardian:, data_table:, params:)
+ StaffActionLogger.new(guardian.user).log_custom(
+ "discourse_workflows_data_table_column_renamed",
+ subject: data_table.name,
+ previous_value: params.column_name,
+ new_value: params.name,
+ )
+ end
+ end
+end
diff --git a/plugins/discourse-workflows/app/services/discourse_workflows/data_table_row/destroy.rb b/plugins/discourse-workflows/app/services/discourse_workflows/data_table_row/destroy.rb
new file mode 100644
index 00000000000..d4560ffae00
--- /dev/null
+++ b/plugins/discourse-workflows/app/services/discourse_workflows/data_table_row/destroy.rb
@@ -0,0 +1,75 @@
+# frozen_string_literal: true
+
+module DiscourseWorkflows
+ class DataTableRow::Destroy
+ include Service::Base
+ include Concerns::DataTableServiceHelpers
+
+ MAX_BULK_DELETE = 500
+
+ params do
+ attribute :data_table_id, :integer
+ attribute :row_id, :integer
+ attribute :row_ids, :array
+ attribute :filter
+
+ before_validation { self.row_ids = row_ids.map(&:to_i).uniq if row_ids.present? }
+
+ validates :data_table_id, presence: true
+ validates :row_ids, length: { maximum: MAX_BULK_DELETE }, allow_nil: true
+ validate :at_least_one_target
+
+ def at_least_one_target
+ return if row_id.present? || row_ids.present? || !filter.nil?
+ errors.add(:base, "one of row_id, row_ids, or filter must be provided")
+ end
+ end
+
+ policy :can_manage_workflows, class_name: Policy::CanManageWorkflows
+ model :data_table
+ model :facade, :build_facade
+
+ only_if(:single_row_mode?) do
+ model :row, :fetch_row
+ model :deleted_count, :delete_batch_rows
+ end
+
+ only_if(:batch_mode?) { model :deleted_count, :delete_batch_rows }
+
+ only_if(:filter_mode?) do
+ model :query, :build_query
+ model :deleted_count, :delete_filtered_rows
+ end
+
+ private
+
+ def single_row_mode?(params:)
+ params.row_id.present?
+ end
+
+ def batch_mode?(params:)
+ params.row_ids.present?
+ end
+
+ def filter_mode?(params:)
+ !params.filter.nil?
+ end
+
+ def fetch_row(facade:, params:)
+ facade.find_row(params.row_id)
+ end
+
+ def build_query(facade:, params:)
+ facade.build_query(filter: params.filter)
+ end
+
+ def delete_batch_rows(facade:, params:)
+ ids = params.row_ids.presence || [params.row_id]
+ facade.delete_rows(ids)
+ end
+
+ def delete_filtered_rows(facade:, query:)
+ facade.delete(query:)
+ end
+ end
+end
diff --git a/plugins/discourse-workflows/app/services/discourse_workflows/data_table_row/get.rb b/plugins/discourse-workflows/app/services/discourse_workflows/data_table_row/get.rb
new file mode 100644
index 00000000000..740d475d980
--- /dev/null
+++ b/plugins/discourse-workflows/app/services/discourse_workflows/data_table_row/get.rb
@@ -0,0 +1,47 @@
+# frozen_string_literal: true
+
+module DiscourseWorkflows
+ class DataTableRow::Get
+ include Service::Base
+ include Concerns::DataTableServiceHelpers
+
+ params do
+ attribute :data_table_id, :integer
+ attribute :filter
+ attribute :limit, :integer
+ attribute :offset, :integer
+ attribute :sort_by, :string
+ attribute :sort_direction, :string
+
+ validates :data_table_id, presence: true
+
+ before_validation do
+ self.limit =
+ limit.to_i.clamp(1, DiscourseWorkflows::Pagination::MAX_LIMIT) if limit.present?
+ end
+ end
+
+ policy :can_manage_workflows, class_name: Policy::CanManageWorkflows
+ model :data_table
+ model :facade, :build_facade
+ model :query, :build_query
+ model :query_result, :execute_query
+
+ private
+
+ def build_query(facade:, params:)
+ facade.build_query(
+ filter: params.filter,
+ limit: params.limit || DiscourseWorkflows::Pagination::DEFAULT_LIMIT,
+ offset: params.offset,
+ sort_by: params.sort_by,
+ sort_direction: params.sort_direction,
+ optional_filter: true,
+ )
+ end
+
+ def execute_query(facade:, query:)
+ facade.query(query)
+ end
+ end
+end
diff --git a/plugins/discourse-workflows/app/services/discourse_workflows/data_table_row/insert.rb b/plugins/discourse-workflows/app/services/discourse_workflows/data_table_row/insert.rb
new file mode 100644
index 00000000000..96a4d46d07f
--- /dev/null
+++ b/plugins/discourse-workflows/app/services/discourse_workflows/data_table_row/insert.rb
@@ -0,0 +1,32 @@
+# frozen_string_literal: true
+
+module DiscourseWorkflows
+ class DataTableRow::Insert
+ include Service::Base
+ include Concerns::DataTableServiceHelpers
+
+ params do
+ attribute :data_table_id, :integer
+ attribute :data, default: -> { {} }
+
+ validates :data_table_id, presence: true
+ end
+
+ policy :can_manage_workflows, class_name: Policy::CanManageWorkflows
+ model :data_table
+ model :facade, :build_facade
+ policy :within_storage_limit
+ model :row_input, :build_row_input
+ model :row, :insert_row
+
+ private
+
+ def build_row_input(facade:, params:)
+ facade.build_row_input(data: params.data, fill_missing: true)
+ end
+
+ def insert_row(facade:, row_input:)
+ facade.insert(row_input)
+ end
+ end
+end
diff --git a/plugins/discourse-workflows/app/services/discourse_workflows/data_table_row/update.rb b/plugins/discourse-workflows/app/services/discourse_workflows/data_table_row/update.rb
new file mode 100644
index 00000000000..ecb8e0bc46e
--- /dev/null
+++ b/plugins/discourse-workflows/app/services/discourse_workflows/data_table_row/update.rb
@@ -0,0 +1,43 @@
+# frozen_string_literal: true
+
+module DiscourseWorkflows
+ class DataTableRow::Update
+ include Service::Base
+ include Concerns::DataTableServiceHelpers
+
+ params do
+ attribute :data_table_id, :integer
+ attribute :filter
+ attribute :data, default: -> { {} }
+
+ validates :data_table_id, presence: true
+ end
+
+ policy :can_manage_workflows, class_name: Policy::CanManageWorkflows
+ model :data_table
+ model :facade, :build_facade
+ policy :within_storage_limit
+ model :query, :build_query
+ model :row_input, :build_row_input
+ model :updated_count, :update_matching_rows
+ step :ensure_rows_matched
+
+ private
+
+ def build_query(facade:, params:)
+ facade.build_query(filter: params.filter)
+ end
+
+ def build_row_input(facade:, params:)
+ facade.build_row_input(data: params.data)
+ end
+
+ def update_matching_rows(facade:, query:, row_input:)
+ facade.update(query:, row_input:)
+ end
+
+ def ensure_rows_matched(updated_count:)
+ fail!(I18n.t("discourse_workflows.errors.no_rows_matched_filter")) if updated_count == 0
+ end
+ end
+end
diff --git a/plugins/discourse-workflows/app/services/discourse_workflows/data_table_row/update_single.rb b/plugins/discourse-workflows/app/services/discourse_workflows/data_table_row/update_single.rb
new file mode 100644
index 00000000000..35b6424f5fb
--- /dev/null
+++ b/plugins/discourse-workflows/app/services/discourse_workflows/data_table_row/update_single.rb
@@ -0,0 +1,39 @@
+# frozen_string_literal: true
+
+module DiscourseWorkflows
+ class DataTableRow::UpdateSingle
+ include Service::Base
+ include Concerns::DataTableServiceHelpers
+
+ params do
+ attribute :data_table_id, :integer
+ attribute :row_id, :integer
+ attribute :data, default: -> { {} }
+
+ validates :data_table_id, presence: true
+ validates :row_id, presence: true
+ end
+
+ policy :can_manage_workflows, class_name: Policy::CanManageWorkflows
+ model :data_table
+ model :facade, :build_facade
+ policy :within_storage_limit
+ model :existing_row
+ model :row_input, :build_row_input
+ model :row, :update_row
+
+ private
+
+ def fetch_existing_row(facade:, params:)
+ facade.find_row(params.row_id)
+ end
+
+ def build_row_input(facade:, params:)
+ facade.build_row_input(data: params.data)
+ end
+
+ def update_row(facade:, params:, row_input:)
+ facade.update_row(row_id: params.row_id, row_input: row_input)
+ end
+ end
+end
diff --git a/plugins/discourse-workflows/app/services/discourse_workflows/execution/check_schedules.rb b/plugins/discourse-workflows/app/services/discourse_workflows/execution/check_schedules.rb
new file mode 100644
index 00000000000..a66a729c6f5
--- /dev/null
+++ b/plugins/discourse-workflows/app/services/discourse_workflows/execution/check_schedules.rb
@@ -0,0 +1,16 @@
+# frozen_string_literal: true
+
+module DiscourseWorkflows
+ class Execution::CheckSchedules
+ include Service::Base
+
+ policy :workflows_enabled, class_name: DiscourseWorkflows::Policy::WorkflowsEnabled
+ step :tick_triggers
+
+ private
+
+ def tick_triggers
+ TriggerRuntime.tick!(now: Time.current.utc)
+ end
+ end
+end
diff --git a/plugins/discourse-workflows/app/services/discourse_workflows/execution/check_stale_topics.rb b/plugins/discourse-workflows/app/services/discourse_workflows/execution/check_stale_topics.rb
new file mode 100644
index 00000000000..491fac60e21
--- /dev/null
+++ b/plugins/discourse-workflows/app/services/discourse_workflows/execution/check_stale_topics.rb
@@ -0,0 +1,31 @@
+# frozen_string_literal: true
+
+module DiscourseWorkflows
+ class Execution::CheckStaleTopics
+ include Service::Base
+
+ policy :workflows_enabled, class_name: DiscourseWorkflows::Policy::WorkflowsEnabled
+ model :stale_trigger_nodes
+ step :process_stale_trigger_nodes
+
+ private
+
+ def fetch_stale_trigger_nodes
+ DiscourseWorkflows::Workflow::Action::FindPublishedTriggers.call(
+ trigger_type: "trigger:stale_topic",
+ )
+ end
+
+ def process_stale_trigger_nodes(stale_trigger_nodes:)
+ stale_trigger_nodes.each do |published_trigger|
+ items =
+ DiscourseWorkflows::Nodes::StaleTopic::V1.trigger_data_for(
+ DiscourseWorkflows::TriggerNodeContext.from_published_trigger(published_trigger),
+ )
+ next if items.empty?
+
+ DiscourseWorkflows::TriggerDispatcher.enqueue(published_trigger, trigger_data: items)
+ end
+ end
+ end
+end
diff --git a/plugins/discourse-workflows/app/services/discourse_workflows/execution/destroy.rb b/plugins/discourse-workflows/app/services/discourse_workflows/execution/destroy.rb
new file mode 100644
index 00000000000..4c2d83f8c90
--- /dev/null
+++ b/plugins/discourse-workflows/app/services/discourse_workflows/execution/destroy.rb
@@ -0,0 +1,31 @@
+# frozen_string_literal: true
+
+module DiscourseWorkflows
+ class Execution::Destroy
+ include Service::Base
+
+ MAX_BULK_DELETE = 500
+
+ params do
+ attribute :execution_ids, :array
+ validates :execution_ids, presence: true, length: { maximum: MAX_BULK_DELETE }
+ end
+
+ policy :can_manage_workflows, class_name: Policy::CanManageWorkflows
+
+ transaction do
+ step :delete_execution_data
+ model :deleted_count, :delete_executions
+ end
+
+ private
+
+ def delete_execution_data(params:)
+ DiscourseWorkflows::ExecutionData.where(execution_id: params.execution_ids).delete_all
+ end
+
+ def delete_executions(params:)
+ DiscourseWorkflows::Execution.where(id: params.execution_ids).delete_all
+ end
+ end
+end
diff --git a/plugins/discourse-workflows/app/services/discourse_workflows/execution/expire_waiting.rb b/plugins/discourse-workflows/app/services/discourse_workflows/execution/expire_waiting.rb
new file mode 100644
index 00000000000..50430acf7e2
--- /dev/null
+++ b/plugins/discourse-workflows/app/services/discourse_workflows/execution/expire_waiting.rb
@@ -0,0 +1,32 @@
+# frozen_string_literal: true
+
+module DiscourseWorkflows
+ class Execution::ExpireWaiting
+ include Service::Base
+
+ policy :workflows_enabled, class_name: DiscourseWorkflows::Policy::WorkflowsEnabled
+ model :expired_executions, optional: true
+
+ each :expired_executions do
+ step :expire_execution
+ end
+
+ private
+
+ def fetch_expired_executions
+ DiscourseWorkflows::Execution.expired_waiting.includes(:execution_data).limit(500)
+ end
+
+ def expire_execution(expired_execution:)
+ if expired_execution.timeout_action == "fail"
+ expired_execution.fail_with_timeout!
+ else
+ response_items = expired_execution.waiting_step_input_items
+ claimed = DiscourseWorkflows::Execution.claim_for_resume(expired_execution)
+ return if claimed.nil?
+
+ Executor.resume(claimed, response_items)
+ end
+ end
+ end
+end
diff --git a/plugins/discourse-workflows/app/services/discourse_workflows/execution/list.rb b/plugins/discourse-workflows/app/services/discourse_workflows/execution/list.rb
new file mode 100644
index 00000000000..348aa370176
--- /dev/null
+++ b/plugins/discourse-workflows/app/services/discourse_workflows/execution/list.rb
@@ -0,0 +1,62 @@
+# frozen_string_literal: true
+
+module DiscourseWorkflows
+ class Execution::List
+ include Service::Base
+
+ policy :can_manage_workflows, class_name: Policy::CanManageWorkflows
+
+ params do
+ attribute :workflow_id, :integer
+ attribute :cursor, :integer
+ attribute :limit, :integer
+
+ before_validation do
+ self.limit =
+ limit.to_i.clamp(1, DiscourseWorkflows::Pagination::MAX_LIMIT) if limit.present?
+ end
+
+ def effective_limit
+ limit || DiscourseWorkflows::Pagination::DEFAULT_LIMIT
+ end
+ end
+
+ model :executions, optional: true
+ model :has_more, :compute_has_more, optional: true
+ only_if(:has_more) { model :load_more_url, :compute_load_more_url, optional: true }
+
+ private
+
+ def fetch_executions(params:)
+ scope =
+ DiscourseWorkflows::Execution
+ .for_workflow(params.workflow_id)
+ .order(id: :desc)
+ .includes(:execution_data, workflow: :active_version)
+ scope = scope.where("discourse_workflows_executions.id < ?", params.cursor) if params.cursor
+
+ scope.limit(params.effective_limit + 1).to_a
+ end
+
+ def compute_has_more(executions:, params:)
+ has_more = executions.size > params.effective_limit
+ executions.pop if has_more
+ has_more
+ end
+
+ def has_more
+ context[:has_more]
+ end
+
+ def compute_load_more_url(params:, executions:)
+ path =
+ if params.workflow_id
+ "/admin/plugins/discourse-workflows/workflows/#{params.workflow_id}/executions.json"
+ else
+ "/admin/plugins/discourse-workflows/executions.json"
+ end
+
+ "#{path}?cursor=#{executions.last.id}&limit=#{params.effective_limit}"
+ end
+ end
+end
diff --git a/plugins/discourse-workflows/app/services/discourse_workflows/execution/show.rb b/plugins/discourse-workflows/app/services/discourse_workflows/execution/show.rb
new file mode 100644
index 00000000000..900a8cab1a0
--- /dev/null
+++ b/plugins/discourse-workflows/app/services/discourse_workflows/execution/show.rb
@@ -0,0 +1,24 @@
+# frozen_string_literal: true
+
+module DiscourseWorkflows
+ class Execution::Show
+ include Service::Base
+
+ params do
+ attribute :execution_id, :integer
+
+ validates :execution_id, presence: true
+ end
+
+ policy :can_manage_workflows, class_name: Policy::CanManageWorkflows
+ model :execution
+
+ private
+
+ def fetch_execution(params:)
+ DiscourseWorkflows::Execution.includes(:execution_data, workflow: :active_version).find_by(
+ id: params.execution_id,
+ )
+ end
+ end
+end
diff --git a/plugins/discourse-workflows/app/services/discourse_workflows/expression/evaluate.rb b/plugins/discourse-workflows/app/services/discourse_workflows/expression/evaluate.rb
new file mode 100644
index 00000000000..038c5f06fbc
--- /dev/null
+++ b/plugins/discourse-workflows/app/services/discourse_workflows/expression/evaluate.rb
@@ -0,0 +1,38 @@
+# frozen_string_literal: true
+
+module DiscourseWorkflows
+ class Expression::Evaluate
+ include Service::Base
+
+ params do
+ attribute :template, :string
+ attribute :workflow_id, :integer
+ attribute :node_id, :string
+
+ validates :template, presence: true
+ end
+
+ policy :can_manage_workflows, class_name: Policy::CanManageWorkflows
+ model :workflow, optional: true
+ model :preview_context, :build_preview_context
+ model :segments, :resolve_segments, optional: true
+
+ private
+
+ def fetch_workflow(params:)
+ DiscourseWorkflows::Workflow.find_by(id: params.workflow_id)
+ end
+
+ def build_preview_context(workflow:, params:)
+ Workflow::Action::BuildExpressionPreviewContext.call(workflow:, node_id: params.node_id)
+ end
+
+ def resolve_segments(params:, preview_context:, guardian:)
+ ExpressionResolver.resolve_segments(
+ params.template,
+ context: preview_context,
+ user: guardian.user,
+ )
+ end
+ end
+end
diff --git a/plugins/discourse-workflows/app/services/discourse_workflows/form/action/find_published_trigger.rb b/plugins/discourse-workflows/app/services/discourse_workflows/form/action/find_published_trigger.rb
new file mode 100644
index 00000000000..a76b8496a17
--- /dev/null
+++ b/plugins/discourse-workflows/app/services/discourse_workflows/form/action/find_published_trigger.rb
@@ -0,0 +1,27 @@
+# frozen_string_literal: true
+
+module DiscourseWorkflows
+ class Form::Action::FindPublishedTrigger < Service::ActionBase
+ option :uuid
+ option :workflow, optional: true
+
+ def call
+ Workflow::Action::FindPublishedTriggers.call(
+ trigger_type: NodeDataShape::FORM_TRIGGER_TYPE,
+ filter: filter_by_uuid_and_workflow,
+ ).first
+ end
+
+ private
+
+ def filter_by_uuid_and_workflow
+ lambda do |published_trigger|
+ node = published_trigger.trigger_node
+ trigger_workflow = published_trigger.workflow
+ next false if workflow && trigger_workflow.id != workflow.id
+
+ node[WorkflowDocument.node_webhook_id_key] == uuid
+ end
+ end
+ end
+end
diff --git a/plugins/discourse-workflows/app/services/discourse_workflows/form/show.rb b/plugins/discourse-workflows/app/services/discourse_workflows/form/show.rb
new file mode 100644
index 00000000000..19fbc37aad3
--- /dev/null
+++ b/plugins/discourse-workflows/app/services/discourse_workflows/form/show.rb
@@ -0,0 +1,96 @@
+# frozen_string_literal: true
+
+module DiscourseWorkflows
+ class Form::Show
+ include Service::Base
+
+ params do
+ attribute :uuid, :string
+ attribute :form_query_parameters, default: -> { {} }
+
+ validates :uuid, presence: true
+ validate :form_query_parameters_must_be_hash
+
+ def form_query_parameters_must_be_hash
+ errors.add(:form_query_parameters, :invalid) unless form_query_parameters.is_a?(Hash)
+ end
+ end
+
+ model :published_trigger, :fetch_published_trigger_by_uuid
+ model :workflow, :fetch_workflow_from_published_trigger
+ model :workflow_version, :fetch_workflow_version_from_published_trigger
+ model :form_node, :fetch_form_node_from_published_trigger
+ policy :authenticated_if_required
+ model :form_data, :build_form_data_from_config
+
+ private
+
+ def authenticated_if_required(form_node:, guardian:)
+ return true if NodeData.parameters(form_node)["authentication"] != "login_required"
+ guardian.authenticated?
+ end
+
+ def fetch_published_trigger_by_uuid(params:)
+ Form::Action::FindPublishedTrigger.call(uuid: params.uuid)
+ end
+
+ def fetch_workflow_from_published_trigger(published_trigger:)
+ published_trigger.workflow
+ end
+
+ def fetch_workflow_version_from_published_trigger(published_trigger:)
+ published_trigger.workflow_version
+ end
+
+ def fetch_form_node_from_published_trigger(published_trigger:)
+ published_trigger.trigger_node
+ end
+
+ def build_form_data_from_config(workflow:, workflow_version:, form_node:, params:, guardian:)
+ resume_token =
+ DiscourseWorkflows::FormTriggerToken.generate(
+ workflow_id: workflow.id,
+ trigger_node_id: form_node["id"],
+ uuid: params.uuid,
+ form_query_parameters: params.form_query_parameters,
+ )
+
+ exec_context = {
+ "__execution" => {
+ "workflow_id" => workflow.id,
+ "workflow_name" => workflow_version.name,
+ "resume_url" => "",
+ "resumeFormUrl" => "",
+ },
+ }
+
+ config =
+ ExpressionResolver.resolve_hash(
+ NodeData.parameters(form_node).deep_stringify_keys,
+ context: exec_context,
+ user: guardian.user,
+ )
+
+ fields =
+ Schemas::FormFields.apply_query_defaults(
+ Schemas::FormFields.with_keys(CollectionParameters.rows(config, "form_fields")),
+ params.form_query_parameters,
+ )
+
+ DiscourseWorkflows::Forms::ViewModel.build(
+ fields: fields,
+ form_title: config["form_title"],
+ form_description: config["form_description"],
+ response_mode: config["response_mode"] || "on_received",
+ has_downstream_form:
+ workflow.node_has_reachable_downstream_of_type?(
+ form_node["id"],
+ "action:form",
+ published: true,
+ ),
+ form_submit_url: "/workflows/form/#{params.uuid}.json",
+ resume_token: resume_token,
+ )
+ end
+ end
+end
diff --git a/plugins/discourse-workflows/app/services/discourse_workflows/form/submit.rb b/plugins/discourse-workflows/app/services/discourse_workflows/form/submit.rb
new file mode 100644
index 00000000000..1d98247bec6
--- /dev/null
+++ b/plugins/discourse-workflows/app/services/discourse_workflows/form/submit.rb
@@ -0,0 +1,113 @@
+# frozen_string_literal: true
+
+module DiscourseWorkflows
+ class Form::Submit
+ include Service::Base
+
+ params do
+ attribute :uuid, :string
+ attribute :resume_token, :string
+ attribute :form_data, default: -> { {} }
+
+ validates :uuid, presence: true
+ validate :form_data_must_be_hash
+
+ def form_data_must_be_hash
+ errors.add(:form_data, :invalid) unless form_data.is_a?(Hash)
+ end
+ end
+
+ model :published_trigger
+ model :workflow
+ model :trigger_node
+ policy :authenticated_if_required
+ policy :valid_initial_submission_token
+ model :submission_token_payload
+ model :form_validation, :validate_form
+ step :ensure_form_valid
+ model :execution, :run_workflow
+ model :response_metadata, :build_response_metadata
+
+ private
+
+ def authenticated_if_required(trigger_node:, guardian:)
+ return true if NodeData.parameters(trigger_node)["authentication"] != "login_required"
+ guardian.authenticated?
+ end
+
+ def validate_form(trigger_node:, params:, submission_token_payload:)
+ fields =
+ Schemas::FormFields.with_keys(
+ CollectionParameters.rows(NodeData.parameters(trigger_node), "form_fields"),
+ )
+ Schemas::FormFields.validate_submission(
+ fields,
+ params.form_data,
+ query_parameters: submission_token_payload["form_query_parameters"],
+ )
+ end
+
+ def ensure_form_valid(form_validation:)
+ unless form_validation.valid?
+ fail!(I18n.t("discourse_workflows.errors.invalid_form_submission"))
+ end
+ end
+
+ def fetch_published_trigger(params:)
+ Form::Action::FindPublishedTrigger.call(uuid: params.uuid)
+ end
+
+ def fetch_workflow(published_trigger:)
+ published_trigger.workflow
+ end
+
+ def fetch_trigger_node(published_trigger:)
+ published_trigger.trigger_node
+ end
+
+ def valid_initial_submission_token(workflow:, trigger_node:, params:)
+ params.resume_token.present? &&
+ DiscourseWorkflows::FormTriggerToken.valid?(
+ params.resume_token,
+ workflow_id: workflow.id,
+ trigger_node_id: trigger_node["id"],
+ uuid: params.uuid,
+ )
+ end
+
+ def fetch_submission_token_payload(workflow:, trigger_node:, params:)
+ DiscourseWorkflows::FormTriggerToken.payload(
+ params.resume_token,
+ workflow_id: workflow.id,
+ trigger_node_id: trigger_node["id"],
+ uuid: params.uuid,
+ )
+ end
+
+ def run_workflow(published_trigger:, form_validation:, submission_token_payload:, guardian:)
+ trigger_data =
+ DiscourseWorkflows::Forms::Payload.build(
+ form_validation.data,
+ query_parameters: submission_token_payload["form_query_parameters"],
+ )
+
+ DiscourseWorkflows::TriggerDispatcher.execute(
+ published_trigger,
+ trigger_data: trigger_data,
+ user: guardian.user,
+ )
+ end
+
+ def build_response_metadata(workflow:, trigger_node:)
+ {
+ has_downstream_form:
+ workflow.node_has_reachable_downstream_of_type?(
+ trigger_node["id"],
+ "action:form",
+ published: true,
+ ),
+ response_mode: NodeData.parameters(trigger_node)["response_mode"] || "on_received",
+ }
+ end
+ end
+end
diff --git a/plugins/discourse-workflows/app/services/discourse_workflows/form_test_session/create.rb b/plugins/discourse-workflows/app/services/discourse_workflows/form_test_session/create.rb
new file mode 100644
index 00000000000..b06107b8e4c
--- /dev/null
+++ b/plugins/discourse-workflows/app/services/discourse_workflows/form_test_session/create.rb
@@ -0,0 +1,43 @@
+# frozen_string_literal: true
+
+module DiscourseWorkflows
+ class FormTestSession::Create
+ include Service::Base
+
+ params do
+ attribute :workflow_id, :integer
+ attribute :trigger_node_id, :string
+
+ validates :workflow_id, presence: true
+ validates :trigger_node_id, presence: true
+ end
+
+ policy :can_manage_workflows, class_name: Policy::CanManageWorkflows
+ model :workflow
+ model :trigger_node
+ policy :form_trigger_node
+ model :token, :create_form_test_session
+
+ private
+
+ def fetch_workflow(params:)
+ Workflow.find_by(id: params.workflow_id)
+ end
+
+ def fetch_trigger_node(workflow:, params:)
+ workflow.find_node(params.trigger_node_id)
+ end
+
+ def form_trigger_node(trigger_node:)
+ trigger_node["type"] == NodeDataShape::FORM_TRIGGER_TYPE
+ end
+
+ def create_form_test_session(workflow:, trigger_node:, guardian:)
+ FormTestSession.create!(
+ workflow: workflow,
+ user: guardian.user,
+ trigger_node_id: trigger_node["id"],
+ )
+ end
+ end
+end
diff --git a/plugins/discourse-workflows/app/services/discourse_workflows/form_test_session/show.rb b/plugins/discourse-workflows/app/services/discourse_workflows/form_test_session/show.rb
new file mode 100644
index 00000000000..2a768a16b83
--- /dev/null
+++ b/plugins/discourse-workflows/app/services/discourse_workflows/form_test_session/show.rb
@@ -0,0 +1,69 @@
+# frozen_string_literal: true
+
+module DiscourseWorkflows
+ class FormTestSession::Show
+ include Service::Base
+
+ params do
+ attribute :token, :string
+
+ validates :token, presence: true
+ end
+
+ model :form_test_session
+ model :workflow
+ policy :owns_form_test_session
+ model :form_node, :fetch_form_node_from_session
+ model :form_data, :build_form_data_from_config
+
+ private
+
+ def fetch_form_test_session(params:)
+ FormTestSession.find(params.token)
+ end
+
+ def fetch_workflow(form_test_session:)
+ Workflow.find_by(id: form_test_session.workflow_id)
+ end
+
+ def owns_form_test_session(form_test_session:, guardian:)
+ form_test_session.owned_by?(guardian.user)
+ end
+
+ def fetch_form_node_from_session(form_test_session:)
+ form_test_session.trigger_node
+ end
+
+ def build_form_data_from_config(form_test_session:, workflow:, form_node:, guardian:, params:)
+ config =
+ ExpressionResolver.resolve_hash(
+ NodeData.parameters(form_node).deep_stringify_keys,
+ context: {
+ "__execution" => {
+ "workflow_id" => workflow.id,
+ "workflow_name" => form_test_session.workflow_snapshot.workflow_name,
+ "resume_url" => "",
+ "resumeFormUrl" => "",
+ },
+ },
+ user: guardian.user,
+ )
+
+ fields = Schemas::FormFields.with_keys(CollectionParameters.rows(config, "form_fields"))
+
+ Forms::ViewModel.build(
+ fields: fields,
+ form_title: config["form_title"],
+ form_description: config["form_description"],
+ response_mode: config["response_mode"] || "on_received",
+ has_downstream_form:
+ form_test_session.workflow_snapshot.node_has_reachable_downstream_of_type?(
+ form_node.id,
+ "action:form",
+ ),
+ form_submit_url: "/workflows/form-test/#{params.token}.json",
+ form_mode: "test",
+ )
+ end
+ end
+end
diff --git a/plugins/discourse-workflows/app/services/discourse_workflows/form_test_session/submit.rb b/plugins/discourse-workflows/app/services/discourse_workflows/form_test_session/submit.rb
new file mode 100644
index 00000000000..dcc21583d67
--- /dev/null
+++ b/plugins/discourse-workflows/app/services/discourse_workflows/form_test_session/submit.rb
@@ -0,0 +1,85 @@
+# frozen_string_literal: true
+
+module DiscourseWorkflows
+ class FormTestSession::Submit
+ include Service::Base
+
+ params do
+ attribute :token, :string
+ attribute :form_data, default: -> { {} }
+
+ validates :token, presence: true
+ validate :form_data_must_be_hash
+
+ def form_data_must_be_hash
+ errors.add(:form_data, :invalid) unless form_data.is_a?(Hash)
+ end
+ end
+
+ model :form_test_session
+ model :workflow
+ policy :owns_form_test_session
+ model :form_node, :fetch_form_node_from_session
+ model :form_validation, :validate_form
+ step :ensure_form_valid
+ model :execution, :run_workflow
+ model :response_metadata, :build_response_metadata
+
+ private
+
+ def fetch_form_test_session(params:)
+ FormTestSession.find(params.token)
+ end
+
+ def fetch_workflow(form_test_session:)
+ Workflow.find_by(id: form_test_session.workflow_id)
+ end
+
+ def owns_form_test_session(form_test_session:, guardian:)
+ form_test_session.owned_by?(guardian.user)
+ end
+
+ def fetch_form_node_from_session(form_test_session:)
+ form_test_session.trigger_node
+ end
+
+ def validate_form(form_node:, params:)
+ fields =
+ Schemas::FormFields.with_keys(
+ CollectionParameters.rows(NodeData.parameters(form_node), "form_fields"),
+ )
+ Schemas::FormFields.validate_submission(fields, params.form_data)
+ end
+
+ def ensure_form_valid(form_validation:)
+ unless form_validation.valid?
+ fail!(I18n.t("discourse_workflows.errors.invalid_form_submission"))
+ end
+ end
+
+ def run_workflow(form_test_session:, workflow:, form_validation:, guardian:)
+ trigger_data =
+ Forms::Payload.build(form_validation.data, form_mode: "test", query_parameters: nil)
+ options =
+ Executor::ExecutionOptions.new(
+ user: guardian.user,
+ execution_mode: :manual,
+ draft_execution: true,
+ workflow_snapshot: form_test_session.workflow_snapshot,
+ )
+
+ Executor.new(workflow, form_test_session.trigger_node_id, trigger_data, options).run
+ end
+
+ def build_response_metadata(form_test_session:, form_node:)
+ {
+ has_downstream_form:
+ form_test_session.workflow_snapshot.node_has_reachable_downstream_of_type?(
+ form_node.id,
+ "action:form",
+ ),
+ response_mode: NodeData.parameters(form_node)["response_mode"] || "on_received",
+ }
+ end
+ end
+end
diff --git a/plugins/discourse-workflows/app/services/discourse_workflows/node_type/list.rb b/plugins/discourse-workflows/app/services/discourse_workflows/node_type/list.rb
new file mode 100644
index 00000000000..9aac35c41ac
--- /dev/null
+++ b/plugins/discourse-workflows/app/services/discourse_workflows/node_type/list.rb
@@ -0,0 +1,44 @@
+# frozen_string_literal: true
+
+module DiscourseWorkflows
+ class NodeType::List
+ include Service::Base
+
+ policy :can_manage_workflows, class_name: Policy::CanManageWorkflows
+
+ model :node_types
+ model :credential_types
+ model :expression_context
+
+ private
+
+ def fetch_node_types
+ DiscourseWorkflows::Registry
+ .nodes
+ .uniq(&:identifier)
+ .filter_map do |klass|
+ identifier = klass.identifier
+ next unless klass.palette_visible?
+
+ NodeTypeSerializer.new(
+ identifier: identifier,
+ available_versions: Registry.available_versions(identifier),
+ ).to_h
+ end
+ end
+
+ def fetch_credential_types
+ DiscourseWorkflows::Registry.credential_types.map do |klass|
+ {
+ identifier: klass.identifier,
+ display_name: klass.display_name,
+ property_schema: klass.property_schema,
+ }
+ end
+ end
+
+ def fetch_expression_context
+ DiscourseWorkflows::ExpressionContextSchema.to_hash
+ end
+ end
+end
diff --git a/plugins/discourse-workflows/app/services/discourse_workflows/policy/can_manage_workflows.rb b/plugins/discourse-workflows/app/services/discourse_workflows/policy/can_manage_workflows.rb
new file mode 100644
index 00000000000..3a0b32d2a92
--- /dev/null
+++ b/plugins/discourse-workflows/app/services/discourse_workflows/policy/can_manage_workflows.rb
@@ -0,0 +1,13 @@
+# frozen_string_literal: true
+
+module DiscourseWorkflows
+ class Policy::CanManageWorkflows < Service::PolicyBase
+ def call
+ guardian.can_manage_workflows?
+ end
+
+ def reason
+ I18n.t("discourse_workflows.errors.no_permission_to_manage")
+ end
+ end
+end
diff --git a/plugins/discourse-workflows/app/services/discourse_workflows/policy/workflows_enabled.rb b/plugins/discourse-workflows/app/services/discourse_workflows/policy/workflows_enabled.rb
new file mode 100644
index 00000000000..176cfb71c14
--- /dev/null
+++ b/plugins/discourse-workflows/app/services/discourse_workflows/policy/workflows_enabled.rb
@@ -0,0 +1,13 @@
+# frozen_string_literal: true
+
+module DiscourseWorkflows
+ class Policy::WorkflowsEnabled < Service::PolicyBase
+ def call
+ SiteSetting.discourse_workflows_enabled
+ end
+
+ def reason
+ I18n.t("discourse_workflows.errors.not_enabled")
+ end
+ end
+end
diff --git a/plugins/discourse-workflows/app/services/discourse_workflows/stats/summary.rb b/plugins/discourse-workflows/app/services/discourse_workflows/stats/summary.rb
new file mode 100644
index 00000000000..0fbe914fbd9
--- /dev/null
+++ b/plugins/discourse-workflows/app/services/discourse_workflows/stats/summary.rb
@@ -0,0 +1,42 @@
+# frozen_string_literal: true
+
+module DiscourseWorkflows
+ class Stats::Summary
+ include Service::Base
+
+ RECENT_PERIOD = 7.days
+
+ policy :can_manage_workflows, class_name: Policy::CanManageWorkflows
+
+ params { attribute :workflow_id, :integer }
+
+ model :recent_executions, optional: true
+ model :stats, :compute_stats
+
+ private
+
+ def fetch_recent_executions(params:)
+ Execution.recent(RECENT_PERIOD).for_workflow(params.workflow_id)
+ end
+
+ def compute_stats(recent_executions:)
+ total, failed, avg_seconds =
+ recent_executions.pick(
+ Arel.sql("COUNT(*)"),
+ Arel.sql("COUNT(*) FILTER (WHERE status = #{Execution.statuses["error"]})"),
+ Arel.sql(
+ "ROUND(AVG(EXTRACT(EPOCH FROM (finished_at - started_at))) FILTER (" \
+ "WHERE finished_at IS NOT NULL AND started_at IS NOT NULL " \
+ "AND status IN (#{[Execution.statuses["success"], Execution.statuses["error"]].join(", ")})" \
+ ")::numeric, 1)",
+ ),
+ )
+
+ avg_seconds = avg_seconds&.to_f || 0
+ failure_rate = total > 0 ? (failed.to_f / total * 100).round(1) : 0
+ avg_duration = avg_seconds < 1 ? "#{(avg_seconds * 1000).round}ms" : "#{avg_seconds}s"
+
+ { total: total, failed: failed, failure_rate: "#{failure_rate}%", avg_duration: avg_duration }
+ end
+ end
+end
diff --git a/plugins/discourse-workflows/app/services/discourse_workflows/template/list.rb b/plugins/discourse-workflows/app/services/discourse_workflows/template/list.rb
new file mode 100644
index 00000000000..35effebf6ec
--- /dev/null
+++ b/plugins/discourse-workflows/app/services/discourse_workflows/template/list.rb
@@ -0,0 +1,16 @@
+# frozen_string_literal: true
+
+module DiscourseWorkflows
+ class Template::List
+ include Service::Base
+
+ policy :can_manage_workflows, class_name: Policy::CanManageWorkflows
+ model :templates, optional: true
+
+ private
+
+ def fetch_templates
+ DiscourseWorkflows::TemplateStore.summaries
+ end
+ end
+end
diff --git a/plugins/discourse-workflows/app/services/discourse_workflows/template/show.rb b/plugins/discourse-workflows/app/services/discourse_workflows/template/show.rb
new file mode 100644
index 00000000000..6c459dc6028
--- /dev/null
+++ b/plugins/discourse-workflows/app/services/discourse_workflows/template/show.rb
@@ -0,0 +1,22 @@
+# frozen_string_literal: true
+
+module DiscourseWorkflows
+ class Template::Show
+ include Service::Base
+
+ params do
+ attribute :template_id, :string
+
+ validates :template_id, presence: true, format: { with: /\A[a-z0-9_-]+\z/ }
+ end
+
+ model :template
+ policy :can_manage_workflows, class_name: Policy::CanManageWorkflows
+
+ private
+
+ def fetch_template(params:)
+ DiscourseWorkflows::TemplateStore.find(params.template_id)
+ end
+ end
+end
diff --git a/plugins/discourse-workflows/app/services/discourse_workflows/variable/create.rb b/plugins/discourse-workflows/app/services/discourse_workflows/variable/create.rb
new file mode 100644
index 00000000000..0bf0210dad0
--- /dev/null
+++ b/plugins/discourse-workflows/app/services/discourse_workflows/variable/create.rb
@@ -0,0 +1,42 @@
+# frozen_string_literal: true
+
+module DiscourseWorkflows
+ class Variable::Create
+ include Service::Base
+
+ policy :can_manage_workflows, class_name: Policy::CanManageWorkflows
+
+ params do
+ attribute :key, :string
+ attribute :value, :string
+ attribute :description, :string
+
+ validates :key,
+ presence: true,
+ length: {
+ maximum: 100,
+ },
+ format: {
+ with: /\A[a-zA-Z_][a-zA-Z0-9_]*\z/,
+ }
+ validates :value, presence: true, length: { maximum: 1000 }
+ validates :description, length: { maximum: 500 }, allow_nil: true
+ end
+
+ model :variable, :create_variable
+ step :log_variable_creation
+
+ private
+
+ def create_variable(params:, guardian:)
+ DiscourseWorkflows::Variable.create(**params, created_by: guardian.user)
+ end
+
+ def log_variable_creation(variable:, guardian:)
+ StaffActionLogger.new(guardian.user).log_custom(
+ "discourse_workflows_variable_created",
+ subject: variable.key,
+ )
+ end
+ end
+end
diff --git a/plugins/discourse-workflows/app/services/discourse_workflows/variable/destroy.rb b/plugins/discourse-workflows/app/services/discourse_workflows/variable/destroy.rb
new file mode 100644
index 00000000000..1f6eb3fa0b9
--- /dev/null
+++ b/plugins/discourse-workflows/app/services/discourse_workflows/variable/destroy.rb
@@ -0,0 +1,36 @@
+# frozen_string_literal: true
+
+module DiscourseWorkflows
+ class Variable::Destroy
+ include Service::Base
+
+ params do
+ attribute :variable_id, :integer
+ validates :variable_id, presence: true
+ end
+
+ policy :can_manage_workflows, class_name: Policy::CanManageWorkflows
+ model :variable
+
+ transaction { step :destroy_variable }
+
+ step :log_variable_deletion
+
+ private
+
+ def fetch_variable(params:)
+ DiscourseWorkflows::Variable.find_by(id: params.variable_id)
+ end
+
+ def log_variable_deletion(variable:, guardian:)
+ StaffActionLogger.new(guardian.user).log_custom(
+ "discourse_workflows_variable_destroyed",
+ subject: variable.key,
+ )
+ end
+
+ def destroy_variable(variable:)
+ variable.destroy!
+ end
+ end
+end
diff --git a/plugins/discourse-workflows/app/services/discourse_workflows/variable/list.rb b/plugins/discourse-workflows/app/services/discourse_workflows/variable/list.rb
new file mode 100644
index 00000000000..255d9f829f3
--- /dev/null
+++ b/plugins/discourse-workflows/app/services/discourse_workflows/variable/list.rb
@@ -0,0 +1,41 @@
+# frozen_string_literal: true
+
+module DiscourseWorkflows
+ class Variable::List
+ include Service::Base
+
+ policy :can_manage_workflows, class_name: Policy::CanManageWorkflows
+
+ params do
+ attribute :cursor, :integer
+ attribute :limit, :integer
+
+ after_validation { self.limit = DiscourseWorkflows::Pagination.normalize_limit(limit) }
+ end
+
+ model :variables, optional: true
+ model :total_rows, :count_total_rows
+ model :load_more_url, :build_load_more_url, optional: true
+
+ private
+
+ def fetch_variables(params:)
+ scope = DiscourseWorkflows::Variable.includes(:created_by).order(id: :desc)
+ context[:page] = DiscourseWorkflows::Pagination.cursor_page(
+ scope: scope,
+ cursor: params.cursor,
+ limit: params.limit,
+ path: "/admin/plugins/discourse-workflows/variables.json",
+ )
+ context[:page].records
+ end
+
+ def count_total_rows
+ context[:page].total_rows
+ end
+
+ def build_load_more_url
+ context[:page].load_more_url
+ end
+ end
+end
diff --git a/plugins/discourse-workflows/app/services/discourse_workflows/variable/update.rb b/plugins/discourse-workflows/app/services/discourse_workflows/variable/update.rb
new file mode 100644
index 00000000000..d33f8a19531
--- /dev/null
+++ b/plugins/discourse-workflows/app/services/discourse_workflows/variable/update.rb
@@ -0,0 +1,49 @@
+# frozen_string_literal: true
+
+module DiscourseWorkflows
+ class Variable::Update
+ include Service::Base
+
+ params do
+ attribute :variable_id, :integer
+ attribute :key, :string
+ attribute :value, :string
+ attribute :description, :string
+
+ validates :variable_id, presence: true
+ validates :key,
+ presence: true,
+ length: {
+ maximum: 100,
+ },
+ format: {
+ with: /\A[a-zA-Z_][a-zA-Z0-9_]*\z/,
+ }
+ validates :value, presence: true, length: { maximum: 1000 }
+ validates :description, length: { maximum: 500 }, allow_nil: true
+ end
+
+ policy :can_manage_workflows, class_name: Policy::CanManageWorkflows
+ model :variable
+
+ model :variable, :save_variable
+ step :log_variable_update
+
+ private
+
+ def fetch_variable(params:)
+ DiscourseWorkflows::Variable.find_by(id: params.variable_id)
+ end
+
+ def save_variable(variable:, params:)
+ variable.tap { |v| v.update(**params.slice(:key, :value, :description)) }
+ end
+
+ def log_variable_update(variable:, guardian:)
+ StaffActionLogger.new(guardian.user).log_custom(
+ "discourse_workflows_variable_updated",
+ subject: variable.key,
+ )
+ end
+ end
+end
diff --git a/plugins/discourse-workflows/app/services/discourse_workflows/webhook/action/activate_webhooks.rb b/plugins/discourse-workflows/app/services/discourse_workflows/webhook/action/activate_webhooks.rb
new file mode 100644
index 00000000000..5b3cedb8059
--- /dev/null
+++ b/plugins/discourse-workflows/app/services/discourse_workflows/webhook/action/activate_webhooks.rb
@@ -0,0 +1,81 @@
+# frozen_string_literal: true
+
+module DiscourseWorkflows
+ class Webhook::Action::ActivateWebhooks < Service::ActionBase
+ class CollisionError < StandardError
+ attr_reader :method, :path
+
+ def initialize(method:, path:)
+ @method = method
+ @path = path
+ super("Webhook route already registered for #{method} #{path}")
+ end
+ end
+
+ option :workflow
+ option :workflow_version
+
+ def call
+ rows = build_rows
+ collision = detect_collision(rows)
+ raise collision if collision
+
+ begin
+ Webhook.transaction(requires_new: true) do
+ Webhook.production.where(workflow_id: workflow.id).delete_all
+ Webhook.insert_all!(rows) if rows.any?
+ end
+ rescue ActiveRecord::RecordNotUnique
+ raise(detect_collision(rows) || generic_collision(rows))
+ end
+
+ ActiveWebhooks.invalidate!
+ rows
+ end
+
+ private
+
+ def build_rows
+ workflow_version.nodes.filter_map do |node|
+ next unless node["type"] == "trigger:webhook"
+
+ parameters = NodeData.parameters(node)
+ path = parameters["path"].to_s
+ method = parameters["http_method"].to_s
+ next if path.blank? || method.blank?
+
+ dynamic = Webhook.dynamic_path?(path)
+ {
+ workflow_id: workflow.id,
+ workflow_version_id: workflow_version.version_id,
+ node_name: node["name"].to_s,
+ webhook_path: Webhook.normalize_path(path),
+ http_method: Webhook.normalize_method(method),
+ webhook_id: dynamic ? node["webhookId"] : nil,
+ path_length: dynamic ? Webhook.path_length_for(path) : nil,
+ test_webhook: false,
+ created_at: Time.current,
+ }
+ end
+ end
+
+ def detect_collision(rows)
+ rows.each do |row|
+ owner =
+ Webhook.production.find_by(
+ http_method: row[:http_method],
+ webhook_path: row[:webhook_path],
+ )
+ next if owner.nil? || owner.workflow_id == workflow.id
+
+ return CollisionError.new(method: row[:http_method], path: row[:webhook_path])
+ end
+ nil
+ end
+
+ def generic_collision(rows)
+ row = rows.first || { http_method: "", webhook_path: "" }
+ CollisionError.new(method: row[:http_method], path: row[:webhook_path])
+ end
+ end
+end
diff --git a/plugins/discourse-workflows/app/services/discourse_workflows/webhook/action/authenticate_node.rb b/plugins/discourse-workflows/app/services/discourse_workflows/webhook/action/authenticate_node.rb
new file mode 100644
index 00000000000..61900ab485c
--- /dev/null
+++ b/plugins/discourse-workflows/app/services/discourse_workflows/webhook/action/authenticate_node.rb
@@ -0,0 +1,111 @@
+# frozen_string_literal: true
+
+module DiscourseWorkflows
+ class Webhook::Action::AuthenticateNode < Service::ActionBase
+ AUTHENTICATED = :authenticated
+ CHALLENGE = :challenge
+ DENIED = :denied
+ MISCONFIGURED = :misconfigured
+
+ BASIC_AUTH = "basic_auth"
+ BEARER_AUTH = "bearer_auth"
+ HEADER_AUTH = "header_auth"
+ NO_AUTH = "none"
+
+ SUPPORTED_AUTH_MODES = [NO_AUTH, BASIC_AUTH, BEARER_AUTH, HEADER_AUTH].freeze
+
+ option :node
+ option :params
+ option :credentials, default: -> { {} }
+
+ def call
+ auth_mode = NodeData.resolved_parameters(node)["authentication"] || NO_AUTH
+ return AUTHENTICATED if auth_mode == NO_AUTH
+
+ if SUPPORTED_AUTH_MODES.exclude?(auth_mode)
+ Rails.logger.warn("Unsupported webhook auth mode '#{auth_mode}' for node #{node["id"]}")
+ return MISCONFIGURED
+ end
+
+ credential = lookup_credential
+ return MISCONFIGURED unless credential
+
+ case auth_mode
+ when BASIC_AUTH
+ authenticate_basic_auth(credential)
+ when BEARER_AUTH
+ authenticate_bearer_auth(credential)
+ when HEADER_AUTH
+ authenticate_header_auth(credential)
+ end
+ end
+
+ private
+
+ def lookup_credential
+ credential_ref = NodeData.credentials(node)["auth"]
+ unless credential_ref
+ Rails.logger.warn("Workflow credential not configured for node #{node["id"]}")
+ return nil
+ end
+
+ credential = credentials[credential_ref["id"].to_i]
+ unless credential
+ Rails.logger.warn("Workflow credential not found for node #{node["id"]}")
+ return nil
+ end
+
+ credential
+ end
+
+ def authenticate_basic_auth(credential)
+ cred_data = credential.data || {}
+ expected_user = ExpressionResolver.resolve(cred_data["user"])
+ expected_password = ExpressionResolver.resolve(cred_data["password"])
+
+ return MISCONFIGURED if expected_user.blank? || expected_password.blank?
+
+ auth_header = params.raw_authorization
+ return CHALLENGE if auth_header.blank? || !auth_header.start_with?("Basic ")
+
+ decoded = Base64.decode64(auth_header.split(" ", 2).last)
+ request_user, request_password = decoded.split(":", 2)
+
+ if secure_compare(request_user, expected_user) &&
+ secure_compare(request_password, expected_password)
+ AUTHENTICATED
+ else
+ DENIED
+ end
+ end
+
+ def authenticate_bearer_auth(credential)
+ cred_data = credential.data || {}
+ expected_token = ExpressionResolver.resolve(cred_data["token"])
+
+ return MISCONFIGURED if expected_token.blank?
+
+ auth_header = params.raw_authorization.to_s
+ return DENIED unless auth_header.start_with?("Bearer ")
+
+ provided_token = auth_header.split(" ", 2).last
+ secure_compare(provided_token, expected_token) ? AUTHENTICATED : DENIED
+ end
+
+ def authenticate_header_auth(credential)
+ cred_data = credential.data || {}
+ expected_name = ExpressionResolver.resolve(cred_data["name"])
+ expected_value = ExpressionResolver.resolve(cred_data["value"])
+
+ return MISCONFIGURED if expected_name.blank? || expected_value.blank?
+
+ header_key = expected_name.to_s.downcase
+ provided_value = (params.headers[header_key] || params.headers[header_key.to_sym]).to_s
+ secure_compare(provided_value, expected_value) ? AUTHENTICATED : DENIED
+ end
+
+ def secure_compare(a, b)
+ ActiveSupport::SecurityUtils.secure_compare(a.to_s, b.to_s)
+ end
+ end
+end
diff --git a/plugins/discourse-workflows/app/services/discourse_workflows/webhook/action/deactivate_webhooks.rb b/plugins/discourse-workflows/app/services/discourse_workflows/webhook/action/deactivate_webhooks.rb
new file mode 100644
index 00000000000..c063b9f6dc8
--- /dev/null
+++ b/plugins/discourse-workflows/app/services/discourse_workflows/webhook/action/deactivate_webhooks.rb
@@ -0,0 +1,13 @@
+# frozen_string_literal: true
+
+module DiscourseWorkflows
+ class Webhook::Action::DeactivateWebhooks < Service::ActionBase
+ option :workflow
+
+ def call
+ deleted = Webhook.production.where(workflow_id: workflow.id).delete_all
+ ActiveWebhooks.invalidate! if deleted.positive?
+ deleted
+ end
+ end
+end
diff --git a/plugins/discourse-workflows/app/services/discourse_workflows/webhook/action/find_webhook.rb b/plugins/discourse-workflows/app/services/discourse_workflows/webhook/action/find_webhook.rb
new file mode 100644
index 00000000000..c3bd87c35b6
--- /dev/null
+++ b/plugins/discourse-workflows/app/services/discourse_workflows/webhook/action/find_webhook.rb
@@ -0,0 +1,13 @@
+# frozen_string_literal: true
+
+module DiscourseWorkflows
+ class Webhook::Action::FindWebhook < Service::ActionBase
+ option :method
+ option :path
+ option :test_webhook, default: -> { false }
+
+ def call
+ ActiveWebhooks.find(method: method, path: path, test_webhook: test_webhook)
+ end
+ end
+end
diff --git a/plugins/discourse-workflows/app/services/discourse_workflows/webhook/receive.rb b/plugins/discourse-workflows/app/services/discourse_workflows/webhook/receive.rb
new file mode 100644
index 00000000000..9d1d8e65f6a
--- /dev/null
+++ b/plugins/discourse-workflows/app/services/discourse_workflows/webhook/receive.rb
@@ -0,0 +1,455 @@
+# frozen_string_literal: true
+
+require "ipaddr"
+
+module DiscourseWorkflows
+ class Webhook::Receive
+ include Service::Base
+
+ params do
+ attribute :execution_id, :integer
+ attribute :token, :string
+ attribute :webhook_suffix, :string
+ attribute :path, :string
+ attribute :test_listener_id, :string
+ attribute :http_method, :string
+ attribute :body, default: -> { {} }
+ attribute :headers, default: -> { {} }
+ attribute :path_params, default: -> { {} }
+ attribute :query_params, default: -> { {} }
+ attribute :raw_body, :string
+ attribute :remote_ip, :string
+ attribute :ips, default: -> { [] }
+ attribute :raw_authorization, :string
+ attribute :test_webhook, :boolean, default: false
+
+ validates :http_method, presence: true
+
+ def webhook_url
+ if execution_id.present?
+ DiscourseWorkflows::WaitingExecution.webhook_url_with_signature(
+ execution_id: execution_id,
+ signature: token,
+ suffix: webhook_suffix,
+ )
+ elsif test_webhook
+ test_path = test_listener_id.present? ? "#{test_listener_id}/#{path}" : path
+ "#{Discourse.base_url}/workflows/webhook-test/#{test_path}"
+ else
+ "#{Discourse.base_url}/workflows/webhooks/#{path}"
+ end
+ end
+
+ def webhook_request
+ DiscourseWorkflows::WebhookRequest.new(
+ method: http_method,
+ path: path,
+ headers: headers,
+ params: path_params,
+ query: query_params,
+ body: body,
+ raw_body: raw_body,
+ ip: remote_ip,
+ ips: ips,
+ webhook_url: webhook_url,
+ )
+ end
+ end
+
+ model :waiting_execution, optional: true
+ model :webhook_context, :build_webhook_context
+ policy :valid_resume_request
+
+ only_if(:test_webhook_request) do
+ model :webhook_test_listener, :find_webhook_test_listener
+ model :webhook_nodes, :test_webhook_nodes
+ model :authenticated_nodes, :filter_authenticated_nodes
+ model :request_allowed_nodes, :filter_request_allowed_nodes
+ model :claimed_webhook_test_listener, :claim_webhook_test_listener
+ model :sync_result, :execute_test_workflow
+ model :webhook_response, :trigger_response
+ end
+
+ only_if(:resuming_execution) do
+ model :waiting_node
+ policy :valid_http_method
+
+ only_if(:async_resume?) do
+ step :enqueue_async_resume
+ model :webhook_response, :immediate_resume_response
+ end
+
+ only_if(:sync_resume?) do
+ model :claimed_execution
+ model :sync_result, :resume_execution_synchronously
+ model :webhook_response, :sync_response
+ end
+ end
+
+ only_if(:triggering_new_workflow) do
+ model :webhook_nodes, :find_webhook_nodes
+ model :authenticated_nodes, :filter_authenticated_nodes
+ model :request_allowed_nodes, :filter_request_allowed_nodes
+ step :enqueue_async_workflows
+ model :sync_result, :execute_sync_workflows, optional: true
+ model :webhook_response, :trigger_response
+ end
+
+ private
+
+ def build_webhook_context(params:)
+ DiscourseWorkflows::WebhookContext.new(request: params.webhook_request)
+ end
+
+ def valid_resume_request(waiting_execution:, params:)
+ params.execution_id.blank? || waiting_execution.present?
+ end
+
+ def test_webhook_request(params:)
+ params.test_webhook
+ end
+
+ def fetch_waiting_execution(params:)
+ return nil if params.execution_id.blank? || params.token.blank?
+
+ execution =
+ DiscourseWorkflows::WaitingExecution.find(
+ execution_id: params.execution_id,
+ signature: params.token,
+ expected_node_type: "flow:wait",
+ )
+ return nil unless execution
+
+ waiting_node = execution.find_waiting_node
+ return nil unless waiting_node
+
+ suffix = params.webhook_suffix.to_s
+ stored_suffix = NodeData.parameters(waiting_node)["webhook_suffix"].to_s
+ return nil unless suffix == stored_suffix
+
+ execution
+ end
+
+ def fetch_claimed_execution(waiting_execution:, params:)
+ DiscourseWorkflows::WaitingExecution.claim(waiting_execution, signature: params.token)
+ end
+
+ def resuming_execution(waiting_execution:)
+ waiting_execution.present?
+ end
+
+ def triggering_new_workflow(waiting_execution:, params:)
+ waiting_execution.nil? && params.execution_id.blank? && !params.test_webhook
+ end
+
+ def find_webhook_test_listener(params:)
+ WebhookTestListener.find_for_request(
+ listener_id: params.test_listener_id,
+ method: params.http_method,
+ path: params.path,
+ )
+ end
+
+ def claim_webhook_test_listener(webhook_test_listener:)
+ WebhookTestListener.claim(webhook_test_listener)
+ end
+
+ def test_webhook_nodes(webhook_test_listener:)
+ workflow = Workflow.find_by(id: webhook_test_listener.workflow_id)
+ trigger_node = webhook_test_listener.trigger_node
+ return [] unless workflow
+ return [] unless trigger_node
+
+ [PublishedTrigger.new(workflow: workflow, workflow_version: nil, trigger_node: trigger_node)]
+ end
+
+ def fetch_waiting_node(waiting_execution:)
+ waiting_execution.find_waiting_node
+ end
+
+ def valid_http_method(waiting_node:, params:)
+ NodeData.parameters(waiting_node)["http_method"] == params.http_method
+ end
+
+ def async_resume?(waiting_node:)
+ wait_node_response_mode(waiting_node) == Schemas::Webhook::RESPONSE_MODE_ON_RECEIVED
+ end
+
+ def sync_resume?(waiting_node:)
+ !async_resume?(waiting_node:)
+ end
+
+ def enqueue_async_resume(waiting_execution:, webhook_context:)
+ webhook_context.resume([{ "json" => webhook_context.request.item_json }])
+
+ Jobs.enqueue(
+ Jobs::DiscourseWorkflows::ResumeWebhookWaiting,
+ execution_id: waiting_execution.id,
+ response_items: webhook_context.resume_items,
+ )
+ end
+
+ def immediate_resume_response(waiting_node:)
+ WebhookResponseBuilder.immediate(NodeData.parameters(waiting_node))
+ end
+
+ def resume_execution_synchronously(claimed_execution:, waiting_node:, webhook_context:)
+ parameters = NodeData.parameters(waiting_node)
+ webhook_context.resume([{ "json" => webhook_context.request.item_json }])
+ execution =
+ DiscourseWorkflows::WaitingExecution.resume_claimed(
+ claimed_execution,
+ webhook_context.resume_items,
+ webhook_context: webhook_context,
+ )
+ {
+ execution: execution,
+ response_mode: parameters["response_mode"],
+ response_code: parameters["response_code"],
+ response_data: parameters["response_data"],
+ response_parameters: parameters,
+ webhook_context: webhook_context,
+ }
+ end
+
+ def find_webhook_nodes(params:, webhook_context:)
+ match =
+ Webhook::Action::FindWebhook.call(
+ method: params.http_method,
+ path: params.path,
+ test_webhook: false,
+ )
+ return [] unless match
+
+ webhook_context.apply_path_params(match[:path_params])
+ published_trigger = build_published_trigger(match[:webhook])
+ published_trigger ? [published_trigger] : []
+ end
+
+ def build_published_trigger(webhook)
+ workflow = Workflow.find_by(id: webhook.workflow_id)
+ return nil unless workflow
+
+ workflow_version =
+ WorkflowVersion.find_by(
+ version_id: webhook.workflow_version_id,
+ ) if webhook.workflow_version_id.present?
+ return nil unless workflow_version
+
+ node = workflow_version.nodes.find { |candidate| candidate["name"] == webhook.node_name }
+ return nil unless node
+
+ PublishedTrigger.new(
+ workflow: workflow,
+ workflow_version: workflow_version,
+ trigger_node: node,
+ )
+ end
+
+ def filter_authenticated_nodes(webhook_nodes:, params:)
+ credentials = preload_auth_credentials(webhook_nodes)
+ authenticated = []
+ failure_reasons = []
+
+ webhook_nodes.each do |published_trigger|
+ result =
+ Webhook::Action::AuthenticateNode.call(
+ node: published_trigger.trigger_node,
+ params: params,
+ credentials: credentials,
+ )
+
+ if result == Webhook::Action::AuthenticateNode::AUTHENTICATED
+ authenticated << published_trigger
+ else
+ failure_reasons << result
+ end
+ end
+
+ if authenticated.empty? && failure_reasons.any?
+ context[:auth_failure_reason] = primary_auth_failure_reason(failure_reasons)
+ context[:auth_failure_mode] = primary_auth_mode(webhook_nodes)
+ end
+
+ authenticated
+ end
+
+ def preload_auth_credentials(webhook_nodes)
+ credential_ids =
+ webhook_nodes.filter_map do |published_trigger|
+ NodeData.credentials(published_trigger.trigger_node).dig("auth", "id")&.to_i
+ end
+ DiscourseWorkflows::Credential.where(id: credential_ids).index_by(&:id)
+ end
+
+ def primary_auth_failure_reason(reasons)
+ if reasons.include?(Webhook::Action::AuthenticateNode::CHALLENGE)
+ return Webhook::Action::AuthenticateNode::CHALLENGE
+ end
+ if reasons.include?(Webhook::Action::AuthenticateNode::DENIED)
+ return Webhook::Action::AuthenticateNode::DENIED
+ end
+ Webhook::Action::AuthenticateNode::MISCONFIGURED
+ end
+
+ def primary_auth_mode(webhook_nodes)
+ webhook_nodes.each do |published_trigger|
+ mode = NodeData.parameters(published_trigger.trigger_node)["authentication"]
+ return mode if mode.present? && mode != Webhook::Action::AuthenticateNode::NO_AUTH
+ end
+ nil
+ end
+
+ def filter_request_allowed_nodes(authenticated_nodes:, params:)
+ authenticated_nodes.select do |published_trigger|
+ request_allowed?(published_trigger.trigger_node, params)
+ end
+ end
+
+ def enqueue_async_workflows(request_allowed_nodes:, webhook_context:)
+ request_allowed_nodes.each do |published_trigger|
+ node = published_trigger.trigger_node
+ response_mode = trigger_node_response_mode(node)
+ next unless response_mode == Schemas::Webhook::RESPONSE_MODE_ON_RECEIVED
+
+ DiscourseWorkflows::TriggerDispatcher.enqueue(
+ published_trigger,
+ trigger_data: webhook_context.request.item_json,
+ )
+ end
+ end
+
+ def execute_sync_workflows(request_allowed_nodes:, webhook_context:)
+ first = nil
+ request_allowed_nodes.each do |published_trigger|
+ node = published_trigger.trigger_node
+ parameters = NodeData.parameters(node)
+ response_mode = trigger_node_response_mode(node)
+ next if response_mode == Schemas::Webhook::RESPONSE_MODE_ON_RECEIVED
+
+ execution =
+ DiscourseWorkflows::TriggerDispatcher.execute(
+ published_trigger,
+ trigger_data: webhook_context.request.item_json,
+ webhook_context: webhook_context,
+ )
+ first ||= {
+ execution: execution,
+ response_mode: response_mode,
+ response_code: parameters["response_code"],
+ response_data: parameters["response_data"],
+ response_parameters: parameters,
+ webhook_context: webhook_context,
+ }
+ end
+ first
+ end
+
+ def execute_test_workflow(
+ claimed_webhook_test_listener:,
+ request_allowed_nodes:,
+ webhook_context:
+ )
+ published_trigger = request_allowed_nodes.first
+ node = published_trigger.trigger_node
+ parameters = NodeData.parameters(node)
+ execution_options =
+ Executor::ExecutionOptions.new(
+ user: User.find_by(id: claimed_webhook_test_listener.user_id),
+ execution_mode: :manual,
+ draft_execution: true,
+ workflow_snapshot: claimed_webhook_test_listener.workflow_snapshot,
+ webhook_context: webhook_context,
+ )
+ execution =
+ Executor.new(
+ published_trigger.workflow,
+ claimed_webhook_test_listener.trigger_node_id,
+ webhook_context.request.item_json,
+ execution_options,
+ ).run
+
+ {
+ execution: execution,
+ response_mode: trigger_node_response_mode(node),
+ response_code: parameters["response_code"],
+ response_data: parameters["response_data"],
+ response_parameters: parameters,
+ webhook_context: webhook_context,
+ }
+ end
+
+ def trigger_response(request_allowed_nodes:)
+ sync_result = context[:sync_result]
+
+ if sync_result
+ sync_response(sync_result:)
+ else
+ WebhookResponseBuilder.immediate(
+ NodeData.parameters(request_allowed_nodes.first.trigger_node),
+ )
+ end
+ end
+
+ def sync_response(sync_result:)
+ case sync_result[:response_mode]
+ when Schemas::Webhook::RESPONSE_MODE_RESPONSE_NODE
+ sync_result[:webhook_context].response || WebhookResponse.success
+ when Schemas::Webhook::RESPONSE_MODE_LAST_NODE
+ WebhookResponseBuilder.last_node(
+ sync_result[:execution],
+ sync_result[:response_parameters] || {},
+ )
+ when Schemas::Webhook::RESPONSE_MODE_ON_RECEIVED
+ WebhookResponseBuilder.immediate(sync_result[:response_parameters] || {})
+ else
+ WebhookResponse.success
+ end
+ end
+
+ def wait_node_response_mode(waiting_node)
+ NodeData.parameters(waiting_node)["response_mode"] ||
+ Schemas::Webhook::RESPONSE_MODE_ON_RECEIVED
+ end
+
+ def trigger_node_response_mode(node)
+ NodeData.parameters(node)["response_mode"] || Schemas::Webhook::RESPONSE_MODE_ON_RECEIVED
+ end
+
+ def request_allowed?(node, params)
+ parameters = NodeData.parameters(node)
+ if parameters["ignore_bots"] == true && bot_user_agent?(params.headers["user-agent"])
+ return false
+ end
+
+ ip_allowlist = parameters["ip_allowlist"].to_s
+ return true if ip_allowlist.blank?
+
+ request_ips = ([params.remote_ip] + Array.wrap(params.ips)).compact.map(&:to_s)
+ request_ips.any? { |ip| ip_allowed?(ip, ip_allowlist) }
+ end
+
+ def bot_user_agent?(user_agent)
+ user_agent.to_s.match?(/bot|crawler|spider|preview|slurp|facebookexternalhit|whatsapp/i)
+ end
+
+ def ip_allowed?(ip, allowlist)
+ return false if ip.blank?
+
+ request_ip = IPAddr.new(ip)
+ allowlist
+ .split(",")
+ .map(&:strip)
+ .reject(&:blank?)
+ .any? { |entry| ip_entry_allowed?(request_ip, entry) }
+ rescue IPAddr::InvalidAddressError
+ false
+ end
+
+ def ip_entry_allowed?(request_ip, entry)
+ IPAddr.new(entry).include?(request_ip)
+ rescue IPAddr::InvalidAddressError
+ false
+ end
+ end
+end
diff --git a/plugins/discourse-workflows/app/services/discourse_workflows/webhook_test_listener/cancel.rb b/plugins/discourse-workflows/app/services/discourse_workflows/webhook_test_listener/cancel.rb
new file mode 100644
index 00000000000..1fb62adb31f
--- /dev/null
+++ b/plugins/discourse-workflows/app/services/discourse_workflows/webhook_test_listener/cancel.rb
@@ -0,0 +1,44 @@
+# frozen_string_literal: true
+
+module DiscourseWorkflows
+ class WebhookTestListener::Cancel
+ include Service::Base
+
+ params do
+ attribute :workflow_id, :integer
+ attribute :listener_id, :string
+
+ validates :workflow_id, presence: true
+ validates :listener_id, presence: true
+ end
+
+ policy :can_manage_workflows, class_name: Policy::CanManageWorkflows
+ model :workflow
+ model :listener, :find_webhook_test_listener
+ policy :listener_belongs_to_workflow
+ policy :owns_webhook_test_listener
+ step :cancel_webhook_test_listener
+
+ private
+
+ def fetch_workflow(params:)
+ Workflow.find_by(id: params.workflow_id)
+ end
+
+ def find_webhook_test_listener(params:)
+ WebhookTestListener.find(params.listener_id)
+ end
+
+ def listener_belongs_to_workflow(workflow:, listener:)
+ listener.workflow_id == workflow.id
+ end
+
+ def owns_webhook_test_listener(listener:, guardian:)
+ listener.owned_by?(guardian.user)
+ end
+
+ def cancel_webhook_test_listener(listener:)
+ WebhookTestListener.cancel!(listener)
+ end
+ end
+end
diff --git a/plugins/discourse-workflows/app/services/discourse_workflows/webhook_test_listener/start.rb b/plugins/discourse-workflows/app/services/discourse_workflows/webhook_test_listener/start.rb
new file mode 100644
index 00000000000..2e7da0649cd
--- /dev/null
+++ b/plugins/discourse-workflows/app/services/discourse_workflows/webhook_test_listener/start.rb
@@ -0,0 +1,45 @@
+# frozen_string_literal: true
+
+module DiscourseWorkflows
+ class WebhookTestListener::Start
+ include Service::Base
+
+ params do
+ attribute :workflow_id, :integer
+ attribute :trigger_node_id, :string
+
+ validates :workflow_id, presence: true
+ validates :trigger_node_id, presence: true
+ end
+
+ policy :can_manage_workflows, class_name: Policy::CanManageWorkflows
+ model :workflow
+ model :trigger_node
+ policy :webhook_trigger_node
+ model :listener, :start_webhook_test_listener
+
+ private
+
+ def fetch_workflow(params:)
+ Workflow.find_by(id: params.workflow_id)
+ end
+
+ def fetch_trigger_node(workflow:, params:)
+ workflow.find_node(params.trigger_node_id)
+ end
+
+ def webhook_trigger_node(trigger_node:)
+ trigger_node["type"] == "trigger:webhook"
+ end
+
+ def start_webhook_test_listener(workflow:, trigger_node:, guardian:)
+ WebhookTestListener.create!(
+ workflow: workflow,
+ user: guardian.user,
+ trigger_node: trigger_node,
+ )
+ rescue WebhookTestListener::ActiveRouteExists
+ fail!(I18n.t("discourse_workflows.errors.webhook_test_listener_active"))
+ end
+ end
+end
diff --git a/plugins/discourse-workflows/app/services/discourse_workflows/workflow/action/build_expression_preview_context.rb b/plugins/discourse-workflows/app/services/discourse_workflows/workflow/action/build_expression_preview_context.rb
new file mode 100644
index 00000000000..f86133ac140
--- /dev/null
+++ b/plugins/discourse-workflows/app/services/discourse_workflows/workflow/action/build_expression_preview_context.rb
@@ -0,0 +1,170 @@
+# frozen_string_literal: true
+
+module DiscourseWorkflows
+ class Workflow::Action::BuildExpressionPreviewContext < Service::ActionBase
+ option :workflow, optional: true
+ option :node_id, optional: true
+
+ def call
+ return default_context unless workflow
+ context = default_context
+ context["__execution"] = initial_execution_metadata
+ context["__current_node_id"] = node_id.to_s if node_id.present?
+ context["__node_parameters_by_name"] = node_parameters_by_name
+ overlay_last_execution(context)
+ context
+ end
+
+ private
+
+ def default_context
+ { "$json" => {}, "$trigger" => {} }
+ end
+
+ def initial_execution_metadata
+ { "id" => 0, "workflow_id" => workflow.id, "workflow_name" => workflow.name }
+ end
+
+ def overlay_last_execution(context)
+ execution = workflow.last_successful_execution
+ return unless execution
+ context["__execution"]["id"] = execution.id
+ return unless execution.execution_data
+
+ node_runs = node_runs_for_expression(execution.execution_data.run_data)
+ context["__node_runs"] = node_runs
+ overlay_execution_run_data(context, node_runs)
+ end
+
+ def overlay_execution_run_data(context, node_runs)
+ upstream_connections = upstream_connections_for(node_id)
+ primary_upstream_connection = upstream_connections.first
+ current_input = current_node_input(node_runs, primary_upstream_connection)
+ if upstream_connections.present?
+ context["__input_sources"] = input_sources_for_connections(upstream_connections)
+ end
+
+ workflow.nodes.each do |node|
+ next if node["name"].blank?
+ runs = Array(node_runs[node["name"]])
+ run = runs.last
+ next unless run
+
+ output_index = primary_output_index_for(node, primary_upstream_connection)
+ items = Array(run.dig("outputs", output_index))
+ first_json = items.dig(0, "json") || {}
+
+ if node["type"]&.start_with?("trigger:")
+ context["$trigger"] = first_json
+ context["$json"] = first_json unless node_id
+ end
+
+ context[node["name"]] = items
+
+ if current_input.blank? &&
+ primary_upstream_connection&.source_node_id.to_s == node["id"].to_s
+ context["$json"] = first_json
+ context["__input_item"] = items.first || { "json" => {} }
+ context["__input_items"] = items
+ end
+ end
+
+ overlay_current_input(context, current_input) if current_input
+ end
+
+ def primary_output_index_for(node, primary_upstream_connection)
+ if primary_upstream_connection&.source_node_id.to_s == node["id"].to_s
+ return primary_upstream_connection.source_output_index.to_i
+ end
+
+ 0
+ end
+
+ def current_node_input(node_runs, primary_upstream_connection)
+ return if node_id.blank?
+
+ current_node = workflow.find_node(node_id)
+ return if current_node.nil? || current_node["name"].blank?
+
+ run = Array(node_runs[current_node["name"]]).last
+ return unless run
+
+ input_index = (primary_upstream_connection&.target_input_index || 0).to_i
+ items = run.dig("inputs", input_index)
+ return unless items
+
+ { "items" => Array(items), "input_sources" => Array(run["input_sources"]) }
+ end
+
+ def overlay_current_input(context, current_input)
+ items = current_input["items"]
+ context["$json"] = items.dig(0, "json") || {}
+ context["__input_item"] = items.first || { "json" => {} }
+ context["__input_items"] = items
+ if current_input["input_sources"].present?
+ context["__input_sources"] = current_input["input_sources"]
+ end
+ end
+
+ def upstream_connections_for(target_node_id)
+ return [] if target_node_id.blank?
+
+ target_node = workflow_snapshot.find_node(target_node_id)
+ return [] unless target_node
+
+ workflow_snapshot.connections_to(target_node)
+ end
+
+ def input_sources_for_connections(connections)
+ connections.map do |connection|
+ {
+ "node_name" => workflow_snapshot.source_node(connection)&.name,
+ "output_index" => connection.source_output_index.to_i,
+ }
+ end
+ end
+
+ def workflow_snapshot
+ @workflow_snapshot ||=
+ DiscourseWorkflows::WorkflowSnapshot.new(
+ "name" => workflow.name,
+ "nodes" => workflow.nodes,
+ "connections" => workflow.connections,
+ )
+ end
+
+ def node_runs_for_expression(run_data)
+ run_data.each_with_object({}) do |(node_name, runs), result|
+ result[node_name] = Array(runs).filter_map do |run|
+ next unless run["status"] == "success"
+
+ {
+ "inputs" => ports_to_item_groups(run["inputs"]),
+ "outputs" => ports_to_item_groups(run["outputs"]),
+ "input_sources" => input_sources(run["inputs"]),
+ }
+ end
+ end
+ end
+
+ def ports_to_item_groups(ports)
+ Array(ports).map { |port| Array(port["items"]) }
+ end
+
+ def input_sources(input_ports)
+ Array(input_ports).map { |port| port["source"] || {} }
+ end
+
+ def node_parameters_by_name
+ workflow
+ .nodes
+ .each_with_object({}) do |node, by_name|
+ name = node["name"].to_s
+ next if name.blank?
+
+ by_name[name] = by_name.key?(name) ? nil : node["parameters"] || {}
+ end
+ .compact
+ end
+ end
+end
diff --git a/plugins/discourse-workflows/app/services/discourse_workflows/workflow/action/expire_caches.rb b/plugins/discourse-workflows/app/services/discourse_workflows/workflow/action/expire_caches.rb
new file mode 100644
index 00000000000..924ffdbf69a
--- /dev/null
+++ b/plugins/discourse-workflows/app/services/discourse_workflows/workflow/action/expire_caches.rb
@@ -0,0 +1,10 @@
+# frozen_string_literal: true
+
+module DiscourseWorkflows
+ class Workflow::Action::ExpireCaches < Service::ActionBase
+ def call
+ WorkflowDependency.clear_cache!
+ ActiveWebhooks.invalidate!
+ end
+ end
+end
diff --git a/plugins/discourse-workflows/app/services/discourse_workflows/workflow/action/find_published_triggers.rb b/plugins/discourse-workflows/app/services/discourse_workflows/workflow/action/find_published_triggers.rb
new file mode 100644
index 00000000000..be2e9b45844
--- /dev/null
+++ b/plugins/discourse-workflows/app/services/discourse_workflows/workflow/action/find_published_triggers.rb
@@ -0,0 +1,58 @@
+# frozen_string_literal: true
+
+module DiscourseWorkflows
+ class Workflow::Action::FindPublishedTriggers < Service::ActionBase
+ option :trigger_type
+ option :dependency_type, default: -> { "node_type" }
+ option :dependency_key, default: -> { trigger_type }
+ option :filter, optional: true
+
+ def call
+ workflow_node_pairs.filter_map do |workflow_id, workflow_version_id, node_id|
+ workflow = workflows_by_id[workflow_id]
+ version = versions_by_id[workflow_version_id]
+ node = version&.nodes&.find { |candidate| candidate["id"] == node_id.to_s }
+ next unless node&.dig("type") == trigger_type
+
+ published_trigger =
+ DiscourseWorkflows::PublishedTrigger.new(
+ workflow: workflow,
+ workflow_version: version,
+ trigger_node: node,
+ )
+ next if filter && !filter.call(published_trigger)
+
+ published_trigger
+ end
+ end
+
+ private
+
+ def workflow_node_pairs
+ @workflow_node_pairs ||=
+ WorkflowDependency
+ .joins(:workflow)
+ .where(dependency_type: dependency_type, dependency_key: dependency_key.to_s)
+ .where(
+ "discourse_workflows_workflows.active_version_id = " \
+ "discourse_workflows_workflow_dependencies.workflow_version_id",
+ )
+ .pluck(:workflow_id, :workflow_version_id, :node_id)
+ end
+
+ def workflows_by_id
+ @workflows_by_id ||=
+ Workflow
+ .includes(:active_version)
+ .where(id: workflow_node_pairs.map(&:first).uniq)
+ .index_by(&:id)
+ end
+
+ def versions_by_id
+ @versions_by_id ||=
+ WorkflowVersion.where(version_id: workflow_node_pairs.map(&:second).uniq).index_by(
+ &:version_id
+ )
+ end
+ end
+end
diff --git a/plugins/discourse-workflows/app/services/discourse_workflows/workflow/action/populate_graph.rb b/plugins/discourse-workflows/app/services/discourse_workflows/workflow/action/populate_graph.rb
new file mode 100644
index 00000000000..f452f9fd238
--- /dev/null
+++ b/plugins/discourse-workflows/app/services/discourse_workflows/workflow/action/populate_graph.rb
@@ -0,0 +1,24 @@
+# frozen_string_literal: true
+
+module DiscourseWorkflows
+ class Workflow::Action::PopulateGraph < Service::ActionBase
+ MAX_NODES = WorkflowGraphValidator::MAX_NODES
+
+ option :workflow
+ option :nodes_data
+ option :connections_data
+
+ def call
+ validator = WorkflowGraphValidator.new(workflow:, nodes_data:, connections_data:)
+ return false unless validator.valid?
+
+ persist_graph(validator)
+ end
+
+ private
+
+ def persist_graph(validator)
+ workflow.update(nodes: validator.nodes, connections: validator.connections)
+ end
+ end
+end
diff --git a/plugins/discourse-workflows/app/services/discourse_workflows/workflow/create.rb b/plugins/discourse-workflows/app/services/discourse_workflows/workflow/create.rb
new file mode 100644
index 00000000000..9d03f70037b
--- /dev/null
+++ b/plugins/discourse-workflows/app/services/discourse_workflows/workflow/create.rb
@@ -0,0 +1,76 @@
+# frozen_string_literal: true
+
+module DiscourseWorkflows
+ class Workflow::Create
+ include Service::Base
+
+ params do
+ attribute :name, :string
+ attribute :nodes, default: -> { [] }
+ attribute :connections, default: -> { {} }
+ attribute :static_data, default: -> { {} }
+
+ validates :name, presence: true, length: { maximum: 100 }
+ validate :static_data_is_valid_map
+
+ def static_data_is_valid_map
+ return if DiscourseWorkflows::Workflow.valid_static_data_map?(static_data)
+
+ errors.add(:static_data, :invalid)
+ end
+ end
+
+ policy :can_manage_workflows, class_name: Policy::CanManageWorkflows
+
+ transaction do
+ model :workflow, :create_workflow
+ step :populate_graph
+ model :workflow_version, :create_initial_snapshot
+ step :index_dependencies
+ end
+
+ step :log
+ step :expire_workflow_caches
+
+ private
+
+ def create_workflow(params:, guardian:)
+ DiscourseWorkflows::Workflow.create(
+ name: params.name,
+ static_data: params.static_data,
+ created_by: guardian.user,
+ updated_by: guardian.user,
+ )
+ end
+
+ def populate_graph(workflow:, params:)
+ result =
+ Workflow::Action::PopulateGraph.call(
+ workflow:,
+ nodes_data: params.nodes,
+ connections_data: params.connections,
+ )
+ fail!(workflow.errors.full_messages) if result == false
+ end
+
+ def create_initial_snapshot(workflow:, guardian:)
+ workflow.initial_snapshot!(user: guardian.user)
+ end
+
+ def index_dependencies(workflow:, workflow_version:)
+ DiscourseWorkflows::WorkflowDependencyIndexer.call(workflow, version: workflow_version)
+ end
+
+ def log(workflow:, guardian:)
+ StaffActionLogger.new(guardian.user).log_custom(
+ "discourse_workflows_workflow_created",
+ subject: workflow.name,
+ workflow_id: workflow.id,
+ )
+ end
+
+ def expire_workflow_caches
+ Workflow::Action::ExpireCaches.call
+ end
+ end
+end
diff --git a/plugins/discourse-workflows/app/services/discourse_workflows/workflow/destroy.rb b/plugins/discourse-workflows/app/services/discourse_workflows/workflow/destroy.rb
new file mode 100644
index 00000000000..c9ec6d2768b
--- /dev/null
+++ b/plugins/discourse-workflows/app/services/discourse_workflows/workflow/destroy.rb
@@ -0,0 +1,42 @@
+# frozen_string_literal: true
+
+module DiscourseWorkflows
+ class Workflow::Destroy
+ include Service::Base
+
+ params do
+ attribute :workflow_id, :integer
+ validates :workflow_id, presence: true
+ end
+
+ policy :can_manage_workflows, class_name: Policy::CanManageWorkflows
+ model :workflow
+
+ transaction { step :delete_workflow }
+
+ step :log
+ step :expire_workflow_caches
+
+ private
+
+ def fetch_workflow(params:)
+ DiscourseWorkflows::Workflow.find_by(id: params.workflow_id)
+ end
+
+ def delete_workflow(workflow:)
+ workflow.destroy!
+ end
+
+ def log(workflow:, guardian:)
+ StaffActionLogger.new(guardian.user).log_custom(
+ "discourse_workflows_workflow_destroyed",
+ subject: workflow.name,
+ workflow_id: workflow.id,
+ )
+ end
+
+ def expire_workflow_caches
+ Workflow::Action::ExpireCaches.call
+ end
+ end
+end
diff --git a/plugins/discourse-workflows/app/services/discourse_workflows/workflow/discard_draft.rb b/plugins/discourse-workflows/app/services/discourse_workflows/workflow/discard_draft.rb
new file mode 100644
index 00000000000..e3eb264a714
--- /dev/null
+++ b/plugins/discourse-workflows/app/services/discourse_workflows/workflow/discard_draft.rb
@@ -0,0 +1,41 @@
+# frozen_string_literal: true
+
+module DiscourseWorkflows
+ class Workflow::DiscardDraft
+ include Service::Base
+
+ params do
+ attribute :workflow_id, :integer
+
+ validates :workflow_id, presence: true
+ end
+
+ policy :can_manage_workflows, class_name: Policy::CanManageWorkflows
+
+ lock(:workflow_id) do
+ model :workflow
+ model :active_version
+ step :restore_published_version
+ end
+
+ step :expire_workflow_caches
+
+ private
+
+ def fetch_workflow(params:)
+ DiscourseWorkflows::Workflow.find_by(id: params.workflow_id)
+ end
+
+ def fetch_active_version(workflow:)
+ workflow.active_version
+ end
+
+ def restore_published_version(workflow:, active_version:, guardian:)
+ workflow.restore_from_version!(active_version, user: guardian.user)
+ end
+
+ def expire_workflow_caches
+ Workflow::Action::ExpireCaches.call
+ end
+ end
+end
diff --git a/plugins/discourse-workflows/app/services/discourse_workflows/workflow/execute.rb b/plugins/discourse-workflows/app/services/discourse_workflows/workflow/execute.rb
new file mode 100644
index 00000000000..f27207ded08
--- /dev/null
+++ b/plugins/discourse-workflows/app/services/discourse_workflows/workflow/execute.rb
@@ -0,0 +1,73 @@
+# frozen_string_literal: true
+
+module DiscourseWorkflows
+ class Workflow::Execute
+ include Service::Base
+
+ params do
+ attribute :workflow_id, :integer
+ attribute :workflow_version_id, :string
+ attribute :trigger_node_id, :string
+ attribute :trigger_data, default: -> { {} }
+ attribute :execution_mode, :string, default: "normal"
+ attribute :user_id, :integer
+
+ validates :trigger_node_id, presence: true
+ end
+
+ policy :can_execute, class_name: DiscourseWorkflows::Policy::WorkflowsEnabled
+ model :workflow
+ model :workflow_version
+ model :trigger_node
+ model :user, optional: true
+ model :execution, :run_workflow
+
+ private
+
+ def fetch_workflow(params:)
+ if params.workflow_id.present?
+ return(
+ DiscourseWorkflows::Workflow.includes(:active_version).find_by(id: params.workflow_id)
+ )
+ end
+
+ DiscourseWorkflows::Workflow
+ .published
+ .includes(:active_version)
+ .joins(:workflow_dependencies)
+ .where(discourse_workflows_workflow_dependencies: { node_id: params.trigger_node_id })
+ .where(
+ "discourse_workflows_workflows.active_version_id = " \
+ "discourse_workflows_workflow_dependencies.workflow_version_id",
+ )
+ .first
+ end
+
+ def fetch_workflow_version(workflow:, params:)
+ return workflow.active_version if params.workflow_version_id.blank?
+
+ workflow.workflow_versions.find_by(version_id: params.workflow_version_id)
+ end
+
+ def fetch_trigger_node(workflow:, workflow_version:, params:)
+ workflow.find_node_in(workflow_version.nodes, params.trigger_node_id)
+ end
+
+ def fetch_user(params:)
+ User.find_by(id: params.user_id) if params.user_id.present?
+ end
+
+ def run_workflow(trigger_node:, workflow:, workflow_version:, params:, user:)
+ options =
+ DiscourseWorkflows::Executor::ExecutionOptions.new(
+ user: user,
+ execution_mode: params.execution_mode.to_sym,
+ workflow_version: workflow_version,
+ )
+ executor =
+ DiscourseWorkflows::Executor.new(workflow, trigger_node["id"], params.trigger_data, options)
+ executor.run
+ executor.execution
+ end
+ end
+end
diff --git a/plugins/discourse-workflows/app/services/discourse_workflows/workflow/list.rb b/plugins/discourse-workflows/app/services/discourse_workflows/workflow/list.rb
new file mode 100644
index 00000000000..7d40e11d0f4
--- /dev/null
+++ b/plugins/discourse-workflows/app/services/discourse_workflows/workflow/list.rb
@@ -0,0 +1,97 @@
+# frozen_string_literal: true
+
+module DiscourseWorkflows
+ class Workflow::List
+ include Service::Base
+
+ LATEST_EXECUTION_JOIN = <<~SQL
+ LEFT JOIN LATERAL (
+ SELECT status, discourse_workflows_executions.created_at AS executed_at
+ FROM discourse_workflows_executions
+ WHERE discourse_workflows_executions.workflow_id = discourse_workflows_workflows.id
+ ORDER BY discourse_workflows_executions.created_at DESC, discourse_workflows_executions.id DESC
+ LIMIT 1
+ ) latest_execution ON TRUE
+ SQL
+
+ policy :can_manage_workflows, class_name: Policy::CanManageWorkflows
+
+ params do
+ attribute :cursor, :integer
+ attribute :limit, :integer
+ attribute :filter, :string
+ attribute :trigger_type, :string
+ attribute :exclude_id, :integer
+
+ after_validation do
+ self.limit =
+ (limit || DiscourseWorkflows::Pagination::DEFAULT_LIMIT).clamp(
+ 1,
+ DiscourseWorkflows::Pagination::MAX_LIMIT,
+ )
+ end
+ end
+
+ model :workflows, optional: true
+ model :has_more, :compute_has_more, optional: true
+ model :total_rows, optional: true
+ model :load_more_url, :build_load_more_url, optional: true
+
+ private
+
+ def fetch_workflows(params:)
+ scope =
+ DiscourseWorkflows::Workflow
+ .filtered(
+ name: params.filter,
+ trigger_type: params.trigger_type,
+ exclude_id: params.exclude_id,
+ )
+ .includes(:created_by, :updated_by, :error_workflow)
+ .joins(LATEST_EXECUTION_JOIN)
+ .select(
+ "discourse_workflows_workflows.*",
+ "latest_execution.status AS last_execution_status_value",
+ "latest_execution.executed_at AS last_execution_at",
+ )
+ .order(id: :desc)
+
+ scope = scope.where("discourse_workflows_workflows.id < ?", params.cursor) if params.cursor
+
+ scope.limit(params.limit + 1).to_a
+ end
+
+ def compute_has_more(workflows:, params:)
+ has_more = workflows.size > params.limit
+ workflows.pop if has_more
+ context[:has_more] = has_more
+ has_more
+ end
+
+ def has_more
+ context[:has_more]
+ end
+
+ def fetch_total_rows(params:)
+ DiscourseWorkflows::Workflow.filtered(
+ name: params.filter,
+ trigger_type: params.trigger_type,
+ exclude_id: params.exclude_id,
+ ).count
+ end
+
+ def build_load_more_url(params:, workflows:)
+ return if !has_more || workflows.blank?
+
+ query = {
+ cursor: workflows.last.id,
+ limit: params.limit,
+ filter: params.filter.presence,
+ trigger_type: params.trigger_type.presence,
+ exclude_id: params.exclude_id,
+ }.compact
+
+ "/admin/plugins/discourse-workflows/workflows.json?#{query.to_query}"
+ end
+ end
+end
diff --git a/plugins/discourse-workflows/app/services/discourse_workflows/workflow/manual_execute.rb b/plugins/discourse-workflows/app/services/discourse_workflows/workflow/manual_execute.rb
new file mode 100644
index 00000000000..721daf6783e
--- /dev/null
+++ b/plugins/discourse-workflows/app/services/discourse_workflows/workflow/manual_execute.rb
@@ -0,0 +1,74 @@
+# frozen_string_literal: true
+
+module DiscourseWorkflows
+ class Workflow::ManualExecute
+ include Service::Base
+
+ params do
+ attribute :workflow_id, :integer
+ attribute :trigger_node_id, :string
+ attribute :trigger_data, default: -> { {} }
+ attribute :user_id, :integer
+
+ validates :trigger_node_id, presence: true
+ end
+
+ policy :can_manage_workflows, class_name: Policy::CanManageWorkflows
+ model :workflow
+ model :trigger_node
+ model :execution, :run_workflow
+
+ private
+
+ def fetch_workflow(params:)
+ DiscourseWorkflows::Workflow.find_by(id: params.workflow_id)
+ end
+
+ def fetch_trigger_node(workflow:, params:)
+ workflow.find_node(params.trigger_node_id)
+ end
+
+ def run_workflow(workflow:, trigger_node:, params:, guardian:)
+ options =
+ DiscourseWorkflows::Executor::ExecutionOptions.new(
+ user: guardian.user,
+ execution_mode: :manual,
+ draft_execution: true,
+ )
+
+ DiscourseWorkflows::Executor.new(
+ workflow,
+ params.trigger_node_id,
+ trigger_data(workflow:, trigger_node:, params:, user: guardian.user),
+ options,
+ ).run
+ end
+
+ def trigger_data(workflow:, trigger_node:, params:, user:)
+ return params.trigger_data if params.trigger_data.present?
+ return {} if workflow.node_pinned?(trigger_node["name"])
+ return {} if trigger_node["type"] == "trigger:manual"
+
+ node_type_class = node_type_for(trigger_node)
+
+ if node_type_class.respond_to?(:trigger_data_for)
+ return(
+ node_type_class.trigger_data_for(DiscourseWorkflows::TriggerNodeContext.new(trigger_node))
+ )
+ end
+
+ if node_type_class&.capability_enabled?(:synthesizes_manual_data)
+ return TriggerRuntime.manual_trigger_data(workflow:, trigger_node:, user:)
+ end
+
+ {}
+ end
+
+ def node_type_for(trigger_node)
+ DiscourseWorkflows::Registry.find_node_type(
+ trigger_node["type"],
+ version: trigger_node["typeVersion"],
+ )
+ end
+ end
+end
diff --git a/plugins/discourse-workflows/app/services/discourse_workflows/workflow/publish.rb b/plugins/discourse-workflows/app/services/discourse_workflows/workflow/publish.rb
new file mode 100644
index 00000000000..89a6de9c229
--- /dev/null
+++ b/plugins/discourse-workflows/app/services/discourse_workflows/workflow/publish.rb
@@ -0,0 +1,57 @@
+# frozen_string_literal: true
+
+module DiscourseWorkflows
+ class Workflow::Publish
+ include Service::Base
+
+ params do
+ attribute :workflow_id, :integer
+
+ validates :workflow_id, presence: true
+ end
+
+ policy :can_manage_workflows, class_name: Policy::CanManageWorkflows
+
+ lock(:workflow_id) do
+ model :workflow
+
+ transaction do
+ model :workflow_version
+ step :publish_workflow
+ step :activate_triggers
+ end
+ end
+
+ step :expire_workflow_caches
+
+ private
+
+ def fetch_workflow(params:)
+ DiscourseWorkflows::Workflow.find_by(id: params.workflow_id)
+ end
+
+ def fetch_workflow_version(workflow:)
+ workflow.workflow_versions.find_by(version_id: workflow.version_id)
+ end
+
+ def publish_workflow(workflow:, guardian:)
+ workflow.publish!(user: guardian.user)
+ end
+
+ def expire_workflow_caches
+ Workflow::Action::ExpireCaches.call
+ end
+
+ def activate_triggers(workflow:, workflow_version:)
+ TriggerRuntime.activate_workflow!(workflow, workflow_version: workflow_version)
+ rescue Webhook::Action::ActivateWebhooks::CollisionError => e
+ fail!(
+ I18n.t(
+ "discourse_workflows.errors.webhook_route_collision",
+ method: e.method,
+ path: "/#{e.path}",
+ ),
+ )
+ end
+ end
+end
diff --git a/plugins/discourse-workflows/app/services/discourse_workflows/workflow/show.rb b/plugins/discourse-workflows/app/services/discourse_workflows/workflow/show.rb
new file mode 100644
index 00000000000..1b289a4f85f
--- /dev/null
+++ b/plugins/discourse-workflows/app/services/discourse_workflows/workflow/show.rb
@@ -0,0 +1,23 @@
+# frozen_string_literal: true
+
+module DiscourseWorkflows
+ class Workflow::Show
+ include Service::Base
+
+ params do
+ attribute :workflow_id, :integer
+ validates :workflow_id, presence: true
+ end
+
+ policy :can_manage_workflows, class_name: Policy::CanManageWorkflows
+ model :workflow
+
+ private
+
+ def fetch_workflow(params:)
+ DiscourseWorkflows::Workflow.includes(:created_by, :updated_by, :error_workflow).find_by(
+ id: params.workflow_id,
+ )
+ end
+ end
+end
diff --git a/plugins/discourse-workflows/app/services/discourse_workflows/workflow/trigger_topic_admin_button.rb b/plugins/discourse-workflows/app/services/discourse_workflows/workflow/trigger_topic_admin_button.rb
new file mode 100644
index 00000000000..a26f0f962bb
--- /dev/null
+++ b/plugins/discourse-workflows/app/services/discourse_workflows/workflow/trigger_topic_admin_button.rb
@@ -0,0 +1,44 @@
+# frozen_string_literal: true
+
+module DiscourseWorkflows
+ class Workflow::TriggerTopicAdminButton
+ include Service::Base
+
+ params do
+ attribute :trigger_node_id, :string
+ attribute :topic_id, :integer
+
+ validates :trigger_node_id, presence: true
+ validates :topic_id, presence: true
+ end
+
+ policy :can_manage_workflows, class_name: Policy::CanManageWorkflows
+ model :published_trigger
+ model :topic
+ step :enqueue_workflow
+
+ private
+
+ def fetch_published_trigger(params:)
+ DiscourseWorkflows::Workflow::Action::FindPublishedTriggers.call(
+ trigger_type: "trigger:topic_admin_button",
+ filter: ->(published_trigger) do
+ published_trigger.trigger_node_id == params.trigger_node_id
+ end,
+ ).first
+ end
+
+ def fetch_topic(params:)
+ Topic.find_by(id: params.topic_id)
+ end
+
+ def enqueue_workflow(published_trigger:, topic:, guardian:)
+ trigger = DiscourseWorkflows::Nodes::TopicAdminButton::V1.new(topic)
+ DiscourseWorkflows::TriggerDispatcher.enqueue(
+ published_trigger,
+ trigger_data: trigger.output,
+ user_id: guardian.user.id,
+ )
+ end
+ end
+end
diff --git a/plugins/discourse-workflows/app/services/discourse_workflows/workflow/unpublish.rb b/plugins/discourse-workflows/app/services/discourse_workflows/workflow/unpublish.rb
new file mode 100644
index 00000000000..181b2bd4e23
--- /dev/null
+++ b/plugins/discourse-workflows/app/services/discourse_workflows/workflow/unpublish.rb
@@ -0,0 +1,41 @@
+# frozen_string_literal: true
+
+module DiscourseWorkflows
+ class Workflow::Unpublish
+ include Service::Base
+
+ params do
+ attribute :workflow_id, :integer
+
+ validates :workflow_id, presence: true
+ end
+
+ policy :can_manage_workflows, class_name: Policy::CanManageWorkflows
+
+ lock(:workflow_id) do
+ model :workflow
+ step :deactivate_triggers
+ step :unpublish_workflow
+ end
+
+ step :expire_workflow_caches
+
+ private
+
+ def fetch_workflow(params:)
+ DiscourseWorkflows::Workflow.find_by(id: params.workflow_id)
+ end
+
+ def unpublish_workflow(workflow:, guardian:)
+ workflow.unpublish!(user: guardian.user)
+ end
+
+ def deactivate_triggers(workflow:)
+ TriggerRuntime.deactivate_workflow!(workflow)
+ end
+
+ def expire_workflow_caches
+ Workflow::Action::ExpireCaches.call
+ end
+ end
+end
diff --git a/plugins/discourse-workflows/app/services/discourse_workflows/workflow/update.rb b/plugins/discourse-workflows/app/services/discourse_workflows/workflow/update.rb
new file mode 100644
index 00000000000..c7d03f695e8
--- /dev/null
+++ b/plugins/discourse-workflows/app/services/discourse_workflows/workflow/update.rb
@@ -0,0 +1,147 @@
+# frozen_string_literal: true
+
+module DiscourseWorkflows
+ class Workflow::Update
+ include Service::Base
+
+ TIMEZONE_NOT_PROVIDED = Object.new.freeze
+ STATIC_DATA_NOT_PROVIDED = Object.new.freeze
+ ERROR_WORKFLOW_ID_NOT_PROVIDED = Object.new.freeze
+
+ params do
+ attribute :workflow_id, :integer
+ attribute :name, :string
+ attribute :error_workflow_id, default: -> { ERROR_WORKFLOW_ID_NOT_PROVIDED }
+ attribute :timezone, default: -> { TIMEZONE_NOT_PROVIDED }
+ attribute :static_data, default: -> { STATIC_DATA_NOT_PROVIDED }
+ attribute :nodes
+ attribute :connections
+ attribute :autosaved, :boolean, default: false
+
+ validates :workflow_id, presence: true
+ validates :name, presence: true, length: { maximum: 100 }
+ validate :timezone_is_valid
+ validate :static_data_is_valid_map
+
+ def updatable_attributes
+ attrs = { name: }
+ attrs[:error_workflow_id] = error_workflow_id if error_workflow_id_provided?
+ attrs[:static_data] = static_data if static_data_provided?
+ attrs
+ end
+
+ def error_workflow_id_provided?
+ error_workflow_id != ERROR_WORKFLOW_ID_NOT_PROVIDED
+ end
+
+ def timezone_provided?
+ timezone != TIMEZONE_NOT_PROVIDED
+ end
+
+ def static_data_provided?
+ static_data != STATIC_DATA_NOT_PROVIDED
+ end
+
+ def graph_data_provided?
+ !nodes.nil? || !connections.nil?
+ end
+
+ def timezone_is_valid
+ return if !timezone_provided? || timezone.blank?
+ return if WorkflowTimezone.valid?(timezone)
+
+ errors.add(:timezone, :invalid)
+ end
+
+ def static_data_is_valid_map
+ return unless static_data_provided?
+ return if DiscourseWorkflows::Workflow.valid_static_data_map?(static_data)
+
+ errors.add(:static_data, :invalid)
+ end
+ end
+
+ policy :can_manage_workflows, class_name: Policy::CanManageWorkflows
+
+ lock(:workflow_id) do
+ model :workflow
+ model :previous_versioned_payload, :capture_versioned_payload
+
+ transaction do
+ model :workflow, :update_workflow
+ model :workflow, :save_workflow
+ only_if(:graph_data_provided) do
+ step :populate_graph
+ only_if(:versioned_payload_changed) do
+ model :workflow_version, :snapshot_workflow
+ step :index_dependencies
+ end
+ end
+ end
+ end
+
+ step :expire_workflow_caches
+
+ private
+
+ def fetch_workflow(params:)
+ DiscourseWorkflows::Workflow.find_by(id: params.workflow_id)
+ end
+
+ def capture_versioned_payload(workflow:)
+ workflow.versioned_payload
+ end
+
+ def graph_data_provided(params:)
+ params.graph_data_provided?
+ end
+
+ def versioned_payload_changed(workflow:, previous_versioned_payload:)
+ workflow.versioned_payload != previous_versioned_payload
+ end
+
+ def update_workflow(workflow:, params:, guardian:)
+ attrs = params.updatable_attributes
+ attrs[:settings] = settings_with_timezone(workflow, params) if params.timezone_provided?
+ workflow.assign_attributes(**attrs, updated_by: guardian.user)
+ workflow
+ end
+
+ def save_workflow(workflow:)
+ workflow.save
+ workflow
+ end
+
+ def populate_graph(workflow:, params:)
+ result =
+ Workflow::Action::PopulateGraph.call(
+ workflow:,
+ nodes_data: params.nodes || [],
+ connections_data: params.connections || {},
+ )
+ fail!(workflow.errors.full_messages) if result == false
+ end
+
+ def snapshot_workflow(workflow:, params:, guardian:)
+ workflow.snapshot!(user: guardian.user, autosaved: params.autosaved)
+ end
+
+ def index_dependencies(workflow:, workflow_version:)
+ DiscourseWorkflows::WorkflowDependencyIndexer.call(workflow, version: workflow_version)
+ end
+
+ def settings_with_timezone(workflow, params)
+ settings = (workflow.settings || {}).dup
+ if params.timezone.present?
+ settings["timezone"] = params.timezone
+ else
+ settings.delete("timezone")
+ end
+ settings
+ end
+
+ def expire_workflow_caches
+ Workflow::Action::ExpireCaches.call
+ end
+ end
+end
diff --git a/plugins/discourse-workflows/app/services/discourse_workflows/workflow/update_pin_data.rb b/plugins/discourse-workflows/app/services/discourse_workflows/workflow/update_pin_data.rb
new file mode 100644
index 00000000000..3b759ee2c25
--- /dev/null
+++ b/plugins/discourse-workflows/app/services/discourse_workflows/workflow/update_pin_data.rb
@@ -0,0 +1,105 @@
+# frozen_string_literal: true
+
+module DiscourseWorkflows
+ class Workflow::UpdatePinData
+ include Service::Base
+
+ UNPIN = Object.new.freeze
+
+ params do
+ attribute :workflow_id, :integer
+ attribute :node_name, :string
+ attribute :items, default: -> { UNPIN }
+
+ validates :workflow_id, presence: true
+ validates :node_name, presence: true
+
+ def unpin?
+ items == UNPIN
+ end
+
+ def normalized_items
+ return nil if unpin?
+
+ normalized =
+ DiscourseWorkflows::Item
+ .normalize_items(Array.wrap(items))
+ .map { |item| item.slice("json", DiscourseWorkflows::Item::PAIRED_ITEM_KEY) }
+ DiscourseWorkflows::ItemContract.validate_items!(normalized, source: "pin_data")
+ normalized
+ end
+ end
+
+ policy :can_manage_workflows, class_name: Policy::CanManageWorkflows
+ model :workflow
+ model :node
+ policy :items_are_valid
+ policy :node_supports_pinning
+ policy :within_size_cap
+
+ transaction { model :workflow, :persist_pin_data }
+
+ step :publish_pin_data_update
+
+ private
+
+ def fetch_workflow(params:)
+ DiscourseWorkflows::Workflow.find_by(id: params.workflow_id)
+ end
+
+ def fetch_node(workflow:, params:)
+ workflow.nodes.find { |n| n["name"] == params.node_name }
+ end
+
+ def items_are_valid(params:)
+ return true if params.unpin?
+
+ params.normalized_items
+ true
+ rescue DiscourseWorkflows::Item::InconsistentItemFormatError,
+ DiscourseWorkflows::ItemContract::Error
+ false
+ end
+
+ def node_supports_pinning(node:, params:)
+ return true if params.unpin?
+
+ node_type_class = registered_node_type_for(node)
+ return false if node_type_class.nil?
+
+ Array(node_type_class.outputs).length <= 1
+ end
+
+ def within_size_cap(workflow:, params:)
+ candidate = (workflow.pin_data || {}).dup
+ if params.unpin?
+ candidate.delete(params.node_name)
+ else
+ candidate[params.node_name] = params.normalized_items
+ end
+
+ candidate.to_json.bytesize <= SiteSetting.discourse_workflows_max_pin_data_bytes
+ end
+
+ def persist_pin_data(workflow:, params:)
+ items = params.unpin? ? nil : params.normalized_items
+ workflow.update_node_pin_data!(params.node_name, items)
+ workflow
+ end
+
+ def publish_pin_data_update(workflow:, params:)
+ MessageBus.publish(
+ "/discourse-workflows/workflows/#{workflow.id}/pin_data",
+ {
+ node_name: params.node_name,
+ pinned: !params.unpin?,
+ pinned_node_names: workflow.pinned_node_names,
+ },
+ )
+ end
+
+ def registered_node_type_for(node)
+ DiscourseWorkflows::Registry.find_node_type(node["type"], version: node["typeVersion"])
+ end
+ end
+end
diff --git a/plugins/discourse-workflows/assets/javascripts/discourse/components/workflows-form.gjs b/plugins/discourse-workflows/assets/javascripts/discourse/components/workflows-form.gjs
new file mode 100644
index 00000000000..ec01918e735
--- /dev/null
+++ b/plugins/discourse-workflows/assets/javascripts/discourse/components/workflows-form.gjs
@@ -0,0 +1,399 @@
+import Component from "@glimmer/component";
+import { cached, tracked } from "@glimmer/tracking";
+import { action } from "@ember/object";
+import { service } from "@ember/service";
+import { trustHTML } from "@ember/template";
+import Form from "discourse/components/form";
+import { ajax } from "discourse/lib/ajax";
+import { eq } from "discourse/truth-helpers";
+import DConditionalLoadingSpinner from "discourse/ui-kit/d-conditional-loading-spinner";
+import DDecoratedHtml from "discourse/ui-kit/d-decorated-html";
+import dAutoFocus from "discourse/ui-kit/modifiers/d-auto-focus";
+import { i18n } from "discourse-i18n";
+
+function isFormKitType(field, type) {
+ return field.type === type;
+}
+
+function fieldOptions(field) {
+ return field.options || [];
+}
+
+const STRUCTURED_ERROR_TRANSLATIONS = {
+ invalid: "discourse_workflows.form.errors.invalid",
+ invalid_value: "discourse_workflows.form.errors.invalid",
+ missing: "discourse_workflows.form.errors.missing",
+};
+
+function responseErrorMessage(responseJSON) {
+ const errors = responseJSON?.errors;
+
+ if (errors?.length) {
+ return errors.map(formatResponseError).join(", ");
+ }
+
+ return i18n("discourse_workflows.form.error_message");
+}
+
+function formatResponseError(error) {
+ if (typeof error === "string") {
+ return error;
+ }
+
+ if (error?.message) {
+ return error.message;
+ }
+
+ const translationKey = STRUCTURED_ERROR_TRANSLATIONS[error?.code];
+ if (translationKey && error?.field_label) {
+ return i18n(translationKey, { field: error.field_label });
+ }
+
+ return i18n("discourse_workflows.form.error_message");
+}
+
+export default class WorkflowsForm extends Component {
+ @service messageBus;
+
+ @tracked state = "form";
+ @tracked errorMessage = null;
+ @tracked completionData = null;
+ @tracked formSchemaOverride = null;
+ channel = null;
+ pendingFormWaitingUrl = null;
+
+ willDestroy() {
+ super.willDestroy(...arguments);
+ this.#unsubscribe();
+ }
+
+ get formSchema() {
+ return this.formSchemaOverride ?? this.args.model;
+ }
+
+ set formSchema(value) {
+ this.formSchemaOverride = value;
+ }
+
+ @cached
+ get formData() {
+ return this.formSchema.data || {};
+ }
+
+ @cached
+ get fields() {
+ return (this.formSchema.fields || []).map((field, index) => {
+ if (field.type === "html") {
+ return {
+ ...field,
+ html: trustHTML(field.html || ""),
+ autofocus: index === 0,
+ };
+ }
+
+ return {
+ ...field,
+ autofocus: index === 0,
+ };
+ });
+ }
+
+ @cached
+ get completionHtml() {
+ const completion = this.completionData || {};
+
+ return {
+ completion_title: trustHTML(completion.completion_title || ""),
+ completion_message: trustHTML(completion.completion_message || ""),
+ completion_text: trustHTML(completion.completion_text || ""),
+ };
+ }
+
+ get isTestMode() {
+ return this.formSchema.form_mode === "test";
+ }
+
+ @action
+ async handleSubmit(formData) {
+ this.state = "submitting";
+
+ try {
+ const payload = { form_data: formData };
+ const submitUrl = this.formSchema.form_submit_url;
+
+ if (this.formSchema.resume_token) {
+ payload.resume_token = this.formSchema.resume_token;
+ }
+
+ const result = await ajax(submitUrl, {
+ type: "POST",
+ data: payload,
+ });
+
+ this.#handleSubmissionResult(result);
+ } catch (e) {
+ this.state = "error";
+ this.errorMessage = responseErrorMessage(e?.jqXHR?.responseJSON);
+ }
+ }
+
+ #handleSubmissionResult(result) {
+ if (!result) {
+ this.#complete();
+ return;
+ }
+
+ if (result.status === "error") {
+ this.state = "error";
+ this.errorMessage = responseErrorMessage(result);
+ return;
+ }
+
+ if (result.form_channel && result.form_waiting_url) {
+ this.state = "waiting";
+ this.pendingFormWaitingUrl = result.form_waiting_url;
+ this.#subscribe(result.form_channel);
+ return;
+ }
+
+ if (result.form_waiting_url) {
+ this.#loadWaitingForm(result.form_waiting_url);
+ return;
+ }
+
+ this.#complete(result.form_completion);
+ }
+
+ #subscribe(channel) {
+ this.#unsubscribe();
+ this.channel = channel;
+ this.messageBus.subscribe(
+ this.channel,
+ (message) => {
+ this.#handleMessage(message);
+ },
+ 0
+ );
+ }
+
+ #unsubscribe() {
+ if (this.channel) {
+ this.messageBus.unsubscribe(this.channel);
+ this.channel = null;
+ }
+ }
+
+ async #handleMessage(message) {
+ if (message.status === "waiting_for_form") {
+ await this.#loadWaitingForm(
+ message.form_waiting_url || this.pendingFormWaitingUrl
+ );
+ } else if (message.status === "error") {
+ this.#unsubscribe();
+ this.state = "error";
+ this.errorMessage = responseErrorMessage(message);
+ }
+ }
+
+ async #loadWaitingForm(url) {
+ if (!url) {
+ this.state = "error";
+ this.errorMessage = i18n("discourse_workflows.form.error_message");
+ return;
+ }
+
+ try {
+ const schema = await ajax(url);
+ this.formSchema = schema;
+ this.state = "form";
+ this.pendingFormWaitingUrl = null;
+ this.#unsubscribe();
+ } catch (e) {
+ this.state = "error";
+ this.errorMessage = responseErrorMessage(e?.jqXHR?.responseJSON);
+ }
+ }
+
+ #complete(completion) {
+ this.#unsubscribe();
+
+ if (completion?.on_submission === "redirect" && completion.redirect_url) {
+ const url = completion.redirect_url;
+ try {
+ if (url.startsWith("/") && !url.startsWith("//")) {
+ window.location.href = url;
+ } else {
+ const parsed = new URL(url);
+ if (parsed.origin === window.location.origin) {
+ window.location.href = url;
+ }
+ }
+ } catch {
+ // invalid URL, don't redirect
+ }
+ return;
+ }
+
+ this.completionData = completion || null;
+ this.state = "complete";
+ }
+
+ <template>
+ <div class="workflows-form">
+ {{#if (eq this.state "form")}}
+ {{#if this.isTestMode}}
+ <div class="workflows-form__test-banner">
+ {{i18n "discourse_workflows.form.test_mode_banner"}}
+ </div>
+ {{/if}}
+
+ <div class="workflows-form__header">
+ {{#if this.formSchema.form_title}}
+ <h1
+ class="workflows-form__title"
+ >{{this.formSchema.form_title}}</h1>
+ {{/if}}
+ {{#if this.formSchema.form_description}}
+ <p
+ class="workflows-form__description"
+ >{{this.formSchema.form_description}}</p>
+ {{/if}}
+ </div>
+
+ <Form @data={{this.formData}} @onSubmit={{this.handleSubmit}} as |form|>
+ {{#each this.fields as |field|}}
+ {{#if (isFormKitType field "html")}}
+ <DDecoratedHtml
+ @html={{field.html}}
+ @className="workflows-form__html"
+ />
+ {{else if (isFormKitType field "checkbox")}}
+ <form.Field
+ @type="checkbox"
+ @name={{field.name}}
+ @title={{field.title}}
+ @description={{field.description}}
+ @format="full"
+ as |f|
+ >
+ <f.Control {{(if field.autofocus (modifier dAutoFocus))}} />
+ </form.Field>
+ {{else if (isFormKitType field "textarea")}}
+ <form.Field
+ @type="textarea"
+ @name={{field.name}}
+ @title={{field.title}}
+ @description={{field.description}}
+ @format="full"
+ @validation={{field.validation}}
+ @placeholder={{field.placeholder}}
+ as |f|
+ >
+ <f.Control
+ placeholder={{field.placeholder}}
+ {{(if field.autofocus (modifier dAutoFocus))}}
+ />
+ </form.Field>
+ {{else if (isFormKitType field "select")}}
+ <form.Field
+ @type="select"
+ @name={{field.name}}
+ @title={{field.title}}
+ @description={{field.description}}
+ @format="full"
+ @validation={{field.validation}}
+ as |f|
+ >
+ <f.Control
+ {{(if field.autofocus (modifier dAutoFocus))}}
+ as |c|
+ >
+ {{#each (fieldOptions field) as |opt|}}
+ <c.Option @value={{opt.value}}>{{opt.label}}</c.Option>
+ {{/each}}
+ </f.Control>
+ </form.Field>
+ {{else if (isFormKitType field "radio-group")}}
+ <form.Field
+ @type="radio-group"
+ @name={{field.name}}
+ @title={{field.title}}
+ @description={{field.description}}
+ @format="full"
+ @validation={{field.validation}}
+ as |f|
+ >
+ <f.Control
+ {{(if field.autofocus (modifier dAutoFocus))}}
+ as |RadioGroup|
+ >
+ {{#each (fieldOptions field) as |opt|}}
+ <RadioGroup.Radio
+ @value={{opt.value}}
+ >{{opt.label}}</RadioGroup.Radio>
+ {{/each}}
+ </f.Control>
+ </form.Field>
+ {{else}}
+ <form.Field
+ @type={{field.type}}
+ @name={{field.name}}
+ @title={{field.title}}
+ @description={{field.description}}
+ @format="full"
+ @validation={{field.validation}}
+ @placeholder={{field.placeholder}}
+ as |f|
+ >
+ <f.Control
+ placeholder={{field.placeholder}}
+ {{(if field.autofocus (modifier dAutoFocus))}}
+ />
+ </form.Field>
+ {{/if}}
+ {{/each}}
+
+ <form.Submit @label="discourse_workflows.form.submit" />
+ </Form>
+ {{else if (eq this.state "submitting")}}
+ <DConditionalLoadingSpinner @condition={{true}} />
+ {{else if (eq this.state "waiting")}}
+ <DConditionalLoadingSpinner @condition={{true}} />
+ {{else if (eq this.state "complete")}}
+ <div class="workflows-form__complete">
+ {{#if this.completionData}}
+ {{#if (eq this.completionData.on_submission "redirect")}}
+ <p>{{i18n "discourse_workflows.form.redirecting"}}</p>
+ {{else if (eq this.completionData.on_submission "show_text")}}
+ <DDecoratedHtml
+ @html={{this.completionHtml.completion_text}}
+ @className="workflows-form__completion-text"
+ />
+ {{else}}
+ {{#if this.completionData.completion_title}}
+ <DDecoratedHtml
+ @html={{this.completionHtml.completion_title}}
+ @className="workflows-form__completion-title"
+ />
+ {{/if}}
+ {{#if this.completionData.completion_message}}
+ <DDecoratedHtml
+ @html={{this.completionHtml.completion_message}}
+ @className="workflows-form__completion-message"
+ />
+ {{else}}
+ <p>{{i18n "discourse_workflows.form.thank_you"}}</p>
+ {{/if}}
+ {{/if}}
+ {{else}}
+ <p>{{i18n "discourse_workflows.form.thank_you"}}</p>
+ {{/if}}
+ </div>
+ {{else if (eq this.state "error")}}
+ <div class="workflows-form__error">
+ <p>{{this.errorMessage}}</p>
+ </div>
+ {{/if}}
+ </div>
+ </template>
+}
diff --git a/plugins/discourse-workflows/assets/javascripts/discourse/discourse-workflows-public-route-map.js b/plugins/discourse-workflows/assets/javascripts/discourse/discourse-workflows-public-route-map.js
new file mode 100644
index 00000000000..e095f2bd8de
--- /dev/null
+++ b/plugins/discourse-workflows/assets/javascripts/discourse/discourse-workflows-public-route-map.js
@@ -0,0 +1,4 @@
+export default function () {
+ this.route("workflows-form", { path: "/workflows/form/:uuid" });
+ this.route("workflows-form-test", { path: "/workflows/form-test/:token" });
+}
diff --git a/plugins/discourse-workflows/assets/javascripts/discourse/initializers/admin-plugin-configuration-nav.js b/plugins/discourse-workflows/assets/javascripts/discourse/initializers/admin-plugin-configuration-nav.js
new file mode 100644
index 00000000000..1518f8ef53d
--- /dev/null
+++ b/plugins/discourse-workflows/assets/javascripts/discourse/initializers/admin-plugin-configuration-nav.js
@@ -0,0 +1,46 @@
+import { withPluginApi } from "discourse/lib/plugin-api";
+
+const PLUGIN_ID = "discourse-workflows";
+
+export default {
+ name: "discourse-workflows-admin-plugin-configuration-nav",
+
+ initialize(container) {
+ const currentUser = container.lookup("service:current-user");
+ if (!currentUser?.admin) {
+ return;
+ }
+
+ withPluginApi((api) => {
+ api.addAdminPluginConfigurationNav(PLUGIN_ID, [
+ {
+ label: "discourse_workflows.title",
+ route: "adminPlugins.show.discourse-workflows.index",
+ currentWhen:
+ "adminPlugins.show.discourse-workflows.index adminPlugins.show.discourse-workflows.new adminPlugins.show.discourse-workflows.show.index adminPlugins.show.discourse-workflows.show.executions.index adminPlugins.show.discourse-workflows.show.executions.show adminPlugins.show.discourse-workflows.show.settings",
+ },
+ {
+ label: "discourse_workflows.variables.title",
+ route: "adminPlugins.show.discourse-workflows-variables",
+ },
+ {
+ label: "discourse_workflows.credentials.title",
+ route: "adminPlugins.show.discourse-workflows-credentials",
+ },
+ {
+ label: "discourse_workflows.data_tables.title",
+ route: "adminPlugins.show.discourse-workflows-data-tables",
+ },
+ {
+ label: "discourse_workflows.executions.title",
+ route: "adminPlugins.show.discourse-workflows-executions",
+ },
+ {
+ label: "discourse_workflows.templates.title",
+ route: "adminPlugins.show.discourse-workflows-templates",
+ },
+ ]);
+ api.setAdminPluginIcon(PLUGIN_ID, "code-branch");
+ });
+ },
+};
diff --git a/plugins/discourse-workflows/assets/javascripts/discourse/initializers/topic-admin-button-workflows.gjs b/plugins/discourse-workflows/assets/javascripts/discourse/initializers/topic-admin-button-workflows.gjs
new file mode 100644
index 00000000000..710b75664fb
--- /dev/null
+++ b/plugins/discourse-workflows/assets/javascripts/discourse/initializers/topic-admin-button-workflows.gjs
@@ -0,0 +1,41 @@
+import { ajax } from "discourse/lib/ajax";
+import { popupAjaxError } from "discourse/lib/ajax-error";
+import { withPluginApi } from "discourse/lib/plugin-api";
+
+export default {
+ name: "discourse-workflows-topic-admin-button",
+
+ initialize(container) {
+ const site = container.lookup("service:site");
+ const workflows = site.topic_admin_button_workflows || [];
+
+ if (!workflows.length) {
+ return;
+ }
+
+ withPluginApi((api) => {
+ workflows.forEach((workflow) => {
+ api.addTopicAdminMenuButton((topic) => {
+ return {
+ icon: workflow.icon,
+ translatedLabel: workflow.label,
+ className: `workflow-topic-admin-btn-${workflow.workflow_id}`,
+ section: {
+ id: "discourse-workflows",
+ label: "discourse_workflows.title",
+ },
+ action: () => {
+ ajax("/discourse-workflows/trigger-topic-admin-button", {
+ type: "POST",
+ data: {
+ trigger_node_id: workflow.trigger_node_id,
+ topic_id: topic.id,
+ },
+ }).catch(popupAjaxError);
+ },
+ };
+ });
+ });
+ });
+ },
+};
diff --git a/plugins/discourse-workflows/assets/javascripts/discourse/initializers/workflow-webhook-links.js b/plugins/discourse-workflows/assets/javascripts/discourse/initializers/workflow-webhook-links.js
new file mode 100644
index 00000000000..605fc6249ac
--- /dev/null
+++ b/plugins/discourse-workflows/assets/javascripts/discourse/initializers/workflow-webhook-links.js
@@ -0,0 +1,18 @@
+import { withPluginApi } from "discourse/lib/plugin-api";
+
+export default {
+ initialize() {
+ withPluginApi((api) => {
+ api.registerValueTransformer("route-to-url", ({ value }) => {
+ if (
+ value?.includes("/workflows/webhooks/") ||
+ value?.includes("/workflows/waiting/")
+ ) {
+ window.location.href = value;
+ return "";
+ }
+ return value;
+ });
+ });
+ },
+};
diff --git a/plugins/discourse-workflows/assets/javascripts/discourse/pre-initializers/workflow-transformers.js b/plugins/discourse-workflows/assets/javascripts/discourse/pre-initializers/workflow-transformers.js
new file mode 100644
index 00000000000..d73ae4d256a
--- /dev/null
+++ b/plugins/discourse-workflows/assets/javascripts/discourse/pre-initializers/workflow-transformers.js
@@ -0,0 +1,12 @@
+import { withPluginApi } from "discourse/lib/plugin-api";
+
+export default {
+ before: "freeze-valid-transformers",
+
+ initialize() {
+ withPluginApi((api) => {
+ api.addValueTransformerName("workflow-node-defaults");
+ api.addValueTransformerName("workflow-node-icons");
+ });
+ },
+};
diff --git a/plugins/discourse-workflows/assets/javascripts/discourse/routes/workflows-form-test.js b/plugins/discourse-workflows/assets/javascripts/discourse/routes/workflows-form-test.js
new file mode 100644
index 00000000000..9dfb94ff4d0
--- /dev/null
+++ b/plugins/discourse-workflows/assets/javascripts/discourse/routes/workflows-form-test.js
@@ -0,0 +1,8 @@
+import { ajax } from "discourse/lib/ajax";
+import DiscourseRoute from "discourse/routes/discourse";
+
+export default class WorkflowsFormTestRoute extends DiscourseRoute {
+ async model(params) {
+ return await ajax(`/workflows/form-test/${params.token}.json`);
+ }
+}
diff --git a/plugins/discourse-workflows/assets/javascripts/discourse/routes/workflows-form.js b/plugins/discourse-workflows/assets/javascripts/discourse/routes/workflows-form.js
new file mode 100644
index 00000000000..e666a71a3c3
--- /dev/null
+++ b/plugins/discourse-workflows/assets/javascripts/discourse/routes/workflows-form.js
@@ -0,0 +1,10 @@
+import { ajax } from "discourse/lib/ajax";
+import DiscourseRoute from "discourse/routes/discourse";
+
+export default class WorkflowsFormRoute extends DiscourseRoute {
+ async model(params) {
+ return await ajax(
+ `/workflows/form/${params.uuid}.json${window.location.search || ""}`
+ );
+ }
+}
diff --git a/plugins/discourse-workflows/assets/javascripts/discourse/services/workflows-node-types.js b/plugins/discourse-workflows/assets/javascripts/discourse/services/workflows-node-types.js
new file mode 100644
index 00000000000..9823578d873
--- /dev/null
+++ b/plugins/discourse-workflows/assets/javascripts/discourse/services/workflows-node-types.js
@@ -0,0 +1,180 @@
+import { tracked } from "@glimmer/tracking";
+import Service from "@ember/service";
+import { ajax } from "discourse/lib/ajax";
+import { popupAjaxError } from "discourse/lib/ajax-error";
+
+function sortForStableStringify(value) {
+ if (Array.isArray(value)) {
+ return value.map(sortForStableStringify);
+ }
+
+ if (value && typeof value === "object") {
+ return Object.keys(value)
+ .sort()
+ .reduce((result, key) => {
+ result[key] = sortForStableStringify(value[key]);
+ return result;
+ }, {});
+ }
+
+ return value;
+}
+
+function stableStringify(value) {
+ return JSON.stringify(sortForStableStringify(value));
+}
+
+function compactObject(object) {
+ return Object.fromEntries(
+ Object.entries(object).filter(([, value]) => value !== undefined)
+ );
+}
+
+function normalizeNodeForLoadOptions(node, identifier, typeVersion) {
+ return compactObject({
+ id: node?.clientId || node?.id,
+ name: node?.name,
+ type: node?.type || identifier,
+ typeVersion: node?.typeVersion || typeVersion,
+ });
+}
+
+export default class WorkflowsNodeTypes extends Service {
+ @tracked nodeTypes = null;
+ @tracked credentialTypes = null;
+ @tracked expressionContext = {};
+ @tracked workflowVars = null;
+
+ nodeTypeMap = new Map();
+ _nodeParameterOptionsCache = new Map();
+
+ async load() {
+ if (this.nodeTypes) {
+ return this.nodeTypes;
+ }
+
+ try {
+ const result = await ajax(
+ "/admin/plugins/discourse-workflows/node-types.json"
+ );
+ this.nodeTypes = result.node_types || [];
+ this.credentialTypes = result.credential_types || [];
+ this.expressionContext = result.expression_context || {};
+ this.nodeTypeMap = new Map(
+ this.nodeTypes.flatMap((nt) => [
+ [nt.name, nt],
+ [nt.identifier, nt],
+ ])
+ );
+ return this.nodeTypes;
+ } catch (e) {
+ popupAjaxError(e);
+ return [];
+ }
+ }
+
+ findNodeType(identifier) {
+ return this.nodeTypeMap.get(identifier) || null;
+ }
+
+ async loadNodeParameterOptions(
+ identifier,
+ methodName,
+ typeVersion = null,
+ context = {}
+ ) {
+ const requestPayload = this.buildNodeParameterOptionsPayload({
+ identifier,
+ methodName,
+ typeVersion,
+ ...context,
+ });
+ const cacheKey = stableStringify({
+ identifier,
+ typeVersion: typeVersion || "latest",
+ methodName,
+ payload: requestPayload,
+ });
+ if (this._nodeParameterOptionsCache.has(cacheKey)) {
+ return this._nodeParameterOptionsCache.get(cacheKey);
+ }
+
+ try {
+ const result = await ajax(
+ "/admin/plugins/discourse-workflows/dynamic-node-parameters/options.json",
+ {
+ type: "POST",
+ contentType: "application/json",
+ data: JSON.stringify(requestPayload),
+ }
+ );
+ const options = result || [];
+ this._nodeParameterOptionsCache.set(cacheKey, options);
+ return options;
+ } catch (e) {
+ popupAjaxError(e);
+ return [];
+ }
+ }
+
+ buildNodeParameterOptionsPayload({
+ identifier,
+ methodName,
+ typeVersion = null,
+ path = null,
+ currentNodeParameters = null,
+ credentials = null,
+ node = null,
+ filter = null,
+ workflowId = undefined,
+ inputContext = undefined,
+ executionContext = undefined,
+ } = {}) {
+ const resolvedVersion = typeVersion || node?.typeVersion;
+
+ return compactObject({
+ path,
+ nodeTypeAndVersion: compactObject({
+ name: identifier,
+ version: resolvedVersion,
+ }),
+ currentNodeParameters: currentNodeParameters || {},
+ methodName,
+ credentials: credentials || {},
+ filter,
+ node: normalizeNodeForLoadOptions(node, identifier, resolvedVersion),
+ workflowId,
+ inputContext,
+ executionContext,
+ });
+ }
+
+ async loadWorkflowVars() {
+ if (this.workflowVars) {
+ return this.workflowVars;
+ }
+
+ try {
+ const result = await ajax(
+ "/admin/plugins/discourse-workflows/variables.json"
+ );
+ this.workflowVars = result.variables || [];
+ } catch {
+ this.workflowVars = [];
+ }
+ return this.workflowVars;
+ }
+
+ invalidateWorkflowVars() {
+ this.workflowVars = null;
+ }
+
+ clear() {
+ this.nodeTypes = null;
+ this.credentialTypes = null;
+ this.expressionContext = {};
+ this.nodeTypeMap = new Map();
+ this._nodeParameterOptionsCache = new Map();
+ this.invalidateWorkflowVars();
+ }
+}
diff --git a/plugins/discourse-workflows/assets/javascripts/discourse/templates/workflows-form-test.gjs b/plugins/discourse-workflows/assets/javascripts/discourse/templates/workflows-form-test.gjs
new file mode 100644
index 00000000000..3761fb31837
--- /dev/null
+++ b/plugins/discourse-workflows/assets/javascripts/discourse/templates/workflows-form-test.gjs
@@ -0,0 +1,7 @@
+import WorkflowsForm from "../components/workflows-form";
+
+<template>
+ <div class="workflows-form-page">
+ <WorkflowsForm @model={{@model}} />
+ </div>
+</template>
diff --git a/plugins/discourse-workflows/assets/javascripts/discourse/templates/workflows-form.gjs b/plugins/discourse-workflows/assets/javascripts/discourse/templates/workflows-form.gjs
new file mode 100644
index 00000000000..3761fb31837
--- /dev/null
+++ b/plugins/discourse-workflows/assets/javascripts/discourse/templates/workflows-form.gjs
@@ -0,0 +1,7 @@
+import WorkflowsForm from "../components/workflows-form";
+
+<template>
+ <div class="workflows-form-page">
+ <WorkflowsForm @model={{@model}} />
+ </div>
+</template>
diff --git a/plugins/discourse-workflows/assets/stylesheets/common/admin-page.scss b/plugins/discourse-workflows/assets/stylesheets/common/admin-page.scss
new file mode 100644
index 00000000000..3075e43f948
--- /dev/null
+++ b/plugins/discourse-workflows/assets/stylesheets/common/admin-page.scss
@@ -0,0 +1,76 @@
+.admin-plugin-config-page .d-page-header + .admin-plugin-config-page__content {
+ margin-top: 1em;
+}
+
+.workflows-page .d-page-header__title-row,
+.workflows-page .d-page-header__description {
+ display: none;
+}
+
+.workflows-header {
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ margin-bottom: 0.5em;
+ gap: 1em;
+}
+
+.workflows-editable-title {
+ &,
+ &__display,
+ &__actions {
+ display: inline-flex;
+ align-items: center;
+ gap: var(--space-1);
+ }
+
+ &__text,
+ &__input {
+ background: none;
+ border: none;
+ padding: 0;
+ margin: 0;
+ font: inherit;
+ font-size: var(--font-up-3);
+ font-weight: 700;
+ color: inherit;
+ line-height: inherit;
+ box-sizing: content-box;
+ }
+
+ &__text {
+ cursor: text;
+ }
+
+ &__edit,
+ &__save,
+ &__cancel {
+ flex-shrink: 0;
+ }
+
+ &__input {
+ // stylelint-disable declaration-no-important
+ outline: none !important;
+ border: none !important;
+ background: var(--primary-very-low) !important;
+ padding: 0 !important;
+ margin: 0 !important;
+ font-size: var(--font-up-3) !important;
+ font-weight: 700 !important;
+ line-height: inherit !important;
+ box-sizing: content-box !important;
+ width: calc(var(--title-length) * 1ch) !important;
+ // stylelint-enable declaration-no-important
+ }
+}
+
+.workflows-show-nav {
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ margin-bottom: 1em;
+
+ .horizontal-overflow-nav {
+ margin-bottom: 0;
+ }
+}
diff --git a/plugins/discourse-workflows/assets/stylesheets/common/admin-table.scss b/plugins/discourse-workflows/assets/stylesheets/common/admin-table.scss
new file mode 100644
index 00000000000..ff1f306688d
--- /dev/null
+++ b/plugins/discourse-workflows/assets/stylesheets/common/admin-table.scss
@@ -0,0 +1,26 @@
+.workflows-admin-table {
+ &__toolbar {
+ display: flex;
+ justify-content: flex-end;
+ gap: var(--space-2);
+ margin-bottom: var(--space-3);
+ }
+
+ &__table {
+ color: var(--primary-medium);
+ font-size: var(--font-down-1);
+
+ th {
+ border-bottom: 1px solid var(--primary-low);
+ }
+ }
+
+ &__checkbox-cell {
+ white-space: nowrap;
+ }
+
+ &__checkbox {
+ cursor: pointer;
+ margin: 0;
+ }
+}
diff --git a/plugins/discourse-workflows/assets/stylesheets/common/canvas/canvas.scss b/plugins/discourse-workflows/assets/stylesheets/common/canvas/canvas.scss
new file mode 100644
index 00000000000..1abdc67215a
--- /dev/null
+++ b/plugins/discourse-workflows/assets/stylesheets/common/canvas/canvas.scss
@@ -0,0 +1,733 @@
+.workflows-canvas {
+ --socket-size: 10px;
+ --z-canvas-elements: 1;
+ --z-canvas-empty-state: 4;
+ --z-canvas-spinner: 5;
+ --z-canvas-chrome: 10;
+ width: 100%;
+ height: 100%;
+ position: relative;
+ outline: none;
+ background-color: var(--primary-very-low);
+ background-image: radial-gradient(
+ circle,
+ var(--primary-300) 0.3px,
+ transparent 1px
+ );
+ background-size: 16px 16px;
+
+ &__spinner-overlay {
+ position: absolute;
+ inset: 0;
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ z-index: var(--z-canvas-spinner);
+ background: inherit;
+ }
+
+ &__empty-state {
+ position: absolute;
+ inset: 0;
+ z-index: var(--z-canvas-empty-state);
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ pointer-events: none;
+ }
+
+ &__empty-state-options {
+ display: flex;
+ align-items: flex-start;
+ justify-content: center;
+ gap: var(--space-6);
+ pointer-events: auto;
+ }
+
+ &__empty-state-trigger {
+ display: flex;
+ flex-direction: column;
+ align-items: center;
+ gap: 0.35rem;
+ padding: 0;
+ border: 0;
+ background: none;
+ color: var(--primary);
+ font: inherit;
+ cursor: pointer;
+
+ &:focus-visible {
+ outline: none;
+ }
+
+ &:focus-visible .workflows-canvas__empty-state-tile {
+ border-color: var(--tertiary);
+ box-shadow: 0 0 0 2px var(--tertiary-low);
+ }
+ }
+
+ &__empty-state-tile {
+ width: min(88px, calc(100vw - 7rem));
+ aspect-ratio: 1;
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ border: 2px dashed var(--primary-low-mid);
+ border-radius: 10px;
+ background: rgb(from var(--secondary) r g b / 0.86);
+ transition:
+ border-color 0.15s ease,
+ background 0.15s ease;
+
+ .d-icon {
+ width: 1.3rem;
+ height: 1.3rem;
+ color: var(--primary-medium);
+ }
+ }
+
+ &__empty-state-label {
+ font-size: var(--font-down-2);
+ font-weight: 400;
+ line-height: 1.2;
+ text-align: center;
+ max-width: 10rem;
+ }
+
+ &__rete-container {
+ width: 100%;
+ height: 100%;
+ cursor: grab;
+
+ &:active {
+ cursor: grabbing;
+ }
+
+ * {
+ transition: none !important;
+ }
+ }
+
+ &__controls {
+ position: absolute;
+ bottom: var(--space-2);
+ left: var(--space-2);
+ display: flex;
+ align-items: center;
+ gap: var(--space-1);
+ background: var(--secondary);
+ border: 1px solid var(--primary-low-mid);
+ border-radius: var(--d-border-radius);
+ padding: var(--space-1);
+ box-shadow: 0 2px 8px rgb(0, 0, 0, 0.1);
+ }
+
+ &__zoom-label {
+ font-size: var(--font-down-1);
+ color: var(--primary-medium);
+ min-width: 3em;
+ text-align: center;
+ }
+
+ &__publish-btn {
+ min-width: 6.5em;
+ }
+
+ &__publish-status {
+ position: absolute;
+ top: var(--space-2);
+ left: 50%;
+ z-index: var(--z-canvas-chrome);
+ display: flex;
+ align-items: center;
+ gap: var(--space-4);
+ max-width: min(65vw, 36rem);
+ padding: var(--space-1) var(--space-2);
+ border: 1px solid var(--primary-low-mid);
+ border-radius: var(--d-border-radius);
+ background: var(--secondary);
+ box-shadow: 0 2px 8px rgb(0, 0, 0, 0.1);
+ transform: translateX(-50%);
+ }
+
+ &__publish-status-body {
+ display: flex;
+ align-items: flex-start;
+ gap: var(--space-2);
+ min-width: 0;
+ line-height: 1.2;
+ }
+
+ &__publish-status-icon {
+ flex: 0 0 auto;
+ margin-top: 0.1rem;
+ color: var(--workflow-status-running);
+ font-size: var(--font-down-1);
+ }
+
+ &__publish-status-text {
+ display: flex;
+ flex-direction: column;
+ min-width: 0;
+ }
+
+ &__publish-status-title {
+ overflow: hidden;
+ color: var(--primary-high);
+ font-size: var(--font-down-1);
+ font-weight: 600;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+ }
+
+ &__publish-status-detail {
+ overflow: hidden;
+ color: var(--primary-medium);
+ font-size: var(--font-down-2);
+ text-overflow: ellipsis;
+ white-space: nowrap;
+ }
+
+ &__publish-status-btn {
+ flex: 0 0 auto;
+ }
+
+ &__publish-status-actions {
+ display: flex;
+ flex: 0 0 auto;
+ align-items: center;
+ gap: var(--space-1);
+ }
+
+ &__toolbar-top-right {
+ position: absolute;
+ top: var(--space-2);
+ right: var(--space-2);
+ display: flex;
+ gap: 6px;
+ z-index: var(--z-canvas-chrome);
+ }
+
+ &__add-node-btn {
+ background: var(--secondary);
+ border: 1px solid var(--primary-low-mid);
+ box-shadow: 0 2px 8px rgb(0, 0, 0, 0.1);
+ }
+
+ &__menu-btn {
+ background: var(--secondary);
+ border: 1px solid var(--primary-low-mid);
+ box-shadow: 0 2px 8px rgb(0, 0, 0, 0.1);
+ }
+
+ &__context-menu {
+ position: absolute;
+ z-index: var(--z-canvas-chrome);
+ background: var(--secondary);
+ border: 1px solid var(--primary-low-mid);
+ border-radius: var(--d-border-radius);
+ box-shadow: var(--shadow-dropdown);
+ padding: var(--space-1) 0;
+ min-width: 180px;
+ max-height: 400px;
+ overflow-y: auto;
+ }
+
+ &__context-menu-item {
+ width: 100%;
+ justify-content: flex-start;
+ padding: var(--space-1) var(--space-3);
+ border-radius: 0;
+ gap: var(--space-2);
+ font-size: var(--font-down-1);
+
+ .d-icon {
+ color: var(--node-icon-color, var(--primary-medium));
+ }
+
+ &:hover {
+ background: var(--primary-very-low);
+ }
+ }
+}
+
+@media screen and (width <= 767px) {
+ .workflows-canvas {
+ &__empty-state-options {
+ gap: var(--space-4);
+ }
+
+ &__empty-state-trigger {
+ gap: 0.3rem;
+ }
+
+ &__empty-state-tile {
+ width: min(80px, calc(100vw - 3rem));
+ border-radius: 8px;
+
+ .d-icon {
+ width: 1.15rem;
+ height: 1.15rem;
+ }
+ }
+
+ &__empty-state-label {
+ font-size: var(--font-down-3);
+ }
+ }
+}
+
+.workflow-rete-node {
+ display: flex;
+ flex-direction: column;
+ align-items: center;
+ position: relative;
+ cursor: pointer;
+ user-select: none;
+ width: 130px;
+
+ &__icon-row {
+ position: relative;
+ }
+
+ &__icon-block {
+ width: 56px;
+ height: 56px;
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ border-radius: 12px;
+ border: 1px solid var(--primary-low-mid);
+ background: var(--primary-very-low);
+ position: relative;
+ transition: border-color 0.15s;
+ }
+
+ &:hover &__icon-block {
+ border-color: var(--primary-medium);
+ }
+
+ &.is-selected &__icon-block {
+ border-color: var(--tertiary);
+ box-shadow: 0 0 0 1px var(--tertiary);
+ }
+
+ &.is-trigger &__icon-block {
+ width: 74px;
+ border-width: 2px;
+ border-color: var(--node-icon-color, var(--primary-medium));
+ border-radius: 999px 14px 14px 999px;
+ background: rgb(
+ from var(--node-icon-color, var(--primary-medium)) r g b / 0.12
+ );
+ }
+
+ &.is-trigger:hover &__icon-block {
+ border-color: var(--primary-medium);
+ }
+
+ &.is-trigger.is-selected &__icon-block {
+ border-color: var(--tertiary);
+ }
+
+ &__run-scope-tooltip {
+ position: absolute;
+ left: 50%;
+ bottom: calc(100% + 2rem);
+ transform: translateX(-50%);
+ z-index: calc(var(--z-canvas-elements) + 2);
+ padding: var(--space-half) var(--space-2);
+ border-radius: var(--d-border-radius);
+ background: var(--secondary);
+ border: 1px solid var(--primary-low-mid);
+ box-shadow: var(--shadow-dropdown);
+ color: var(--primary);
+ font-size: var(--font-down-3);
+ line-height: 1.2;
+ white-space: nowrap;
+ pointer-events: none;
+ }
+
+ &__icon {
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ color: var(--node-icon-color, var(--primary-medium));
+
+ .d-icon {
+ width: 24px;
+ height: 24px;
+ }
+ }
+
+ &__unavailable-icon {
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ color: var(--danger);
+
+ .d-icon {
+ width: 24px;
+ height: 24px;
+ }
+ }
+
+ &__unavailable-pill {
+ display: inline-flex;
+ align-items: center;
+ max-width: 100%;
+ margin-top: var(--space-half);
+ padding: 1px var(--space-1);
+ border: 1px solid var(--danger-low-mid);
+ border-radius: 3px;
+ background: var(--danger-low);
+ color: var(--danger);
+ font-size: var(--font-down-3);
+ font-weight: 600;
+ line-height: 1.2;
+ }
+
+ &__issues-badge {
+ position: absolute;
+ top: -6px;
+ right: -6px;
+ width: 20px;
+ height: 20px;
+ border-radius: 50%;
+ background: var(--workflow-status-running);
+ color: var(--secondary);
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ pointer-events: all;
+ padding: 0;
+ border: 2px solid var(--secondary);
+ box-shadow: 0 1px 2px rgb(0 0 0 / 0.2);
+ cursor: pointer;
+
+ .d-icon {
+ width: 10px;
+ height: 10px;
+ }
+ }
+
+ &__issues-title {
+ padding: var(--space-1) var(--space-2) var(--space-half);
+ font-size: var(--font-down-2);
+ font-weight: bold;
+ color: var(--primary);
+ }
+
+ &__issues-list {
+ margin: 0;
+ padding: 0 var(--space-2) var(--space-1);
+ font-size: var(--font-down-2);
+ list-style: none;
+ max-width: 260px;
+ display: flex;
+ flex-direction: column;
+ gap: var(--space-half);
+
+ li {
+ margin: 0;
+ color: var(--primary);
+ word-break: break-word;
+ }
+ }
+
+ &__label {
+ margin-top: var(--space-1);
+ font-size: var(--font-down-3);
+ color: var(--primary);
+ line-height: 1.2;
+ text-align: center;
+ max-width: 100%;
+ overflow: hidden;
+ display: -webkit-box;
+ -webkit-line-clamp: 2;
+ -webkit-box-orient: vertical;
+ }
+
+ &__description {
+ margin-top: var(--space-1);
+ font-size: var(--font-down-3);
+ color: var(--primary-medium);
+ line-height: 1.2;
+ text-align: center;
+ max-width: 100%;
+ overflow: hidden;
+ display: -webkit-box;
+ -webkit-line-clamp: 2;
+ -webkit-box-orient: vertical;
+ }
+
+ // Socket (port) styles
+ &__socket {
+ width: var(--socket-size);
+ height: var(--socket-size);
+ border-radius: 50%;
+ background: var(--secondary);
+ border: 1px solid var(--primary-low-mid);
+ cursor: crosshair;
+ flex-shrink: 0;
+ transition: transform 0.15s;
+ position: relative;
+ z-index: var(--z-canvas-elements);
+
+ &:hover {
+ transform: scale(1.3);
+ }
+
+ &.is-connectable-hint {
+ animation: workflow-socket-connectable-pulse 3s ease-in-out infinite;
+ }
+
+ &.--output {
+ &.--loop {
+ cursor: default;
+ pointer-events: none;
+ animation: none;
+ }
+ }
+ }
+
+ &__inputs {
+ position: absolute;
+ left: calc(-1 * (var(--socket-size) / 2));
+ top: calc(50% - (var(--socket-size) / 2));
+ display: flex;
+ flex-direction: column;
+ justify-content: center;
+ gap: var(--space-1);
+ z-index: var(--z-canvas-elements);
+ }
+
+ &__input-row {
+ width: var(--socket-size);
+ height: var(--socket-size);
+ position: relative;
+ display: flex;
+ align-items: center;
+ }
+
+ &__inputs.has-multiple-inputs {
+ top: calc(50% - (var(--socket-size) + 4px));
+ gap: var(--space-2);
+ }
+
+ &__input-label {
+ position: absolute;
+ right: 24px;
+ top: 50%;
+ transform: translateY(-50%);
+ color: var(--primary-medium);
+ font-size: 9px;
+ font-weight: 400;
+ letter-spacing: 0.3px;
+ line-height: 1;
+ pointer-events: none;
+ padding: 2px 4px 2px 8px;
+ background: var(--primary-very-low);
+ border-radius: 3px;
+ white-space: nowrap;
+ z-index: calc(var(--z-canvas-elements) + 1);
+ }
+
+ &__outputs {
+ position: absolute;
+ right: calc(-1 * (var(--socket-size) / 2) + 2px);
+ top: calc(50% - (var(--socket-size) / 2));
+ display: flex;
+ flex-direction: column;
+ justify-content: center;
+ gap: var(--space-1);
+ }
+
+ &.is-branching &__outputs {
+ top: calc(50% - (var(--socket-size) + 4px));
+ gap: var(--space-2);
+ }
+
+ &__output-row {
+ display: flex;
+ align-items: center;
+ gap: 10px;
+ white-space: nowrap;
+ position: relative;
+ width: var(--socket-size);
+ height: var(--socket-size);
+ }
+
+ &__port-pill {
+ font-size: 9px;
+ font-weight: 400;
+ text-transform: uppercase;
+ letter-spacing: 0.3px;
+ pointer-events: none;
+ line-height: 1;
+ white-space: nowrap;
+ position: absolute;
+ left: 14px;
+ top: 50%;
+ transform: translateY(-50%);
+ color: var(--primary-medium);
+ padding: 2px 8px 2px 4px;
+ background: var(--primary-very-low);
+ border-radius: 3px;
+ }
+
+ &.is-unavailable {
+ .workflow-rete-node__icon-block {
+ border-color: var(--danger);
+ border-style: dashed;
+ background: color-mix(in srgb, var(--danger) 9%, var(--secondary));
+ box-shadow: inset 0 0 0 1px rgb(from var(--secondary) r g b / 0.7);
+ }
+
+ &:hover .workflow-rete-node__icon-block {
+ border-color: var(--danger-hover);
+ }
+
+ .workflow-rete-node__label {
+ color: var(--primary-high);
+ }
+ }
+}
+
+.workflow-rete-node__socket.is-invalid-connection-target {
+ opacity: 0;
+ pointer-events: none;
+ transform: scale(0.75);
+}
+
+.workflow-rete-node-view {
+ z-index: var(--z-canvas-elements);
+}
+
+@keyframes workflow-socket-connectable-pulse {
+ 0%,
+ 65%,
+ 100% {
+ border-color: var(--primary-low-mid);
+ box-shadow: 0 0 0 0 rgb(var(--tertiary-rgb), 0);
+ }
+
+ 35% {
+ border-color: var(--tertiary);
+ box-shadow: 0 0 0 5px rgb(var(--tertiary-rgb), 0.18);
+ }
+}
+
+@media (prefers-reduced-motion: reduce) {
+ .workflow-rete-node__socket.is-connectable-hint {
+ animation: none;
+ border-color: var(--tertiary);
+ box-shadow: 0 0 0 2px rgb(var(--tertiary-rgb), 0.18);
+ }
+}
+
+// Handle styles (unlinked input/output -> [+] button)
+.workflow-handle {
+ .is-connection-dragging & {
+ visibility: hidden;
+ }
+
+ &__button-fo {
+ pointer-events: all;
+ }
+
+ &__add-btn {
+ width: 14px;
+ height: 14px;
+ border-radius: 3px;
+ border: 1px solid var(--primary-low-mid);
+ background: var(--secondary);
+ color: var(--primary-medium);
+ cursor: pointer;
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ padding: 0;
+
+ .d-icon {
+ width: 8px;
+ height: 8px;
+ }
+
+ &:hover {
+ border-color: var(--tertiary);
+ color: var(--tertiary);
+ }
+ }
+}
+
+// Connection path styles
+.workflow-connection {
+ &__visible {
+ transition:
+ stroke 0.15s,
+ stroke-width 0.15s;
+ pointer-events: none;
+ }
+
+ &__arrow {
+ transition: fill 0.15s;
+ }
+
+ &__hit {
+ pointer-events: stroke;
+ cursor: pointer;
+
+ &:hover ~ .workflow-connection__visible:not(.is-selected) {
+ stroke: var(--primary-medium);
+ stroke-width: 2;
+ }
+ }
+
+ &__toolbar-fo {
+ pointer-events: none;
+ opacity: 0;
+ transition: opacity 0.15s;
+
+ &.is-visible {
+ pointer-events: all;
+ opacity: 1;
+
+ .workflow-canvas-toolbar {
+ pointer-events: auto;
+ }
+ }
+ }
+}
+
+// Loop-back path (self-loop on Loop Over Items node)
+.workflow-loop-back {
+ &__path {
+ pointer-events: none;
+ }
+
+ &__button-fo {
+ pointer-events: all;
+ }
+
+ &__add-btn {
+ width: 28px;
+ height: 28px;
+ border-radius: 50%;
+ border: 1px solid var(--primary-low-mid);
+ background: var(--secondary);
+ color: var(--primary-medium);
+ font-size: var(--font-up-1);
+ cursor: pointer;
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ padding: 0;
+ line-height: 1;
+
+ &:hover {
+ border-color: var(--tertiary);
+ color: var(--tertiary);
+ }
+ }
+}
diff --git a/plugins/discourse-workflows/assets/stylesheets/common/canvas/hover-toolbar.scss b/plugins/discourse-workflows/assets/stylesheets/common/canvas/hover-toolbar.scss
new file mode 100644
index 00000000000..1bfd8c32894
--- /dev/null
+++ b/plugins/discourse-workflows/assets/stylesheets/common/canvas/hover-toolbar.scss
@@ -0,0 +1,87 @@
+.workflow-canvas-toolbar {
+ position: absolute;
+ top: -30px;
+ left: 50%;
+ transform: translateX(-50%);
+ display: flex;
+ align-items: center;
+ gap: 4px;
+ opacity: 0;
+ pointer-events: none;
+ transition: opacity 0.15s;
+
+ &.is-visible {
+ opacity: 1;
+ pointer-events: auto;
+ }
+
+ &.--inline {
+ position: static;
+ transform: none;
+ opacity: 1;
+ width: fit-content;
+ margin: 0 auto;
+ }
+
+ .workflows-canvas__rete-container.is-dragging & {
+ opacity: 0;
+ pointer-events: none;
+ }
+
+ &__btn,
+ &__btn.btn {
+ width: 22px;
+ height: 22px;
+ border-radius: 4px;
+ border: none;
+ background: var(--primary-very-high);
+ color: var(--secondary);
+ cursor: pointer;
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ padding: 0;
+ box-shadow: 0 2px 8px rgb(0 0 0 / 0.15);
+
+ .d-icon {
+ font-size: var(--font-down-3);
+ color: inherit;
+ }
+
+ &:hover,
+ &:focus-visible {
+ background: var(--primary-high);
+
+ .d-icon {
+ color: inherit;
+ }
+ }
+
+ &.--success {
+ background: var(--workflow-status-success);
+
+ &:hover {
+ background: color-mix(
+ in srgb,
+ var(--workflow-status-success) 85%,
+ black
+ );
+ }
+ }
+
+ &.is-disabled,
+ &:disabled {
+ background: var(--primary-low-mid);
+ color: var(--primary-medium);
+ cursor: not-allowed;
+ box-shadow: none;
+ opacity: 1;
+
+ &:hover,
+ &:focus-visible {
+ background: var(--primary-low-mid);
+ color: var(--primary-medium);
+ }
+ }
+ }
+}
diff --git a/plugins/discourse-workflows/assets/stylesheets/common/canvas/node-panel.scss b/plugins/discourse-workflows/assets/stylesheets/common/canvas/node-panel.scss
new file mode 100644
index 00000000000..550dd13784b
--- /dev/null
+++ b/plugins/discourse-workflows/assets/stylesheets/common/canvas/node-panel.scss
@@ -0,0 +1,181 @@
+.workflows-node-panel {
+ position: fixed;
+ top: 0;
+ right: 0;
+ width: 320px;
+ height: 100vh;
+ display: flex;
+ flex-direction: column;
+ background: var(--secondary);
+ border-left: 1px solid var(--primary-low-mid);
+ overflow: hidden;
+ z-index: 1001;
+
+ &__header {
+ display: flex;
+ align-items: center;
+ gap: var(--space-2);
+ padding: var(--space-3) var(--space-4);
+ border-bottom: 1px solid var(--primary-low-mid);
+ }
+
+ &__title {
+ flex: 1;
+ font-size: var(--font-up-1);
+ font-weight: 700;
+ color: var(--primary);
+ }
+
+ &__back {
+ color: var(--primary-medium);
+ }
+
+ &__close {
+ color: var(--primary-medium);
+ }
+
+ &__search {
+ display: flex;
+ align-items: center;
+ gap: var(--space-2);
+ margin: var(--space-3) var(--space-4);
+ padding: var(--space-2) var(--space-3);
+ border: 1px solid var(--primary-low-mid);
+ border-radius: var(--d-border-radius);
+ background: var(--primary-very-low);
+
+ .d-icon {
+ color: var(--primary-medium);
+ flex-shrink: 0;
+ }
+ }
+
+ &__search-input {
+ border: 0 !important;
+ background: transparent !important;
+ outline: none !important;
+ box-shadow: none !important;
+ margin: 0 !important;
+ padding: 0 !important;
+ width: 100%;
+ font-size: var(--font-0);
+ color: var(--primary);
+
+ &::placeholder {
+ color: var(--primary-medium);
+ }
+ }
+
+ &__list {
+ flex: 1;
+ overflow-y: auto;
+ display: flex;
+ flex-direction: column;
+ padding: 0 var(--space-2);
+ }
+
+ &__category {
+ display: flex;
+ align-items: center;
+ gap: var(--space-3);
+ width: 100%;
+ padding: var(--space-3);
+ border: 0;
+ border-radius: var(--d-border-radius);
+ background: none;
+ cursor: pointer;
+ text-align: left;
+ color: var(--primary);
+ font: inherit;
+
+ &:hover {
+ background: var(--primary-very-low);
+ }
+ }
+
+ &__category-icon {
+ flex-shrink: 0;
+ display: flex;
+ align-items: center;
+
+ .d-icon {
+ color: var(--primary-medium);
+ }
+ }
+
+ &__category-name {
+ flex: 1;
+ font-weight: 700;
+ font-size: var(--font-0);
+ }
+
+ &__category-arrow {
+ flex-shrink: 0;
+ display: flex;
+ align-items: center;
+
+ .d-icon {
+ color: var(--primary-medium);
+ }
+ }
+
+ &__item {
+ display: flex;
+ align-items: center;
+ gap: var(--space-3);
+ width: 100%;
+ padding: var(--space-3);
+ border: 0;
+ border-radius: var(--d-border-radius);
+ background: none;
+ cursor: pointer;
+ text-align: left;
+ color: var(--primary);
+ font: inherit;
+
+ &:hover {
+ background: var(--primary-very-low);
+ }
+ }
+
+ &__item-icon {
+ flex-shrink: 0;
+ display: flex;
+ align-items: center;
+ justify-content: center;
+
+ .d-icon {
+ color: var(--node-icon-color, var(--primary-medium));
+ }
+ }
+
+ &__item-content {
+ flex: 1;
+ min-width: 0;
+ display: flex;
+ flex-direction: column;
+ gap: var(--space-1);
+ }
+
+ &__item-name {
+ font-weight: 700;
+ font-size: var(--font-0);
+ line-height: 1.2;
+ }
+
+ &__item-description {
+ font-size: var(--font-down-1);
+ color: var(--primary-medium);
+ line-height: 1.3;
+ }
+
+ &__item-arrow {
+ flex-shrink: 0;
+ display: flex;
+ align-items: center;
+
+ .d-icon {
+ color: var(--primary-medium);
+ }
+ }
+}
diff --git a/plugins/discourse-workflows/assets/stylesheets/common/canvas/sticky-note.scss b/plugins/discourse-workflows/assets/stylesheets/common/canvas/sticky-note.scss
new file mode 100644
index 00000000000..99ffe1ed30a
--- /dev/null
+++ b/plugins/discourse-workflows/assets/stylesheets/common/canvas/sticky-note.scss
@@ -0,0 +1,191 @@
+.workflow-sticky-note {
+ position: absolute;
+ z-index: -1;
+ border-radius: 4px;
+ box-shadow: 0 2px 8px rgb(0 0 0 / 0.12);
+ pointer-events: auto;
+ cursor: grab;
+ user-select: none;
+ display: flex;
+ flex-direction: column;
+ overflow: visible;
+ border: 1px solid var(--primary-low-mid);
+
+ &:active {
+ cursor: grabbing;
+ }
+
+ &.is-selected {
+ outline: 2px solid var(--tertiary);
+ outline-offset: -1px;
+ }
+
+ &__color-picker {
+ position: absolute;
+ top: -58px;
+ left: 50%;
+ transform: translateX(-50%);
+ display: flex;
+ align-items: center;
+ gap: 4px;
+ padding: 4px 6px;
+ background: var(--secondary);
+ border: 1px solid var(--primary-low-mid);
+ border-radius: var(--d-border-radius);
+ box-shadow: var(--shadow-dropdown);
+ z-index: 10;
+ }
+
+ &__color-swatch {
+ width: 18px;
+ height: 18px;
+ border-radius: 50%;
+ border: 2px solid transparent;
+ cursor: pointer;
+ padding: 0;
+ transition: border-color 0.15s;
+
+ &:hover {
+ border-color: var(--primary-medium);
+ }
+
+ &.is-active {
+ border-color: var(--primary);
+ }
+ }
+
+ &__content {
+ flex: 1;
+ padding: 8px 10px;
+ overflow: hidden;
+ min-height: 0;
+ }
+
+ &__textarea {
+ width: 100%;
+ height: 100%;
+ border: none;
+ background: transparent;
+ resize: none;
+ font-size: var(--font-down-3);
+ font-family: inherit;
+ line-height: 1.4;
+ color: var(--primary);
+ outline: none;
+ padding: 0;
+ cursor: text;
+
+ &:focus {
+ border: none;
+ outline: none;
+ }
+ }
+
+ &__text {
+ font-size: var(--font-down-3);
+ line-height: 1.4;
+ color: var(--primary);
+ word-break: break-word;
+ overflow: hidden;
+ height: 100%;
+
+ p {
+ margin: 0 0 0.4em;
+
+ &:last-child {
+ margin-bottom: 0;
+ }
+ }
+
+ a {
+ color: var(--tertiary);
+ }
+
+ code {
+ background: var(--primary-very-low);
+ padding: 1px 4px;
+ border-radius: 3px;
+ font-size: var(--font-down-2);
+ }
+ }
+
+ &__placeholder {
+ color: var(--primary-medium);
+ font-style: italic;
+ }
+
+ &__edges {
+ position: absolute;
+ inset: 0;
+ pointer-events: none;
+ }
+
+ &__edge {
+ position: absolute;
+ pointer-events: auto;
+
+ &.--n,
+ &.--s {
+ left: 6px;
+ right: 6px;
+ height: 6px;
+ cursor: ns-resize;
+ }
+
+ &.--n {
+ top: -3px;
+ }
+
+ &.--s {
+ bottom: -3px;
+ }
+
+ &.--w,
+ &.--e {
+ top: 6px;
+ bottom: 6px;
+ width: 6px;
+ cursor: ew-resize;
+ }
+
+ &.--w {
+ left: -3px;
+ }
+
+ &.--e {
+ right: -3px;
+ }
+
+ &.--nw,
+ &.--ne,
+ &.--sw,
+ &.--se {
+ width: 10px;
+ height: 10px;
+ }
+
+ &.--nw {
+ top: -3px;
+ left: -3px;
+ cursor: nwse-resize;
+ }
+
+ &.--ne {
+ top: -3px;
+ right: -3px;
+ cursor: nesw-resize;
+ }
+
+ &.--sw {
+ bottom: -3px;
+ left: -3px;
+ cursor: nesw-resize;
+ }
+
+ &.--se {
+ bottom: -3px;
+ right: -3px;
+ cursor: nwse-resize;
+ }
+ }
+}
diff --git a/plugins/discourse-workflows/assets/stylesheets/common/colors.scss b/plugins/discourse-workflows/assets/stylesheets/common/colors.scss
new file mode 100644
index 00000000000..7bcbecfe1da
--- /dev/null
+++ b/plugins/discourse-workflows/assets/stylesheets/common/colors.scss
@@ -0,0 +1,43 @@
+:root {
+ --workflow-node-color-purple: light-dark(#6e5dc6, #8f7ee7);
+ --workflow-node-color-deep-orange: light-dark(#bd5b00, #fca700);
+ --workflow-node-color-orange: light-dark(#e06c00, #fbc828);
+ --workflow-node-color-grey: light-dark(#7d818a, #b7b9be);
+ --workflow-node-color-indigo: light-dark(#05c, #388bff);
+ --workflow-node-color-teal: light-dark(#1d7f8c, #37b4c3);
+ --workflow-node-color-blue: light-dark(#1d7afc, #579dff);
+ --workflow-node-color-violet: light-dark(#8270db, #9f8fef);
+ --workflow-node-color-red: light-dark(#e2483d, #fd9891);
+ --workflow-node-color-pink: light-dark(#ae4787, #e774bb);
+ --workflow-node-color-green: light-dark(#1f845a, #4bce97);
+ --workflow-node-color-light-blue: light-dark(#388bff, #85b8ff);
+ --workflow-node-color-light-green: light-dark(#6a9a23, #94c748);
+ --workflow-node-color-yellow: light-dark(#946f00, #e2b203);
+ --workflow-node-color-cyan: light-dark(#37b4c3, #60c6d2);
+ --workflow-node-color-brown: light-dark(#6b6e76, #b7b9be);
+ --workflow-node-color-salmon: light-dark(#f15b50, #fd9891);
+
+ // Sticky note colors
+ --workflow-sticky-yellow: light-dark(#f5e989, #3d2e00);
+ --workflow-sticky-yellow-border: light-dark(#946f00, #e2b203);
+ --workflow-sticky-blue: light-dark(#cce0ff, #09326c);
+ --workflow-sticky-blue-border: light-dark(#05c, #388bff);
+ --workflow-sticky-green: light-dark(#baf3db, #133527);
+ --workflow-sticky-green-border: light-dark(#216e4e, #2abb7f);
+ --workflow-sticky-pink: light-dark(#fdd0ec, #341829);
+ --workflow-sticky-pink-border: light-dark(#943d73, #da62ac);
+ --workflow-sticky-purple: light-dark(#dfd8fd, #231c3f);
+ --workflow-sticky-purple-border: light-dark(#5e4db2, #8f7ee7);
+ --workflow-sticky-orange: light-dark(#fce4a6, #693200);
+ --workflow-sticky-orange-border: light-dark(#bd5b00, #fca700);
+
+ // Execution status colors
+ --workflow-status-success: light-dark(#1f845a, #4bce97);
+ --workflow-status-success-low: light-dark(#dcfff1, #1c3329);
+ --workflow-status-error: light-dark(#e2483d, #fd9891);
+ --workflow-status-error-low: light-dark(#ffd5d2, #5d1f1a);
+ --workflow-status-running: light-dark(#0c66e4, #579dff);
+ --workflow-status-running-low: light-dark(#cce0ff, #09326c);
+ --workflow-status-waiting: light-dark(#6e5dc6, #9f8fef);
+ --workflow-status-waiting-low: light-dark(#dfd8fd, #231c3f);
+}
diff --git a/plugins/discourse-workflows/assets/stylesheets/common/configurator/configurator-modal.scss b/plugins/discourse-workflows/assets/stylesheets/common/configurator/configurator-modal.scss
new file mode 100644
index 00000000000..5b347a3b723
--- /dev/null
+++ b/plugins/discourse-workflows/assets/stylesheets/common/configurator/configurator-modal.scss
@@ -0,0 +1,242 @@
+.workflows-page {
+ scrollbar-gutter: stable;
+}
+
+.workflows-configurator-modal {
+ .d-modal__container {
+ max-width: 100%;
+ width: 95vw;
+ max-height: 95vh;
+ height: 95vh;
+ }
+
+ .d-modal__body {
+ display: flex;
+ flex-direction: column;
+ overflow: hidden;
+ padding: 0;
+ flex: 1;
+ min-height: 0;
+ border-radius: var(--d-border-radius);
+
+ input {
+ width: 100%;
+ }
+ }
+
+ &__header {
+ display: flex;
+ align-items: center;
+ padding: var(--space-2) var(--space-3);
+ border-bottom: 1px solid var(--primary-low);
+ gap: var(--space-1);
+ }
+
+ &__name,
+ &__name-input {
+ font-size: var(--font-up-1);
+ font-weight: 700;
+ font-family: inherit;
+ padding: var(--space-1) var(--space-2);
+ border: 1px solid transparent;
+ border-radius: var(--d-border-radius);
+ line-height: 1.5;
+ height: 36px;
+ box-sizing: border-box;
+ margin: 0 !important;
+ }
+
+ &__name {
+ flex: 0 1 auto;
+ cursor: pointer;
+
+ &:hover {
+ background: var(--primary-very-low);
+ }
+ }
+
+ &__name-actions {
+ display: inline-flex;
+ align-items: center;
+ gap: var(--space-1);
+ }
+
+ &__edit-name,
+ &__save-name,
+ &__cancel-name {
+ flex-shrink: 0;
+ }
+
+ &__node-icon {
+ color: var(--node-icon-color, var(--primary-medium));
+ }
+
+ &__name-input {
+ flex: 0 1 auto;
+ width: calc(var(--node-name-length) * 1ch) !important;
+ min-width: 8ch;
+ max-width: 100%;
+ outline: none !important;
+ box-shadow: none !important;
+ border-color: var(--tertiary) !important;
+ background: var(--primary-very-low);
+ }
+
+ &__close {
+ margin-left: auto;
+ flex-shrink: 0;
+ }
+
+ &__save-status {
+ display: inline-flex;
+ align-items: center;
+ gap: var(--space-1);
+ margin-left: auto;
+ color: var(--primary-medium);
+ font-size: var(--font-down-1);
+ font-weight: 600;
+ height: 36px;
+ line-height: 1;
+ opacity: 1;
+ transition: opacity 0.5s ease-in-out;
+ white-space: nowrap;
+ }
+
+ &__save-status + &__close {
+ margin-left: 0;
+ }
+
+ &__save-status--saved {
+ color: var(--workflow-status-success);
+ }
+
+ &__save-status--fading {
+ opacity: 0;
+ }
+
+ &__save-spinner {
+ display: inline-block;
+ width: 0.85em;
+ height: 0.85em;
+ margin: 0;
+ border-width: 2px;
+ }
+
+ .loading-container {
+ flex: 1;
+ min-height: 0;
+ display: flex;
+ flex-direction: column;
+ }
+
+ &__columns {
+ display: grid;
+ grid-template-columns: 1fr 1.5fr 1fr;
+ grid-template-rows: 1fr;
+ flex: 1;
+ min-height: 0;
+
+ &:not(:has(> .--right)) {
+ grid-template-columns: 1fr 1.5fr;
+ }
+ }
+
+ &__column {
+ min-height: 0;
+ padding: var(--space-3);
+ overflow-y: auto;
+
+ // custom scrollbar styling
+ --scrollbarBg: transparent;
+ --scrollbarThumbBg: var(--primary-low);
+ --scrollbarWidth: var(--space-2);
+ scrollbar-color: transparent var(--scrollbarBg);
+ transition: scrollbar-color 0.25s ease-in-out;
+ transition-delay: 0.5s;
+
+ &::-webkit-scrollbar {
+ width: var(--scrollbarWidth);
+ }
+
+ &::-webkit-scrollbar-thumb {
+ background-color: transparent;
+ border-radius: calc(var(--scrollbarWidth) / 2);
+ }
+
+ &::-webkit-scrollbar-track {
+ background-color: transparent;
+ }
+
+ &:hover {
+ scrollbar-color: var(--scrollbarThumbBg) var(--scrollbarBg);
+ transition-delay: 0s;
+
+ &::-webkit-scrollbar-thumb {
+ background-color: var(--scrollbarThumbBg);
+ }
+ }
+
+ &.--left,
+ &.--right {
+ background-color: light-dark(var(--primary-very-low), var(--secondary));
+ border-color: var(--primary-low);
+ }
+
+ &.--left {
+ border-right: 1px solid var(--primary-low);
+ padding: var(--space-2);
+ }
+
+ &.--right {
+ border-left: 1px solid var(--primary-low);
+ padding: var(--space-2);
+ }
+ }
+
+ &__node {
+ border: 1px solid var(--content-border-color);
+ padding: var(--space-2);
+ margin-top: var(--space-4);
+ border-radius: 4px;
+ }
+
+ &__node-title {
+ font-weight: bold;
+ font-size: var(--font-down-1);
+ }
+
+ &__node-description {
+ color: var(--primary-medium);
+ font-size: var(--font-down-1);
+ margin: 0;
+ }
+
+ &__node-version {
+ color: var(--primary-medium);
+ font-size: var(--font-down-2);
+ }
+
+ &__unavailable-banner {
+ display: flex;
+ align-items: center;
+ gap: var(--space-2);
+ padding: var(--space-2) var(--space-3);
+ background: var(--workflow-status-running-low);
+ border-bottom: 1px solid var(--workflow-status-running);
+ color: var(--primary-high);
+ font-size: var(--font-down-1);
+
+ .d-icon {
+ color: var(--workflow-status-running);
+ }
+ }
+
+ &__columns.is-unavailable {
+ pointer-events: none;
+ opacity: 0.5;
+ }
+
+ .form-kit__field-code .form-kit__container-content {
+ width: 100% !important;
+ }
+}
diff --git a/plugins/discourse-workflows/assets/stylesheets/common/configurator/configurator.scss b/plugins/discourse-workflows/assets/stylesheets/common/configurator/configurator.scss
new file mode 100644
index 00000000000..aed8dc758fa
--- /dev/null
+++ b/plugins/discourse-workflows/assets/stylesheets/common/configurator/configurator.scss
@@ -0,0 +1,264 @@
+.workflows-configurator {
+ &__tabs {
+ display: flex;
+ border-bottom: 2px solid var(--primary-low);
+ margin-bottom: var(--space-4);
+ }
+
+ &__tab {
+ padding: var(--space-2) var(--space-4);
+ border: 0;
+ background: transparent;
+ cursor: pointer;
+ font-size: var(--font-0);
+ color: var(--primary-medium);
+ border-bottom: 2px solid transparent;
+ margin-bottom: -2px;
+
+ &:hover {
+ color: var(--primary);
+ }
+
+ &.is-active {
+ color: var(--tertiary);
+ border-bottom-color: var(--tertiary);
+ }
+ }
+
+ &__field-with-picker {
+ display: flex;
+ align-items: center;
+ gap: var(--space-1);
+
+ input {
+ flex: 1;
+ }
+ }
+
+ &__description {
+ width: 100%;
+ min-height: 3em;
+ resize: vertical;
+ }
+
+ &__hint {
+ font-size: var(--font-down-1);
+ color: var(--primary-medium);
+ margin: 0 0 var(--space-2);
+ }
+
+ &__key-value-row {
+ display: flex;
+ align-items: center;
+ gap: var(--space-2);
+ margin-bottom: var(--space-2);
+
+ > .form-kit__field {
+ flex: 1;
+ min-width: 0;
+ }
+ }
+}
+
+[data-identifier="filter-navigation-menu-list"] {
+ z-index: 1400;
+}
+
+.workflows-configurator-form {
+ align-items: stretch;
+
+ &.is-hidden {
+ display: none;
+ }
+
+ .topic-query-filter__icon,
+ .topic-query-filter__clear-btn {
+ display: none;
+ }
+
+ .form-kit__errors-summary {
+ width: 100%;
+ max-width: none;
+ }
+
+ .form-kit__control-custom {
+ width: 100%;
+ }
+
+ .form-kit__field-toggle {
+ width: 100%;
+ position: relative;
+ }
+
+ .form-kit__section > .btn-default {
+ width: 100%;
+ justify-content: center;
+ }
+
+ &__setting-toggle {
+ display: grid;
+ grid-template-columns: minmax(0, 1fr) auto;
+ column-gap: var(--space-4);
+ align-items: center;
+
+ .form-kit__container-title,
+ .form-kit__container-description {
+ grid-column: 1;
+ width: auto;
+ min-width: 0;
+ }
+
+ .form-kit__container-content {
+ grid-column: 2;
+ grid-row: 1 / span 2;
+ width: auto;
+ min-width: 0;
+ }
+ }
+}
+
+.workflows-property-engine {
+ &__control-wrapper {
+ position: relative;
+ width: 100%;
+
+ > .combo-box,
+ > .d-select,
+ > .icon-picker,
+ > .select-kit.combo-box.category-chooser,
+ > .user-chooser,
+ > .mini-tag-chooser {
+ width: 100%;
+ min-width: 0;
+ }
+ }
+
+ &__mode-control {
+ position: absolute;
+ top: calc(-1 * var(--space-1));
+ transform: translateY(-100%);
+ right: 0;
+ z-index: 2;
+
+ &.--toggle {
+ top: 50%;
+ transform: translateY(-50%);
+ right: 50px;
+ }
+ }
+
+ &__dynamic-hint {
+ margin: var(--space-1) 0 0;
+ color: var(--primary-medium);
+ font-size: var(--font-down-1);
+ line-height: var(--line-height-small);
+ }
+
+ &__control-wrapper[data-supports-expression] {
+ border-radius: var(--d-border-radius);
+
+ html[data-dragging-variable] & {
+ outline: 2px dashed var(--tertiary);
+ outline-offset: 2px;
+ }
+
+ &.is-drag-over input {
+ border-color: var(--tertiary) !important;
+ background: var(--tertiary-50);
+ }
+ }
+
+ &__collection-row {
+ display: flex;
+ align-items: start;
+
+ + .workflows-property-engine__collection-row {
+ border-top: 2px solid var(--primary-low-mid);
+ padding-top: var(--space-4);
+ margin-top: var(--space-4);
+ }
+ }
+
+ &__collection-delete {
+ display: flex;
+ align-items: center;
+ flex-shrink: 0;
+ padding-top: var(--space-1);
+ }
+
+ &__collection-fields {
+ flex: 1;
+ min-width: 0;
+ display: flex;
+ flex-direction: column;
+ gap: var(--space-2);
+ }
+
+ &__collection-flat {
+ flex: 1;
+ min-width: 0;
+ }
+
+ &__block-field-label {
+ font-size: var(--font-down-1);
+ font-weight: 700;
+ color: var(--primary-high);
+ }
+
+ &__block-actions {
+ display: flex;
+ align-items: center;
+ gap: var(--space-2);
+ }
+
+ &__nested-collection {
+ display: flex;
+ flex-direction: column;
+ gap: var(--space-2);
+ }
+
+ &__nested-collection-item {
+ display: flex;
+ align-items: center;
+ gap: var(--space-2);
+ padding-bottom: var(--space-2);
+ border-bottom: 1px dashed var(--primary-low);
+
+ .form-kit__container {
+ flex: 1;
+ min-width: 0;
+ margin: 0;
+ }
+
+ .form-kit__control-custom,
+ .workflows-property-engine__control-wrapper {
+ width: 100%;
+ min-width: 0;
+ box-sizing: border-box;
+ }
+
+ textarea {
+ min-height: 80px;
+ min-width: 0;
+ resize: vertical;
+ }
+
+ > .btn {
+ flex-shrink: 0;
+ }
+ }
+
+ &__add-attrs-btn {
+ flex: 1;
+ justify-content: center;
+ gap: var(--space-2);
+ }
+}
+
+.workflows-data-table-column-select {
+ width: 100%;
+}
+
+.workflows-code-control {
+ width: 100%;
+}
diff --git a/plugins/discourse-workflows/assets/stylesheets/common/configurator/select-with-action.scss b/plugins/discourse-workflows/assets/stylesheets/common/configurator/select-with-action.scss
new file mode 100644
index 00000000000..a59257b1645
--- /dev/null
+++ b/plugins/discourse-workflows/assets/stylesheets/common/configurator/select-with-action.scss
@@ -0,0 +1,9 @@
+.workflows-property-engine__select-with-action {
+ display: flex;
+ align-items: center;
+ gap: var(--space-2);
+
+ .combo-box {
+ flex: 1;
+ }
+}
diff --git a/plugins/discourse-workflows/assets/stylesheets/common/configurator/url-preview.scss b/plugins/discourse-workflows/assets/stylesheets/common/configurator/url-preview.scss
new file mode 100644
index 00000000000..30ee22070c3
--- /dev/null
+++ b/plugins/discourse-workflows/assets/stylesheets/common/configurator/url-preview.scss
@@ -0,0 +1,88 @@
+.workflows-url-preview {
+ display: flex;
+ align-items: center;
+ gap: var(--space-2);
+ padding: var(--space-2) var(--space-3);
+ box-sizing: border-box;
+ background: var(--primary-very-low);
+ border: 1px solid var(--primary-low);
+ border-radius: var(--d-border-radius);
+ cursor: pointer;
+ transition: border-color 0.15s;
+
+ &:hover {
+ border-color: var(--primary-low-mid);
+ }
+
+ &.is-loading,
+ &.is-disabled {
+ cursor: default;
+ }
+
+ &.is-disabled {
+ opacity: 0.65;
+ }
+
+ code {
+ flex: 1;
+ min-width: 0;
+ overflow: hidden;
+ text-overflow: ellipsis;
+ font-size: var(--font-down-1);
+ color: var(--primary-high);
+ background: none;
+ padding: 0;
+ }
+
+ .d-icon {
+ flex-shrink: 0;
+ color: var(--primary-medium);
+ }
+
+ &.is-copied {
+ border-color: var(--workflow-status-success);
+
+ .d-icon {
+ color: var(--workflow-status-success);
+ }
+ }
+
+ &__status {
+ display: flex;
+ align-items: center;
+ gap: var(--space-2);
+ margin-top: var(--space-1);
+ font-size: var(--font-down-1);
+ color: var(--primary-medium);
+ }
+}
+
+.workflows-url-preview-mode {
+ display: inline-flex;
+ align-items: center;
+ gap: 0;
+ width: max-content;
+ margin-bottom: var(--space-2);
+ border: 1px solid var(--primary-low);
+ border-radius: var(--d-border-radius);
+ overflow: hidden;
+
+ &__button {
+ padding: var(--space-1) var(--space-2);
+ border: 0;
+ border-right: 1px solid var(--primary-low);
+ background: var(--secondary);
+ color: var(--primary-medium);
+ font-size: var(--font-down-1);
+ cursor: pointer;
+
+ &:last-child {
+ border-right: 0;
+ }
+
+ &.is-active {
+ background: var(--tertiary);
+ color: var(--secondary);
+ }
+ }
+}
diff --git a/plugins/discourse-workflows/assets/stylesheets/common/context/context-panel.scss b/plugins/discourse-workflows/assets/stylesheets/common/context/context-panel.scss
new file mode 100644
index 00000000000..257a8692b35
--- /dev/null
+++ b/plugins/discourse-workflows/assets/stylesheets/common/context/context-panel.scss
@@ -0,0 +1,309 @@
+.workflows-context-panel {
+ display: flex;
+ flex-direction: column;
+ gap: var(--space-2);
+ flex: 1;
+ min-height: 0;
+
+ &__hint {
+ border: 1px solid;
+ border-color: var(--tertiary);
+ border-radius: var(--d-border-radius);
+ padding: var(--space-2);
+ background-color: light-dark(var(--tertiary-100), var(--tertiary-500));
+ }
+
+ &__hint-title {
+ display: flex;
+ align-items: center;
+ gap: var(--space-2);
+ font-size: var(--font-down-1);
+ font-weight: 700;
+ margin: 0 0 var(--space-1);
+ text-transform: uppercase;
+ letter-spacing: 0.05em;
+ font-family: monospace;
+ color: var(--primary-900);
+ }
+
+ &__hint-text {
+ margin: 0;
+ font-size: var(--font-down-2);
+ color: var(--primary-900);
+ }
+
+ &__hint-close {
+ margin-left: auto;
+ flex-shrink: 0;
+ padding: 0;
+ }
+
+ &__hint-close .d-icon {
+ margin: 0;
+ }
+
+ &__section {
+ border: 1px solid;
+ border-color: light-dark(var(--primary-100), var(--primary-200));
+ border-radius: var(--d-border-radius);
+ padding: var(--space-2);
+ background-color: light-dark(var(--secondary), var(--primary-50));
+ flex: 1;
+ display: flex;
+ flex-direction: column;
+ min-height: 0;
+ }
+
+ &__header {
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ gap: var(--space-2);
+ margin-bottom: var(--space-2);
+ border-bottom: 2px solid var(--primary-low);
+ }
+
+ &__header-actions {
+ display: flex;
+ align-items: stretch;
+ gap: var(--space-1);
+ }
+
+ &__title {
+ display: flex;
+ align-items: center;
+ gap: var(--space-2);
+ font-size: var(--font-down-1);
+ font-weight: 700;
+ margin: 0;
+ text-transform: uppercase;
+ letter-spacing: 0.05em;
+ font-family: monospace;
+ color: var(--primary-800);
+ }
+
+ &__title-meta {
+ margin-left: auto;
+ color: var(--primary-medium);
+ font-size: var(--font-down-2);
+ font-weight: 400;
+ text-transform: none;
+ }
+
+ &__title-info {
+ color: var(--primary-medium);
+ font-size: var(--font-down-2);
+ font-weight: 400;
+ text-transform: none;
+ }
+
+ &__subsection + &__subsection {
+ margin-top: var(--space-2);
+ }
+
+ &__subtitle {
+ display: flex;
+ align-items: center;
+ gap: var(--space-2);
+ color: var(--primary-medium);
+ font-family: monospace;
+ font-size: var(--font-down-2);
+ font-weight: 700;
+ letter-spacing: 0.05em;
+ margin: 0 0 var(--space-1);
+ text-transform: uppercase;
+ }
+
+ &__empty {
+ color: var(--primary-medium);
+ font-size: var(--font-down-1);
+ font-style: italic;
+ }
+
+ &__tabs {
+ display: flex;
+ align-items: stretch;
+ }
+
+ &__tab {
+ padding: var(--space-1) var(--space-3);
+ border: 0;
+ background: transparent;
+ cursor: pointer;
+ font-size: var(--font-down-1);
+ color: var(--primary-medium);
+ border-bottom: 2px solid transparent;
+ margin-bottom: -2px;
+
+ &:hover {
+ color: var(--primary);
+ }
+
+ &.is-active {
+ color: var(--tertiary);
+ border-bottom-color: var(--tertiary);
+ }
+ }
+
+ &__icon-btn {
+ display: inline-flex;
+ align-items: center;
+ justify-content: center;
+ background: transparent;
+ border: 0;
+ padding: var(--space-1);
+ color: var(--primary-medium);
+ cursor: pointer;
+ border-radius: var(--d-border-radius);
+
+ &:hover:not([disabled]) {
+ color: var(--primary);
+ background: var(--primary-very-low);
+ }
+
+ &[disabled] {
+ opacity: 0.4;
+ cursor: not-allowed;
+ }
+
+ .d-icon {
+ margin: 0;
+ }
+ }
+
+ &__pin-btn.is-pinned {
+ color: var(--tertiary);
+ }
+
+ &__pin-banner {
+ display: flex;
+ align-items: center;
+ gap: var(--space-2);
+ padding: var(--space-1) var(--space-2);
+ margin: 0;
+ background: transparent;
+ border-left: 2px solid var(--tertiary);
+ color: var(--primary-medium);
+ font-size: var(--font-down-1);
+
+ .d-icon {
+ color: var(--tertiary);
+ flex-shrink: 0;
+ }
+ }
+
+ &__pin-banner-text {
+ flex: 1;
+ }
+
+ &__unpin-btn {
+ padding: 0;
+ color: var(--tertiary);
+ font-size: var(--font-down-1);
+
+ &:hover {
+ text-decoration: underline;
+ }
+ }
+
+ &__editor {
+ display: flex;
+ flex-direction: column;
+ gap: var(--space-1);
+ margin-top: var(--space-1);
+ }
+
+ &__editor-toolbar {
+ display: flex;
+ align-items: center;
+ gap: var(--space-1);
+ flex-wrap: wrap;
+ }
+
+ &__editor-size {
+ margin-left: auto;
+ color: var(--primary-medium);
+ font-size: var(--font-down-2);
+ font-family: monospace;
+
+ &--near {
+ color: var(--love);
+ }
+
+ &--exceeded {
+ color: var(--workflow-status-error);
+ font-weight: 700;
+ }
+ }
+
+ &__editor-codemirror {
+ border: 1px solid;
+ border-color: light-dark(var(--primary-100), var(--primary-200));
+ border-radius: var(--d-border-radius);
+ overflow: hidden;
+ font-size: var(--font-down-1);
+
+ .cm-editor {
+ max-height: 50vh;
+ }
+
+ &--read-only .cm-editor {
+ background-color: light-dark(var(--primary-very-low), var(--primary-100));
+ }
+ }
+
+ &__editor-read {
+ margin: 0;
+ padding: var(--space-2);
+ background-color: light-dark(var(--primary-very-low), var(--primary-100));
+ border: 1px solid;
+ border-color: light-dark(var(--primary-100), var(--primary-200));
+ border-radius: var(--d-border-radius);
+ font-size: var(--font-down-1);
+ font-family: monospace;
+ white-space: pre-wrap;
+ word-break: break-word;
+ max-height: 50vh;
+ overflow: auto;
+ }
+
+ &__editor-loading {
+ padding: var(--space-2);
+ color: var(--primary-medium);
+ font-style: italic;
+ font-size: var(--font-down-1);
+ }
+
+ &__editor-error,
+ &__editor-notice {
+ display: flex;
+ align-items: flex-start;
+ gap: var(--space-1);
+ margin: 0;
+ padding: var(--space-1) var(--space-2);
+ font-size: var(--font-down-1);
+ }
+
+ &__empty-state {
+ flex: 1;
+ display: flex;
+ flex-direction: column;
+ align-items: center;
+ justify-content: center;
+ gap: var(--space-3);
+ padding: var(--space-4);
+ text-align: center;
+ }
+
+ &__empty-state-title {
+ margin: 0;
+ color: var(--primary);
+ font-size: var(--font-up-2);
+ font-weight: 600;
+ }
+
+ &__empty-state-btn {
+ padding: var(--space-2) var(--space-4);
+ font-size: var(--font-0);
+ }
+}
diff --git a/plugins/discourse-workflows/assets/stylesheets/common/context/schema-field.scss b/plugins/discourse-workflows/assets/stylesheets/common/context/schema-field.scss
new file mode 100644
index 00000000000..fab715e2305
--- /dev/null
+++ b/plugins/discourse-workflows/assets/stylesheets/common/context/schema-field.scss
@@ -0,0 +1,65 @@
+.workflows-schema-field-list {
+ list-style: none;
+ margin: 0;
+ padding: 0;
+
+ &.is-nested {
+ padding-left: var(--space-9);
+ }
+}
+
+.workflows-schema-field {
+ font-family: monospace;
+
+ &__row {
+ display: flex;
+ align-items: center;
+ padding: 0.35em 0;
+ }
+
+ &.has-children > &__row {
+ &:hover .workflows-schema-field__key {
+ color: var(--primary);
+ }
+ }
+
+ &__toggle {
+ color: var(--primary-medium);
+ margin-right: 0.25em;
+ }
+
+ &__key {
+ border: 1px solid var(--primary-200);
+ padding: var(--space-half) var(--space-1);
+ color: var(--primary-800);
+ border-radius: 2px;
+ gap: var(--space-1);
+ display: flex;
+ align-items: center;
+ cursor: grab;
+
+ &:hover {
+ background-color: var(--primary-100);
+ border-color: var(--primary-300);
+ color: var(--primary);
+
+ .workflows-schema-field__key-icon {
+ border-color: var(--primary-300);
+ }
+ }
+ }
+
+ &__key-icon {
+ border-right: 1px solid var(--primary-200);
+ padding-right: var(--space-1);
+ font-size: var(--font-down-1);
+ }
+
+ &__type {
+ font-size: var(--font-down-2);
+ padding: 0.1em 0.5em;
+ border-radius: 0.75em;
+ font-weight: 700;
+ border: 1px solid;
+ }
+}
diff --git a/plugins/discourse-workflows/assets/stylesheets/common/data-table/data-tables.scss b/plugins/discourse-workflows/assets/stylesheets/common/data-table/data-tables.scss
new file mode 100644
index 00000000000..b8af711516d
--- /dev/null
+++ b/plugins/discourse-workflows/assets/stylesheets/common/data-table/data-tables.scss
@@ -0,0 +1,227 @@
+.workflows-data-tables-manager {
+ &__name-link {
+ background: none;
+ border: none;
+ padding: 0;
+ cursor: pointer;
+ color: var(--tertiary);
+
+ &:hover {
+ text-decoration: underline;
+ }
+ }
+}
+
+.workflows-data-table-viewer {
+ &__header {
+ display: flex;
+ align-items: center;
+ gap: var(--space-3);
+ margin-bottom: var(--space-4);
+ }
+
+ &__title,
+ &__title-input {
+ background: none;
+ border: none;
+ padding: 0;
+ margin: 0;
+ flex: 1;
+ font: inherit;
+ font-size: var(--font-up-3);
+ font-weight: 700;
+ color: inherit;
+ line-height: inherit;
+ box-sizing: content-box;
+ }
+
+ &__title {
+ cursor: text;
+ text-align: left;
+ }
+
+ &__title-input {
+ // stylelint-disable declaration-no-important
+ font: inherit !important;
+ font-size: var(--font-up-3) !important;
+ font-weight: 700 !important;
+ line-height: inherit !important;
+ outline: none !important;
+ border: none !important;
+ padding: 0 var(--space-1) !important;
+ margin: 0 !important;
+ box-sizing: content-box !important;
+ background: var(--primary-very-low) !important;
+ border-radius: var(--d-border-radius) !important;
+ flex: 0 1 auto !important;
+ // stylelint-enable declaration-no-important
+ }
+
+ &__actions {
+ display: flex;
+ gap: var(--space-2);
+ }
+
+ &__scroll {
+ overflow-x: auto;
+ }
+
+ &__table {
+ border-collapse: collapse;
+ width: 100%;
+ min-width: max-content;
+
+ th,
+ td {
+ padding: 0;
+ border: 1px solid var(--primary-low);
+ text-align: left;
+ min-width: 150px;
+ }
+
+ th {
+ padding: var(--space-2) var(--space-3);
+ background: var(--primary-very-low);
+ font-weight: 700;
+ white-space: nowrap;
+ }
+
+ th.--id,
+ td.--id {
+ min-width: 60px;
+ width: 60px;
+ }
+
+ th.--add-column,
+ td.--add-column {
+ min-width: 0;
+ width: 1px;
+ }
+
+ th.--actions,
+ td.--actions {
+ min-width: 50px;
+ width: 50px;
+ }
+ }
+
+ &__col-type {
+ font-size: var(--font-down-2);
+ color: var(--primary-medium);
+ margin-right: var(--space-1);
+ text-transform: uppercase;
+ }
+
+ &__col-name,
+ &__col-name-input {
+ background: none;
+ border: none;
+ padding: 0;
+ margin: 0;
+ font: inherit;
+ font-weight: 700;
+ color: inherit;
+ line-height: inherit;
+ box-sizing: content-box;
+ }
+
+ &__col-name {
+ cursor: text;
+ }
+
+ &__col-name-input {
+ // stylelint-disable declaration-no-important
+ outline: none !important;
+ border: none !important;
+ padding: 0 !important;
+ margin: 0 !important;
+ line-height: inherit !important;
+ box-sizing: content-box !important;
+ width: calc(var(--col-name-length) * 1ch) !important;
+ // stylelint-enable declaration-no-important
+ }
+
+ &__cell {
+ &.--id,
+ &.--system,
+ &.--actions {
+ padding: var(--space-2) var(--space-3);
+ }
+
+ &.--id,
+ &.--system {
+ color: var(--primary-medium);
+ font-size: var(--font-down-1);
+ white-space: nowrap;
+ }
+
+ &.--boolean {
+ padding: var(--space-2) var(--space-3);
+ }
+
+ &.--actions {
+ text-align: right;
+ white-space: nowrap;
+ }
+ }
+
+ &__cell-value {
+ display: block;
+ width: 100%;
+ min-height: 1.5em;
+ background: none;
+ border: none;
+ // stylelint-disable-next-line declaration-no-important
+ outline: none !important;
+ padding: var(--space-2) var(--space-3);
+
+ &.is-null {
+ color: var(--primary-low-mid);
+ font-style: italic;
+ }
+ margin: 0;
+ cursor: pointer;
+ text-align: left;
+ font: inherit;
+ color: inherit;
+ }
+
+ &__cell-input {
+ box-sizing: border-box;
+ width: 100%;
+ // stylelint-disable-next-line declaration-no-important
+ margin: 0 !important;
+ padding: var(--space-2) var(--space-3);
+ // stylelint-disable-next-line declaration-no-important
+ border: none !important;
+ border-radius: 0;
+ // stylelint-disable-next-line declaration-no-important
+ outline: none !important;
+ font: inherit;
+ }
+
+ &__checkbox {
+ cursor: pointer;
+ margin: 0;
+ }
+
+ &__empty {
+ text-align: center;
+ color: var(--primary-medium);
+ padding: var(--space-4);
+ }
+
+ &__add-row td {
+ border-bottom: 1px solid var(--primary-low);
+ }
+
+ &__th {
+ &.--id {
+ width: 60px;
+ }
+
+ &.--actions {
+ width: 50px;
+ }
+ }
+}
diff --git a/plugins/discourse-workflows/assets/stylesheets/common/editor/editor.scss b/plugins/discourse-workflows/assets/stylesheets/common/editor/editor.scss
new file mode 100644
index 00000000000..03bb0e0ae66
--- /dev/null
+++ b/plugins/discourse-workflows/assets/stylesheets/common/editor/editor.scss
@@ -0,0 +1,67 @@
+.workflows-editor {
+ display: flex;
+ flex-direction: column;
+ align-items: stretch;
+ height: calc(100vh - 200px);
+
+ &__body {
+ flex: 1 0 auto;
+ overflow: hidden;
+ position: relative;
+ display: flex;
+ flex-direction: row;
+ }
+
+ &__name-field {
+ position: absolute;
+ top: var(--space-3);
+ left: var(--space-3);
+ z-index: 2;
+ }
+
+ &__name-row {
+ display: flex;
+ align-items: stretch;
+ border: 1px solid var(--primary-low-mid);
+ border-radius: var(--d-border-radius);
+ background: var(--secondary);
+ box-shadow: 0 2px 8px rgb(0, 0, 0, 0.1);
+ overflow: hidden;
+
+ .form-kit__container {
+ margin: 0;
+ border: 0;
+ }
+
+ .form-kit__container-content {
+ width: auto;
+ }
+
+ .form-kit__field-toggle {
+ width: auto;
+ }
+ }
+
+ &__name-input {
+ width: 280px;
+ font-size: var(--font-up-2);
+ padding: var(--space-2);
+ text-align: left;
+ border: 0 !important;
+ outline: none !important;
+ box-shadow: none !important;
+ background: transparent;
+ }
+
+ &__name-toggle {
+ display: flex;
+ align-items: center;
+ padding: 0 var(--space-2);
+ }
+}
+
+.workflows-unpublished-draft-dialog {
+ .dialog-footer &__discard-btn {
+ margin-left: auto;
+ }
+}
diff --git a/plugins/discourse-workflows/assets/stylesheets/common/empty-state.scss b/plugins/discourse-workflows/assets/stylesheets/common/empty-state.scss
new file mode 100644
index 00000000000..1f6777740ae
--- /dev/null
+++ b/plugins/discourse-workflows/assets/stylesheets/common/empty-state.scss
@@ -0,0 +1,23 @@
+.workflows-empty-state {
+ display: flex;
+ flex-direction: column;
+ align-items: center;
+ padding: var(--space-8) var(--space-4);
+ border: 2px dashed var(--primary-low);
+ border-radius: var(--d-border-radius);
+ text-align: center;
+
+ &__title {
+ margin: 0 0 var(--space-2);
+ }
+
+ &__description {
+ color: var(--primary-medium);
+ margin: 0 0 var(--space-4);
+ }
+
+ &__icon {
+ font-size: var(--font-up-6);
+ margin-bottom: var(--space-3);
+ }
+}
diff --git a/plugins/discourse-workflows/assets/stylesheets/common/executions/execution-detail.scss b/plugins/discourse-workflows/assets/stylesheets/common/executions/execution-detail.scss
new file mode 100644
index 00000000000..a9e067f7535
--- /dev/null
+++ b/plugins/discourse-workflows/assets/stylesheets/common/executions/execution-detail.scss
@@ -0,0 +1,286 @@
+.workflows-execution-detail {
+ &__step {
+ border: 1.5px solid var(--primary-low);
+ border-radius: 0.375em;
+ padding: var(--space-3) var(--space-3);
+ margin-bottom: var(--space-3);
+
+ &.--success {
+ border-color: var(--workflow-status-success);
+ background: var(--workflow-status-success-low);
+ }
+
+ &.--error {
+ border-color: var(--workflow-status-error);
+ }
+
+ &.--running {
+ border-color: var(--workflow-status-running);
+ }
+
+ &.--skipped {
+ border-color: var(--primary-low);
+ opacity: 0.7;
+ }
+
+ &.--filtered {
+ border-color: var(--primary-medium);
+ opacity: 0.7;
+ }
+
+ &.--waiting {
+ border-color: var(--workflow-status-waiting);
+ }
+ }
+
+ &__step-header {
+ display: flex;
+ align-items: center;
+ gap: var(--space-2);
+ }
+
+ &__step-icon {
+ flex-shrink: 0;
+ width: 1.25em;
+ text-align: center;
+ color: var(--primary-medium);
+
+ .--kind-trigger & {
+ color: var(--workflow-node-color-orange);
+ }
+
+ .--kind-condition & {
+ color: var(--workflow-node-color-teal);
+ }
+
+ .--kind-action & {
+ color: var(--workflow-node-color-purple);
+ }
+
+ .--kind-flow & {
+ color: var(--workflow-node-color-indigo);
+ }
+ }
+
+ &__step-name {
+ font-weight: bold;
+ }
+
+ &__step-operation {
+ font-size: var(--font-down-1);
+ color: var(--primary-medium);
+
+ &::before {
+ content: "›";
+ margin-right: var(--space-1);
+ }
+ }
+
+ &__kind-badge {
+ font-size: var(--font-down-2);
+ font-weight: bold;
+ text-transform: lowercase;
+ letter-spacing: 0.04em;
+ padding: 0.15em 0.45em;
+ border-radius: 0.25em;
+
+ &.--trigger {
+ background: color-mix(
+ in srgb,
+ var(--workflow-node-color-orange) 15%,
+ transparent
+ );
+ color: var(--workflow-node-color-orange);
+ }
+
+ &.--condition {
+ background: color-mix(
+ in srgb,
+ var(--workflow-node-color-teal) 15%,
+ transparent
+ );
+ color: var(--workflow-node-color-teal);
+ }
+
+ &.--action {
+ background: color-mix(
+ in srgb,
+ var(--workflow-node-color-purple) 15%,
+ transparent
+ );
+ color: var(--workflow-node-color-purple);
+ }
+
+ &.--flow {
+ background: color-mix(
+ in srgb,
+ var(--workflow-node-color-indigo) 15%,
+ transparent
+ );
+ color: var(--workflow-node-color-indigo);
+ }
+ }
+
+ &__step-summary {
+ font-size: var(--font-down-1);
+ color: var(--workflow-status-error);
+ margin-top: var(--space-1);
+ padding-left: calc(1.25em + var(--space-2));
+ }
+
+ &__step-type {
+ font-size: var(--font-down-1);
+ color: var(--primary-medium);
+ }
+
+ &__step-badge {
+ font-size: var(--font-down-2);
+ font-weight: bold;
+ text-transform: lowercase;
+ padding: 0.1em 0.4em;
+ border-radius: 0.25em;
+
+ &.--success {
+ background: var(--workflow-status-success-low);
+ color: var(--workflow-status-success);
+ }
+
+ &.--error {
+ background: var(--workflow-status-error-low);
+ color: var(--workflow-status-error);
+ }
+
+ &.--running {
+ background: var(--workflow-status-running-low);
+ color: var(--workflow-status-running);
+ }
+
+ &.--skipped {
+ background: var(--primary-low);
+ color: var(--primary-medium);
+ }
+
+ &.--filtered {
+ background: var(--workflow-status-running-low);
+ color: var(--workflow-status-running);
+ }
+
+ &.--waiting {
+ background: var(--workflow-status-waiting-low);
+ color: var(--workflow-status-waiting);
+ }
+ }
+
+ &__step-time {
+ font-size: var(--font-down-1);
+ color: var(--primary-medium);
+ margin-left: auto;
+ }
+
+ &__step.--success .workflows-execution-detail__step-time {
+ color: var(--workflow-status-success);
+ }
+
+ &__step.--success .workflows-execution-detail__step-body {
+ border-color: var(--workflow-status-success);
+ }
+
+ &__conditions {
+ display: flex;
+ flex-direction: column;
+ gap: var(--space-1);
+ margin-bottom: var(--space-2);
+ }
+
+ &__condition {
+ display: flex;
+ align-items: center;
+ gap: var(--space-2);
+ font-size: var(--font-down-1);
+ padding: var(--space-1) var(--space-2);
+ border-radius: 0.25em;
+
+ &.--passed {
+ background: var(--workflow-status-success-low);
+ }
+
+ &.--failed {
+ background: var(--workflow-status-running-low);
+ }
+
+ code {
+ background: var(--primary-very-low);
+ padding: 0.1em 0.3em;
+ border-radius: 0.2em;
+ font-size: var(--font-down-1);
+ }
+ }
+
+ &__condition-result {
+ font-weight: bold;
+
+ .--passed > & {
+ color: var(--workflow-status-success);
+ }
+
+ .--failed > & {
+ color: var(--workflow-status-running);
+ }
+ }
+
+ &__condition-value {
+ display: inline-flex;
+ align-items: center;
+ gap: var(--space-2);
+ }
+
+ &__condition-expression {
+ color: var(--primary-medium);
+ background: none;
+ padding: 0;
+ font-size: var(--font-down-1);
+ }
+
+ &__condition-arrow {
+ color: var(--primary-medium);
+ }
+
+ &__condition-operator {
+ color: var(--primary-medium);
+ font-style: italic;
+ }
+
+ &__step-body {
+ margin-top: var(--space-2);
+ padding-top: var(--space-2);
+ border-top: 1px solid var(--primary-low);
+ font-size: var(--font-down-1);
+ }
+
+ &__item-count {
+ font-size: var(--font-down-1);
+ color: var(--primary-medium);
+ margin-left: var(--space-1);
+ }
+
+ &__step-section {
+ margin-bottom: var(--space-2);
+
+ pre {
+ background: var(--primary-very-low);
+ padding: var(--space-2);
+ border-radius: 0.25em;
+ font-size: var(--font-down-1);
+ max-height: 200px;
+ overflow: auto;
+ white-space: pre-wrap;
+ word-break: break-all;
+ }
+ }
+
+ &__footer {
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ }
+}
diff --git a/plugins/discourse-workflows/assets/stylesheets/common/executions/executions-manager.scss b/plugins/discourse-workflows/assets/stylesheets/common/executions/executions-manager.scss
new file mode 100644
index 00000000000..dfd00a27891
--- /dev/null
+++ b/plugins/discourse-workflows/assets/stylesheets/common/executions/executions-manager.scss
@@ -0,0 +1,31 @@
+.workflows-executions-manager {
+ &__status {
+ display: inline-flex;
+ align-items: center;
+ gap: var(--space-2);
+
+ .d-icon {
+ font-size: var(--font-up-1);
+ }
+
+ &.--success .d-icon {
+ color: var(--workflow-status-success);
+ }
+
+ &.--error .d-icon {
+ color: var(--workflow-status-error);
+ }
+
+ &.--running .d-icon {
+ color: var(--workflow-status-running);
+ }
+
+ &.--waiting .d-icon {
+ color: var(--workflow-status-waiting);
+ }
+
+ &.--pending .d-icon {
+ color: var(--primary-medium);
+ }
+ }
+}
diff --git a/plugins/discourse-workflows/assets/stylesheets/common/executions/executions.scss b/plugins/discourse-workflows/assets/stylesheets/common/executions/executions.scss
new file mode 100644
index 00000000000..1cb09a21823
--- /dev/null
+++ b/plugins/discourse-workflows/assets/stylesheets/common/executions/executions.scss
@@ -0,0 +1,44 @@
+.workflows-executions {
+ &__table {
+ width: 100%;
+
+ td {
+ padding: var(--space-2) var(--space-1);
+ }
+ }
+
+ &__badge {
+ font-size: var(--font-down-1);
+ padding: 0.2em 0.5em;
+ border-radius: 0.25em;
+
+ &.--success {
+ background: var(--workflow-status-success-low);
+ color: var(--workflow-status-success);
+ }
+
+ &.--error {
+ background: var(--workflow-status-error-low);
+ color: var(--workflow-status-error);
+ }
+
+ &.--running {
+ background: var(--workflow-status-running-low);
+ color: var(--workflow-status-running);
+ }
+
+ &.--pending {
+ background: var(--primary-low);
+ color: var(--primary-medium);
+ }
+ }
+
+ &__time {
+ font-size: var(--font-down-1);
+ color: var(--primary-medium);
+ }
+
+ &__empty {
+ color: var(--primary-medium);
+ }
+}
diff --git a/plugins/discourse-workflows/assets/stylesheets/common/form/workflows-form.scss b/plugins/discourse-workflows/assets/stylesheets/common/form/workflows-form.scss
new file mode 100644
index 00000000000..ce7f48a46a0
--- /dev/null
+++ b/plugins/discourse-workflows/assets/stylesheets/common/form/workflows-form.scss
@@ -0,0 +1,71 @@
+.workflows-form-page {
+ display: flex;
+ justify-content: center;
+ padding: 4em 1em;
+ min-height: 100vh;
+ box-sizing: border-box;
+}
+
+.workflows-form {
+ max-width: 500px;
+ width: 100%;
+ padding: 2em 2.5em;
+ box-sizing: border-box;
+ background: var(--primary-very-low);
+ border: 1px solid var(--primary-low);
+ border-radius: 12px;
+ box-shadow: var(--shadow-footer-nav);
+ align-self: flex-start;
+
+ &__header {
+ text-align: center;
+ margin-bottom: 1.5em;
+ }
+
+ &__test-banner {
+ margin: 0 0 var(--space-4);
+ padding: var(--space-2) var(--space-3);
+ border: 1px solid var(--workflow-status-running);
+ border-radius: var(--d-border-radius);
+ background: var(--workflow-status-running-low);
+ color: var(--primary-high);
+ font-size: var(--font-down-1);
+ text-align: center;
+ }
+
+ &__title {
+ margin: 0 0 0.25em;
+ font-size: var(--font-up-3);
+ }
+
+ &__description {
+ color: var(--primary-medium);
+ margin: 0;
+ }
+
+ .form-kit__section {
+ margin-bottom: 0;
+ }
+
+ &__complete,
+ &__error {
+ text-align: center;
+ padding: 2em 0;
+ }
+
+ &__error {
+ color: var(--workflow-status-error);
+ }
+
+ &__completion-title {
+ margin-bottom: 0.5em;
+ font-size: var(--font-up-2);
+ font-weight: 700;
+ line-height: var(--line-height-medium);
+ }
+
+ &__completion-message,
+ &__completion-text {
+ color: var(--primary);
+ }
+}
diff --git a/plugins/discourse-workflows/assets/stylesheets/common/index.scss b/plugins/discourse-workflows/assets/stylesheets/common/index.scss
new file mode 100644
index 00000000000..d2704338743
--- /dev/null
+++ b/plugins/discourse-workflows/assets/stylesheets/common/index.scss
@@ -0,0 +1,25 @@
+@import "colors";
+@import "workflows-index";
+@import "editor/editor";
+@import "canvas/canvas";
+@import "canvas/hover-toolbar";
+@import "canvas/node-panel";
+@import "canvas/sticky-note";
+@import "configurator/configurator";
+@import "configurator/configurator-modal";
+@import "configurator/select-with-action";
+@import "configurator/url-preview";
+@import "context/context-panel";
+@import "context/schema-field";
+@import "variable/variable-input";
+@import "variable/variables-manager";
+@import "executions/executions";
+@import "executions/executions-manager";
+@import "executions/execution-detail";
+@import "data-table/data-tables";
+@import "settings";
+@import "form/workflows-form";
+@import "empty-state";
+@import "templates";
+@import "admin-table";
+@import "admin-page";
diff --git a/plugins/discourse-workflows/assets/stylesheets/common/settings.scss b/plugins/discourse-workflows/assets/stylesheets/common/settings.scss
new file mode 100644
index 00000000000..f722b517e83
--- /dev/null
+++ b/plugins/discourse-workflows/assets/stylesheets/common/settings.scss
@@ -0,0 +1,33 @@
+.workflows-settings {
+ display: flex;
+ flex-direction: column;
+ gap: var(--space-6);
+ padding: var(--space-4) 0;
+
+ &__section {
+ padding: var(--space-4);
+
+ &.--danger {
+ border: 1px solid var(--workflow-status-error-low);
+ border-radius: var(--d-border-radius);
+ }
+ }
+
+ &__section-title {
+ font-size: var(--font-up-1);
+ margin: 0 0 var(--space-2) 0;
+
+ .--danger & {
+ color: var(--workflow-status-error);
+ }
+ }
+
+ &__section-description {
+ color: var(--primary-medium);
+ margin: 0 0 var(--space-3) 0;
+ }
+
+ .form-kit__field-custom {
+ width: 100% !important;
+ }
+}
diff --git a/plugins/discourse-workflows/assets/stylesheets/common/templates.scss b/plugins/discourse-workflows/assets/stylesheets/common/templates.scss
new file mode 100644
index 00000000000..76d957e883e
--- /dev/null
+++ b/plugins/discourse-workflows/assets/stylesheets/common/templates.scss
@@ -0,0 +1,55 @@
+.workflows-templates {
+ display: grid;
+ grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
+ gap: var(--space-4);
+
+ &__tile {
+ display: flex;
+ flex-direction: column;
+ gap: var(--space-3);
+ padding: var(--space-4);
+ background: var(--primary-very-low);
+ border: 1px solid var(--primary-low);
+ border-radius: var(--d-border-radius);
+ cursor: pointer;
+ text-align: left;
+
+ &:hover {
+ border-color: var(--primary-medium);
+ }
+
+ &[disabled] {
+ opacity: 0.6;
+ cursor: wait;
+ }
+ }
+
+ &__description {
+ font-size: var(--font-0);
+ color: var(--primary);
+ line-height: var(--line-height-large);
+ }
+
+ &__icons {
+ display: flex;
+ gap: var(--space-2);
+ }
+
+ &__icon {
+ display: inline-flex;
+ align-items: center;
+ justify-content: center;
+ width: 32px;
+ height: 32px;
+ border-radius: var(--d-border-radius);
+ background: var(--primary-low);
+ color: var(--primary-high);
+ font-size: var(--font-down-1);
+
+ &.--overflow {
+ font-size: var(--font-down-2);
+ font-weight: 700;
+ color: var(--primary-medium);
+ }
+ }
+}
diff --git a/plugins/discourse-workflows/assets/stylesheets/common/variable/variable-input.scss b/plugins/discourse-workflows/assets/stylesheets/common/variable/variable-input.scss
new file mode 100644
index 00000000000..b6d1046a7bc
--- /dev/null
+++ b/plugins/discourse-workflows/assets/stylesheets/common/variable/variable-input.scss
@@ -0,0 +1,338 @@
+.workflows-variable-input {
+ width: 100%;
+ border: 1px solid var(--primary-low-mid);
+ border-radius: var(--d-border-radius);
+ background: var(--secondary);
+ box-sizing: border-box;
+
+ .cm-editor .cm-content {
+ min-height: 60px;
+ padding: 0.5em;
+ font-size: var(--font-0);
+ font-family: inherit;
+ }
+
+ .cm-editor .cm-lineWrapping {
+ word-break: break-all;
+ }
+
+ &:focus-within {
+ outline: none;
+ border-color: var(--tertiary);
+ box-shadow: 0 0 0 1px var(--tertiary);
+ }
+
+ .is-drag-over & {
+ border-color: var(--tertiary);
+ background: var(--tertiary-50);
+ }
+
+ .cm-editor {
+ background: transparent;
+ color: var(--primary);
+
+ &.cm-focused {
+ outline: none;
+ }
+
+ .cm-cursor {
+ border-left-color: var(--primary);
+ }
+
+ .cm-selectionBackground {
+ background: var(--tertiary-low) !important;
+ }
+
+ .cm-content {
+ caret-color: var(--primary);
+ }
+
+ .cm-activeLine {
+ background: transparent;
+ }
+
+ // Base override for all CM tooltips — CM injects a light baseTheme
+ // dynamically, so we must override it for dark mode support.
+ .cm-tooltip {
+ z-index: z("modal", "tooltip") !important;
+ background: var(--secondary);
+ border: 1px solid var(--primary-low-mid);
+ border-radius: var(--d-border-radius);
+ color: var(--primary);
+ font-size: var(--font-down-2);
+ box-shadow: var(--shadow-dropdown);
+ }
+
+ .cm-tooltip-autocomplete {
+ > ul {
+ font-family: inherit;
+
+ > li {
+ padding: 1px 0.4em;
+ }
+ }
+
+ li[aria-selected] {
+ background: var(--tertiary-low);
+ color: var(--primary);
+ }
+ }
+
+ // Section headers in the autocomplete dropdown
+ .cm-expr-section-header {
+ padding: 0.1em 0.4em;
+ font-size: var(--font-down-3);
+ font-weight: 700;
+ color: var(--primary-medium);
+ text-transform: uppercase;
+ letter-spacing: 0.05em;
+ border-bottom: 1px solid var(--primary-low);
+ }
+
+ // Info tooltip panel next to autocomplete — inherits font-size
+ // from .cm-tooltip (--font-down-2) for consistency with the list.
+ .cm-completionInfo {
+ padding: 0.3em 0.5em;
+ max-width: 200px;
+ width: 200px;
+ box-sizing: border-box;
+ overflow-wrap: break-word;
+ }
+
+ .cm-expr-completion-info {
+ &__signature {
+ font-family: var(--d-font-family--monospace);
+ font-weight: 600;
+ margin-bottom: 0.15em;
+ color: var(--primary-medium);
+ word-break: break-all;
+ }
+
+ &__description {
+ color: var(--primary-high);
+ margin-bottom: 0.15em;
+ line-height: 1.3;
+ }
+
+ &__example code {
+ background: var(--primary-very-low);
+ padding: 0.1em 0.2em;
+ border-radius: 2px;
+ font-family: var(--d-font-family--monospace);
+ font-size: 0.9em;
+ word-break: break-all;
+ }
+ }
+
+ // Syntax highlighting — theme-aware via Discourse CSS vars
+ .cm-wf-text {
+ color: var(--primary);
+ }
+
+ .cm-wf-brace {
+ color: var(--tertiary);
+ opacity: 0.7;
+ font-weight: 700;
+ }
+
+ .cm-wf-keyword {
+ color: var(--tertiary);
+ }
+
+ .cm-wf-string {
+ color: var(--success);
+ }
+
+ .cm-wf-number {
+ color: var(--success);
+ }
+
+ .cm-wf-bool,
+ .cm-wf-null {
+ color: var(--tertiary);
+ }
+
+ .cm-wf-variable {
+ color: var(--primary-high);
+ }
+
+ .cm-wf-property {
+ color: var(--primary-high);
+ }
+
+ .cm-wf-function {
+ color: var(--tertiary-hover);
+ }
+
+ .cm-wf-operator,
+ .cm-wf-punctuation {
+ color: var(--primary);
+ }
+
+ .cm-wf-comment {
+ color: var(--primary-medium);
+ font-style: italic;
+ }
+
+ // Validation underlines
+ .cm-wf-error {
+ text-decoration: wavy underline var(--danger);
+ text-decoration-skip-ink: none;
+ text-underline-offset: 3px;
+ }
+
+ // Expression state colors — applied by backend evaluation results
+ .cm-wf-valid-expression {
+ background: color-mix(in srgb, var(--success) 12%, transparent);
+ border-radius: 2px;
+ }
+
+ .cm-wf-invalid-expression {
+ background: color-mix(in srgb, var(--danger) 20%, transparent);
+ border-radius: 2px;
+ outline: 1px solid color-mix(in srgb, var(--danger) 30%, transparent);
+ }
+
+ .cm-wf-empty-expression {
+ background: color-mix(in srgb, var(--primary-low-mid) 20%, transparent);
+ border-radius: 2px;
+ outline: 1px dashed
+ color-mix(in srgb, var(--primary-medium) 40%, transparent);
+ }
+
+ .cm-wf-warning-expression {
+ background: color-mix(in srgb, var(--highlight-medium) 40%, transparent);
+ border-radius: 2px;
+ }
+
+ .cm-wf-pending-expression {
+ background: color-mix(in srgb, var(--primary-low-mid) 30%, transparent);
+ border-radius: 2px;
+ }
+
+ // Drop cursor during variable drag
+ .cm-dropCursor {
+ position: absolute;
+ width: 2px;
+ background: var(--tertiary);
+ pointer-events: none;
+ z-index: 10;
+ }
+ }
+
+ .cm-tooltip-hover {
+ background: var(--secondary) !important;
+ border: 1px solid var(--primary-low-mid) !important;
+ border-radius: var(--d-border-radius);
+ box-shadow: var(--shadow-dropdown);
+ }
+
+ .cm-wf-hover-tooltip {
+ padding: 0.4em 0.6em;
+ max-width: 260px;
+ font-size: var(--font-down-2);
+
+ &__name {
+ color: var(--tertiary);
+ margin-bottom: 0.15em;
+ }
+
+ &__description {
+ color: var(--primary-high);
+ line-height: 1.3;
+ }
+ }
+
+ .workflows-property-engine__collection-fields & {
+ background: transparent;
+ min-height: 100px;
+
+ &:focus-within {
+ box-shadow: none;
+ }
+ }
+}
+
+.fk-d-tooltip__content[data-identifier="expression-preview"] {
+ // Above normal content, below modal tooltips/popovers where CM autocomplete lives
+ z-index: z("tooltip") !important;
+ box-sizing: border-box;
+ pointer-events: auto;
+ user-select: text;
+
+ .fk-d-tooltip__inner-content {
+ display: block;
+ width: 100%;
+ pointer-events: auto;
+ user-select: text;
+ }
+}
+
+.expression-preview {
+ padding: 0.3em 0.5em;
+ font-size: var(--font-down-2);
+ font-family: var(--d-font-family--monospace);
+ max-height: 80px;
+ overflow-y: auto;
+
+ &__result {
+ white-space: pre-wrap;
+ word-break: break-word;
+ }
+
+ &__label {
+ float: right;
+ font-weight: 700;
+ font-size: var(--font-down-3);
+ text-transform: uppercase;
+ letter-spacing: 0.05em;
+ color: var(--primary-low-mid);
+ margin-left: 0.5em;
+ user-select: none;
+ pointer-events: none;
+ }
+
+ &__error-text {
+ color: var(--danger);
+ background: color-mix(in srgb, var(--danger) 10%, transparent);
+ border-radius: 2px;
+ padding: 0.1em 0.2em;
+ }
+
+ &__resolved {
+ &.--valid {
+ color: var(--tertiary);
+ }
+
+ &.--invalid,
+ &.--undefined {
+ color: var(--danger);
+ background: color-mix(in srgb, var(--danger) 10%, transparent);
+ border-radius: 2px;
+ padding: 0.1em 0.2em;
+ }
+
+ &.--warning {
+ color: var(--warning, light-dark(#b5651d, #e6a33e));
+ background: color-mix(in srgb, var(--warning, #e6a33e) 10%, transparent);
+ border-radius: 2px;
+ padding: 0.1em 0.2em;
+ font-style: italic;
+ }
+
+ &.--pending {
+ color: var(--primary-medium);
+ }
+
+ &.--label {
+ background: color-mix(in srgb, var(--primary-low-mid) 40%, transparent);
+ border-radius: 2px;
+ padding: 0.1em 0.4em;
+ font-size: var(--font-down-1);
+ }
+ }
+
+ &__plaintext {
+ color: var(--primary);
+ }
+}
diff --git a/plugins/discourse-workflows/assets/stylesheets/common/variable/variables-manager.scss b/plugins/discourse-workflows/assets/stylesheets/common/variable/variables-manager.scss
new file mode 100644
index 00000000000..551ea8cfda1
--- /dev/null
+++ b/plugins/discourse-workflows/assets/stylesheets/common/variable/variables-manager.scss
@@ -0,0 +1,7 @@
+.workflows-variables {
+ &__creator {
+ display: inline-flex;
+ align-items: center;
+ gap: var(--space-1);
+ }
+}
diff --git a/plugins/discourse-workflows/assets/stylesheets/common/workflows-index.scss b/plugins/discourse-workflows/assets/stylesheets/common/workflows-index.scss
new file mode 100644
index 00000000000..a39f13eb798
--- /dev/null
+++ b/plugins/discourse-workflows/assets/stylesheets/common/workflows-index.scss
@@ -0,0 +1,100 @@
+.workflows-index {
+ &__tabs {
+ display: flex;
+ border-bottom: 2px solid var(--primary-low);
+ margin-bottom: var(--space-4);
+ }
+
+ &__tab {
+ padding: var(--space-2) var(--space-4);
+ border: 0;
+ background: transparent;
+ cursor: pointer;
+ font-size: var(--font-0);
+ color: var(--primary-medium);
+ border-bottom: 2px solid transparent;
+ margin-bottom: -2px;
+
+ &:hover {
+ color: var(--primary);
+ }
+
+ &.is-active {
+ color: var(--tertiary);
+ border-bottom-color: var(--tertiary);
+ }
+ }
+
+ &__name-content {
+ display: inline-flex;
+ align-items: center;
+ gap: var(--space-2);
+ }
+
+ &__name-link {
+ min-width: 0;
+ }
+
+ &__last-editor-link {
+ display: inline-flex;
+ align-items: center;
+ gap: var(--space-1);
+ }
+
+ &__warning {
+ display: inline-flex;
+ align-items: center;
+ color: var(--workflow-status-error);
+ line-height: 1;
+ }
+
+ &__empty {
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ box-sizing: border-box;
+ width: 100%;
+ padding: var(--space-8) var(--space-4);
+ background: var(--primary-very-low);
+ border: 1px solid var(--primary-low);
+ border-radius: var(--d-border-radius);
+ }
+
+ &__badge {
+ display: inline-flex;
+ align-items: center;
+ gap: 0.4em;
+ font-size: var(--font-down-1);
+ padding: 0.25em 0.6em;
+ border-radius: var(--d-border-radius);
+ border: 1px solid var(--primary-low);
+ color: var(--primary-high);
+
+ &::before {
+ content: "";
+ display: inline-block;
+ width: 0.55em;
+ height: 0.55em;
+ border-radius: 50%;
+ }
+
+ &.is-published::before {
+ background: var(--workflow-status-success);
+ }
+
+ &.is-unpublished::before {
+ background: var(--workflow-status-running);
+ }
+
+ &.is-unpublished-changes {
+ border-color: var(--tertiary-medium);
+ background: var(--tertiary-low);
+ color: var(--primary);
+ font-weight: 600;
+
+ &::before {
+ background: var(--tertiary);
+ }
+ }
+ }
+}
diff --git a/plugins/discourse-workflows/config/locales/client.en.yml b/plugins/discourse-workflows/config/locales/client.en.yml
new file mode 100644
index 00000000000..26eca1cfb43
--- /dev/null
+++ b/plugins/discourse-workflows/config/locales/client.en.yml
@@ -0,0 +1,911 @@
+en:
+ admin_js:
+ admin:
+ logs:
+ staff_actions:
+ actions:
+ discourse_workflows_credential_created: "Create workflow credential"
+ discourse_workflows_credential_destroyed: "Delete workflow credential"
+ discourse_workflows_credential_updated: "Update workflow credential"
+ discourse_workflows_data_table_column_created: "Create workflow data table column"
+ discourse_workflows_data_table_column_destroyed: "Delete workflow data table column"
+ discourse_workflows_data_table_column_renamed: "Rename workflow data table column"
+ discourse_workflows_data_table_created: "Create workflow data table"
+ discourse_workflows_data_table_destroyed: "Delete workflow data table"
+ discourse_workflows_data_table_updated: "Update workflow data table"
+ discourse_workflows_variable_created: "Create workflow variable"
+ discourse_workflows_variable_destroyed: "Delete workflow variable"
+ discourse_workflows_variable_updated: "Update workflow variable"
+ discourse_workflows_workflow_created: "Create workflow"
+ discourse_workflows_workflow_destroyed: "Delete workflow"
+ js:
+ discourse_workflows:
+ node_unavailable:
+ default: "This node is currently unavailable"
+ short: "Unavailable"
+ node_issues:
+ title: "Configuration issues"
+ required: "%{label} is required"
+ unknown: "%{label}: %{message}"
+ header_auth:
+ name: "Header name"
+ value: "Header value"
+ run_scope:
+ per_item: "One run per item"
+ all_items: "One run for all items"
+ admin:
+ title: "Workflows"
+ title: "Workflows"
+ templates:
+ title: "Templates"
+ description: "Start with a pre-built workflow template"
+ new_workflow: "New workflow"
+ default_workflow_name: "My workflow"
+ delete: "Delete"
+ edit: "Edit"
+ save: "Save"
+ cancel: "Cancel"
+ more_options: "More options"
+ publish: "Publish"
+ discard_changes: "Discard changes"
+ discard_changes_confirmation: "Discard unpublished changes? This will restore the published workflow and remove the current draft."
+ published: "Published"
+ unpublish: "Unpublish"
+ unpublished: "Unpublished"
+ unpublished_changes: "Unpublished changes"
+ unpublished_changes_message: "You have unpublished changes"
+ unpublished_changes_message_detail: "Publish to make them live"
+ unpublished_changes_confirmation: "This workflow has unpublished changes. If you leave now, those changes will stay in draft and won't run until you publish them."
+ leave_without_publishing: "Leave without publishing"
+ keep_editing: "Keep editing"
+ workflow_name: "Workflow name"
+ last_editor: "Last editor"
+ last_update: "Last update"
+ last_run: "Last run"
+ status: "Status"
+ last_execution_never: "Never"
+ last_execution_failed: "Last execution failed"
+ create_first_workflow: "Create your first workflow"
+ empty_title: "%{username}, let's set up a workflow"
+ empty_description: "Workflows automate tasks by connecting triggers, conditions, and actions into a visual flow"
+ delete_confirm: "Are you sure you want to delete the workflow \"%{name}\"?"
+ tabs:
+ workflow: "Workflow"
+ executions: "Executions"
+ settings: "Settings"
+ data_tables: "Data tables"
+ templates: "Templates"
+ credentials: "Credentials"
+ variables: "Variables"
+ all_workflows: "All workflows"
+ settings:
+ saved: "Settings saved"
+ error_workflow: "Error workflow"
+ error_workflow_description: "When this workflow fails, trigger the selected error workflow. If none is selected and this workflow has an Error trigger, it handles its own errors."
+ error_workflow_none: "None"
+ no_error_workflows_available: "No workflows with an Error trigger node are available"
+ timezone: "Timezone"
+ timezone_description: "Schedule triggers use this timezone. If unset, they use the site timezone."
+ danger_zone: "Danger zone"
+ delete_description: "Permanently delete this workflow and all its executions. This action cannot be undone."
+ add_node:
+ title: "Add step"
+ first_step: "Add first step"
+ browse_templates: "Browse templates"
+ search: "Search steps..."
+ categories:
+ discourse_triggers: "Discourse triggers"
+ triggers: "Triggers"
+ discourse_actions: "Discourse actions"
+ ai: "AI"
+ data: "Data transformation"
+ utilities: "Utilities"
+ flow: "Flow"
+ human_review: "Human review"
+ configurator:
+ title: "Configure"
+ save: "Done"
+ saving: "Saving"
+ saved: "Saved"
+ no_configuration: "This node has no configurable options"
+ description: "Note"
+ description_placeholder: "Add a note about this step..."
+ always_output_data: "Always output data"
+ always_output_data_help: "If on, this node emits an empty item when it would otherwise produce no items, so the next node still runs."
+ tabs:
+ parameters: "Parameters"
+ settings: "Settings"
+ drag_drop_hint_title: "Tip"
+ drag_drop_hint: "Drag and drop a property from this panel into a field"
+ output_context: "Output"
+ no_input_context: "No input data yet. It will appear after the first run."
+ no_input_fields: "No input fields"
+ environment: "Environment"
+ no_output_context: "No output data"
+ no_output_fields: "No output fields"
+ no_output_context_run_to_discover: "Run the workflow to discover output fields"
+ schema_input_label: "Input %{number}"
+ schema_item_count:
+ one: "%{count} item"
+ other: "%{count} items"
+ nodes:
+ "trigger:topic_closed": "Topic closed"
+ "trigger:post_created": "Post created"
+ "trigger:topic_created": "Topic created"
+ "trigger:topic_category_changed": "Topic category changed"
+ "trigger:topic_tag_changed": "Topic tag changed"
+ "trigger:webhook": "Webhook"
+ "trigger:manual": "Manual trigger"
+ "condition:if": "If"
+ "condition:filter": "Filter"
+ "action:topic_tags": "Topic tags"
+ "action:code": "Code"
+ "action:topic": "Topic"
+ "action:create_post": "Create post"
+ "action:set_fields": "Set fields"
+ "trigger:stale_topic": "Stale topic"
+ "trigger:schedule": "Schedule"
+ "flow:merge": "Merge"
+ "flow:loop_over_items": "Loop over items"
+ "action:split_out": "Split out"
+ "action:sort": "Sort"
+ "action:http_request": "HTTP request"
+ "action:data_table": "Data table"
+ "action:group": "Group"
+ "action:badge": "Badge"
+ "trigger:form": "Form trigger"
+ "action:form": "Form"
+ "action:limit": "Limit"
+ "action:log": "Log"
+ "action:markdown_table": "Markdown table"
+ "action:respond_to_webhook": "Respond to webhook"
+ "trigger:topic_admin_button": "Topic admin button"
+ "trigger:error": "Error trigger"
+ "flow:wait": "Wait"
+ node_descriptions:
+ "trigger:topic_closed": "Fires when a topic is closed by a user or auto-close timer"
+ "trigger:post_created": "Fires when a new post or reply is created"
+ "trigger:topic_created": "Fires when a new topic is created"
+ "trigger:topic_category_changed": "Fires when a topic is moved to a different category"
+ "trigger:topic_tag_changed": "Fires when tags are added to or removed from a topic"
+ "trigger:webhook": "Fires when an external service sends a webhook request"
+ "trigger:manual": "Fires when triggered manually by an admin"
+ "condition:if": "Branch the workflow based on a condition"
+ "condition:filter": "Continue only if conditions are met"
+ "action:topic_tags": "Add or remove tags on a topic"
+ "action:code": "Run custom JavaScript code"
+ "action:topic": "Create, retrieve, or list topics"
+ "action:create_post": "Create a reply in an existing topic"
+ "action:set_fields": "Set or modify data fields in the workflow context"
+ "trigger:stale_topic": "Fires when a topic has had no activity for a period"
+ "trigger:schedule": "Fires on a recurring schedule"
+ "flow:merge": "Merge data from multiple workflow branches"
+ "flow:loop_over_items": "Iterate over a list of items and run steps for each"
+ "action:split_out": "Split an array into individual items for parallel processing"
+ "action:sort": "Sort items by field values, randomly, or with custom code"
+ "action:http_request": "Make an HTTP request to an external API"
+ "action:data_table": "Read, write, or query a workflow data table"
+ "action:group": "Add or remove a user from a group"
+ "action:badge": "Grant or revoke a badge"
+ "trigger:form": "Generates a public web form and fires when it is submitted"
+ "action:form": "Adds a page to a multi-step form"
+ "action:limit": "Keep only the first or last N items"
+ "action:log": "Record key/value data to the execution log without affecting the workflow"
+ "action:markdown_table": "Build a markdown table from a list of items"
+ "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:error": "Fires when another workflow fails"
+ "flow:wait": "Pause workflow execution and resume after a delay or webhook callback"
+ topic_admin_button:
+ label: "Button label"
+ label_placeholder: "Run workflow"
+ icon: "Button icon"
+ if:
+ no_conditions_body: "Conditions are used to filter items based on their values"
+ add_condition: "Add condition"
+ conditions: "Conditions"
+ column: "Column"
+ field: "Field"
+ operator: "Operator"
+ value: "Value"
+ combinator:
+ title: "Match mode"
+ all: "All conditions must pass"
+ any: "Any condition can pass"
+ operators:
+ equals: "equals"
+ not_equals: "does not equal"
+ contains: "contains"
+ not_contains: "does not contain"
+ empty: "is empty"
+ not_empty: "is not empty"
+ gt: "greater than"
+ lt: "less than"
+ gte: "greater than or equal"
+ lte: "less than or equal"
+ "true": "is true"
+ "false": "is false"
+ topic_tags:
+ operation: "Operation"
+ operations:
+ add: "Add tag"
+ remove: "Remove tag"
+ topic_id: "Topic ID"
+ tag_names: "Tags"
+ actor_username: "Performed by user"
+ limit:
+ max_items: "Max items"
+ keep: "Keep"
+ keep_first: "First items"
+ keep_last: "Last items"
+ group:
+ operation: "Operation"
+ operations:
+ add: "Add user"
+ remove: "Remove user"
+ get: "Get group"
+ username: "User"
+ group_id: "Group"
+ group_id_placeholder: "Select a group"
+ manage_groups: "Manage groups"
+ actor_username: "Performed by user"
+ badge:
+ operation: "Operation"
+ operations:
+ grant: "Grant badge"
+ revoke: "Revoke badge"
+ username: "User"
+ badge_id: "Badge"
+ badge_id_placeholder: "Select a badge"
+ actor_username: "Performed by user"
+ create_post:
+ topic_id: "Topic ID"
+ raw: "Body"
+ raw_description: "Raw content for the reply"
+ reply_to_post_number: "Reply to post number"
+ reply_to_post_number_description: "Reply to a specific post number in the topic"
+ author_username: "Author"
+ topic:
+ operation: "Operation"
+ operations:
+ create: "Create topic"
+ get: "Get topic"
+ list: "List topics"
+ topic_id: "Topic ID"
+ title: "Title"
+ raw: "Body"
+ raw_description: "Raw content for the first post"
+ category_id: "Category"
+ tag_names: "Tags"
+ query: "Query"
+ query_description: "Filter query using the same syntax as `/filter` (e.g. category:support status:open order:activity)"
+ query_placeholder: "category:support status:open"
+ limit: "Limit"
+ limit_description: "Maximum number of topics to return (1-100, default 30)"
+ actor_username: "Performed by user"
+ set_fields:
+ mode: "Mode"
+ mode_manual: "Manual"
+ mode_raw: "JSON"
+ assignments: "Fields"
+ json_output: "JSON"
+ include_other_fields: "Include input fields"
+ include: "Input fields to include"
+ include_all: "All"
+ include_selected: "Selected"
+ include_except: "All except"
+ include_fields: "Fields to include"
+ include_fields_placeholder: "company, id"
+ exclude_fields: "Fields to exclude"
+ exclude_fields_placeholder: "debug, internal.notes"
+ options: "Options"
+ dot_notation: "Support dot notation"
+ ignore_conversion_errors: "Ignore type conversion errors"
+ type_string: "String"
+ type_number: "Number"
+ type_boolean: "Boolean"
+ type_array: "Array"
+ type_object: "Object"
+ add_field: "Add field"
+ code:
+ mode: "Mode"
+ mode_description: "Choose whether the code runs once per item or once for all items"
+ mode_run_once_for_each_item: "Run once for each item"
+ mode_run_once_for_all_items: "Run once for all items"
+ code: "JavaScript code"
+ code_description: "Access the previous step's output via $json. Return an object to pass data to the next step."
+ parameter_field:
+ fixed: "Fixed"
+ plain: "Plain"
+ dynamic: "Dynamic"
+ expression_preview:
+ result: "Result"
+ empty: "Empty"
+ undefined: "Undefined"
+ invalid: "Invalid JavaScript"
+ warning: "Missing function call"
+ pending: "Not resolved yet"
+ expression_docs:
+ vars:
+ input: "Current node input helpers. Use $input.item, $input.all(), $input.first(), $input.last(), or $input.params."
+ item_index: "Index of the input item currently being processed."
+ json: "JSON data of the current input item. Shorthand for $input.item.json."
+ trigger: "Alias for $json — the trigger node's output data."
+ site_settings: "Access Discourse site settings. Example: $site_settings.title"
+ current_user: "The user who triggered the workflow. Properties: id, username"
+ workflow_vars: "Workflow variables defined in the admin panel."
+ execution: "Execution metadata: id, workflow_id, workflow_name"
+ node_ref: "Reference a previous node's output. Example: $('Node Name').item.json"
+ methods:
+ input:
+ all: "Returns an array of the current node's input items."
+ first: "Returns the current node's first input item."
+ last: "Returns the current node's last input item."
+ property_engine:
+ add_item: "Add item"
+ add_option: "Add option"
+ add_field: "Add field"
+ clear_fields: "Clear fields"
+ remove_item: "Remove item"
+ dynamic_hint: "Must resolve to %{value}."
+ dynamic_values:
+ badge_id: "a badge ID"
+ boolean: "true or false"
+ category_id: "a category ID"
+ chat_channel_id: "a chat channel ID"
+ column_name: "a column name"
+ data_table_id: "a data table ID"
+ group_id: "a group ID"
+ id: "an ID"
+ number: "a number"
+ option_value: "an option value"
+ query_id: "a query ID"
+ tag_names: "tag names"
+ username: "a username"
+ user_or_group_name: "a username or group name"
+ add_attributes: "Attributes"
+ assignment_name: "Name"
+ assignment_type: "Type"
+ assignment_value: "Value"
+ max_items_reached:
+ one: "Limited to %{count} item"
+ other: "Limited to %{count} items"
+ webhook:
+ http_method: "HTTP method"
+ path: "Path"
+ path_placeholder: "my-webhook"
+ url_preview: "Webhook URL"
+ click_to_copy: "Click to copy"
+ copy_test_url: "Copy test URL"
+ listening_seconds: "Listening for test event for %{seconds}s"
+ cancel_test_listener: "Cancel"
+ response_mode: "Respond"
+ response_mode_on_received: "Immediately"
+ response_mode_last_node: "When last node finishes"
+ response_mode_response_node: "Using Respond to webhook node"
+ response_code: "Response code"
+ response_data: "Response data"
+ response_data_first_entry_json: "First entry JSON"
+ response_data_all_entries: "All entries"
+ response_data_no_data: "No data"
+ response_body: "Response body"
+ no_response_body: "No response body"
+ response_headers: "Response headers"
+ add_response_header: "Add response header"
+ ip_allowlist: "IP allowlist"
+ ignore_bots: "Ignore bots"
+ authentication: "Authentication"
+ authentication_none: "None"
+ authentication_basic_auth: "Basic auth"
+ authentication_bearer_auth: "Bearer token"
+ authentication_header_auth: "Header auth"
+ credential: "Credential"
+ stale_topic:
+ hours: "Hours with no reply"
+ description: "Fires when a topic has had no replies for the specified number of hours"
+ category_id: "Category"
+ category_id_description: "Only consider topics in this category"
+ tag_names: "Tags"
+ tag_names_description: "Only consider topics that have at least one of these tags"
+ topic_closed:
+ category_id: "Category"
+ category_id_description: "Only trigger for topics in this category"
+ tag_names: "Tags"
+ tag_names_description: "Only trigger for topics that have at least one of these tags"
+ post_created:
+ category_id: "Category"
+ category_id_description: "Only trigger for posts in this category"
+ tag_names: "Tags"
+ tag_names_description: "Only trigger for posts in topics that have at least one of these tags"
+ topic_created:
+ category_id: "Category"
+ category_id_description: "Only trigger for topics in this category"
+ tag_names: "Tags"
+ tag_names_description: "Only trigger for topics that have at least one of these tags"
+ topic_tag_changed:
+ category_id: "Category"
+ category_id_description: "Only trigger for topics in this category"
+ schedule:
+ rule: "Trigger rules"
+ add_rule: "Add rule"
+ field: "Trigger interval"
+ field_minutes: "Minutes"
+ field_hours: "Hours"
+ field_days: "Days"
+ field_weeks: "Weeks"
+ field_months: "Months"
+ field_cron_expression: "Custom (Cron)"
+ minutes_interval: "Minutes between triggers"
+ minutes_interval_description: "Must be in range 1-59"
+ hours_interval: "Hours between triggers"
+ hours_interval_description: "Must be in range 1-23"
+ days_interval: "Days between triggers"
+ days_interval_description: "Must be in range 1-31"
+ weeks_interval: "Weeks between triggers"
+ months_interval: "Months between triggers"
+ months_interval_description: "Must be in range 1-12"
+ trigger_at_day: "Trigger on weekdays"
+ trigger_at_day_of_month: "Trigger at day of month"
+ trigger_at_day_of_month_description: "If a month doesn't have this day, the node won't trigger"
+ trigger_at_hour: "Trigger at hour"
+ trigger_at_minute: "Trigger at minute"
+ expression: "Cron expression"
+ expression_description: "Standard 5-field cron (minute hour day-of-month month day-of-week). Example: 0 9 * * 1-5 for weekdays at 9 AM. <a href='https://crontab.guru/examples.html' target='_blank'>Help on cron</a>."
+ cron: "Cron expression"
+ cron_invalid: "Must be a valid 5-field cron expression"
+ wait:
+ resume: "Resume when"
+ resume_time_interval: "After time interval"
+ resume_webhook: "On webhook call"
+ wait_amount: "Wait"
+ wait_unit: "Unit"
+ wait_unit_seconds: "Seconds"
+ wait_unit_minutes: "Minutes"
+ wait_unit_hours: "Hours"
+ wait_unit_days: "Days"
+ webhook_info_description: "The webhook URL will be generated at run time. Reference the base URL in earlier nodes with the <code>$execution.resume_url</code> variable. If this node has a webhook suffix, append it to that URL."
+ http_method: "HTTP method"
+ response_mode: "Respond"
+ response_mode_on_received: "Immediately"
+ response_mode_last_node: "When last node finishes"
+ response_mode_response_node: "Using Respond to webhook node"
+ response_code: "Response code"
+ response_data: "Response data"
+ response_data_first_entry_json: "First entry JSON"
+ response_data_all_entries: "All entries"
+ response_data_no_data: "No data"
+ response_body: "Response body"
+ no_response_body: "No response body"
+ response_headers: "Response headers"
+ add_response_header: "Add response header"
+ ip_allowlist: "IP allowlist"
+ ignore_bots: "Ignore bots"
+ webhook_suffix: "Webhook suffix"
+ limit_wait_time: "Limit wait time"
+ timeout_amount: "Timeout after"
+ timeout_unit: "Timeout unit"
+ loop_over_items:
+ batch_size: "Batch size"
+ batch_size_description: "Number of items to process per iteration"
+ http_request:
+ authentication: "Authentication"
+ authentication_none: "None"
+ authentication_basic_auth: "Basic auth"
+ authentication_bearer_token: "Bearer token"
+ credential: "Credential"
+ method: "Method"
+ url: "URL"
+ headers: "Headers"
+ query_params: "Query parameters"
+ key_placeholder: "key"
+ value_placeholder: "value"
+ add_query_param: "Add parameter"
+ add_header: "Add header"
+ content_type: "Content type"
+ content_type_json: "JSON"
+ content_type_form_urlencoded: "Form URL-encoded"
+ content_type_raw: "Raw"
+ body_json: "Request body"
+ body_json_placeholder: '{"key": "value"}'
+ body_raw: "Request body"
+ body_form: "Form data"
+ add_body_form: "Add field"
+ raw_content_type: "Content type"
+ raw_content_type_placeholder: "text/plain"
+ never_error: "Never error"
+ never_error_description: "Return non-2xx responses instead of raising an error"
+ full_response: "Include response headers and status"
+ full_response_description: "Return the full response instead of only the body"
+ split_out:
+ field: "Fields to split out"
+ field_description: "Comma-separated field name(s) containing arrays to split. Supports dot notation for nested fields."
+ field_placeholder: "items"
+ include: "Include"
+ no_other_fields: "No other fields"
+ all_other_fields: "All other fields"
+ selected_other_fields: "Selected other fields"
+ fields_to_include: "Fields to include"
+ fields_to_include_description: "Comma-separated list of fields to carry over from the input item"
+ fields_to_include_placeholder: "company, id"
+ destination_field_name: "Destination field name"
+ destination_field_name_description: "Rename the split field in output. If splitting multiple fields, provide matching count of names."
+ sort:
+ type: "Sort type"
+ simple: "Simple"
+ random: "Random"
+ code: "Code"
+ sort_fields: "Sort fields"
+ field_name: "Field name"
+ field_name_placeholder: "name"
+ order: "Order"
+ ascending: "Ascending"
+ descending: "Descending"
+ code_field: "JavaScript code"
+ code_description: "Write a comparator function body. Variables a and b are item objects. Return -1, 0, or 1."
+ merge:
+ mode: "Mode"
+ number_inputs: "Number of inputs"
+ append: "Append"
+ combine: "Combine"
+ choose_branch: "Choose branch"
+ combine_by: "Combine by"
+ matching_fields: "Matching fields"
+ position: "Position"
+ all: "All possible combinations"
+ fields_to_match: "Fields to match"
+ field_1: "Input 1 field"
+ field_2: "Input 2 field"
+ join_mode: "Output type"
+ keep_matches: "Keep matches"
+ keep_non_matches: "Keep non-matches"
+ keep_everything: "Keep everything"
+ enrich_input_1: "Enrich input 1"
+ enrich_input_2: "Enrich input 2"
+ output_data_from: "Output data from"
+ both: "Both inputs"
+ input_1: "Input 1"
+ input_2: "Input 2"
+ multiple_matches: "Multiple matches"
+ first: "First match"
+ use_data_of_input: "Use data of input"
+ choose_output: "Output"
+ specified_input: "Specified input"
+ empty: "A single, empty item"
+ include_unpaired: "Include unpaired items"
+ resolve_clash: "When field values clash"
+ prefer_last: "Prefer last input"
+ prefer_input_1: "Prefer input 1"
+ prefer_input_2: "Prefer input 2"
+ add_suffix: "Add suffix"
+ merge_mode: "Merging nested fields"
+ deep_merge: "Deep merge"
+ shallow_merge: "Shallow merge"
+ override_empty: "Minimize empty fields"
+ fuzzy_compare: "Fuzzy compare"
+ log:
+ mode: "Mode"
+ mode_description: "Choose whether entries are logged once per item or once for all items"
+ mode_run_once_for_each_item: "Run once for each item"
+ mode_run_once_for_all_items: "Run once for all items"
+ entries: "Log entries"
+ key: "Key"
+ value: "Value"
+ add_entry: "Add entry"
+ markdown_table:
+ mapping_mode: "Mapping column mode"
+ mapping_mode_manual: "Map each column manually"
+ mapping_mode_auto: "Map automatically"
+ columns: "Columns"
+ header: "Header"
+ value: "Value"
+ add_column: "Add column"
+ form:
+ page_type: "Page type"
+ page_type_page: "Next form page"
+ page_type_completion: "Form ending"
+ form_title: "Form title"
+ form_title_placeholder: "My form"
+ form_description: "Form description"
+ form_description_placeholder: "Describe the purpose of this form..."
+ form_fields: "Form fields"
+ add_form_field: "Add field"
+ field_label: "Label"
+ field_label_placeholder: "Field label"
+ field_type: "Type"
+ field_type_text: "Text"
+ field_type_textarea: "Textarea"
+ field_type_number: "Number"
+ field_type_email: "Email"
+ field_type_password: "Password"
+ field_type_date: "Date"
+ field_type_checkbox: "Checkbox"
+ field_type_dropdown: "Dropdown"
+ field_type_radio: "Radio"
+ field_type_hiddenField: "Hidden field"
+ field_type_html: "HTML"
+ field_name: "Custom field name"
+ required: "Required"
+ description: "Description"
+ placeholder: "Placeholder"
+ placeholder_placeholder: "Enter placeholder text..."
+ field_value: "Field value"
+ html: "HTML"
+ default_value: "Default value"
+ options: "Field options"
+ value: "Option"
+ on_submission: "On form submission"
+ on_submission_completion_screen: "Show completion screen"
+ on_submission_redirect: "Redirect to URL"
+ on_submission_show_text: "Show text"
+ completion_title: "Title"
+ completion_title_placeholder: "Thank you!"
+ completion_message: "Message"
+ completion_message_placeholder: "Your response has been recorded"
+ redirect_url: "URL"
+ redirect_url_placeholder: "https://example.com/thanks"
+ completion_text: "Text"
+ completion_text_placeholder: "Thank you for your submission"
+ response_mode: "Respond when"
+ response_mode_on_received: "Form is submitted"
+ response_mode_workflow_finishes: "Workflow finishes"
+ authentication: "Authentication"
+ authentication_description: "Who can access and submit this form"
+ authentication_none: "Anyone"
+ authentication_login_required: "Logged-in users only"
+ form_url: "Form URL"
+ test_url: "Test"
+ production_url: "Production"
+ listen_for_test_event: "Listen for test event"
+ test_mode_banner: "This is a test version of your form"
+ thank_you: "Thank you! Your response has been recorded."
+ redirecting: "Redirecting..."
+ error_message: "Something went wrong. Please try again."
+ errors:
+ invalid: "%{field} is invalid"
+ missing: "%{field} is required"
+ submitting: "Submitting..."
+ submit: "Submit"
+ save_for_url: "Save the workflow to generate a form URL"
+ respond_to_webhook:
+ response_type: "Respond with"
+ response_type_json: "JSON"
+ response_type_redirect: "Redirect"
+ response_type_text: "Text"
+ response_type_no_data: "No data"
+ response_type_first_incoming_item: "First incoming item"
+ response_type_all_incoming_items: "All incoming items"
+ status_code: "Status code"
+ redirect_url: "Redirect URL"
+ redirect_url_placeholder: "https://example.com/thanks"
+ allowed_redirect_domains: "Allowed redirect domains"
+ allowed_redirect_domains_description: "External domains this node may redirect to. Use exact hostnames such as example.com or wildcard subdomains such as *.example.com. Only use wildcards when the redirect URL cannot be influenced by untrusted request data."
+ add_allowed_redirect_domain: "Add domain"
+ domain: "Domain"
+ domain_placeholder: "example.com"
+ response_body: "Response body"
+ response_body_placeholder: '{"success": true}'
+ response_key: "Response key"
+ response_headers: "Response headers"
+ add_response_header: "Add response header"
+ data_table_node:
+ resource: "Resource"
+ resources:
+ row: "Row"
+ operation: "Operation"
+ operations:
+ insert: "Insert"
+ get: "Get"
+ update: "Update"
+ delete: "Delete"
+ upsert: "Upsert"
+ row_exists: "If row exists"
+ row_not_exists: "If row does not exist"
+ data_table_id: "Data table"
+ data_table_id_placeholder: "Select a data table..."
+ mapping_mode: "Mapping column mode"
+ mapping_mode_manual: "Map each column manually"
+ mapping_mode_auto: "Map automatically"
+ columns_case_sensitive_hint_description: "Column mappings must match the data table column names exactly (case sensitive)"
+ columns: "Columns"
+ filter_combinator: "Match mode"
+ filter_combinator_and: "All conditions must match"
+ filter_combinator_or: "Any condition can match"
+ filter: "Conditions"
+ limit: "Limit"
+ sort_column: "Sort by"
+ sort_column_placeholder: "Select a column..."
+ sort_direction: "Sort direction"
+ sort_direction_asc: "Ascending"
+ sort_direction_desc: "Descending"
+ value_placeholder: "Value"
+ executions:
+ title: "Executions"
+ workflow: "Workflow"
+ view_executions: "Executions"
+ back_to_editor: "Back to editor"
+ status: "Status"
+ started_at: "Started"
+ finished_at: "Finished"
+ run_time: "Run time"
+ id: "ID"
+ expand: "Details"
+ collapse: "Hide"
+ details: "Details"
+ no_executions: "No executions recorded yet"
+ empty_title: "Hey %{username}, no runs yet"
+ empty_description: "Once your first workflow runs, execution logs will appear here so you can monitor activity and troubleshoot issues"
+ delete_selected: "Delete selected"
+ select: "Select"
+ cancel_select: "Cancel"
+ show: "Show"
+ delete_confirm:
+ one: "Are you sure you want to delete %{count} execution?"
+ other: "Are you sure you want to delete %{count} executions?"
+ input: "Input"
+ output: "Output"
+ items: "items"
+ logs: "Console"
+ total_time: "Total time:"
+ export: "Export"
+ error: "Error"
+ reason: "Reason"
+ with_value: "with value"
+ truncated:
+ input: "Input truncated"
+ output: "Output truncated"
+ value: "Value truncated"
+ original_bytes: "%{count} bytes before truncation"
+ original_size: "%{count} items before truncation"
+ max_bytes: "%{count} byte limit"
+ statuses:
+ pending: "Pending"
+ running: "Running"
+ success: "Completed"
+ error: "Error"
+ skipped: "Skipped"
+ filtered: "Filtered"
+ waiting: "Waiting"
+ kept: "Kept"
+ rejected: "Rejected"
+ rate_limited: "Rate limited"
+
+ kinds:
+ trigger: "Trigger"
+ condition: "Condition"
+ action: "Action"
+ flow: "Flow"
+ stats:
+ executions: "Executions"
+ failures: "Failures"
+ failure_rate: "Failure rate"
+ avg_run_time: "Avg. run time"
+ period: "Last 7 days"
+ variables:
+ title: "Variables"
+ description: "Global constants available in all workflows via $vars.KEY"
+ add: "Add variable"
+ key: "Key"
+ key_placeholder: "my_variable"
+ key_invalid: "Must start with a letter or underscore and contain only letters, numbers, and underscores"
+ value: "Value"
+ value_placeholder: "Variable value"
+ creator: "Creator"
+ no_variables: "No variables defined yet"
+ delete_confirm: "Are you sure you want to delete the variable \"%{key}\"?"
+ empty_title: "%{username}, let's set up a variable"
+ empty_description: "Variables can be used to store data that can be referenced easily across multiple workflows"
+ add_first: "Add first variable"
+ usage_syntax: "Usage syntax"
+ copy_syntax: "Copy to clipboard"
+ copied: "Copied to clipboard"
+ edit: "Edit variable"
+ credentials:
+ title: "Credentials"
+ description: "Encrypted credentials for authenticating workflow integrations"
+ add: "Add credential"
+ edit: "Edit credential"
+ name: "Name"
+ name_placeholder: "My credential"
+ type: "Type"
+ created: "Created"
+ no_credentials: "No credentials defined yet"
+ delete_confirm: "Are you sure you want to delete the credential \"%{name}\"?"
+ empty_title: "%{username}, let's set up a credential"
+ empty_description: "Credentials store encrypted authentication data for use in workflows"
+ add_first: "Add first credential"
+ set_up_credential: "Set up credential"
+ select_type: "Select type"
+ referenced_by_workflows: "This credential is used by workflows and cannot be deleted. Remove references first."
+ in_use_title: "Credential in use"
+ in_use_description: "This credential cannot be deleted because it is used by the following workflows:"
+ data_tables:
+ title: "Data tables"
+ add: "Add data table"
+ edit: "Edit data table"
+ name: "Name"
+ name_placeholder: "my_table"
+ name_invalid: "Must start with a letter or underscore and contain only letters, numbers, underscores, and spaces"
+ no_data_tables: "No data tables yet"
+ empty_title: "%{username}, let's set up a data table"
+ empty_description: "Data tables can be used to store structured data that your workflows can read and write"
+ add_first: "Add first data table"
+ manage_data_tables: "Manage data tables"
+ columns: "Columns"
+ size: "Size"
+ rows: "Rows"
+ column_name: "Column name"
+ column_name_invalid: "Must start with a letter or underscore and contain only letters, numbers, and underscores"
+ column_type: "Column type"
+ column_types:
+ string: "String"
+ number: "Number"
+ boolean: "Boolean"
+ date: "Date"
+ add_column: "Add column"
+ add_row: "Add row"
+ edit_row: "Edit row"
+ no_rows: "No rows yet"
+ back: "Back"
+ delete_confirm: "Are you sure you want to delete this data table and all its rows?"
+ in_use_title: "Data table in use"
+ in_use_description: "This data table cannot be deleted because it is used by the following workflows:"
+ delete_selected: "Delete selected"
+ clear_selection: "Clear selection"
+ delete_rows_confirm:
+ one: "Are you sure you want to delete %{count} row?"
+ other: "Are you sure you want to delete %{count} rows?"
+ canvas:
+ fit_to_view: "Fit"
+ zoom_to_fit: "Zoom to fit [1]"
+ zoom_in: "Zoom in [+]"
+ zoom_out: "Zoom out [-]"
+ undo: "Undo"
+ redo: "Redo"
+ auto_layout: "Auto layout [2]"
+ add_step: "Add step"
+ remove_connection: "Remove connection"
+ export_nodes: "Export"
+ import_nodes: "Import"
+ import_error: "Failed to import: invalid file format"
+ import_version_error: "Failed to import: unsupported format version"
+ max_nodes_reached: "Workflows are limited to %{max} nodes"
+ sync_error: "Failed to sync canvas changes. Please reload the page."
+ sticky_note:
+ add: "Add sticky note"
+ delete: "Delete"
+ change_color: "Change color"
+ placeholder: "Double-click to edit..."
+ manual_trigger:
+ run: "Run manually with the sample pinned data"
+ triggered: "Triggered"
+ failed: "Execution failed"
+ view_execution: "View execution"
+ listening: "Listening for test webhook event"
+ needs_pin_data: "Pin sample data on this trigger before running it manually."
+ pin_data:
+ pin: "Pin data"
+ unpin: "Unpin"
+ is_pinned: "This data is pinned for test executions."
+ output_available_tip: "Now that you have output data for this node, you can pin it and use it when executing this trigger manually with the green play button."
+ save: "Save"
+ cancel: "Cancel"
+ schema_view: "Schema"
+ json_view: "JSON"
+ add_sample_data: "Add sample data"
+ empty_title: "No output yet"
+ no_data_yet: "No output yet. Add sample data to test this node manually."
+ no_data_no_edit: "No output data."
+ loading_editor: "Loading editor…"
+ invalid_json: "Invalid JSON"
+ invalid_json_empty: "JSON cannot be empty."
+ invalid_shape_not_array: "Pinned data must be an array of items."
+ invalid_shape_empty: "Pinned data must contain at least one item."
+ invalid_shape_item_not_object: "Each item must be a JSON object."
+ size_hint: "%{bytes} / %{max} bytes"
+ size_exceeded: "Pinned data exceeds the maximum size."
+ confirm_discard: "Discard your unsaved changes to the pinned data?"
+ branch:
+ "true": "Yes"
+ "false": "No"
+ done: "Done"
+ loop: "Loop"
diff --git a/plugins/discourse-workflows/config/locales/server.en.yml b/plugins/discourse-workflows/config/locales/server.en.yml
new file mode 100644
index 00000000000..368ebac2513
--- /dev/null
+++ b/plugins/discourse-workflows/config/locales/server.en.yml
@@ -0,0 +1,93 @@
+en:
+ activerecord:
+ errors:
+ models:
+ discourse_workflows/workflow:
+ attributes:
+ error_workflow_id:
+ cannot_be_self: "cannot be set to the workflow itself"
+ discourse_workflows:
+ errors:
+ approval_timed_out: "Approval timed out"
+ webhook_timed_out: "Webhook timed out"
+ schedule_rules_required: "At least one schedule rule is required."
+ invalid_schedule_rule: "One or more schedule rules are invalid."
+ not_enabled: "The discourse-workflows plugin is not enabled."
+ no_permission_to_manage: "You don't have permission to manage workflows."
+ invalid_form_submission: "The form submission has invalid or missing fields."
+ invalid_form_token: "The form token is invalid or has expired."
+ webhook_test_listener_active: "A webhook test listener is already active for this URL."
+ webhook_route_collision: "Another active workflow already owns %{method} %{path}."
+ workflow_failed: "Error in workflow"
+ already_resumed: "This execution has already been resumed."
+ javascript_execution_failed: "JavaScript execution failed"
+ storage_limit_exceeded: "Data table storage limit exceeded."
+ invalid_nodes: "Nodes must be an array of workflow node objects."
+ invalid_connections: "Connections must be a workflow connection map."
+ invalid_node_fields: "Nodes must use supported node field shapes."
+ invalid_node_json_keys: "Nodes must use supported JSON keys."
+ node_names_required: "Node names are required."
+ node_types_required: "Node types are required."
+ unsupported_node_version: "Unsupported version %{version} for %{type}."
+ max_nodes_exceeded: "Workflows cannot have more than %{max} nodes"
+ max_nodes_of_type_exceeded: "Workflows cannot have more than %{max} %{type} node"
+ node_does_not_accept_inputs: "%{node} does not accept inputs."
+ duplicate_node_names: "Node names must be unique within a workflow. Duplicates: %{names}"
+ no_rows_matched_filter: "No rows matched the provided filter."
+ item:
+ inconsistent_format_title: "Inconsistent item format"
+ inconsistent_format: "Every returned item must use the same format."
+ create_post:
+ topic_closed_or_archived: "Cannot create a post in a closed or archived topic."
+ topic:
+ create_failed: "Failed to create topic."
+ unknown_operation: "Unknown operation: %{operation}."
+ credential:
+ missing_required_field: "is missing required field '%{field}'"
+ wait:
+ amount_must_be_positive: "Wait amount must be greater than 0."
+ invalid_unit: "Invalid wait unit: %{unit}."
+ invalid_timeout_unit: "Invalid timeout unit: %{unit}."
+ timeout_amount_must_be_positive: "Timeout amount must be greater than 0."
+ topic_tags:
+ no_tag_names: "No tag names provided."
+ operation_failed: "Tag operation failed: %{errors}"
+ sort:
+ code_missing_return: "Code must contain a return statement."
+ merge:
+ invalid_fields_to_match: "Invalid fields to match"
+ fields_to_match_pair_missing_fields: "Fields to match pair %{index} must define both input fields"
+ missing_fields_to_match: "Missing fields to match"
+ fields_to_match_required: 'You need to define at least one pair of fields in "Fields to match"'
+ split_out:
+ destination_count_mismatch: "Destination field name count must match field count."
+ fields_to_include_required: "No fields specified."
+ too_many_items: "Cannot split into more than %{max} items (array has %{count} elements)."
+ set_fields:
+ json_blank: "JSON string is blank."
+ json_must_be_object: "JSON must be an object."
+ http_request:
+ url_required: "URL is required."
+ unsupported_scheme: "Only HTTP and HTTPS URLs are supported."
+ host_required: "URL must include a host."
+ credential_required: "Credential is required for authentication mode '%{mode}'."
+ exec_ctx_required: "Execution context is required for authentication mode '%{mode}'."
+ data_table:
+ unknown_column: "Unknown column name '%{column}'."
+ unknown_operation: "Unknown operation: %{operation}."
+ invalid_query: "Invalid query: %{errors}"
+ invalid_row: "Invalid row: %{errors}"
+ filter_required: "Filter must not be empty"
+ workflow_version:
+ referenced_by_workflow: "Cannot delete a workflow version that is still referenced as the current or active version."
+ pin_data:
+ errors:
+ unsupported_node: "Only nodes with a single output can have pinned data."
+ invalid_items: "Pinned data must be an array of items with a 'json' object."
+ size_limit_exceeded: "Pinned data exceeds the per-workflow size limit (%{limit} bytes)."
+ no_sample_data: "Pin sample data on this trigger to run the workflow manually."
+ hints:
+ split_out:
+ field_not_found: "The field '%{field}' wasn't found in any input item."
+ site_settings:
+ discourse_workflows_enabled: "Enable the discourse-workflows plugin."
diff --git a/plugins/discourse-workflows/config/routes.rb b/plugins/discourse-workflows/config/routes.rb
new file mode 100644
index 00000000000..a8dac8a6713
--- /dev/null
+++ b/plugins/discourse-workflows/config/routes.rb
@@ -0,0 +1,118 @@
+# frozen_string_literal: true
+
+DiscourseWorkflows::Engine.routes.draw do
+ scope "/admin/plugins/discourse-workflows",
+ as: "admin_discourse_workflows",
+ constraints: AdminConstraint.new do
+ scope format: false do
+ get "/" => "admin#index"
+ get "/variables" => "admin#index"
+ get "/executions" => "admin#index"
+ get "/templates" => "admin#index"
+ get "/data-tables" => "admin#index"
+ get "/data-tables/:id" => "admin#index", :constraints => { id: /\d+/ }
+ get "/credentials" => "admin#index"
+ get "/workflows/new" => "admin#index"
+ get "/workflows/:id" => "admin#index", :constraints => { id: /\d+/ }
+ get "/workflows/:id/executions" => "admin#index", :constraints => { id: /\d+/ }
+ get "/workflows/:id/executions/:execution_id" => "admin#index",
+ :constraints => {
+ id: /\d+/,
+ execution_id: /\d+/,
+ }
+ get "/workflows/:id/settings" => "admin#index", :constraints => { id: /\d+/ }
+ end
+
+ scope format: :json do
+ get "/workflows" => "workflows#index"
+ post "/workflows" => "workflows#create"
+ get "/workflows/:id" => "workflows#show"
+ put "/workflows/:id" => "workflows#update"
+ post "/workflows/:id/discard-draft" => "workflows#discard_draft"
+ put "/workflows/:id/pin-data" => "workflows#update_pin_data"
+ post "/workflows/:id/form-test-sessions" => "form_test_sessions#create"
+ post "/workflows/:id/webhook-test-listeners" => "webhook_test_listeners#create"
+ delete "/workflows/:id/webhook-test-listeners/:listener_id" =>
+ "webhook_test_listeners#destroy"
+ delete "/workflows/:id" => "workflows#destroy"
+ get "/node-types" => "node_types#index"
+ post "/dynamic-node-parameters/options" => "dynamic_node_parameters#options"
+ get "/templates" => "templates#index"
+ get "/templates/:id" => "templates#show"
+ post "/executions" => "executions#create"
+ get "/executions" => "executions#index"
+ get "/workflows/:workflow_id/executions" => "executions#index"
+ delete "/executions" => "executions#destroy"
+ get "/executions/:id" => "executions#show"
+ get "/stats" => "stats#index"
+ get "/stats/:workflow_id" => "stats#index"
+ post "/expressions/evaluate" => "expressions#evaluate"
+ get "/variables" => "variables#index"
+ post "/variables" => "variables#create"
+ put "/variables/:id" => "variables#update"
+ delete "/variables/:id" => "variables#destroy"
+ get "/credentials" => "credentials#index"
+ post "/credentials" => "credentials#create"
+ put "/credentials/:id" => "credentials#update"
+ delete "/credentials/:id" => "credentials#destroy"
+ get "/data-tables" => "data_tables#index"
+ post "/data-tables" => "data_tables#create"
+ get "/data-tables/:id" => "data_tables#show", :constraints => { id: /\d+/ }
+ put "/data-tables/:id" => "data_tables#update"
+ delete "/data-tables/:id" => "data_tables#destroy"
+ post "/data-tables/:data_table_id/columns" => "data_table_columns#create"
+ patch "/data-tables/:data_table_id/columns/:column_name/rename" => "data_table_columns#rename"
+ delete "/data-tables/:data_table_id/columns/:column_name" => "data_table_columns#destroy"
+ get "/data-tables/:data_table_id/rows" => "data_table_rows#index"
+ post "/data-tables/:data_table_id/rows" => "data_table_rows#create"
+ put "/data-tables/:data_table_id/rows" => "data_table_rows#update_bulk"
+ put "/data-tables/:data_table_id/rows/:id" => "data_table_rows#update"
+ delete "/data-tables/:data_table_id/rows/:id" => "data_table_rows#destroy"
+ delete "/data-tables/:data_table_id/rows" => "data_table_rows#destroy_bulk"
+ end
+ end
+
+ scope "/discourse-workflows", defaults: { format: :json } do
+ post "/trigger-topic-admin-button" => "topic_admin_button#create"
+ end
+
+ scope "/workflows", defaults: { format: :json } do
+ match "/waiting/:execution_id/webhook(/*suffix)" => "webhooks#receive",
+ :via => :all,
+ :constraints => {
+ execution_id: /\d+/,
+ }
+ match "/webhook-test/:listener_id/*path" => "webhooks#receive_test", :via => :all
+ match "/webhooks/*path" => "webhooks#receive", :via => :all
+ end
+
+ scope "/workflows/form", defaults: { format: :json } do
+ get "/:uuid" => "forms#show",
+ :constraints => {
+ uuid: /[0-9a-f-]{36}/,
+ },
+ :defaults => {
+ format: :html,
+ }
+ post "/:uuid" => "forms#create", :constraints => { uuid: /[0-9a-f-]{36}/ }
+ end
+
+ scope "/workflows/form-test", defaults: { format: :json } do
+ get "/:token" => "forms#test_show",
+ :constraints => {
+ token: /[0-9a-f-]{36}/,
+ },
+ :defaults => {
+ format: :html,
+ }
+ post "/:token" => "forms#test_create", :constraints => { token: /[0-9a-f-]{36}/ }
+ end
+
+ scope "/workflows/forms/waiting", defaults: { format: :json } do
+ get "/:execution_id/status" => "forms#waiting_status", :constraints => { execution_id: /\d+/ }
+ get "/:execution_id" => "forms#waiting_show", :constraints => { execution_id: /\d+/ }
+ post "/:execution_id" => "forms#waiting_create", :constraints => { execution_id: /\d+/ }
+ end
+end
+
+Discourse::Application.routes.draw { mount ::DiscourseWorkflows::Engine, at: "/" }
diff --git a/plugins/discourse-workflows/config/settings.yml b/plugins/discourse-workflows/config/settings.yml
new file mode 100644
index 00000000000..15f7228071e
--- /dev/null
+++ b/plugins/discourse-workflows/config/settings.yml
@@ -0,0 +1,21 @@
+plugins:
+ discourse_workflows_enabled:
+ default: false
+ client: true
+ hidden: true
+ discourse_workflows_max_executions_per_minute:
+ default: 20
+ hidden: true
+ discourse_workflows_max_executions_per_minute_per_workflow:
+ default: 10
+ hidden: true
+ workflow_executions_retention_days:
+ default: 30
+ min: 0
+ max: 36500
+ hidden: true
+ discourse_workflows_max_pin_data_bytes:
+ default: 1048576
+ min: 0
+ max: 16777216
+ hidden: true
diff --git a/plugins/discourse-workflows/config/templates/auto-tag-topics.json b/plugins/discourse-workflows/config/templates/auto-tag-topics.json
new file mode 100644
index 00000000000..eabfaa43ce9
--- /dev/null
+++ b/plugins/discourse-workflows/config/templates/auto-tag-topics.json
@@ -0,0 +1,121 @@
+{
+ "name": "Auto-tag new topics",
+ "description": "Automatically adds tags to new topics based on their category.",
+ "nodes": [
+ {
+ "id": "topic-created",
+ "type": "trigger:topic_created",
+ "typeVersion": "1.0",
+ "name": "Topic created",
+ "parameters": {},
+ "credentials": {},
+ "webhookId": null,
+ "position": {
+ "x": 12,
+ "y": 22
+ }
+ },
+ {
+ "id": "check-category",
+ "type": "condition:if",
+ "typeVersion": "1.0",
+ "name": "Check category",
+ "parameters": {
+ "combinator": "and",
+ "conditions": [
+ {
+ "id": "a1404264-d341-43a9-84b8-d7d6c67e477d",
+ "operator": {
+ "type": "number",
+ "operation": "equals",
+ "singleValue": false
+ },
+ "leftValue": "={{ $json.topic.category_id }}",
+ "rightValue": ""
+ }
+ ]
+ },
+ "credentials": {},
+ "webhookId": null,
+ "position": {
+ "x": 252,
+ "y": 17
+ }
+ },
+ {
+ "id": "topic-tags",
+ "type": "action:topic_tags",
+ "typeVersion": "1.0",
+ "name": "Topic tags",
+ "parameters": {
+ "topic_id": "={{ $json.topic.id }} "
+ },
+ "credentials": {},
+ "webhookId": null,
+ "position": {
+ "x": 492,
+ "y": 12
+ }
+ },
+ {
+ "id": "sticky-note-category",
+ "type": "flow:sticky_note",
+ "typeVersion": "1.0",
+ "name": "Sticky Note",
+ "parameters": {
+ "content": "Double click Check category to set the category id you want to auto tag",
+ "width": 248.7421875,
+ "height": 172.73046875,
+ "color": "green"
+ },
+ "credentials": {},
+ "webhookId": null,
+ "position": {
+ "x": 193.94921875,
+ "y": -49.4921875
+ }
+ },
+ {
+ "id": "sticky-note-tags",
+ "type": "flow:sticky_note",
+ "typeVersion": "1.0",
+ "name": "Sticky Note",
+ "parameters": {
+ "content": "Double click Topic tags to define the tags you want to apply",
+ "width": 209.0859375,
+ "height": 213.1796875,
+ "color": "blue"
+ },
+ "credentials": {},
+ "webhookId": null,
+ "position": {
+ "x": 484.63671875,
+ "y": -104.71875
+ }
+ }
+ ],
+ "connections": {
+ "Topic created": {
+ "main": [
+ [
+ {
+ "node": "Check category",
+ "type": "main",
+ "index": 0
+ }
+ ]
+ ]
+ },
+ "Check category": {
+ "main": [
+ [
+ {
+ "node": "Topic tags",
+ "type": "main",
+ "index": 0
+ }
+ ]
+ ]
+ }
+ }
+}
diff --git a/plugins/discourse-workflows/db/migrate/20260312000000_create_workflow_tables.rb b/plugins/discourse-workflows/db/migrate/20260312000000_create_workflow_tables.rb
new file mode 100644
index 00000000000..32060ab1ee2
--- /dev/null
+++ b/plugins/discourse-workflows/db/migrate/20260312000000_create_workflow_tables.rb
@@ -0,0 +1,244 @@
+# frozen_string_literal: true
+
+class CreateWorkflowTables < ActiveRecord::Migration[8.0]
+ def change
+ create_table :discourse_workflows_workflows do |t|
+ t.string :name, null: false, limit: 100
+ t.jsonb :nodes, null: false, default: []
+ t.jsonb :connections, null: false, default: {}
+ t.jsonb :static_data, null: false, default: {}
+ t.jsonb :pin_data, null: false, default: {}
+ t.jsonb :trigger_state, null: false, default: {}
+ t.jsonb :settings, null: false, default: {}
+ t.string :version_id, null: false, limit: 36
+ t.string :active_version_id, limit: 36
+ t.integer :version_counter, null: false, default: 1
+ t.bigint :error_workflow_id
+ t.integer :created_by_id, null: false
+ t.integer :updated_by_id
+ t.timestamps null: false
+ end
+
+ add_index :discourse_workflows_workflows,
+ :created_by_id,
+ name: "idx_dwf_workflows_on_created_by_id"
+ add_index :discourse_workflows_workflows,
+ :updated_by_id,
+ name: "idx_dwf_workflows_on_updated_by_id"
+ add_index :discourse_workflows_workflows,
+ :error_workflow_id,
+ name: "idx_dwf_workflows_on_error_workflow_id"
+ add_index :discourse_workflows_workflows,
+ :version_id,
+ unique: true,
+ name: "idx_dwf_workflows_on_version_id"
+ add_index :discourse_workflows_workflows,
+ :active_version_id,
+ name: "idx_dwf_workflows_on_active_version_id"
+
+ create_table :discourse_workflows_workflow_versions, id: false do |t|
+ t.string :version_id, null: false, limit: 36, primary_key: true
+ t.bigint :workflow_id, null: false
+ t.integer :version_number, null: false
+ t.string :name, null: false, limit: 100
+ t.jsonb :nodes, null: false, default: []
+ t.jsonb :connections, null: false, default: {}
+ t.jsonb :settings, null: false, default: {}
+ t.boolean :autosaved, null: false, default: false
+ t.text :authors
+ t.integer :created_by_id, null: false
+ t.integer :updated_by_id
+ t.timestamps null: false
+ end
+
+ add_index :discourse_workflows_workflow_versions,
+ :workflow_id,
+ name: "idx_dwf_versions_on_workflow_id"
+ add_index :discourse_workflows_workflow_versions,
+ %i[workflow_id version_number],
+ unique: true,
+ name: "idx_dwf_versions_on_workflow_version_number"
+ add_index :discourse_workflows_workflow_versions,
+ %i[workflow_id created_at],
+ order: {
+ created_at: :desc,
+ },
+ name: "idx_dwf_versions_on_workflow_created_at"
+
+ create_table :discourse_workflows_workflow_publish_history do |t|
+ t.bigint :workflow_id, null: false
+ t.string :version_id, limit: 36
+ t.string :event, null: false, limit: 32
+ t.integer :user_id
+ t.datetime :created_at, null: false, default: -> { "CURRENT_TIMESTAMP" }
+ end
+
+ add_index :discourse_workflows_workflow_publish_history,
+ %i[workflow_id created_at id],
+ order: {
+ created_at: :desc,
+ id: :desc,
+ },
+ name: "idx_dwf_publish_history_on_workflow_created_at_id_desc"
+
+ create_table :discourse_workflows_executions do |t|
+ t.bigint :workflow_id, null: false
+ t.string :workflow_version_id, null: false, limit: 36
+ t.integer :status, null: false, default: 0
+ t.integer :execution_mode, default: 0, null: false
+ t.jsonb :trigger_data, default: {}
+ t.text :error
+ t.string :waiting_node_id, limit: 100
+ t.datetime :waiting_until
+ t.string :resume_token, limit: 64
+ t.string :timeout_action, limit: 32
+ t.string :trigger_node_id, limit: 100
+ t.integer :run_time_ms
+ t.datetime :started_at
+ t.datetime :finished_at
+ t.timestamps null: false
+ end
+
+ add_index :discourse_workflows_executions,
+ :resume_token,
+ where: "resume_token IS NOT NULL",
+ name: "idx_dwf_executions_on_resume_token"
+ add_index :discourse_workflows_executions,
+ :waiting_until,
+ where: "waiting_until IS NOT NULL AND status = 4",
+ name: "idx_dwf_executions_on_waiting_until"
+ add_index :discourse_workflows_executions,
+ %i[status waiting_until],
+ name: "idx_dwf_executions_on_status_waiting_until"
+ add_index :discourse_workflows_executions,
+ %i[workflow_id created_at id],
+ order: {
+ created_at: :desc,
+ id: :desc,
+ },
+ name: "idx_dwf_executions_on_workflow_created_at_id_desc"
+ add_index :discourse_workflows_executions,
+ :workflow_version_id,
+ name: "idx_dwf_executions_on_workflow_version_id"
+ add_index :discourse_workflows_executions,
+ :created_at,
+ where: "status IN (2, 3, 5, 6)",
+ name: "idx_dwf_executions_on_retention"
+
+ create_table :discourse_workflows_execution_data, id: false do |t|
+ t.bigint :execution_id, null: false
+ t.jsonb :data, default: {}, null: false
+ t.jsonb :workflow_data, default: {}, null: false
+ end
+
+ add_index :discourse_workflows_execution_data,
+ :execution_id,
+ unique: true,
+ name: "idx_dwf_execution_data_on_execution_id"
+
+ create_table :discourse_workflows_variables do |t|
+ t.string :key, null: false, limit: 100
+ t.string :value, null: false, default: "", limit: 1000
+ t.text :description
+ t.integer :created_by_id, null: false
+ t.timestamps
+ end
+
+ add_index :discourse_workflows_variables, :key, unique: true, name: "idx_dwf_variables_on_key"
+ add_index :discourse_workflows_variables,
+ :created_by_id,
+ name: "idx_dwf_variables_on_created_by_id"
+
+ create_table :discourse_workflows_data_tables do |t|
+ t.string :name, null: false, limit: 100
+ t.integer :created_by_id
+ t.integer :updated_by_id
+ t.timestamps null: false
+ end
+
+ add_index :discourse_workflows_data_tables,
+ :name,
+ unique: true,
+ name: "idx_dwf_data_tables_on_name"
+ add_index :discourse_workflows_data_tables,
+ :created_by_id,
+ name: "idx_dwf_data_tables_on_created_by_id"
+ add_index :discourse_workflows_data_tables,
+ :updated_by_id,
+ name: "idx_dwf_data_tables_on_updated_by_id"
+
+ create_table :discourse_workflows_credentials do |t|
+ t.string :name, limit: 128, null: false
+ t.string :credential_type, limit: 64, null: false
+ t.jsonb :data, null: false, default: {}
+ t.integer :created_by_id
+ t.integer :updated_by_id
+ t.timestamps
+ end
+
+ add_index :discourse_workflows_credentials,
+ :credential_type,
+ name: "idx_dwf_credentials_on_credential_type"
+ add_index :discourse_workflows_credentials,
+ :created_by_id,
+ name: "idx_dwf_credentials_on_created_by_id"
+ add_index :discourse_workflows_credentials,
+ :updated_by_id,
+ name: "idx_dwf_credentials_on_updated_by_id"
+ add_index :discourse_workflows_credentials,
+ %i[name credential_type],
+ unique: true,
+ name: "idx_dwf_credentials_on_name_credential_type"
+
+ create_table :discourse_workflows_workflow_dependencies do |t|
+ t.bigint :workflow_id, null: false
+ t.string :dependency_type, null: false, limit: 50
+ t.string :dependency_key, null: false, limit: 500
+ t.string :node_id, limit: 100
+ t.string :workflow_version_id, limit: 36
+ t.datetime :created_at, null: false, default: -> { "CURRENT_TIMESTAMP" }
+ end
+
+ add_index :discourse_workflows_workflow_dependencies,
+ :workflow_id,
+ name: "idx_dwf_deps_on_workflow_id"
+ add_index :discourse_workflows_workflow_dependencies,
+ %i[dependency_type dependency_key],
+ name: "idx_dwf_deps_on_type_key"
+ add_index :discourse_workflows_workflow_dependencies,
+ :workflow_version_id,
+ name: "idx_dwf_deps_on_workflow_version_id"
+
+ create_table :discourse_workflows_webhooks do |t|
+ t.bigint :workflow_id, null: false
+ t.string :workflow_version_id, limit: 36
+ t.string :node_name, null: false, limit: 100
+ t.string :webhook_path, null: false, limit: 500
+ t.string :http_method, null: false, limit: 10
+ t.string :webhook_id, limit: 36
+ t.integer :path_length
+ t.boolean :test_webhook, null: false, default: false
+ t.integer :user_id
+ t.jsonb :workflow_snapshot
+ t.datetime :expires_at
+ t.datetime :created_at, null: false, default: -> { "CURRENT_TIMESTAMP" }
+ end
+
+ add_index :discourse_workflows_webhooks,
+ %i[http_method webhook_path test_webhook],
+ unique: true,
+ name: "idx_dwf_webhooks_on_method_path_test"
+ add_index :discourse_workflows_webhooks,
+ %i[webhook_id http_method test_webhook],
+ name: "idx_dwf_webhooks_on_webhook_id_method_test",
+ where: "webhook_id IS NOT NULL"
+ add_index :discourse_workflows_webhooks, :workflow_id, name: "idx_dwf_webhooks_on_workflow_id"
+ add_index :discourse_workflows_webhooks,
+ :workflow_version_id,
+ name: "idx_dwf_webhooks_on_workflow_version_id"
+ add_index :discourse_workflows_webhooks,
+ :expires_at,
+ name: "idx_dwf_webhooks_on_expires_at",
+ where: "expires_at IS NOT NULL"
+ end
+end
diff --git a/plugins/discourse-workflows/lib/discourse_workflows/active_webhooks.rb b/plugins/discourse-workflows/lib/discourse_workflows/active_webhooks.rb
new file mode 100644
index 00000000000..db141f3c32e
--- /dev/null
+++ b/plugins/discourse-workflows/lib/discourse_workflows/active_webhooks.rb
@@ -0,0 +1,91 @@
+# frozen_string_literal: true
+
+module DiscourseWorkflows
+ class ActiveWebhooks
+ VERSION_KEY = "version"
+
+ class << self
+ def cache
+ @cache ||= DistributedCache.new("discourse_workflows_active_webhooks")
+ end
+
+ def invalidate!
+ cache.delete(VERSION_KEY)
+ @snapshot = nil
+ @snapshot_version = nil
+ end
+
+ def find(method:, path:, test_webhook: false)
+ snapshot.find(method: method, path: path, test_webhook: test_webhook)
+ end
+
+ def reset_for_tests!
+ @cache = nil
+ @snapshot = nil
+ @snapshot_version = nil
+ end
+
+ private
+
+ def snapshot
+ current_version = cache.defer_get_set(VERSION_KEY) { SecureRandom.uuid }
+ if @snapshot.nil? || @snapshot_version != current_version
+ @snapshot = Snapshot.new(Webhook.live.to_a)
+ @snapshot_version = current_version
+ end
+ @snapshot
+ end
+ end
+
+ class Snapshot
+ def initialize(webhooks)
+ @static = Hash.new
+ @dynamic = Hash.new { |h, k| h[k] = [] }
+ @test_static = Hash.new
+ @test_dynamic = Hash.new { |h, k| h[k] = [] }
+
+ webhooks.each { |webhook| add(webhook) }
+
+ @dynamic.each_value { |list| list.sort_by!(&:path_length).reverse! }
+ @test_dynamic.each_value { |list| list.sort_by!(&:path_length).reverse! }
+ end
+
+ def find(method:, path:, test_webhook:)
+ http_method = Webhook.normalize_method(method)
+ normalized_path = Webhook.normalize_path(path)
+
+ static_map = test_webhook ? @test_static : @static
+ if (static_webhook = static_map[[http_method, normalized_path]])
+ return { webhook: static_webhook, path_params: {} }
+ end
+
+ segments = Webhook.segments_for(normalized_path)
+ return nil if segments.empty?
+
+ dynamic_map = test_webhook ? @test_dynamic : @dynamic
+ candidate_id = segments.first
+ remaining = segments[1..]
+
+ dynamic_map[[http_method, candidate_id]].each do |dynamic_webhook|
+ params =
+ Webhook.match_dynamic_path(template: dynamic_webhook.webhook_path, segments: remaining)
+ return { webhook: dynamic_webhook, path_params: params } if params
+ end
+
+ nil
+ end
+
+ private
+
+ def add(webhook)
+ if webhook.dynamic?
+ target = webhook.test_webhook? ? @test_dynamic : @dynamic
+ target[[webhook.http_method, webhook.webhook_id]] << webhook
+ else
+ target = webhook.test_webhook? ? @test_static : @static
+ target[[webhook.http_method, webhook.webhook_path]] = webhook
+ end
+ end
+ end
+ end
+end
diff --git a/plugins/discourse-workflows/lib/discourse_workflows/collection_parameters.rb b/plugins/discourse-workflows/lib/discourse_workflows/collection_parameters.rb
new file mode 100644
index 00000000000..31c3afce313
--- /dev/null
+++ b/plugins/discourse-workflows/lib/discourse_workflows/collection_parameters.rb
@@ -0,0 +1,46 @@
+# frozen_string_literal: true
+
+module DiscourseWorkflows
+ module CollectionParameters
+ DEFAULT_GROUP = "values"
+ ASSIGNMENTS_GROUP = "assignments"
+
+ module_function
+
+ def rows(configuration, field_name, group: DEFAULT_GROUP)
+ rows_from_value(fetch_value(configuration, field_name), group: group)
+ end
+
+ def assignments(configuration, field_name = ASSIGNMENTS_GROUP)
+ rows(configuration, field_name, group: ASSIGNMENTS_GROUP)
+ end
+
+ def option_bag(configuration, field_name)
+ value = fetch_value(configuration, field_name)
+ value.is_a?(Hash) ? value : {}
+ end
+
+ def rows_from_value(value, group: DEFAULT_GROUP)
+ case value
+ when Array
+ value
+ when Hash
+ rows = value[group.to_s] || value[group.to_sym]
+ return rows if rows.is_a?(Array)
+ return [rows] if rows.is_a?(Hash)
+
+ []
+ else
+ []
+ end
+ end
+
+ def fetch_value(configuration, field_name)
+ return if configuration.blank?
+
+ if configuration.respond_to?(:[])
+ configuration[field_name.to_s] || configuration[field_name.to_sym]
+ end
+ end
+ end
+end
diff --git a/plugins/discourse-workflows/lib/discourse_workflows/context_helpers.rb b/plugins/discourse-workflows/lib/discourse_workflows/context_helpers.rb
new file mode 100644
index 00000000000..51ce511ce1d
--- /dev/null
+++ b/plugins/discourse-workflows/lib/discourse_workflows/context_helpers.rb
@@ -0,0 +1,33 @@
+# frozen_string_literal: true
+
+module DiscourseWorkflows
+ class ContextHelpers
+ include NodeErrorHandling
+
+ def initialize(node_identifier:, data_table_access_validator: nil, guardian: nil)
+ @data_table_proxy_provider =
+ DataTables::NodeProxyProvider.new(
+ node_identifier: node_identifier,
+ data_table_access_validator: data_table_access_validator,
+ guardian: guardian,
+ )
+ end
+
+ def get_data_table_proxy(data_table_id)
+ @data_table_proxy_provider.get_data_table_proxy(data_table_id)
+ end
+
+ def get_data_table_aggregate_proxy
+ @data_table_proxy_provider.get_data_table_aggregate_proxy
+ end
+
+ def normalize_items(items)
+ Item.normalize_items(items)
+ rescue Item::InconsistentItemFormatError
+ raise_node_error!(
+ I18n.t("discourse_workflows.errors.item.inconsistent_format_title"),
+ description: I18n.t("discourse_workflows.errors.item.inconsistent_format"),
+ )
+ end
+ end
+end
diff --git a/plugins/discourse-workflows/lib/discourse_workflows/credential_data_validator.rb b/plugins/discourse-workflows/lib/discourse_workflows/credential_data_validator.rb
new file mode 100644
index 00000000000..b8afc051cff
--- /dev/null
+++ b/plugins/discourse-workflows/lib/discourse_workflows/credential_data_validator.rb
@@ -0,0 +1,14 @@
+# frozen_string_literal: true
+
+module DiscourseWorkflows
+ class CredentialDataValidator
+ def self.call(credential_type:, data:)
+ schema = credential_type.property_schema || {}
+ normalized = (data || {}).stringify_keys
+
+ schema.filter_map do |field_name, field_def|
+ field_name.to_s if field_def[:required] && normalized[field_name.to_s].blank?
+ end
+ end
+ end
+end
diff --git a/plugins/discourse-workflows/lib/discourse_workflows/credential_types/basic_auth.rb b/plugins/discourse-workflows/lib/discourse_workflows/credential_types/basic_auth.rb
new file mode 100644
index 00000000000..4e54de26413
--- /dev/null
+++ b/plugins/discourse-workflows/lib/discourse_workflows/credential_types/basic_auth.rb
@@ -0,0 +1,31 @@
+# frozen_string_literal: true
+
+module DiscourseWorkflows
+ module CredentialTypes
+ class BasicAuth
+ def self.identifier
+ "basic_auth"
+ end
+
+ def self.display_name
+ "Basic Auth"
+ end
+
+ def self.property_schema
+ {
+ user: {
+ type: :string,
+ required: true,
+ },
+ password: {
+ type: :string,
+ required: true,
+ ui: {
+ control: :password,
+ },
+ },
+ }
+ end
+ end
+ end
+end
diff --git a/plugins/discourse-workflows/lib/discourse_workflows/credential_types/bearer_token.rb b/plugins/discourse-workflows/lib/discourse_workflows/credential_types/bearer_token.rb
new file mode 100644
index 00000000000..ab39f87ddfc
--- /dev/null
+++ b/plugins/discourse-workflows/lib/discourse_workflows/credential_types/bearer_token.rb
@@ -0,0 +1,19 @@
+# frozen_string_literal: true
+
+module DiscourseWorkflows
+ module CredentialTypes
+ class BearerToken
+ def self.identifier
+ "bearer_token"
+ end
+
+ def self.display_name
+ "Bearer Token"
+ end
+
+ def self.property_schema
+ { token: { type: :string, required: true, ui: { control: :password } } }
+ end
+ end
+ end
+end
diff --git a/plugins/discourse-workflows/lib/discourse_workflows/credential_types/header_auth.rb b/plugins/discourse-workflows/lib/discourse_workflows/credential_types/header_auth.rb
new file mode 100644
index 00000000000..c3edf0b40fc
--- /dev/null
+++ b/plugins/discourse-workflows/lib/discourse_workflows/credential_types/header_auth.rb
@@ -0,0 +1,31 @@
+# frozen_string_literal: true
+
+module DiscourseWorkflows
+ module CredentialTypes
+ class HeaderAuth
+ def self.identifier
+ "header_auth"
+ end
+
+ def self.display_name
+ "Header Auth"
+ end
+
+ def self.property_schema
+ {
+ name: {
+ type: :string,
+ required: true,
+ },
+ value: {
+ type: :string,
+ required: true,
+ ui: {
+ control: :password,
+ },
+ },
+ }
+ end
+ end
+ end
+end
diff --git a/plugins/discourse-workflows/lib/discourse_workflows/cron_parser.rb b/plugins/discourse-workflows/lib/discourse_workflows/cron_parser.rb
new file mode 100644
index 00000000000..51a5ee17123
--- /dev/null
+++ b/plugins/discourse-workflows/lib/discourse_workflows/cron_parser.rb
@@ -0,0 +1,196 @@
+# frozen_string_literal: true
+
+module DiscourseWorkflows
+ class CronParser
+ InvalidExpression = Class.new(StandardError)
+
+ FieldDefinition =
+ Struct.new(
+ :name,
+ :range,
+ :value_extractor,
+ :value_normalizer,
+ :aliases,
+ keyword_init: true,
+ ) do
+ def value_for(time)
+ normalize(value_extractor.call(time))
+ end
+
+ def normalize(value)
+ return value if value_normalizer.nil?
+
+ value_normalizer.call(value)
+ end
+
+ def value_from_token(token)
+ aliases&.fetch(token.to_s.upcase, nil) || Integer(token)
+ rescue ArgumentError, TypeError
+ raise InvalidExpression
+ end
+ end
+
+ CompiledField =
+ Struct.new(:definition, :values, :unrestricted, keyword_init: true) do
+ def matches?(time)
+ values.include?(definition.value_for(time))
+ end
+
+ def restricted?
+ !unrestricted
+ end
+ end
+
+ CompiledExpression =
+ Struct.new(:fields, keyword_init: true) do
+ def matches?(time)
+ unless fields
+ .values_at(:second, :minute, :hour, :month)
+ .all? { |field| field.matches?(time) }
+ return false
+ end
+
+ day_of_month_match = fields[:day_of_month].matches?(time)
+ day_of_week_match = fields[:day_of_week].matches?(time)
+
+ if fields[:day_of_month].restricted? && fields[:day_of_week].restricted?
+ day_of_month_match || day_of_week_match
+ else
+ day_of_month_match && day_of_week_match
+ end
+ end
+ end
+
+ MONTH_ALIASES =
+ %w[JAN FEB MAR APR MAY JUN JUL AUG SEP OCT NOV DEC]
+ .each_with_index
+ .to_h { |name, index| [name, index + 1] }
+ .freeze
+
+ WEEKDAY_ALIASES = %w[SUN MON TUE WED THU FRI SAT].each_with_index.to_h.freeze
+
+ FIELD_DEFINITIONS = [
+ FieldDefinition.new(name: :second, range: 0..59, value_extractor: ->(time) { time.sec }),
+ FieldDefinition.new(name: :minute, range: 0..59, value_extractor: ->(time) { time.min }),
+ FieldDefinition.new(name: :hour, range: 0..23, value_extractor: ->(time) { time.hour }),
+ FieldDefinition.new(
+ name: :day_of_month,
+ range: 1..31,
+ value_extractor: ->(time) { time.mday },
+ ),
+ FieldDefinition.new(
+ name: :month,
+ range: 1..12,
+ value_extractor: ->(time) { time.month },
+ aliases: MONTH_ALIASES,
+ ),
+ FieldDefinition.new(
+ name: :day_of_week,
+ range: 0..7,
+ value_extractor: ->(time) { time.wday },
+ value_normalizer: ->(value) { value == 7 ? 0 : value },
+ aliases: WEEKDAY_ALIASES,
+ ),
+ ].freeze
+
+ def self.matches?(expression, time)
+ compiled = compile(expression)
+ compiled.present? && compiled.matches?(time)
+ end
+
+ def self.valid?(expression)
+ compile(expression).present?
+ end
+
+ def self.minute_granularity?(expression)
+ fields = tokenize(expression)
+ second_field = compile_field(fields.first, FIELD_DEFINITIONS.first)
+ second_field.values == Set[0]
+ rescue InvalidExpression
+ false
+ end
+
+ def self.compile(expression)
+ fields = tokenize(expression)
+
+ compiled_fields =
+ FIELD_DEFINITIONS.each_with_index.to_h do |definition, index|
+ [definition.name, compile_field(fields[index], definition)]
+ end
+
+ CompiledExpression.new(fields: compiled_fields.freeze)
+ rescue InvalidExpression
+ nil
+ end
+
+ def self.tokenize(expression)
+ raise InvalidExpression if expression.blank?
+
+ fields = expression.strip.split(/\s+/)
+ fields.unshift("0") if fields.size == FIELD_DEFINITIONS.size - 1
+ raise InvalidExpression unless fields.size == FIELD_DEFINITIONS.size
+
+ fields
+ end
+
+ def self.compile_field(field, definition)
+ values = Set.new
+
+ field
+ .split(",")
+ .each do |part|
+ raise InvalidExpression if part.blank?
+
+ expand_part(part, definition).each { |value| values << value }
+ end
+
+ raise InvalidExpression if values.empty?
+
+ CompiledField.new(definition: definition, values: values.freeze, unrestricted: field == "*")
+ end
+
+ def self.expand_part(part, definition)
+ case part
+ when "*"
+ normalize_values(definition.range, definition)
+ when %r{\A\*/(\d+)\z}
+ expand_range(definition.range.begin, definition.range.end, $1, definition)
+ when %r{\A([[:alnum:]]+)-([[:alnum:]]+)(?:/(\d+))?\z}
+ expand_range(
+ definition.value_from_token($1),
+ definition.value_from_token($2),
+ $3 || 1,
+ definition,
+ )
+ when /\A[[:alnum:]]+\z/
+ [normalize_value(definition.value_from_token(part), definition)]
+ else
+ raise InvalidExpression
+ end
+ end
+
+ def self.expand_range(start_value, end_value, step, definition)
+ step = Integer(step)
+
+ raise InvalidExpression if step <= 0
+ raise InvalidExpression if start_value > end_value
+ raise InvalidExpression unless definition.range.cover?(start_value)
+ raise InvalidExpression unless definition.range.cover?(end_value)
+
+ normalize_values((start_value..end_value).step(step), definition)
+ end
+
+ def self.normalize_value(value, definition)
+ raise InvalidExpression unless definition.range.cover?(value)
+
+ definition.normalize(value)
+ end
+
+ def self.normalize_values(values, definition)
+ values.map { |value| definition.normalize(value) }
+ end
+
+ private_class_method :tokenize, :compile_field, :expand_part, :expand_range
+ private_class_method :normalize_value, :normalize_values
+ end
+end
diff --git a/plugins/discourse-workflows/lib/discourse_workflows/data_tables/aggregate_node_proxy.rb b/plugins/discourse-workflows/lib/discourse_workflows/data_tables/aggregate_node_proxy.rb
new file mode 100644
index 00000000000..6ee5ea7479e
--- /dev/null
+++ b/plugins/discourse-workflows/lib/discourse_workflows/data_tables/aggregate_node_proxy.rb
@@ -0,0 +1,105 @@
+# frozen_string_literal: true
+
+module DiscourseWorkflows
+ module DataTables
+ class AggregateNodeProxy
+ DEFAULT_TAKE = 100
+
+ def get_project_id
+ nil
+ end
+
+ def get_many_and_count(options = {})
+ options = normalize_options(options)
+ scope = DiscourseWorkflows::DataTable.all
+ scope = apply_filter(scope, options["filter"])
+ count = scope.count
+ scope = apply_sort(scope, options["sort_by"])
+ scope = scope.offset(options["skip"].to_i) if options["skip"].present?
+ scope = scope.limit((options["take"] || DEFAULT_TAKE).to_i)
+
+ { count: count, data: scope.map { |data_table| serialize_data_table(data_table) } }
+ end
+
+ def create_data_table(options)
+ options = normalize_options(options)
+
+ DiscourseWorkflows::DataTable.transaction do
+ data_table = DiscourseWorkflows::DataTable.create!(name: options.fetch("name"))
+ DiscourseWorkflows::DataTables::Facade.create_table!(
+ data_table,
+ columns: normalize_columns(options["columns"] || []),
+ )
+ serialize_data_table(data_table.reload)
+ end
+ end
+
+ def delete_data_table_all
+ DiscourseWorkflows::DataTable.find_each(&:destroy!)
+ true
+ end
+
+ private
+
+ def normalize_options(options)
+ options.respond_to?(:to_h) ? options.to_h.deep_stringify_keys : {}
+ end
+
+ def apply_filter(scope, filter)
+ return scope if filter.blank?
+
+ filter = filter.to_h.stringify_keys
+ name = filter["name"].presence
+ return scope if name.blank?
+
+ escaped = ActiveRecord::Base.sanitize_sql_like(name.downcase)
+ scope.where("LOWER(name) LIKE ?", "%#{escaped}%")
+ end
+
+ def apply_sort(scope, sort_by)
+ column, direction = sort_by.to_s.split(":", 2)
+ direction = direction == "desc" ? :desc : :asc
+
+ case column
+ when "created_at", "createdAt"
+ scope.order(created_at: direction)
+ when "updated_at", "updatedAt"
+ scope.order(updated_at: direction)
+ else
+ scope.order(name: direction)
+ end
+ end
+
+ def serialize_data_table(data_table)
+ {
+ id: data_table.id,
+ name: data_table.name,
+ columns: data_table.columns.map { |column| serialize_column(column) },
+ }
+ end
+
+ def serialize_column(column)
+ name = DiscourseWorkflows::DataTable.column_name(column)
+ type = DiscourseWorkflows::DataTable.column_type(column)
+ serialized = { name: name, type: type }
+ serialized[:reserved] = true if Types.system_column?(name)
+ serialized
+ end
+
+ def normalize_columns(columns)
+ columns.filter_map do |column|
+ column = column.respond_to?(:to_h) ? column.to_h.deep_stringify_keys : {}
+ name = column["name"].to_s
+ type = column["type"].to_s
+ next if name.blank? || type.blank?
+ next unless DiscourseWorkflows::DataTable::COLUMN_NAME_FORMAT.match?(name)
+ next if DiscourseWorkflows::DataTable::VALID_COLUMN_TYPES.exclude?(type)
+ next if Types.system_column?(name)
+ next if name.length > DiscourseWorkflows::DataTable::MAX_COLUMN_NAME_LENGTH
+
+ { "name" => name, "type" => type }
+ end
+ end
+ end
+ end
+end
diff --git a/plugins/discourse-workflows/lib/discourse_workflows/data_tables/columns_resolver.rb b/plugins/discourse-workflows/lib/discourse_workflows/data_tables/columns_resolver.rb
new file mode 100644
index 00000000000..dd06a971a29
--- /dev/null
+++ b/plugins/discourse-workflows/lib/discourse_workflows/data_tables/columns_resolver.rb
@@ -0,0 +1,48 @@
+# frozen_string_literal: true
+
+module DiscourseWorkflows
+ module DataTables
+ class ColumnsResolver
+ def initialize(data_table)
+ @column_names =
+ data_table
+ .columns
+ .filter_map do |column|
+ name = DiscourseWorkflows::DataTable.column_name(column)
+ name unless Types.system_column?(name)
+ end
+ .to_set
+ end
+
+ def resolve(fields)
+ normalize_fields(fields).each_with_object({}) do |(column_name, value), result|
+ validate_column!(column_name)
+ result[column_name] = value
+ end
+ end
+
+ def validate_column!(column_name)
+ return if @column_names.include?(column_name)
+
+ raise ArgumentError,
+ I18n.t("discourse_workflows.errors.data_table.unknown_column", column: column_name)
+ end
+
+ private
+
+ def normalize_fields(fields)
+ case fields
+ when Hash
+ fields.stringify_keys
+ when Array
+ fields.to_h do |field|
+ field = field.with_indifferent_access
+ [field[:columnName], field[:value]]
+ end
+ else
+ {}
+ end
+ end
+ end
+ end
+end
diff --git a/plugins/discourse-workflows/lib/discourse_workflows/data_tables/facade.rb b/plugins/discourse-workflows/lib/discourse_workflows/data_tables/facade.rb
new file mode 100644
index 00000000000..6db3084a534
--- /dev/null
+++ b/plugins/discourse-workflows/lib/discourse_workflows/data_tables/facade.rb
@@ -0,0 +1,367 @@
+# frozen_string_literal: true
+
+module DiscourseWorkflows
+ module DataTables
+ class Facade
+ LOCK_TIMEOUT_MS = 5_000
+ STATEMENT_TIMEOUT_MS = 500
+
+ class StatementTimeout < StandardError
+ end
+
+ class Query
+ include ActiveModel::Validations
+
+ attr_reader :normalized_filter, :limit, :offset, :sort_by, :sort_direction
+
+ validate :check_filter_errors
+
+ def initialize(
+ data_table:,
+ filter: nil,
+ limit: nil,
+ offset: nil,
+ sort_by: nil,
+ sort_direction: nil,
+ optional_filter: false
+ )
+ normalized_filter =
+ DiscourseWorkflows::NormalizedFilter.new(
+ data_table:,
+ filter:,
+ optional: optional_filter,
+ )
+
+ @invalid_filter = normalized_filter if normalized_filter.invalid?
+ @normalized_filter = normalized_filter.value
+ @limit = limit
+ @offset = offset
+ @sort_by = sort_by
+ @sort_direction = sort_direction
+ end
+
+ def has_changes_to_save?
+ true
+ end
+
+ private
+
+ def check_filter_errors
+ @invalid_filter&.errors&.full_messages&.each { |message| errors.add(:base, message) }
+ end
+ end
+
+ class RowInput
+ include ActiveModel::Validations
+
+ attr_reader :columns
+
+ validate :check_normalization_error
+
+ def initialize(data_table:, data:, fill_missing: false)
+ @columns = DataTableRow.normalize_row_data(data_table, data, fill_missing: fill_missing)
+ rescue ArgumentError => e
+ @normalization_error = e.message
+ @columns = {}
+ end
+
+ def has_changes_to_save?
+ true
+ end
+
+ private
+
+ def check_normalization_error
+ errors.add(:base, @normalization_error) if @normalization_error.present?
+ end
+ end
+
+ MAX_TOTAL_SIZE_BYTES = 50.megabytes
+
+ class << self
+ def within_storage_limit?
+ Storage.total_size_bytes < MAX_TOTAL_SIZE_BYTES
+ end
+
+ def total_size_bytes
+ Storage.total_size_bytes
+ end
+
+ def batch_size_bytes(data_table_ids)
+ Storage.batch_size_bytes(data_table_ids)
+ end
+
+ def size_bytes(data_table_id)
+ Storage.size_bytes(data_table_id)
+ end
+
+ def create_table!(data_table, columns: [])
+ Storage.create_table!(data_table, columns: columns)
+ end
+
+ def drop_table!(data_table_id)
+ Storage.drop_table!(data_table_id)
+ end
+ end
+
+ SORT_DIRECTIONS = { "asc" => "ASC", "desc" => "DESC" }.freeze
+ MAX_LIMIT = 100
+
+ attr_reader :data_table
+
+ def initialize(data_table)
+ @data_table = data_table
+ @table_name = Storage.table_name(data_table.id)
+ @table = Arel::Table.new(@table_name)
+ end
+
+ def build_query(**options)
+ Query.new(data_table: @data_table, **options)
+ end
+
+ def build_row_input(**options)
+ RowInput.new(data_table: @data_table, **options)
+ end
+
+ def query(query)
+ with_statement_timeout { query_rows(query) }
+ end
+
+ def find_row(row_id)
+ with_statement_timeout do
+ query = @table.project(Arel.star).where(@table[:id].eq(row_id))
+ connection.exec_query(query.to_sql).to_a.first&.then { |row| serialize_row(row) }
+ end
+ end
+
+ def count(query = nil)
+ with_statement_timeout { count_rows(normalized_filter: query&.normalized_filter) }
+ end
+
+ def insert(row_input)
+ validate_storage_limit!
+ with_statement_timeout { insert_row(row_input.columns) }
+ end
+
+ def update_row(row_id:, row_input:)
+ return nil if row_input.columns.empty?
+
+ validate_storage_limit!
+ with_statement_timeout do
+ um = build_update_manager(row_input.columns)
+ um.where(@table[:id].eq(row_id))
+ connection
+ .exec_query("#{um.to_sql} RETURNING *")
+ .to_a
+ .first
+ &.then { |row| serialize_row(row) }
+ end
+ end
+
+ def update(query:, row_input:)
+ return 0 if row_input.columns.empty?
+
+ validate_storage_limit!
+ with_statement_timeout do
+ um = build_update_manager(row_input.columns)
+ um = apply_filters(um, query.normalized_filter)
+ connection.exec_update(um.to_sql)
+ end
+ end
+
+ def delete(query:)
+ with_statement_timeout do
+ dm = Arel::DeleteManager.new
+ dm.from(@table)
+ dm = apply_filters(dm, query.normalized_filter)
+ connection.exec_delete(dm.to_sql)
+ end
+ end
+
+ def delete_rows(row_ids)
+ return 0 if row_ids.empty?
+
+ with_statement_timeout do
+ dm = Arel::DeleteManager.new
+ dm.from(@table)
+ dm.where(@table[:id].in(row_ids))
+ connection.exec_delete(dm.to_sql)
+ end
+ end
+
+ def add_column!(name, type)
+ with_lock_timeout do
+ connection.add_column(@table_name, name, Storage::SCHEMA_TYPES.fetch(type))
+ end
+ end
+
+ def rename_column!(old_name:, new_name:)
+ with_lock_timeout { connection.rename_column(@table_name, old_name, new_name) }
+ end
+
+ def drop_column!(column_name)
+ with_lock_timeout { connection.remove_column(@table_name, column_name) }
+ end
+
+ private
+
+ def validate_storage_limit!
+ return if self.class.within_storage_limit?
+ raise ArgumentError, "Data table storage limit exceeded"
+ end
+
+ def query_rows(data_query)
+ query = @table.project(Arel.star, Arel.sql("COUNT(*) OVER() AS _total_count"))
+ query = apply_filters(query, data_query.normalized_filter)
+ query = apply_ordering(query, data_query.sort_by, data_query.sort_direction)
+ query = apply_pagination(query, data_query.limit, data_query.offset)
+
+ results = connection.exec_query(query.to_sql).to_a
+ total_count = results.first&.[]("_total_count") || 0
+ rows = results.map { |row| serialize_row(row.except("_total_count")) }
+
+ { rows: rows, count: total_count }
+ end
+
+ def count_rows(normalized_filter: nil)
+ query = @table.project(Arel.star.count)
+ query = apply_filters(query, normalized_filter)
+ connection.exec_query(query.to_sql).rows.first.first.to_i
+ end
+
+ def insert_row(normalized_data)
+ result =
+ if normalized_data.empty?
+ im = Arel::InsertManager.new
+ im.into(@table)
+ connection.exec_query("#{im.to_sql} DEFAULT VALUES RETURNING *").to_a.first
+ else
+ execute_insert(normalized_data)
+ end
+
+ serialize_row(result)
+ end
+
+ def execute_insert(normalized_data)
+ im = Arel::InsertManager.new
+ im.into(@table)
+ im.insert(normalized_data.map { |name, value| [@table[name], value] })
+ connection.exec_query("#{im.to_sql} RETURNING *").to_a.first
+ end
+
+ def build_update_manager(normalized_data)
+ um = Arel::UpdateManager.new
+ um.table(@table)
+ assignments =
+ normalized_data.map { |name, value| [@table[name], value] } +
+ [[@table[:updated_at], Arel.sql("CURRENT_TIMESTAMP")]]
+ um.set(assignments)
+ um
+ end
+
+ def apply_filters(query, normalized_filter)
+ return query if normalized_filter.blank? || normalized_filter["filters"].blank?
+
+ conditions = normalized_filter["filters"].map { |f| build_arel_condition(f) }
+ combiner = normalized_filter["type"] == "or" ? :or : :and
+ query.where(conditions.reduce(combiner))
+ end
+
+ def apply_ordering(query, sort_by, sort_direction)
+ return query.order(@table[:id].asc) if sort_by.blank?
+
+ if valid_sort_columns.exclude?(sort_by.to_s)
+ raise ArgumentError, "Invalid sort column: #{sort_by.inspect}"
+ end
+
+ direction = SORT_DIRECTIONS[sort_direction.to_s.downcase] || "ASC"
+ query.order(
+ Arel.sql("#{Storage.quoted_column(sort_by)} #{direction} NULLS LAST"),
+ @table[:id].asc,
+ )
+ end
+
+ def valid_sort_columns
+ @valid_sort_columns ||= @data_table.columns.map { |c| c["name"] }.to_set
+ end
+
+ def apply_pagination(query, limit, offset)
+ if limit.present?
+ parsed_limit = [Integer(limit), MAX_LIMIT].min
+ query = query.take(parsed_limit) if parsed_limit > 0
+ end
+ if offset.present?
+ parsed_offset = Integer(offset)
+ query = query.skip(parsed_offset) if parsed_offset > 0
+ end
+ query
+ end
+
+ def build_arel_condition(filter)
+ col = @table[filter["columnName"]]
+ value = filter["value"]
+
+ return filter["condition"] == "eq" ? col.eq(nil) : col.not_eq(nil) if value.nil?
+
+ case filter["condition"]
+ when "eq"
+ col.eq(value)
+ when "neq"
+ col.not_eq(value).or(col.eq(nil))
+ when "gt"
+ col.gt(value)
+ when "gte"
+ col.gteq(value)
+ when "lt"
+ col.lt(value)
+ when "lte"
+ col.lteq(value)
+ when "like"
+ col.matches(escape_like_specials(value), "!", true)
+ when "ilike"
+ col.matches(escape_like_specials(value), "!", false)
+ when "not_ilike"
+ col.does_not_match(escape_like_specials(value), "!", false)
+ else
+ raise ArgumentError, "Unknown filter condition: #{filter["condition"].inspect}"
+ end
+ end
+
+ def escape_like_specials(value)
+ "%#{ActiveRecord::Base.sanitize_sql_like(value.to_s, "!")}%"
+ end
+
+ def connection
+ ActiveRecord::Base.connection
+ end
+
+ def serialize_row(row)
+ row.transform_values { |value| serialize_value(value) }
+ end
+
+ def serialize_value(value)
+ return nil if value.nil?
+
+ value.respond_to?(:iso8601) ? value.utc.iso8601 : value
+ end
+
+ def with_lock_timeout
+ connection.transaction do
+ connection.execute("SET LOCAL lock_timeout = '#{LOCK_TIMEOUT_MS}ms'")
+ yield
+ end
+ rescue PG::LockNotAvailable
+ raise
+ end
+
+ def with_statement_timeout
+ connection.transaction do
+ connection.execute("SET LOCAL statement_timeout = '#{STATEMENT_TIMEOUT_MS}ms'")
+ yield
+ end
+ rescue ActiveRecord::QueryCanceled
+ raise StatementTimeout, "Data table query exceeded the maximum allowed execution time"
+ end
+ end
+ end
+end
diff --git a/plugins/discourse-workflows/lib/discourse_workflows/data_tables/node_proxy.rb b/plugins/discourse-workflows/lib/discourse_workflows/data_tables/node_proxy.rb
new file mode 100644
index 00000000000..c25173d426a
--- /dev/null
+++ b/plugins/discourse-workflows/lib/discourse_workflows/data_tables/node_proxy.rb
@@ -0,0 +1,204 @@
+# frozen_string_literal: true
+
+module DiscourseWorkflows
+ module DataTables
+ class NodeProxy
+ attr_reader :facade
+ delegate :data_table, to: :facade
+
+ def initialize(facade)
+ @facade = facade
+ reset_columns_resolver
+ end
+
+ def update_data_table(options)
+ options = normalize_options(options)
+ @facade.data_table.update!(name: options.fetch("name"))
+ true
+ end
+
+ def delete_data_table
+ @facade.data_table.destroy!
+ true
+ end
+
+ def get_columns
+ user_columns.map.with_index { |column, index| serialize_column(column, index) }
+ end
+
+ def add_column(options)
+ options = normalize_options(options)
+ name = options.fetch("name").to_s
+ type = options.fetch("type").to_s
+
+ validate_column_definition!(name, type)
+ @facade.add_column!(name, type)
+ reset_columns_resolver
+ get_columns.find { |column| column[:name] == name }
+ end
+
+ def delete_column(column_id)
+ @columns_resolver.validate_column!(column_id)
+ @facade.drop_column!(column_id)
+ reset_columns_resolver
+ true
+ end
+
+ def get_many_rows_and_count(options = {})
+ options = normalize_options(options)
+ query = build_query(options, optional_filter: true)
+ result = @facade.query(query)
+
+ { count: result[:count], data: result[:rows] }
+ end
+
+ def insert_rows(rows, return_type)
+ inserted_rows = rows.map { |row| @facade.insert(build_row_input(row)) }
+
+ case return_type.to_s
+ when "all"
+ inserted_rows
+ when "id"
+ inserted_rows.map { |row| { "id" => row.fetch("id") } }
+ when "count"
+ { "success" => true, "insertedRows" => inserted_rows.size }
+ else
+ raise ArgumentError, "Unsupported data table insert return type: #{return_type.inspect}"
+ end
+ end
+
+ def update_rows(options)
+ options = normalize_options(options)
+ query = build_query(options, optional_filter: false)
+ row_input = build_row_input(options["data"] || {})
+ rows = @facade.query(query)[:rows]
+
+ return dry_run_update_rows(rows, row_input) if options["dry_run"]
+
+ rows.filter_map { |row| @facade.update_row(row_id: row.fetch("id"), row_input:) }
+ end
+
+ def upsert_row(options)
+ options = normalize_options(options)
+ query = build_query(options, optional_filter: false)
+ row_input = build_row_input(options["data"] || {})
+ matching_rows = @facade.query(query)[:rows]
+
+ if matching_rows.present?
+ return dry_run_update_rows(matching_rows, row_input) if options["dry_run"]
+
+ matching_rows.filter_map { |row| @facade.update_row(row_id: row.fetch("id"), row_input:) }
+ elsif options["dry_run"]
+ [dry_run_insert_row(row_input)]
+ else
+ [@facade.insert(row_input)]
+ end
+ end
+
+ def delete_rows(options)
+ options = normalize_options(options)
+ query = build_query(options, optional_filter: false)
+ rows = @facade.query(query)[:rows]
+ return rows if options["dry_run"]
+
+ @facade.delete(query:)
+ rows
+ end
+
+ private
+
+ def normalize_options(options)
+ options.respond_to?(:to_h) ? options.to_h.deep_stringify_keys : {}
+ end
+
+ def reset_columns_resolver
+ @columns_resolver = ColumnsResolver.new(@facade.data_table)
+ end
+
+ def user_columns
+ @facade.data_table.columns.filter_map do |column|
+ name = DiscourseWorkflows::DataTable.column_name(column)
+ next if Types.system_column?(name)
+
+ column
+ end
+ end
+
+ def serialize_column(column, index)
+ name = DiscourseWorkflows::DataTable.column_name(column)
+ {
+ id: name,
+ name: name,
+ type: DiscourseWorkflows::DataTable.column_type(column),
+ index: index,
+ data_table_id: @facade.data_table.id,
+ }
+ end
+
+ def validate_column_definition!(name, type)
+ raise ArgumentError, "Column name is required" if name.blank?
+ raise ArgumentError, "Column type is required" if type.blank?
+ unless DiscourseWorkflows::DataTable::COLUMN_NAME_FORMAT.match?(name)
+ raise ArgumentError,
+ "Column name must start with a letter or underscore and contain only letters, numbers, and underscores"
+ end
+ if name.length > DiscourseWorkflows::DataTable::MAX_COLUMN_NAME_LENGTH
+ raise ArgumentError,
+ "Column name must be #{DiscourseWorkflows::DataTable::MAX_COLUMN_NAME_LENGTH} characters or fewer"
+ end
+ raise ArgumentError, "Column name is reserved" if Types.system_column?(name)
+ if DiscourseWorkflows::DataTable::VALID_COLUMN_TYPES.exclude?(type)
+ raise ArgumentError, "Unsupported column type: #{type.inspect}"
+ end
+ if get_columns.any? { |c| c[:name] == name }
+ raise ArgumentError, "Column name already exists"
+ end
+ end
+
+ def build_query(options, optional_filter:)
+ sort_column, sort_direction = options["sort_by"]
+ query =
+ @facade.build_query(
+ filter: options["filter"],
+ limit: options["take"],
+ offset: options["skip"],
+ sort_by: sort_column,
+ sort_direction: sort_direction,
+ optional_filter: optional_filter,
+ )
+ raise_invalid(:query, query) if query.invalid?
+ query
+ end
+
+ def build_row_input(data)
+ row_input =
+ @facade.build_row_input(data: @columns_resolver.resolve(data || {}), fill_missing: false)
+ raise_invalid(:row, row_input) if row_input.invalid?
+ row_input
+ end
+
+ def dry_run_update_rows(rows, row_input)
+ rows.flat_map do |row|
+ [
+ row.merge("dryRunState" => "before"),
+ row.merge(row_input.columns).merge("dryRunState" => "after"),
+ ]
+ end
+ end
+
+ def dry_run_insert_row(row_input)
+ { "id" => nil, "created_at" => nil, "updated_at" => nil, "dryRunState" => "after" }.merge(
+ row_input.columns,
+ )
+ end
+
+ def raise_invalid(type, value)
+ raise ArgumentError,
+ I18n.t(
+ "discourse_workflows.errors.data_table.invalid_#{type}",
+ errors: value.errors.full_messages.join(", "),
+ )
+ end
+ end
+ end
+end
diff --git a/plugins/discourse-workflows/lib/discourse_workflows/data_tables/node_proxy_provider.rb b/plugins/discourse-workflows/lib/discourse_workflows/data_tables/node_proxy_provider.rb
new file mode 100644
index 00000000000..984169e4bb1
--- /dev/null
+++ b/plugins/discourse-workflows/lib/discourse_workflows/data_tables/node_proxy_provider.rb
@@ -0,0 +1,46 @@
+# frozen_string_literal: true
+
+module DiscourseWorkflows
+ module DataTables
+ class NodeProxyProvider
+ ALLOWED_NODE_IDENTIFIERS = %w[action:data_table].freeze
+
+ def initialize(node_identifier:, data_table_access_validator: nil, guardian: nil)
+ @node_identifier = node_identifier.to_s
+ @data_table_access_validator = data_table_access_validator
+ @guardian = guardian
+ end
+
+ def get_data_table_proxy(data_table_id)
+ validate_request!
+ ensure_can_manage_workflows!
+ data_table_id = data_table_id.to_s
+ @data_table_access_validator&.call(data_table_id)
+ data_table = DiscourseWorkflows::DataTable.find(data_table_id)
+
+ NodeProxy.new(Facade.new(data_table))
+ end
+
+ def get_data_table_aggregate_proxy
+ validate_request!
+ ensure_can_manage_workflows!
+
+ AggregateNodeProxy.new
+ end
+
+ private
+
+ def validate_request!
+ return if ALLOWED_NODE_IDENTIFIERS.include?(@node_identifier)
+
+ raise Discourse::InvalidAccess
+ end
+
+ def ensure_can_manage_workflows!
+ return if @guardian.nil? || @guardian.can_manage_workflows?
+
+ raise Discourse::InvalidAccess
+ end
+ end
+ end
+end
diff --git a/plugins/discourse-workflows/lib/discourse_workflows/data_tables/storage.rb b/plugins/discourse-workflows/lib/discourse_workflows/data_tables/storage.rb
new file mode 100644
index 00000000000..998fb0969b8
--- /dev/null
+++ b/plugins/discourse-workflows/lib/discourse_workflows/data_tables/storage.rb
@@ -0,0 +1,140 @@
+# frozen_string_literal: true
+
+module DiscourseWorkflows
+ module DataTables
+ class Storage
+ SCHEMA_TYPES = {
+ "string" => :text,
+ "number" => :float,
+ "boolean" => :boolean,
+ "date" => :timestamp,
+ }.freeze
+
+ RESERVED_COLUMN_NAMES = Types::SYSTEM_COLUMN_NAMES
+
+ TABLE_NAME_PREFIX = "discourse_workflows_data_table_"
+ TABLE_NAME_SUFFIX = "_rows"
+
+ REVERSE_TYPE_MAP = {
+ "int8" => "number",
+ "int4" => "number",
+ "float8" => "number",
+ "text" => "string",
+ "varchar" => "string",
+ "bool" => "boolean",
+ "timestamp" => "date",
+ "timestamptz" => "date",
+ }.freeze
+
+ class << self
+ def table_name(data_table_id)
+ "#{TABLE_NAME_PREFIX}#{Integer(data_table_id)}#{TABLE_NAME_SUFFIX}"
+ end
+
+ def table_name_like_pattern
+ "#{TABLE_NAME_PREFIX}%#{TABLE_NAME_SUFFIX}"
+ end
+
+ def columns(data_table_id)
+ name = table_name(data_table_id)
+ DB
+ .query(<<~SQL, table_name: name)
+ SELECT a.attname AS name, t.typname AS pg_type
+ FROM pg_attribute a
+ JOIN pg_class c ON c.oid = a.attrelid
+ JOIN pg_namespace n ON n.oid = c.relnamespace
+ JOIN pg_type t ON t.oid = a.atttypid
+ WHERE c.relname = :table_name
+ AND n.nspname = current_schema()
+ AND a.attnum > 0
+ AND NOT a.attisdropped
+ ORDER BY a.attnum
+ SQL
+ .map do |row|
+ mapped_type =
+ REVERSE_TYPE_MAP[row.pg_type] ||
+ raise(ArgumentError, "Unmapped PG type '#{row.pg_type}' for column '#{row.name}'")
+ { "name" => row.name, "type" => mapped_type }
+ end
+ end
+
+ def create_table!(data_table, columns: [])
+ name = table_name(data_table.id)
+ return if connection.data_source_exists?(name)
+
+ connection.create_table(name) do |t|
+ columns.each do |column|
+ t.column DataTable.column_name(column), schema_type(DataTable.column_type(column))
+ end
+ t.timestamps default: -> { "CURRENT_TIMESTAMP" }, null: false
+ end
+ end
+
+ def drop_table!(data_table_id)
+ name = table_name(data_table_id)
+ return unless connection.data_source_exists?(name)
+
+ connection.drop_table(name)
+ end
+
+ def total_size_bytes
+ pattern = table_name_like_pattern
+ DB.query_single(<<~SQL, pattern: pattern).first.to_i
+ SELECT COALESCE(SUM(pg_total_relation_size(c.oid)), 0)
+ FROM pg_class c
+ JOIN pg_namespace n ON n.oid = c.relnamespace
+ WHERE n.nspname = current_schema()
+ AND c.relname LIKE :pattern
+ AND c.relkind = 'r'
+ SQL
+ end
+
+ def size_bytes(data_table_id)
+ batch_size_bytes([data_table_id]).fetch(data_table_id, 0)
+ end
+
+ def batch_size_bytes(data_table_ids)
+ return {} if data_table_ids.empty?
+
+ names = data_table_ids.map { |id| table_name(id) }
+ DB
+ .query(<<~SQL, names: names)
+ SELECT c.relname, pg_total_relation_size(c.oid) AS size_bytes
+ FROM pg_class c
+ JOIN pg_namespace n ON n.oid = c.relnamespace
+ WHERE n.nspname = current_schema()
+ AND c.relname = ANY(ARRAY[:names])
+ AND c.relkind = 'r'
+ SQL
+ .to_h do |row|
+ id =
+ row
+ .relname
+ .delete_prefix("discourse_workflows_data_table_")
+ .delete_suffix("_rows")
+ .to_i
+ [id, row.size_bytes.to_i]
+ end
+ end
+
+ def quoted_table(data_table_id)
+ connection.quote_table_name(table_name(data_table_id))
+ end
+
+ def quoted_column(name)
+ connection.quote_column_name(name)
+ end
+
+ private
+
+ def connection
+ ActiveRecord::Base.connection
+ end
+
+ def schema_type(type)
+ SCHEMA_TYPES.fetch(type) { raise ArgumentError, "Unsupported column type '#{type}'" }
+ end
+ end
+ end
+ end
+end
diff --git a/plugins/discourse-workflows/lib/discourse_workflows/data_tables/types.rb b/plugins/discourse-workflows/lib/discourse_workflows/data_tables/types.rb
new file mode 100644
index 00000000000..eb9d9cae950
--- /dev/null
+++ b/plugins/discourse-workflows/lib/discourse_workflows/data_tables/types.rb
@@ -0,0 +1,19 @@
+# frozen_string_literal: true
+
+module DiscourseWorkflows
+ module DataTables
+ module Types
+ SYSTEM_COLUMN_TYPE_MAP = {
+ "id" => "number",
+ "created_at" => "date",
+ "updated_at" => "date",
+ }.freeze
+
+ SYSTEM_COLUMN_NAMES = SYSTEM_COLUMN_TYPE_MAP.keys.freeze
+
+ def self.system_column?(name)
+ SYSTEM_COLUMN_TYPE_MAP.key?(name.to_s)
+ end
+ end
+ end
+end
diff --git a/plugins/discourse-workflows/lib/discourse_workflows/engine.rb b/plugins/discourse-workflows/lib/discourse_workflows/engine.rb
new file mode 100644
index 00000000000..8a47e56f4b8
--- /dev/null
+++ b/plugins/discourse-workflows/lib/discourse_workflows/engine.rb
@@ -0,0 +1,13 @@
+# frozen_string_literal: true
+
+module DiscourseWorkflows
+ class Engine < ::Rails::Engine
+ engine_name PLUGIN_NAME
+ isolate_namespace DiscourseWorkflows
+ config.autoload_paths << File.join(config.root, "lib")
+ scheduled_job_dir = "#{config.root}/app/jobs/scheduled"
+ config.to_prepare do
+ Rails.autoloaders.main.eager_load_dir(scheduled_job_dir) if Dir.exist?(scheduled_job_dir)
+ end
+ end
+end
diff --git a/plugins/discourse-workflows/lib/discourse_workflows/event_listener.rb b/plugins/discourse-workflows/lib/discourse_workflows/event_listener.rb
new file mode 100644
index 00000000000..fe9cbc41202
--- /dev/null
+++ b/plugins/discourse-workflows/lib/discourse_workflows/event_listener.rb
@@ -0,0 +1,35 @@
+# frozen_string_literal: true
+
+module DiscourseWorkflows
+ class EventListener
+ def self.handle(trigger_class, *args)
+ return unless SiteSetting.discourse_workflows_enabled
+
+ trigger = trigger_class.new(*args)
+ return unless trigger.valid?
+
+ trigger_data = nil
+
+ DiscourseWorkflows::Workflow::Action::FindPublishedTriggers
+ .call(
+ trigger_type: trigger_class.identifier,
+ filter: ->(published_trigger) do
+ trigger.matches?(
+ DiscourseWorkflows::TriggerNodeContext.from_published_trigger(published_trigger),
+ )
+ end,
+ )
+ .each do |published_trigger|
+ DiscourseWorkflows::TriggerDispatcher.enqueue(
+ published_trigger,
+ trigger_data: (trigger_data ||= trigger.output),
+ )
+ rescue => e
+ Rails.logger.error(
+ "discourse-workflows: trigger #{trigger_class.identifier} failed " \
+ "for workflow #{published_trigger.workflow_id}: #{e.message}",
+ )
+ end
+ end
+ end
+end
diff --git a/plugins/discourse-workflows/lib/discourse_workflows/executor.rb b/plugins/discourse-workflows/lib/discourse_workflows/executor.rb
new file mode 100644
index 00000000000..a3f5e82e4cd
--- /dev/null
+++ b/plugins/discourse-workflows/lib/discourse_workflows/executor.rb
@@ -0,0 +1,912 @@
+# frozen_string_literal: true
+
+module DiscourseWorkflows
+ class Executor
+ MAX_ITERATIONS = 1000
+ MAX_WAIT_DURATION_SECONDS = 30.days.to_i
+
+ class WaitRequested < StandardError
+ attr_reader :waiting_until
+
+ def initialize(waiting_until)
+ @waiting_until = waiting_until
+ super("Wait requested")
+ end
+ end
+
+ delegate :execution, to: :@store
+
+ def initialize(workflow, trigger_node_id, trigger_data, options = ExecutionOptions.new)
+ @workflow = workflow
+ @trigger_node_id = trigger_node_id.to_s
+ @trigger_data =
+ if trigger_data.is_a?(Array)
+ trigger_data.map(&:deep_stringify_keys)
+ else
+ trigger_data.deep_stringify_keys
+ end
+ @options = options
+ workflow_version = @options.workflow_version
+ workflow_nodes =
+ if @options.workflow_snapshot
+ @options.workflow_snapshot.to_h["nodes"]
+ elsif workflow_version
+ workflow_version.nodes
+ elsif @options.draft_execution
+ @workflow.nodes
+ else
+ @workflow.published_nodes
+ end
+ @context =
+ ExecutionContext.new(
+ workflow: @workflow,
+ trigger_data: @trigger_data,
+ user: @options.user,
+ workflow_nodes: workflow_nodes,
+ workflow_name: workflow_version&.name,
+ )
+ @store =
+ ExecutionStore.new(
+ trigger_node_id: @trigger_node_id,
+ execution_context: @context,
+ execution_mode: @options.execution_mode,
+ options: @options,
+ )
+ @steps = []
+ @queue = []
+ @waiting_inputs = {}
+ @waiting_input_sources = {}
+ @waiting_input_targets = {}
+ @input_wait_requirements = {}
+ @sandbox = nil
+ @waiting_node = nil
+ @waiting_step = nil
+ @pin_data_by_node_name = resolved_pin_data
+ end
+
+ def self.resume(execution, response_items, user: nil, webhook_context: nil)
+ unless execution.running?
+ raise ArgumentError,
+ "Cannot resume execution #{execution.id} with status '#{execution.status}' " \
+ "(callers must claim via Execution.claim_for_resume first)"
+ end
+
+ workflow = execution.workflow
+ trigger_node_id = execution.trigger_node_id
+
+ snapshot =
+ if execution.execution_data&.workflow_data.present?
+ WorkflowSnapshot.new(execution.execution_data.workflow_data)
+ else
+ WorkflowSnapshot.from_workflow(workflow, published: true)
+ end
+
+ unless snapshot.find_node(trigger_node_id)
+ raise "Trigger node #{trigger_node_id} not found in workflow #{workflow.id}"
+ end
+
+ options =
+ ExecutionOptions.new(
+ user: user,
+ execution_mode: execution.execution_mode.to_sym,
+ webhook_context: webhook_context,
+ )
+ new(workflow, trigger_node_id, execution.trigger_data, options).resume_from(
+ execution,
+ response_items,
+ )
+ end
+
+ def run
+ unless @workflow.published? || @options.draft_execution || @options.workflow_version
+ return @store.create_execution_with_status(:skipped)
+ end
+ return @store.create_rate_limited_execution unless rate_limiter.within_limits?
+
+ execute_flow(:start_execution!) do
+ trigger_node = @snapshot.find_node(@trigger_node_id)
+ raise "Trigger node #{@trigger_node_id} not found in workflow snapshot" if trigger_node.nil?
+
+ trigger_items =
+ pinned_items_for(trigger_node) ||
+ (
+ if @trigger_data.is_a?(Array)
+ @trigger_data.map { |data| Item.wrap(data) }
+ else
+ [Item.wrap(@trigger_data)]
+ end
+ )
+ ItemContract.validate_items!(trigger_items, source: "trigger:#{trigger_node.type}")
+ record_step(trigger_node, [], output: trigger_items, status: Step::SUCCESS)
+ @context.store_node_output(trigger_node, trigger_items)
+ @context.store_node_run(trigger_node, inputs: [], outputs: [trigger_items])
+ enqueue_downstream(trigger_node, 0, trigger_items)
+ end
+ end
+
+ def resume_from(execution, response_items)
+ execute_flow(:resume_execution!, execution) do
+ waiting_node_id = execution.waiting_node_id
+ waiting_node = @snapshot.find_node(waiting_node_id)
+ raise "Waiting node #{waiting_node_id} not found in workflow snapshot" if waiting_node.nil?
+
+ update_waiting_step(waiting_node, response_items)
+ @context.store_node_output(waiting_node, response_items)
+ @context.store_node_run(
+ waiting_node,
+ inputs: [],
+ outputs: [response_items],
+ input_sources: @context.consume_waiting_input_sources,
+ )
+ clear_waiting!
+
+ ItemContract.validate_items!(response_items, source: "resume:#{waiting_node.type}")
+ enqueue_downstream(waiting_node, 0, response_items)
+ end
+ end
+
+ private
+
+ def execute_flow(setup_method, *setup_args, &block)
+ send(setup_method, *setup_args)
+ yield
+ process_queue
+ @store.finish!(steps: @steps)
+ rescue WaitRequested => e
+ begin_wait!(e.waiting_until)
+ rescue => e
+ @store.fail!(error: e, steps: @steps)
+ ensure
+ commit_static_data!
+ @sandbox&.dispose
+ end
+
+ # Persists any static_data mutations made by action nodes during the run.
+ # Skipped when no node ever called `get_workflow_static_data` (the state
+ # tracks a dirty flag). Reloads under a row lock so we don't clobber
+ # concurrent executions that wrote to other nodes' flat `node:<name>` slots.
+ def commit_static_data!
+ state = @context&.static_data_state
+ return unless state&.dirty?
+
+ @workflow.with_lock do
+ @workflow.reload
+ existing_node_data = @workflow.node_static_data_entries
+ changed_node_data =
+ state
+ .node
+ .each_with_object({}) do |(node_name, node_data), result|
+ next if node_data.blank? && !existing_node_data.key?(node_name)
+
+ result[node_name] = node_data
+ end
+ merged_node = existing_node_data.merge(changed_node_data)
+ @workflow.commit_static_data!(global: state.global, node: merged_node)
+ end
+ rescue => e
+ Rails.logger.warn(
+ "discourse-workflows: failed to commit static_data for workflow " \
+ "#{@workflow.id}: #{e.class}: #{e.message}",
+ )
+ end
+
+ def process_queue
+ iterations = 0
+ queue_index = 0
+
+ loop do
+ while queue_index < @queue.length
+ iterations += 1
+ raise "Max iterations (#{MAX_ITERATIONS}) exceeded" if iterations > MAX_ITERATIONS
+
+ node, input_groups, input_sources = @queue[queue_index]
+ queue_index += 1
+ execute_node(node, input_groups, input_sources || {})
+ end
+
+ break unless flush_partial_waiting_inputs
+ end
+ end
+
+ def execute_node(node, input_groups, input_sources = {})
+ input_items = primary_input_items(input_groups)
+ node_type_class =
+ DiscourseWorkflows::Registry.find_node_type(node.type, version: node.type_version)
+ return handle_unknown_node(node, input_items) unless node_type_class
+
+ unless node_type_class.available?
+ return handle_unavailable_node(node, node_type_class, input_items)
+ end
+
+ if (pinned = pinned_items_for(node, node_type_class:))
+ return(handle_pinned_node(node, input_items, input_groups, input_sources, pinned))
+ end
+
+ issues = NodeIssues.for_node(node, node_type_class)
+ return handle_node_issues(node, input_items, issues) if issues.any?
+
+ step = record_step(node, input_items)
+ capture_operation_metadata(step, node, node_type_class)
+ js_elapsed_before = sandbox_budget_tracker.current_elapsed_ms
+ node_context = @context.node_context_for(node)
+ resolver_ctx = build_resolver_context(node, input_groups, node_context, input_sources)
+ resolver = build_resolver(resolver_ctx)
+ runtime_state = NodeExecutionContext::RuntimeState.new
+
+ exec_ctx = nil
+ begin
+ exec_ctx =
+ build_node_execution_context(
+ node,
+ input_groups,
+ node_context,
+ node_type_class,
+ resolver,
+ resolver_ctx,
+ runtime_state,
+ )
+ result =
+ node_type_class.new(
+ parameters: node.parameters,
+ credentials: node.credentials,
+ webhook_id: node.webhook_id,
+ ).execute(exec_ctx)
+
+ attach_form_completion(step, node, resolver)
+
+ wait_request = runtime_state.wait_request
+ if wait_request
+ step.mark_waiting!
+ @waiting_node = node
+ @waiting_step = step
+ @context.store_waiting_input_sources(
+ input_sources_for_storage(input_sources, input_groups),
+ )
+ raise WaitRequested, wait_request.waiting_until
+ end
+
+ step_log = collect_step_log(exec_ctx, resolver)
+ attach_step_log(step, step_log)
+ if step_log&.errors?
+ step.fail!(step_log.error_summary)
+ raise StandardError, step.error
+ end
+
+ ports = node_type_class.ports(node.parameters)
+ output_arrays = normalize_result(result, node, ports, input_groups)
+ output_arrays = apply_always_output_data(output_arrays, node, input_groups)
+ all_items = output_arrays.flatten(1)
+ primary_empty = output_arrays.fetch(0) { [] }.empty?
+
+ if node_type_class.branching? && primary_empty
+ step.filter!(output: all_items)
+ else
+ step.succeed!(output: all_items)
+ end
+
+ @context.store_node_output(node, all_items)
+ @context.store_node_run(
+ node,
+ inputs: input_groups_for_storage(input_groups),
+ outputs: output_arrays,
+ input_sources: input_sources_for_storage(input_sources, input_groups),
+ )
+ route_downstream(node, output_arrays)
+ rescue WaitRequested
+ raise
+ rescue => e
+ unless step.metadata&.key?("logs")
+ attach_step_log(step, collect_step_log(exec_ctx, resolver))
+ end
+
+ if (handled_outputs = continued_error_outputs(node, input_groups, e))
+ step.add_metadata("handled_error", error_metadata(e))
+ all_items = handled_outputs.flatten(1)
+ step.succeed!(output: all_items)
+ step.apply_updates!("error" => nil)
+ @context.store_node_output(node, all_items)
+ @context.store_node_run(
+ node,
+ inputs: input_groups_for_storage(input_groups),
+ outputs: handled_outputs,
+ input_sources: input_sources_for_storage(input_sources, input_groups),
+ )
+ route_downstream(node, handled_outputs)
+ return
+ end
+
+ step.fail!(e.message) unless step.error?
+ raise
+ ensure
+ resolver&.dispose
+ js_elapsed = (sandbox_budget_tracker.current_elapsed_ms - js_elapsed_before).round(1)
+ step.add_metadata("js_elapsed_ms", js_elapsed) if js_elapsed > 0
+ runtime_state.step_metadata.each { |key, value| step.add_metadata(key, value) }
+ end
+ end
+
+ def collect_step_log(exec_ctx, resolver)
+ return unless exec_ctx
+
+ log = exec_ctx.log || StepLog.new
+ errors = resolver&.expression_errors || []
+ errors.each { |err| log.error("#{err[:expression]}: #{err[:error]}") } if errors.present?
+ log
+ end
+
+ def attach_step_log(step, step_log)
+ return if step_log.nil? || step_log.empty?
+
+ step.add_metadata("logs", step_log.as_json)
+ end
+
+ def attach_form_completion(step, node, resolver)
+ return unless DiscourseWorkflows::FormCompletion.completion_node?(node)
+
+ step.add_metadata(
+ DiscourseWorkflows::FormCompletion::METADATA_KEY,
+ DiscourseWorkflows::FormCompletion.for_node(node, resolver: resolver),
+ )
+ end
+
+ def handle_unknown_node(node, input_items)
+ Rails.logger.warn(
+ "discourse-workflows: unknown node type '#{node.type}' (version: #{node.type_version}) " \
+ "in workflow #{@context.workflow.id}, skipping node '#{node.name}'",
+ )
+ record_step(node, input_items, status: Step::ERROR, error: "Unknown node type '#{node.type}'")
+ end
+
+ def handle_unavailable_node(node, node_type_class, input_items)
+ reason = node_type_class.unavailable_reason_key || "discourse_workflows.node_unavailable"
+ Rails.logger.warn(
+ "discourse-workflows: node type '#{node.type}' is unavailable " \
+ "in workflow #{@context.workflow.id}, passing through node '#{node.name}'",
+ )
+ step = record_step(node, input_items)
+ step.skip!(output: input_items, reason: reason)
+ @context.store_node_output(node, input_items)
+ @context.store_node_run(node, inputs: [input_items], outputs: [input_items])
+ enqueue_downstream(node, 0, input_items)
+ end
+
+ def handle_node_issues(node, input_items, issues)
+ reason = issues.map { |i| "#{i[:path]}: #{i[:message]}" }.join(", ")
+ step = record_step(node, input_items)
+ step.skip!(output: input_items, reason: reason)
+ @context.store_node_output(node, input_items)
+ @context.store_node_run(node, inputs: [input_items], outputs: [input_items])
+ enqueue_downstream(node, 0, input_items)
+ end
+
+ def handle_pinned_node(node, input_items, input_groups, input_sources, pinned_items)
+ step = record_step(node, input_items)
+ step.succeed!(output: pinned_items)
+ step.add_metadata("pinned", true)
+ @context.store_node_output(node, pinned_items)
+ @context.store_node_run(
+ node,
+ inputs: input_groups_for_storage(input_groups),
+ outputs: [pinned_items],
+ input_sources: input_sources_for_storage(input_sources, input_groups),
+ )
+ enqueue_downstream(node, 0, pinned_items)
+ end
+
+ # Returns pinned items for this node when:
+ # - the run is in :manual mode (pin data is never used in :normal mode),
+ # - the workflow has pin data for this node name,
+ # - the node type has a single primary output.
+ # Returns nil otherwise.
+ def pinned_items_for(node, node_type_class: nil)
+ return nil if @pin_data_by_node_name.empty?
+
+ raw_items = @pin_data_by_node_name[node.name.to_s]
+ return nil if raw_items.blank?
+
+ node_type_class ||=
+ DiscourseWorkflows::Registry.find_node_type(node.type, version: node.type_version)
+ return nil if node_type_class.nil?
+ return nil if Array(node_type_class.outputs).length > 1
+
+ Item.normalize_items(raw_items)
+ rescue Item::InconsistentItemFormatError
+ nil
+ end
+
+ def resolved_pin_data
+ return {} unless @options.execution_mode == :manual
+
+ data = @workflow.respond_to?(:pin_data) ? @workflow.pin_data : nil
+ return {} if data.blank?
+
+ data.transform_keys(&:to_s)
+ end
+
+ def build_node_execution_context(
+ node,
+ input_groups,
+ node_context,
+ node_type_class,
+ resolver,
+ resolver_ctx,
+ runtime_state
+ )
+ NodeExecutionContext.new(
+ input_items: primary_input_items(input_groups),
+ input_groups: input_groups,
+ parameters: node.parameters,
+ credentials: node.credentials,
+ node_settings: DiscourseWorkflows::NodeData.direct_settings(node),
+ webhook_id: node.webhook_id,
+ property_schema: node_type_class.property_schema,
+ credential_schema: node_type_class.credentials,
+ node_context: node_context,
+ user: @options.user,
+ resolver: resolver,
+ vars: preloaded_vars,
+ workflow: @workflow,
+ execution_id: @store.execution&.id,
+ resume_token: @context.resume_token,
+ node_id: node.id.to_s,
+ node_name: node.name.to_s,
+ node_identifier: node.type,
+ execution_mode: @options.execution_mode,
+ flow_context: @context.context,
+ resolver_context: resolver_ctx,
+ workflow_dependencies: preloaded_workflow_dependencies,
+ workflow_snapshot: @snapshot,
+ webhook_context: @options.webhook_context,
+ runtime_state: runtime_state,
+ static_data_state: @context.static_data_state,
+ )
+ end
+
+ def normalize_result(result, node, ports, input_groups)
+ source = "#{node.name} (#{node.type})"
+ ItemContract.validate_output_arrays!(result, source: source, ports: ports)
+
+ apply_item_linking_defaults!(result, input_groups:)
+ ItemContract.validate_output_arrays!(result, source: source, ports: ports)
+ result
+ end
+
+ def apply_item_linking_defaults!(output_arrays, input_groups:)
+ input_lookup = input_item_lookup(input_groups)
+ sole_input_pair = sole_input_pair(input_groups)
+ primary_items = primary_input_items(input_groups)
+ one_output = output_arrays.length == 1
+
+ output_arrays.each do |items|
+ items.each_with_index do |item, index|
+ pair =
+ if input_lookup.key?(item.object_id)
+ input_lookup[item.object_id]
+ elsif Item.paired_item(item).present?
+ Item.paired_item(item)
+ elsif sole_input_pair
+ sole_input_pair
+ elsif one_output && index < primary_items.length && items.length == primary_items.length
+ pair_for(input: 0, item: index)
+ end
+
+ items[index] = Item.with_paired_item(item, pair) if pair.present?
+ end
+ end
+ end
+
+ def input_item_lookup(input_groups)
+ input_groups.each_with_object({}) do |(input_index, items), lookup|
+ items.each_with_index do |item, item_index|
+ lookup[item.object_id] = pair_for(input: input_index, item: item_index)
+ end
+ end
+ end
+
+ def sole_input_pair(input_groups)
+ pairs =
+ input_groups.flat_map do |input_index, items|
+ items.each_index.map { |item_index| pair_for(input: input_index, item: item_index) }
+ end
+ pairs.one? ? pairs.first : nil
+ end
+
+ def pair_for(input:, item:, include_input: false)
+ pair = { "item" => item }
+ pair["input"] = input if include_input || input != 0
+ pair
+ end
+
+ def apply_always_output_data(output_arrays, node, input_groups)
+ return output_arrays unless always_output_data?(node)
+ return output_arrays if output_arrays.fetch(0) { [] }.any?
+
+ pairs =
+ input_groups.flat_map do |input_index, items|
+ items.each_index.map do |item_index|
+ pair_for(input: input_index, item: item_index, include_input: true)
+ end
+ end
+ synthetic = { "json" => {}, "pairedItem" => pairs }
+
+ output_arrays = output_arrays.dup
+ output_arrays[0] = [synthetic]
+ output_arrays
+ end
+
+ def always_output_data?(node)
+ ActiveModel::Type::Boolean.new.cast(
+ DiscourseWorkflows::NodeData.read(node, "alwaysOutputData"),
+ ) == true
+ end
+
+ def continued_error_outputs(node, input_groups, error)
+ case node_error_mode(node)
+ when "continueRegularOutput"
+ [primary_input_items(input_groups)]
+ when "continueErrorOutput"
+ [[], error_output_items(primary_input_items(input_groups), error)]
+ end
+ end
+
+ def node_error_mode(node)
+ on_error = DiscourseWorkflows::NodeData.read(node, "onError").presence
+ return on_error if %w[continueRegularOutput continueErrorOutput].include?(on_error)
+ return "stopWorkflow" if on_error == "stopWorkflow"
+ return if on_error.present?
+
+ if ActiveModel::Type::Boolean.new.cast(
+ DiscourseWorkflows::NodeData.read(node, "continueOnFail"),
+ ) == true
+ "continueRegularOutput"
+ end
+ end
+
+ def error_output_items(input_items, error)
+ metadata = error_metadata(error)
+ return [{ "json" => {}, "error" => metadata }] if input_items.empty?
+
+ input_items.map.with_index do |item, index|
+ item.deep_dup.merge("error" => metadata, "pairedItem" => pair_for(input: 0, item: index))
+ end
+ end
+
+ def error_metadata(error)
+ { "message" => error.message, "name" => error.class.name }
+ end
+
+ def route_downstream(node, output_arrays)
+ output_arrays.each_with_index { |items, index| enqueue_downstream(node, index, items) }
+ end
+
+ def enqueue_downstream(node, output_index, items)
+ @snapshot
+ .connections_from_output_index(node, output_index)
+ .each do |conn|
+ target = @snapshot.target_node(conn)
+ if target
+ enqueue_target(
+ target,
+ conn.target_input_index,
+ items,
+ source: {
+ "node_name" => node.name,
+ "output_index" => output_index,
+ },
+ )
+ end
+ end
+ end
+
+ def enqueue_target(target, target_input_index, items, source:)
+ target_input_index = target_input_index.to_i
+ requirements = input_wait_requirements(target)
+ inputs_to_wait_for = requirements[:inputs_to_wait_for]
+
+ if requirements[:minimum_input_count]
+ return enqueue_minimum_input_target(target, target_input_index, items, source, requirements)
+ end
+
+ if inputs_to_wait_for.length <= 1
+ return if items.empty?
+
+ @queue << [target, { 0 => items }, { 0 => source }]
+ return
+ end
+
+ inputs = (@waiting_inputs[target.id] ||= {})
+ sources = (@waiting_input_sources[target.id] ||= {})
+ @waiting_input_targets[target.id] = target
+ inputs[target_input_index] = items
+ sources[target_input_index] = source
+
+ return unless inputs_to_wait_for.all? { |index| inputs.key?(index) }
+
+ @waiting_inputs.delete(target.id)
+ @waiting_input_sources.delete(target.id)
+ @waiting_input_targets.delete(target.id)
+ @queue << [target, inputs, sources]
+ end
+
+ def enqueue_minimum_input_target(target, target_input_index, items, source, requirements)
+ inputs = (@waiting_inputs[target.id] ||= {})
+ sources = (@waiting_input_sources[target.id] ||= {})
+ @waiting_input_targets[target.id] = target
+ inputs[target_input_index] = items
+ sources[target_input_index] = source
+
+ connected_inputs = requirements[:connected_inputs]
+ if connected_inputs.length <= requirements[:minimum_input_count] ||
+ connected_inputs.all? { |index| inputs.key?(index) }
+ return enqueue_waiting_input_target(target)
+ end
+
+ return if available_input_count(inputs) >= requirements[:minimum_input_count]
+
+ @waiting_inputs.delete(target.id)
+ @waiting_input_sources.delete(target.id)
+ @waiting_input_targets.delete(target.id)
+ end
+
+ def enqueue_waiting_input_target(target)
+ inputs = @waiting_inputs.delete(target.id) || {}
+ sources = @waiting_input_sources.delete(target.id) || {}
+ @waiting_input_targets.delete(target.id)
+ return if available_input_count(inputs).zero?
+
+ @queue << [target, inputs, sources]
+ end
+
+ def flush_partial_waiting_inputs
+ queued_any = false
+ waiting_target_ids = @waiting_input_targets.keys
+ @waiting_input_targets.dup.each_value do |target|
+ requirements = input_wait_requirements(target)
+ next unless requirements[:minimum_input_count]
+ next if waiting_input_parent?(target, waiting_target_ids)
+
+ inputs = @waiting_inputs[target.id] || {}
+ next if available_input_count(inputs) < requirements[:minimum_input_count]
+
+ enqueue_waiting_input_target(target)
+ queued_any = true
+ end
+ queued_any
+ end
+
+ def available_input_count(inputs)
+ inputs.count { |_index, items| items.present? }
+ end
+
+ def waiting_input_parent?(target, waiting_target_ids)
+ @snapshot
+ .connections_to(target)
+ .any? { |conn| waiting_target_ids.include?(conn.source_node_id.to_s) }
+ end
+
+ def input_wait_requirements(target)
+ @input_wait_requirements[target.id] ||= begin
+ node_type_class =
+ DiscourseWorkflows::Registry.find_node_type(target.type, version: target.type_version)
+ input_ports =
+ node_type_class&.input_ports(target.parameters) ||
+ [{ key: "main", index: 0, required: true }]
+ explicit_required_inputs = node_type_class&.required_inputs(target.parameters)
+ required_inputs = input_ports.select { |port| port[:required] }.map { |port| port[:index] }
+ connected_inputs = @snapshot.connections_to(target).map(&:target_input_index).uniq
+
+ if explicit_required_inputs.is_a?(Integer)
+ {
+ connected_inputs: connected_inputs,
+ inputs_to_wait_for: [],
+ minimum_input_count: explicit_required_inputs,
+ }
+ elsif explicit_required_inputs.present?
+ {
+ connected_inputs: connected_inputs,
+ inputs_to_wait_for: Array(explicit_required_inputs).map(&:to_i),
+ }
+ else
+ {
+ connected_inputs: connected_inputs,
+ inputs_to_wait_for: (required_inputs + connected_inputs).uniq,
+ }
+ end
+ end
+ end
+
+ def primary_input_items(input_groups)
+ input_groups.fetch(0) { input_groups.values.first || [] }
+ end
+
+ def input_groups_for_storage(input_groups)
+ max_index = input_groups.keys.max || 0
+ Array.new(max_index + 1) { |index| input_groups[index] || [] }
+ end
+
+ def input_sources_for_storage(input_sources, input_groups)
+ max_index = [input_groups.keys.max || 0, input_sources.keys.max || 0].max
+ Array.new(max_index + 1) { |index| input_sources[index] || {} }
+ end
+
+ def capture_operation_metadata(step, node, node_type_class)
+ properties = node_type_class.properties
+ return unless properties.is_a?(Hash) && properties.key?(:operation)
+
+ operation_value = node.parameters&.dig("operation") || node.parameters&.dig(:operation)
+ return if operation_value.blank?
+
+ step.add_metadata("operation", operation_value)
+ end
+
+ def record_step(node, input_items, output: [], status: Step::RUNNING, error: nil)
+ step =
+ Step.build(
+ node: node,
+ position: @steps.size,
+ input: input_items,
+ output: output,
+ status: status,
+ error: error,
+ )
+ @steps << step
+ step
+ end
+
+ def update_waiting_step(waiting_node, response_items)
+ step = @steps.find { |s| s.node_id == waiting_node.id.to_s && s.status == Step::WAITING }
+ if step.nil?
+ Rails.logger.warn(
+ "discourse-workflows: waiting step not found for node '#{waiting_node.id}' " \
+ "in workflow #{@context.workflow.id}",
+ )
+ return
+ end
+ step.apply_updates!(
+ "status" => Step::SUCCESS,
+ "output" => response_items,
+ "finished_at" => Time.current.iso8601,
+ )
+ end
+
+ def begin_wait!(waiting_until)
+ now = Time.current
+ ceiling = now + MAX_WAIT_DURATION_SECONDS
+ resolved = waiting_until.blank? ? ceiling : [waiting_until, ceiling].min
+
+ execution =
+ @store.pause_waiting_execution!(node: @waiting_node, waiting_until: resolved, steps: @steps)
+
+ duration = [resolved - now, 0].max
+ Jobs.enqueue_in(
+ duration,
+ Jobs::DiscourseWorkflows::ResumeWaitingExecution,
+ execution_id: @store.execution.id,
+ )
+
+ execution
+ rescue => e
+ @store.fail!(error: e, steps: @steps)
+ end
+
+ def start_execution!
+ @store.start!
+ @snapshot = @store.workflow_snapshot
+ @steps = []
+ @queue = []
+ @waiting_inputs = {}
+ @waiting_input_sources = {}
+ @waiting_input_targets = {}
+ @input_wait_requirements = {}
+ end
+
+ def resume_execution!(execution)
+ @store.resume!(execution)
+ @snapshot = @store.workflow_snapshot
+ @steps = restore_steps_from(execution)
+ @queue = []
+ @waiting_inputs = {}
+ @waiting_input_sources = {}
+ @waiting_input_targets = {}
+ @input_wait_requirements = {}
+ end
+
+ def clear_waiting!
+ @store.clear_waiting_execution!
+ @waiting_node = nil
+ @waiting_step = nil
+ end
+
+ def restore_steps_from(execution)
+ entries = execution.execution_data&.entries || {}
+ entries.values.flatten.map { |h| Step.from_h(h) }
+ end
+
+ def build_resolver_context(node, input_groups, node_context, input_sources)
+ input_items = primary_input_items(input_groups)
+ current_item = input_items.first || { "json" => {} }
+ base =
+ @context.resolver_context(
+ "__input_item" => current_item,
+ "__input_items" => input_items,
+ "__input_params" => node.parameters,
+ "__input_context" => DiscourseWorkflows::InputContext.from_node_context(node_context),
+ "__current_node_id" => node.id.to_s,
+ "__node_parameters_by_name" => node_parameters_by_name,
+ "$itemIndex" => 0,
+ )
+ base["__input_sources"] = input_sources_for_storage(input_sources, input_groups)
+ base.merge("$json" => current_item.fetch("json") { {} })
+ end
+
+ def node_parameters_by_name
+ @node_parameters_by_name ||=
+ @snapshot
+ .nodes
+ .each_with_object({}) do |node, by_name|
+ name = node.name.to_s
+ next if name.blank?
+
+ by_name[name] = by_name.key?(name) ? nil : node.parameters
+ end
+ .compact
+ end
+
+ def build_resolver(resolver_ctx)
+ ExpressionResolver.new(resolver_ctx, user: @options.user, sandbox: shared_sandbox)
+ end
+
+ def shared_sandbox
+ @sandbox ||=
+ DiscourseWorkflows::JsSandbox.new(
+ @context.resolver_context,
+ user: @options.user,
+ vars: preloaded_vars,
+ budget_tracker: sandbox_budget_tracker,
+ )
+ end
+
+ def preloaded_vars
+ @preloaded_vars ||= DiscourseWorkflows::Variable.pluck(:key, :value).to_h
+ end
+
+ def preloaded_workflow_dependencies
+ @preloaded_workflow_dependencies ||=
+ @snapshot
+ .nodes
+ .each_with_object(Hash.new { |h, k| h[k] = Set.new }) do |node, dependencies|
+ node_dependencies(node).each do |type, key|
+ dependencies[node.id.to_s] << "#{type}:#{key}"
+ end
+ end
+ end
+
+ def node_dependencies(node)
+ parameters = NodeData.parameters(node)
+ credentials =
+ NodeData.split(
+ parameters: parameters,
+ credentials: NodeData.credentials(node),
+ node_type: node.type,
+ )[
+ "credentials"
+ ]
+ dependencies = []
+ credentials.each_value do |credential|
+ dependencies << ["credential_id", credential["id"]] if credential["id"].present?
+ end
+ if parameters["data_table_id"].present?
+ dependencies << ["data_table_id", parameters["data_table_id"]]
+ end
+ dependencies
+ end
+
+ def sandbox_budget_tracker
+ @sandbox_budget_tracker ||= DiscourseWorkflows::SandboxBudget.new(@context.context)
+ end
+
+ def rate_limiter
+ @rate_limiter ||= ExecutionRateLimiter.new(@workflow)
+ end
+ end
+end
diff --git a/plugins/discourse-workflows/lib/discourse_workflows/executor/actor_policy.rb b/plugins/discourse-workflows/lib/discourse_workflows/executor/actor_policy.rb
new file mode 100644
index 00000000000..ec2842c4afd
--- /dev/null
+++ b/plugins/discourse-workflows/lib/discourse_workflows/executor/actor_policy.rb
@@ -0,0 +1,21 @@
+# frozen_string_literal: true
+
+module DiscourseWorkflows
+ class Executor
+ class ActorPolicy
+ def initialize(exec_ctx)
+ @exec_ctx = exec_ctx
+ end
+
+ def ensure_allowed!(actor, field:, item_index:, source:, purpose:)
+ raise Discourse::InvalidAccess if actor.blank?
+ raise Discourse::InvalidAccess if actor.staged?
+ raise Discourse::InvalidAccess if actor.silenced?
+ raise Discourse::InvalidAccess if actor.suspended?
+ raise Discourse::InvalidAccess if !actor.active?
+
+ true
+ end
+ end
+ end
+end
diff --git a/plugins/discourse-workflows/lib/discourse_workflows/executor/code_runner.rb b/plugins/discourse-workflows/lib/discourse_workflows/executor/code_runner.rb
new file mode 100644
index 00000000000..16c80ebadab
--- /dev/null
+++ b/plugins/discourse-workflows/lib/discourse_workflows/executor/code_runner.rb
@@ -0,0 +1,252 @@
+# frozen_string_literal: true
+
+module DiscourseWorkflows
+ class Executor
+ class CodeRunner
+ RUN_CODE = "runCode"
+ RUN_ONCE_FOR_ALL_ITEMS = "runOnceForAllItems"
+ RUN_ONCE_FOR_EACH_ITEM = "runOnceForEachItem"
+ JAVASCRIPT_UNDEFINED =
+ Object
+ .new
+ .tap do |undefined|
+ def undefined.to_s
+ "undefined"
+ end
+
+ def undefined.inspect
+ "undefined"
+ end
+ end
+ .freeze
+
+ def initialize(
+ input_items:,
+ parameters:,
+ input_context:,
+ resolver_context:,
+ user:,
+ vars:,
+ flow_context:,
+ runtime_state:
+ )
+ @input_items = input_items
+ @parameters = parameters
+ @input_context = input_context
+ @resolver_context = resolver_context || {}
+ @user = user
+ @vars = vars
+ @flow_context = flow_context || {}
+ @runtime_state = runtime_state
+ end
+
+ def run(settings, item_index)
+ item_index = normalize_item_index(item_index)
+
+ case settings.fetch("nodeMode")
+ when RUN_CODE
+ run_javascript_code(settings, item_index)
+ when RUN_ONCE_FOR_ALL_ITEMS
+ run_javascript_for_all_items(settings, item_index)
+ when RUN_ONCE_FOR_EACH_ITEM
+ run_javascript_for_each_item(settings)
+ else
+ raise ArgumentError, "Unsupported JavaScript node mode: #{settings["nodeMode"]}"
+ end
+ end
+
+ private
+
+ def run_javascript_code(settings, item_index)
+ with_javascript_sandbox(item_index:) do |sandbox|
+ declare_additional_properties(sandbox, settings["additionalProperties"])
+ raw_javascript_result(sandbox, settings.fetch("code"))
+ end
+ end
+
+ def run_javascript_for_all_items(settings, item_index)
+ with_javascript_sandbox(item_index:) do |sandbox|
+ setup_code_sandbox!(
+ sandbox,
+ @input_items,
+ @parameters,
+ input_context,
+ item_alias: @input_items.fetch(item_index) { @input_items.first || { "json" => {} } },
+ )
+ declare_additional_properties(
+ sandbox,
+ { "items" => @input_items }.merge(settings["additionalProperties"] || {}),
+ )
+ raw_javascript_result(sandbox, settings.fetch("code"))
+ end
+ end
+
+ def run_javascript_for_each_item(settings)
+ chunk = settings["chunk"] || {}
+ start_index = chunk.fetch("startIndex") { 0 }.to_i
+ end_index = start_index + chunk.fetch("count") { @input_items.length }.to_i
+
+ with_javascript_sandbox(item_index: start_index) do |sandbox|
+ setup_code_sandbox!(
+ sandbox,
+ @input_items,
+ @parameters,
+ input_context,
+ item_alias: @input_items[start_index] || { "json" => {} },
+ )
+ declare_additional_properties(sandbox, settings["additionalProperties"])
+
+ @input_items[start_index...end_index].each_with_index.filter_map do |item, offset|
+ item_index = start_index + offset
+ sandbox.rebind_code_item(item, item_index: item_index)
+ sandbox.eval("item = $input.item;")
+ result = raw_javascript_result(sandbox, settings.fetch("code"))
+ next if result.nil?
+
+ result
+ end
+ end
+ end
+
+ def with_javascript_sandbox(capture_logs: true, item_index: 0)
+ sandbox =
+ JsSandbox.new(
+ resolver_context_for_item_index(item_index),
+ user: @user,
+ vars: @vars,
+ capture_logs: capture_logs,
+ budget_tracker: sandbox_budget_tracker,
+ )
+ yield sandbox
+ ensure
+ @runtime_state.log.merge(sandbox.log) if capture_logs && sandbox&.log
+ sandbox&.dispose
+ end
+
+ def sandbox_budget_tracker
+ @sandbox_budget_tracker ||= DiscourseWorkflows::SandboxBudget.new(@flow_context)
+ end
+
+ def resolver_context_for_item_index(item_index)
+ item = @input_items.fetch(item_index) { { "json" => {} } }
+ @resolver_context.merge(
+ "__input_item" => item,
+ "$json" => item.fetch("json") { {} },
+ "$itemIndex" => item_index,
+ )
+ end
+
+ def declare_additional_properties(sandbox, additional_properties)
+ (additional_properties || {}).each do |name, value|
+ name = name.to_s
+ unless js_identifier?(name)
+ raise ArgumentError, "Invalid JavaScript property name: #{name}"
+ end
+
+ sandbox.declare_json(name, value)
+ end
+ end
+
+ def setup_code_sandbox!(sandbox, input_items, input_params, input_context, item_alias:)
+ sandbox.declare_json("__allInputItems", input_items)
+ sandbox.declare_json("__inputParams", input_params)
+ sandbox.declare_json("__inputContext", input_context)
+ sandbox.declare_json("__initialItem", item_alias)
+ sandbox.eval(<<~JS)
+ function __WorkflowCodeInput(item) {
+ this.item = item;
+ this.params = __inputParams;
+ this.context = __inputContext;
+ }
+
+ __WorkflowCodeInput.prototype.all = function() {
+ if (arguments.length) {
+ throw new Error("$input.all() should have no arguments");
+ }
+
+ return __allInputItems;
+ };
+
+ __WorkflowCodeInput.prototype.first = function() {
+ if (arguments.length) {
+ throw new Error("$input.first() should have no arguments");
+ }
+
+ return __allInputItems[0] || { json: {} };
+ };
+
+ __WorkflowCodeInput.prototype.last = function() {
+ if (arguments.length) {
+ throw new Error("$input.last() should have no arguments");
+ }
+
+ return __allInputItems[__allInputItems.length - 1] || { json: {} };
+ };
+
+ var $input = new __WorkflowCodeInput(__initialItem);
+ var __itemIndex = 0;
+ var item = $input.item;
+ Object.defineProperty(this, '$json', {
+ get: function() { return $input.item.json; },
+ set: function(value) { $input.item.json = value; },
+ configurable: true
+ });
+ Object.defineProperty(this, '$itemIndex', {
+ get: function() { return __itemIndex; },
+ set: function(value) { __itemIndex = value; },
+ configurable: true
+ });
+ JS
+ end
+
+ def evaluate_code(sandbox, code)
+ sandbox.eval(<<~JS)
+ (function() {
+ var __discourseWorkflowsCodeResult = (function() { #{code} })();
+
+ if (__discourseWorkflowsCodeResult === null) {
+ return { type: "null" };
+ }
+
+ if (typeof __discourseWorkflowsCodeResult === "undefined") {
+ return { type: "undefined" };
+ }
+
+ return {
+ type: typeof __discourseWorkflowsCodeResult,
+ value: __discourseWorkflowsCodeResult
+ };
+ })()
+ JS
+ end
+
+ def raw_javascript_result(sandbox, code)
+ result = evaluate_code(sandbox, code)
+
+ case result["type"]
+ when "null"
+ nil
+ when "undefined"
+ JAVASCRIPT_UNDEFINED
+ else
+ result["value"]
+ end
+ end
+
+ def input_context
+ @input_context.respond_to?(:call) ? @input_context.call : @input_context
+ end
+
+ def js_identifier?(name)
+ name.match?(/\A[$A-Za-z_][$0-9A-Za-z_]*\z/)
+ end
+
+ def normalize_item_index(item_index)
+ return 0 if item_index.nil?
+ return item_index if item_index.is_a?(Integer)
+
+ raise ArgumentError, "item_index must be an Integer"
+ end
+ end
+ end
+end
diff --git a/plugins/discourse-workflows/lib/discourse_workflows/executor/error_workflow_trigger.rb b/plugins/discourse-workflows/lib/discourse_workflows/executor/error_workflow_trigger.rb
new file mode 100644
index 00000000000..ad79405038e
--- /dev/null
+++ b/plugins/discourse-workflows/lib/discourse_workflows/executor/error_workflow_trigger.rb
@@ -0,0 +1,98 @@
+# frozen_string_literal: true
+
+module DiscourseWorkflows
+ class Executor
+ class ErrorWorkflowTrigger
+ def initialize(workflow, steps, execution: nil, execution_mode:)
+ @workflow = workflow
+ @steps = steps
+ @execution = execution
+ @execution_mode = execution_mode
+ end
+
+ def trigger_error_workflow(error)
+ error_workflow = error_workflow_for_failure
+ return unless error_workflow&.published?
+ return if @execution_mode == :error_mode && error_workflow.id == @workflow.id
+
+ workflow_version = error_workflow.active_version
+ trigger_node = trigger_node_for(workflow_version)
+ unless trigger_node
+ Rails.logger.warn(
+ "discourse-workflows: error workflow #{error_workflow.id} has no trigger:error node, skipping error handling",
+ )
+ return
+ end
+
+ Jobs.enqueue(
+ Jobs::DiscourseWorkflows::ExecuteWorkflow,
+ workflow_id: error_workflow.id,
+ workflow_version_id: workflow_version.version_id,
+ trigger_node_id: trigger_node["id"],
+ trigger_data: build_error_data(error),
+ execution_mode: "error_mode",
+ )
+ end
+
+ private
+
+ def error_workflow_for_failure
+ return @workflow.error_workflow if @workflow.error_workflow_id.present?
+ @workflow if trigger_node_for(@workflow.active_version)
+ end
+
+ def trigger_node_for(workflow_version)
+ workflow_version&.nodes&.find { |n| n["type"] == "trigger:error" }
+ end
+
+ def build_error_data(error)
+ {
+ "workflow" => {
+ "id" => @workflow.id.to_s,
+ "name" => @workflow.name,
+ },
+ "execution" => {
+ "id" => @execution&.id&.to_s,
+ "url" => execution_url,
+ "retryOf" => nil,
+ "error" => serialized_error(error),
+ "lastNodeExecuted" => last_failed_step_node_name,
+ "mode" => compatible_execution_mode,
+ },
+ }
+ end
+
+ def execution_url
+ return nil unless @execution
+ "#{Discourse.base_url}/admin/plugins/discourse-workflows/workflows/" \
+ "#{@workflow.id}/executions/#{@execution.id}"
+ end
+
+ def serialized_error(error)
+ serialized = { "message" => error.message.to_s.truncate(1000), "name" => error.class.name }
+
+ stack = Array(error.backtrace).first(50).join("\n")
+ serialized["stack"] = stack.truncate(10_000) if stack.present?
+
+ serialized
+ end
+
+ def compatible_execution_mode
+ return "error" if @execution_mode == :error_mode
+ return "manual" if @execution_mode == :manual
+
+ trigger_node = @execution&.workflow_node(@execution.trigger_node_id)
+ %w[trigger:form trigger:webhook].include?(trigger_node&.dig("type")) ? "webhook" : "trigger"
+ end
+
+ def last_failed_step_node_name
+ step =
+ @steps.reverse_each.find do |s|
+ s.respond_to?(:error?) ? s.error? : s["status"] == "error"
+ end
+
+ step.respond_to?(:node_name) ? step.node_name : step&.dig("node_name")
+ end
+ end
+ end
+end
diff --git a/plugins/discourse-workflows/lib/discourse_workflows/executor/execution_context.rb b/plugins/discourse-workflows/lib/discourse_workflows/executor/execution_context.rb
new file mode 100644
index 00000000000..b087de17951
--- /dev/null
+++ b/plugins/discourse-workflows/lib/discourse_workflows/executor/execution_context.rb
@@ -0,0 +1,227 @@
+# frozen_string_literal: true
+
+module DiscourseWorkflows
+ class Executor
+ class ExecutionContext
+ RESERVED_KEYS = %w[
+ $trigger
+ __resume_token
+ __sandbox_elapsed_ms
+ __node_contexts
+ __node_runs
+ __execution
+ __input_item
+ __input_items
+ __input_sources
+ __input_params
+ __input_context
+ __current_node_id
+ __node_parameters_by_name
+ __waiting_input_sources
+ $json
+ $itemIndex
+ ].freeze
+
+ attr_reader :workflow, :trigger_data, :context, :user, :workflow_name, :static_data_state
+ attr_accessor :execution
+
+ def initialize(
+ workflow:,
+ trigger_data:,
+ user:,
+ execution: nil,
+ workflow_nodes: nil,
+ workflow_name: nil
+ )
+ @workflow = workflow
+ @workflow_nodes = workflow_nodes
+ @workflow_name = workflow_name || workflow.name
+ @trigger_data = trigger_data
+ @user = user
+ @execution = execution
+ @static_data_state = StaticDataState.from_workflow(workflow)
+ reset!
+ end
+
+ RESUME_TOKEN_BYTES = 32
+
+ def self.generate_resume_token
+ SecureRandom.urlsafe_base64(RESUME_TOKEN_BYTES)
+ end
+
+ def reset!(resume_token: self.class.generate_resume_token)
+ @context = { "$trigger" => trigger_data }
+ @node_contexts_by_id = {}
+ @context["__resume_token"] = resume_token
+ end
+
+ def restore!(context:, node_contexts:, resume_token: self.class.generate_resume_token)
+ @context = context.deep_stringify_keys
+ @context["$trigger"] ||= trigger_data
+ @node_contexts_by_id = normalize_node_contexts(node_contexts)
+ @context["__resume_token"] = resume_token
+ end
+
+ def use_workflow_nodes(workflow_nodes, workflow_name: nil)
+ @workflow_nodes = workflow_nodes
+ @workflow_name = workflow_name if workflow_name.present?
+ @nodes_by_id = nil
+ @nodes_by_name = nil
+ end
+
+ def store_context(key, value)
+ if RESERVED_KEYS.include?(key)
+ Rails.logger.warn(
+ "discourse-workflows: node name '#{key}' collides with reserved context key " \
+ "in workflow #{workflow.id}, context may be corrupted",
+ )
+ end
+
+ @context[key] = value
+ end
+
+ def store_node_output(node, value)
+ return if node.name.blank?
+
+ store_context(node.name, value)
+ end
+
+ def store_node_run(node, inputs:, outputs:, input_sources: [])
+ return if node.name.blank?
+
+ @context["__node_runs"] ||= {}
+ @context["__node_runs"][node.name] ||= []
+ @context["__node_runs"][node.name] << {
+ "inputs" => inputs,
+ "outputs" => outputs,
+ "input_sources" => input_sources,
+ }
+ end
+
+ def store_waiting_input_sources(input_sources)
+ @context["__waiting_input_sources"] = input_sources
+ end
+
+ def consume_waiting_input_sources
+ @context.delete("__waiting_input_sources") || []
+ end
+
+ def resolver_context(extra_context = {})
+ @context.merge(
+ **extra_context,
+ "__node_contexts" => resolver_node_contexts,
+ "__execution" => execution_variables(extra_context),
+ )
+ end
+
+ def node_context_for(node)
+ @node_contexts_by_id[node_context_key(node)] ||= {}
+ end
+
+ def node_contexts
+ @node_contexts_by_id.deep_stringify_keys
+ end
+
+ def resume_token
+ @context["__resume_token"]
+ end
+
+ private
+
+ EXECUTION_VALUE_SOURCES = {
+ "id" => ->(execution_context, _extra_context) { execution_context.execution&.id },
+ "workflow_id" => ->(execution_context, _extra_context) { execution_context.workflow&.id },
+ "workflow_name" => ->(execution_context, _extra_context) do
+ execution_context.workflow_name
+ end,
+ "resume_url" =>
+ lambda do |execution_context, extra_context|
+ token = execution_context.resume_token
+ execution_id = execution_context.execution&.id
+ return if token.blank? || execution_id.blank?
+
+ suffix = extra_context&.dig("__webhook_suffix")
+ DiscourseWorkflows::WaitingExecution.webhook_url(
+ execution_id: execution_id,
+ resume_token: token,
+ suffix: suffix,
+ )
+ end,
+ "resumeFormUrl" =>
+ lambda do |execution_context, _extra_context|
+ token = execution_context.resume_token
+ execution_id = execution_context.execution&.id
+ return if token.blank? || execution_id.blank?
+
+ DiscourseWorkflows::WaitingExecution.form_waiting_url_for(
+ execution_id: execution_id,
+ resume_token: token,
+ absolute: true,
+ )
+ end,
+ }.freeze
+
+ def execution_variables(extra_context = {})
+ schema_fields = ExpressionContextSchema.environment_symbols.dig("$execution", :fields) || {}
+ schema_fields.each_with_object({}) do |(field_name, _), vars|
+ source = EXECUTION_VALUE_SOURCES[field_name]
+ next unless source
+ value = source.call(self, extra_context)
+ vars[field_name] = value unless value.nil?
+ end
+ end
+
+ def normalize_node_contexts(node_contexts)
+ node_contexts
+ .deep_stringify_keys
+ .each_with_object({}) do |(node_key, value), normalized|
+ normalized[normalize_node_context_key(node_key)] = value
+ end
+ end
+
+ def normalize_node_context_key(node_key)
+ node_id = node_key.to_s
+ return node_id if nodes_by_id.key?(node_id)
+
+ named_node = nodes_by_name[node_id]
+ return named_node["id"].to_s if named_node
+
+ node_id
+ end
+
+ def resolver_node_contexts
+ @node_contexts_by_id.each_with_object({}) do |(node_key, value), by_name|
+ by_name[resolver_node_key(node_key)] = value
+ end
+ end
+
+ def resolver_node_key(node_key)
+ nodes_by_id[node_key.to_s]&.dig("name").presence || node_key
+ end
+
+ def node_context_key(node)
+ node.id.to_s
+ end
+
+ def nodes_by_name
+ @nodes_by_name ||=
+ graph_nodes
+ .each_with_object({}) do |node, by_name|
+ name = node["name"].to_s
+ next if name.blank?
+
+ by_name[name] = by_name.key?(name) ? nil : node
+ end
+ .compact
+ end
+
+ def nodes_by_id
+ @nodes_by_id ||= graph_nodes.index_by { |node| node["id"].to_s }
+ end
+
+ def graph_nodes
+ @workflow_nodes || workflow.nodes
+ end
+ end
+ end
+end
diff --git a/plugins/discourse-workflows/lib/discourse_workflows/executor/execution_options.rb b/plugins/discourse-workflows/lib/discourse_workflows/executor/execution_options.rb
new file mode 100644
index 00000000000..0eaf93da4bf
--- /dev/null
+++ b/plugins/discourse-workflows/lib/discourse_workflows/executor/execution_options.rb
@@ -0,0 +1,26 @@
+# frozen_string_literal: true
+
+module DiscourseWorkflows
+ class Executor
+ ExecutionOptions =
+ Data.define(
+ :user,
+ :execution_mode,
+ :draft_execution,
+ :workflow_version,
+ :workflow_snapshot,
+ :webhook_context,
+ ) do
+ def initialize(
+ user: nil,
+ execution_mode: :normal,
+ draft_execution: false,
+ workflow_version: nil,
+ workflow_snapshot: nil,
+ webhook_context: nil
+ )
+ super
+ end
+ end
+ end
+end
diff --git a/plugins/discourse-workflows/lib/discourse_workflows/executor/execution_rate_limiter.rb b/plugins/discourse-workflows/lib/discourse_workflows/executor/execution_rate_limiter.rb
new file mode 100644
index 00000000000..0c9eee2a21c
--- /dev/null
+++ b/plugins/discourse-workflows/lib/discourse_workflows/executor/execution_rate_limiter.rb
@@ -0,0 +1,37 @@
+# frozen_string_literal: true
+
+module DiscourseWorkflows
+ class Executor
+ class ExecutionRateLimiter
+ def initialize(workflow)
+ @workflow = workflow
+ end
+
+ def within_limits?
+ per_workflow_limiter.performed!(raise_error: false) &&
+ global_limiter.performed!(raise_error: false)
+ end
+
+ private
+
+ def global_limiter
+ RateLimiter.new(
+ nil,
+ "discourse_workflows_executions",
+ SiteSetting.discourse_workflows_max_executions_per_minute,
+ 1.minute,
+ global: true,
+ )
+ end
+
+ def per_workflow_limiter
+ RateLimiter.new(
+ nil,
+ "discourse_workflows_workflow_#{@workflow.id}",
+ SiteSetting.discourse_workflows_max_executions_per_minute_per_workflow,
+ 1.minute,
+ )
+ end
+ end
+ end
+end
diff --git a/plugins/discourse-workflows/lib/discourse_workflows/executor/execution_store.rb b/plugins/discourse-workflows/lib/discourse_workflows/executor/execution_store.rb
new file mode 100644
index 00000000000..5ae926471e3
--- /dev/null
+++ b/plugins/discourse-workflows/lib/discourse_workflows/executor/execution_store.rb
@@ -0,0 +1,485 @@
+# frozen_string_literal: true
+
+module DiscourseWorkflows
+ class Executor
+ class ExecutionStore
+ MAX_EXECUTION_DATA_SIZE = 5.megabytes
+ MAX_STEP_IO_SIZE = 128.kilobytes
+ MAX_STEP_STRING_BYTES = 16.kilobytes
+ MAX_STEP_COLLECTION_SIZE = 50
+ MAX_STEP_IO_DEPTH = 8
+
+ delegate :workflow, :trigger_data, to: :@execution_context
+
+ attr_reader :trigger_node_id, :execution, :workflow_snapshot
+
+ def initialize(trigger_node_id:, execution_context:, execution_mode:, options:)
+ @trigger_node_id = trigger_node_id.to_s
+ @execution_context = execution_context
+ @execution_mode = execution_mode
+ @options = options
+ @workflow_snapshot = nil
+ @existing_run_data = {}
+ @last_execution_run_data = {}
+ end
+
+ def start!
+ @workflow_snapshot =
+ if @options.workflow_snapshot
+ @options.workflow_snapshot
+ elsif @options.workflow_version
+ WorkflowSnapshot.from_version(workflow, @options.workflow_version)
+ else
+ WorkflowSnapshot.from_workflow(workflow, published: [email protected]_execution)
+ end
+ @execution_context.use_workflow_nodes(
+ @workflow_snapshot.to_h["nodes"],
+ workflow_name: @workflow_snapshot.workflow_name,
+ )
+ @execution = create_execution!
+ reset_collaborators!
+ @execution
+ end
+
+ def resume!(execution)
+ @execution = execution
+ @execution_context.execution = execution
+ restore_from!(execution.execution_data)
+ @execution
+ end
+
+ def finish!(steps:)
+ save!(steps)
+ execution.update!(
+ status: :success,
+ finished_at: Time.current,
+ run_time_ms: Execution.compute_run_time_ms(steps),
+ resume_token: nil,
+ waiting_node_id: nil,
+ waiting_until: nil,
+ timeout_action: nil,
+ )
+ publish_execution_run_data
+ execution
+ end
+
+ def fail!(error:, steps: [])
+ save!(steps)
+ execution.update!(
+ status: :error,
+ error: error.message.to_s.truncate(1000),
+ finished_at: Time.current,
+ run_time_ms: Execution.compute_run_time_ms(steps),
+ resume_token: nil,
+ waiting_node_id: nil,
+ waiting_until: nil,
+ timeout_action: nil,
+ )
+ trigger_error_workflow(error, steps)
+ publish_execution_run_data(force: @options.draft_execution)
+ execution
+ end
+
+ def create_execution_with_status(status, trigger_data: self.trigger_data)
+ now = Time.current
+
+ DiscourseWorkflows::Execution.create!(
+ workflow: workflow,
+ workflow_version_id: execution_workflow_version_id,
+ trigger_node_id: @trigger_node_id,
+ status: status,
+ trigger_data: trigger_data,
+ execution_mode: @options.execution_mode,
+ started_at: now,
+ finished_at: now,
+ )
+ end
+
+ def create_rate_limited_execution
+ create_execution_with_status(:rate_limited, trigger_data: { "rate_limited" => true })
+ end
+
+ def pause_waiting_execution!(node:, waiting_until: nil, steps: [])
+ execution.update!(
+ status: :waiting,
+ waiting_node_id: node.id,
+ waiting_until: waiting_until,
+ resume_token: @execution_context.resume_token,
+ )
+ save!(steps)
+ publish_waiting_form_notification(node)
+ execution
+ end
+
+ def clear_waiting_execution!
+ execution.update!(
+ status: :running,
+ waiting_node_id: nil,
+ waiting_until: nil,
+ resume_token: nil,
+ timeout_action: nil,
+ )
+ end
+
+ private
+
+ def create_execution!
+ DiscourseWorkflows::Execution.create!(
+ workflow: workflow,
+ workflow_version_id: execution_workflow_version_id,
+ trigger_node_id: @trigger_node_id,
+ status: :running,
+ trigger_data: trigger_data,
+ execution_mode: @execution_mode,
+ started_at: Time.current,
+ )
+ end
+
+ def execution_workflow_version_id
+ @options.workflow_version&.version_id || workflow.version_id
+ end
+
+ def reset_collaborators!
+ @execution_context.execution = @execution
+ @execution_context.reset!
+ end
+
+ def restore_from!(execution_data)
+ @workflow_snapshot =
+ if execution_data&.workflow_data.present?
+ WorkflowSnapshot.new(execution_data.workflow_data)
+ else
+ WorkflowSnapshot.from_workflow(workflow, published: true)
+ end
+ @execution_context.use_workflow_nodes(
+ @workflow_snapshot.to_h["nodes"],
+ workflow_name: @workflow_snapshot.workflow_name,
+ )
+ @execution_context.restore!(
+ context: execution_data&.context_data || {},
+ node_contexts: execution_data&.node_contexts || {},
+ )
+ @existing_run_data = execution_data&.run_data || {}
+ restore_node_runs_from_run_data
+ end
+
+ def save!(steps)
+ entries = steps_to_entries(steps)
+ @last_execution_run_data = run_data_from_context(steps)
+
+ ed = execution.execution_data || execution.build_execution_data
+ ed.update!(
+ data: bounded_execution_data(entries, @last_execution_run_data),
+ workflow_data: @workflow_snapshot&.to_h,
+ )
+ end
+
+ def bounded_execution_data(entries, run_data)
+ truncated_context = { "__truncated" => true }
+ payload =
+ execution_data_payload(
+ entries,
+ stored_context,
+ @execution_context.node_contexts,
+ run_data,
+ )
+ return payload if within_size_limit?(payload)
+
+ log_oversized_execution_data("exceeds #{MAX_EXECUTION_DATA_SIZE} bytes, truncating context")
+ payload = execution_data_payload(entries, truncated_context, {}, run_data)
+ return payload if within_size_limit?(payload)
+
+ log_oversized_execution_data(
+ "still exceeds #{MAX_EXECUTION_DATA_SIZE} bytes, truncating entries",
+ )
+ payload = execution_data_payload(compact_entries(entries), truncated_context, {}, run_data)
+ return payload if within_size_limit?(payload)
+
+ log_oversized_execution_data(
+ "still exceeds #{MAX_EXECUTION_DATA_SIZE} bytes, compacting run data",
+ )
+ payload =
+ execution_data_payload(
+ compact_entries(entries),
+ truncated_context,
+ {},
+ compact_run_data(run_data),
+ )
+ return payload if within_size_limit?(payload)
+
+ log_oversized_execution_data(
+ "still exceeds #{MAX_EXECUTION_DATA_SIZE} bytes after all truncation attempts, storing minimal record",
+ )
+ execution_data_payload({}, truncated_context, {}, {})
+ end
+
+ def stored_context
+ @execution_context.context.except("__node_runs")
+ end
+
+ def execution_data_payload(entries, context, node_contexts = {}, run_data = {})
+ {
+ "entries" => entries,
+ "context" => context,
+ "node_contexts" => node_contexts,
+ "run_data" => run_data,
+ }
+ end
+
+ def within_size_limit?(payload)
+ payload.to_json.bytesize <= MAX_EXECUTION_DATA_SIZE
+ end
+
+ def log_oversized_execution_data(message)
+ Rails.logger.warn(
+ "discourse-workflows: execution data for execution #{execution.id} #{message}",
+ )
+ end
+
+ def steps_to_entries(steps)
+ steps
+ .group_by(&:node_id)
+ .transform_values { |node_steps| node_steps.map { |step| step_to_entry(step) } }
+ end
+
+ def step_to_entry(step)
+ entry = step.to_h
+ entry["input"] = bounded_step_io(entry["input"]) if entry.key?("input")
+ entry["output"] = bounded_step_io(entry["output"]) if entry.key?("output")
+ entry
+ end
+
+ def bounded_step_io(value)
+ bounded_value = bound_execution_value(value)
+ return bounded_value if bounded_value.to_json.bytesize <= MAX_STEP_IO_SIZE
+
+ truncated_value(value, MAX_STEP_IO_SIZE, "step_io_size_limit")
+ end
+
+ def bound_execution_value(value, depth = 0)
+ return truncated_value(value, nil, "step_io_depth_limit") if depth >= MAX_STEP_IO_DEPTH
+
+ case value
+ when String
+ bound_string(value)
+ when Array
+ bound_array(value, depth)
+ when Hash
+ bound_hash(value, depth)
+ else
+ value
+ end
+ end
+
+ def bound_string(value)
+ return value if value.bytesize <= MAX_STEP_STRING_BYTES
+
+ {
+ "__truncated" => true,
+ "__reason" => "step_string_size_limit",
+ "__original_bytes" => value.bytesize,
+ "preview" => value.byteslice(0, MAX_STEP_STRING_BYTES).scrub,
+ }
+ end
+
+ def bound_array(value, depth)
+ kept_items =
+ value
+ .first(MAX_STEP_COLLECTION_SIZE)
+ .map { |item| bound_execution_value(item, depth + 1) }
+ return kept_items if value.size <= MAX_STEP_COLLECTION_SIZE
+
+ kept_items << truncated_value(value, nil, "step_collection_size_limit")
+ end
+
+ def bound_hash(value, depth)
+ kept_pairs =
+ value
+ .first(MAX_STEP_COLLECTION_SIZE)
+ .to_h { |key, hash_value| [key, bound_execution_value(hash_value, depth + 1)] }
+ return kept_pairs if value.size <= MAX_STEP_COLLECTION_SIZE
+
+ kept_pairs.merge(
+ "__truncated" => true,
+ "__reason" => "step_collection_size_limit",
+ "__omitted_keys" => value.size - MAX_STEP_COLLECTION_SIZE,
+ )
+ end
+
+ def truncated_value(value, max_bytes, reason)
+ result = { "__truncated" => true, "__reason" => reason, "__class" => value.class.name }
+ result["__max_bytes"] = max_bytes if max_bytes
+ result["__original_size"] = value.size if value.respond_to?(:size)
+ result
+ end
+
+ def compact_entries(entries)
+ entries.transform_values do |node_steps|
+ Array(node_steps).map do |step|
+ step.except("input", "output").merge(
+ "input" => truncated_value(step["input"] || [], nil, "execution_data_size_limit"),
+ "output" => truncated_value(step["output"] || [], nil, "execution_data_size_limit"),
+ )
+ end
+ end
+ end
+
+ def run_data_from_context(steps)
+ current_run_data =
+ serialized_node_runs(@execution_context.context["__node_runs"] || {}, steps)
+ merge_run_data(@existing_run_data, current_run_data)
+ end
+
+ def serialized_node_runs(node_runs, steps)
+ steps_by_name = steps.group_by(&:node_name)
+
+ node_runs.each_with_object({}) do |(node_name, runs), result|
+ existing_run_count = Array(@existing_run_data[node_name]).length
+ result[node_name] = Array(runs)
+ .drop(existing_run_count)
+ .map
+ .with_index do |run, index|
+ step = Array(steps_by_name[node_name])[existing_run_count + index]
+ serialize_node_run(node_name, run, step, existing_run_count + index)
+ end
+ end
+ end
+
+ def restore_node_runs_from_run_data
+ return if @existing_run_data.blank?
+
+ @execution_context.context["__node_runs"] = @existing_run_data.each_with_object(
+ {},
+ ) do |(node_name, runs), node_runs|
+ node_runs[node_name] = Array(runs).map do |run|
+ {
+ "inputs" => ports_to_item_groups(run["inputs"]),
+ "outputs" => ports_to_item_groups(run["outputs"]),
+ "input_sources" => input_sources(run["inputs"]),
+ }
+ end
+ end
+ end
+
+ def ports_to_item_groups(ports)
+ Array(ports).map { |port| Array(port["items"]) }
+ end
+
+ def input_sources(input_ports)
+ Array(input_ports).map { |port| port["source"] || {} }
+ end
+
+ def merge_run_data(existing_run_data, current_run_data)
+ merged = existing_run_data.deep_dup
+ current_run_data.each do |node_name, runs|
+ merged[node_name] ||= []
+ merged[node_name].concat(runs)
+ end
+ merged
+ end
+
+ def serialize_node_run(node_name, run, step, run_index)
+ {
+ "node_id" => step&.node_id,
+ "node_name" => node_name,
+ "node_type" => step&.node_type,
+ "status" => step&.status,
+ "run_index" => run_index,
+ "inputs" =>
+ serialize_ports(
+ run["inputs"] || run[:inputs],
+ sources: run["input_sources"] || run[:input_sources],
+ ),
+ "outputs" => serialize_ports(run["outputs"] || run[:outputs]),
+ "started_at" => step&.started_at,
+ "finished_at" => step&.finished_at,
+ }.compact
+ end
+
+ def serialize_ports(port_items, sources: nil)
+ Array(port_items).map.with_index do |items, index|
+ source = Array(sources)[index] if sources
+ serialize_port(index, items, source:)
+ end
+ end
+
+ def serialize_port(index, items, source: nil)
+ raw_items = items.is_a?(Array) ? items : []
+ bounded_items =
+ raw_items.first(MAX_STEP_COLLECTION_SIZE).map { |item| bound_execution_value(item) }
+
+ {
+ "index" => index,
+ "items" => bounded_items,
+ "item_count" => raw_items.length,
+ "truncated" => raw_items.length > bounded_items.length,
+ "source" => source,
+ }.compact
+ end
+
+ def compact_run_data(run_data)
+ run_data.transform_values do |runs|
+ Array(runs).map do |run|
+ run.merge(
+ "inputs" => compact_run_ports(run["inputs"]),
+ "outputs" => compact_run_ports(run["outputs"]),
+ )
+ end
+ end
+ end
+
+ def compact_run_ports(ports)
+ Array(ports).map { |port| port.except("items").merge("items" => [], "truncated" => true) }
+ end
+
+ def trigger_error_workflow(error, steps)
+ ErrorWorkflowTrigger.new(
+ workflow,
+ steps,
+ execution: execution,
+ execution_mode: @options.execution_mode,
+ ).trigger_error_workflow(error)
+ end
+
+ def publish_waiting_form_notification(node)
+ return unless node.type == "action:form"
+ return if @workflow_snapshot.nil?
+
+ trigger_node = @workflow_snapshot.find_node(@trigger_node_id)
+ return unless trigger_node&.type == "trigger:form"
+
+ channel = DiscourseWorkflows::WaitingExecution.form_channel(execution)
+ return if channel.blank?
+
+ MessageBus.publish(
+ channel,
+ {
+ status: "waiting_for_form",
+ form_waiting_url: DiscourseWorkflows::WaitingExecution.form_waiting_url(execution),
+ form_submit_url: DiscourseWorkflows::WaitingExecution.form_waiting_url(execution),
+ form_status_url: DiscourseWorkflows::WaitingExecution.form_status_url(execution),
+ },
+ )
+ end
+
+ def publish_execution_run_data(force: false)
+ return if @last_execution_run_data.blank? && !force
+
+ MessageBus.publish(
+ "/discourse-workflows/workflow/#{workflow.id}",
+ {
+ type: "execution_completed",
+ execution: {
+ id: execution.id,
+ workflow_id: execution.workflow_id,
+ trigger_node_id: execution.trigger_node_id,
+ status: execution.status,
+ },
+ lastExecutionRunData: @last_execution_run_data,
+ },
+ group_ids: [Group::AUTO_GROUPS[:admins]],
+ )
+ end
+ end
+ end
+end
diff --git a/plugins/discourse-workflows/lib/discourse_workflows/executor/filter_parameter.rb b/plugins/discourse-workflows/lib/discourse_workflows/executor/filter_parameter.rb
new file mode 100644
index 00000000000..1927a446a77
--- /dev/null
+++ b/plugins/discourse-workflows/lib/discourse_workflows/executor/filter_parameter.rb
@@ -0,0 +1,146 @@
+# frozen_string_literal: true
+
+module DiscourseWorkflows
+ class Executor
+ module FilterParameter
+ def self.execute_filter(conditions, combinator, options, resolver)
+ details = conditions.map { |c| execute_filter_condition(c, options, resolver) }
+ passed =
+ if combinator == "or"
+ details.any? { |d| d["passed"] }
+ else
+ details.all? { |d| d["passed"] }
+ end
+
+ { "passed" => passed, "details" => details }
+ end
+
+ def self.execute_filter_condition(condition, options, resolver)
+ left_expression = condition["leftValue"]
+ left = resolver.resolve(left_expression)
+ operator = condition.fetch("operator") { {} }
+ type = operator.fetch("type") { "string" }
+ operation = operator["operation"]
+ right = resolver.resolve(condition["rightValue"]) unless operator["singleValue"]
+ passed = evaluate_type(type, left, right, operation, options)
+
+ {
+ "left" => left,
+ "leftExpression" => left_expression,
+ "operator" => operation,
+ "right" => right,
+ "type" => type,
+ "passed" => passed,
+ }
+ end
+
+ def self.evaluate_type(type, left, right, operation, options)
+ case type
+ when "string"
+ evaluate_string(left, right, operation, options)
+ when "number"
+ evaluate_number(left, right, operation)
+ when "boolean"
+ evaluate_boolean(left, right, operation)
+ when "array"
+ evaluate_array(left, right, operation)
+ else
+ false
+ end
+ end
+
+ def self.evaluate_string(left, right, operation, options)
+ case_sensitive = options.fetch("caseSensitive", true)
+ left = left.to_s
+ right = right.to_s unless right.nil?
+
+ unless case_sensitive
+ left = left.downcase
+ right = right&.downcase
+ end
+
+ case operation
+ when "equals"
+ left == right
+ when "notEquals"
+ left != right
+ when "contains"
+ right.present? && left.include?(right)
+ when "notContains"
+ right.blank? || !left.include?(right)
+ when "empty"
+ left.blank?
+ when "notEmpty"
+ left.present?
+ else
+ false
+ end
+ end
+
+ def self.evaluate_number(left, right, operation)
+ left = coerce_number(left)
+ right = coerce_number(right)
+ return false if left.nil? || right.nil?
+
+ compare_values(left, right, operation)
+ end
+
+ def self.evaluate_boolean(left, right, operation)
+ case operation
+ when "true"
+ left == true
+ when "false"
+ left == false
+ when "equals"
+ left == right
+ when "notEquals"
+ left != right
+ else
+ false
+ end
+ end
+
+ def self.evaluate_array(left, right, operation)
+ case operation
+ when "contains"
+ Array.wrap(left).include?(right)
+ when "notContains"
+ !Array.wrap(left).include?(right)
+ when "empty"
+ return false if left.nil?
+ Array.wrap(left).empty?
+ when "notEmpty"
+ Array.wrap(left).present?
+ else
+ false
+ end
+ end
+
+ def self.compare_values(left, right, operation)
+ case operation
+ when "equals"
+ left == right
+ when "notEquals"
+ left != right
+ when "gt"
+ left > right
+ when "lt"
+ left < right
+ when "gte"
+ left >= right
+ when "lte"
+ left <= right
+ else
+ false
+ end
+ end
+
+ def self.coerce_number(value)
+ Float(value)
+ rescue ArgumentError, TypeError
+ nil
+ end
+ private_class_method :coerce_number
+ end
+ end
+end
diff --git a/plugins/discourse-workflows/lib/discourse_workflows/executor/http_client.rb b/plugins/discourse-workflows/lib/discourse_workflows/executor/http_client.rb
new file mode 100644
index 00000000000..290a2022b7e
--- /dev/null
+++ b/plugins/discourse-workflows/lib/discourse_workflows/executor/http_client.rb
@@ -0,0 +1,104 @@
+# frozen_string_literal: true
+
+module DiscourseWorkflows
+ class Executor
+ class HttpClient
+ include Nodes::HttpHelpers
+ include NodeErrorHandling
+
+ Response = Struct.new(:status, :headers, :body, :status_message, keyword_init: true)
+
+ TIMEOUT_SECONDS = 30
+ DEFAULT_MAX_RETRIES = 0
+ DEFAULT_RETRY_STATUSES = Set[429, 500, 502, 503, 504].freeze
+
+ def initialize(exec_ctx, item_index = 0)
+ @exec_ctx = exec_ctx
+ @item_index = item_index
+ end
+
+ def request(method:, url:, headers: {}, body: nil, options: {})
+ config = build_config(method, url, headers, body, options)
+ request_method, uri, request_headers, request_body =
+ DiscourseWorkflows::Nodes::HttpRequest::RequestBuilder.new(
+ config,
+ @exec_ctx,
+ @item_index,
+ ).build
+ never_error = config.fetch("never_error", false)
+ response = run_with_retries(request_method, uri, request_headers, request_body, config)
+ if !never_error && !(200..299).cover?(response.status)
+ filtered_url = filtered_url_for_logging(config["url"], config["query_params"])
+ raise_node_error!(
+ "HTTP #{config["method"]} #{filtered_url} failed with status #{response.status}",
+ )
+ end
+
+ parsed =
+ DiscourseWorkflows::Nodes::HttpRequest::ResponseParser.parse(
+ response,
+ max_size_kb: config["max_response_size_kb"],
+ log: @exec_ctx.log,
+ )
+ Response.new(
+ status: parsed[:status],
+ headers: parsed[:headers],
+ body: parsed[:body],
+ status_message: parsed[:status_message],
+ )
+ end
+
+ private
+
+ def build_config(method, url, headers, body, options)
+ config =
+ options.to_h.stringify_keys.merge(
+ "method" => method.to_s.upcase,
+ "url" => url,
+ "headers" => headers,
+ )
+ config["body"] = body unless body.nil?
+ config
+ end
+
+ def run_with_retries(method, uri, headers, body, config)
+ attempts = max_retries(config, method) + 1
+ statuses = retry_statuses(config)
+ response = nil
+
+ attempts.times do |attempt|
+ response = connection.run_request(method, uri.to_s, body, headers)
+ break if statuses.exclude?(response.status) || attempt >= attempts - 1
+ end
+
+ response
+ end
+
+ def connection
+ @connection ||=
+ Faraday.new(nil, request: request_options) do |f|
+ f.adapter FinalDestination::FaradayAdapter
+ end
+ end
+
+ def request_options
+ { timeout: TIMEOUT_SECONDS, open_timeout: TIMEOUT_SECONDS, write_timeout: TIMEOUT_SECONDS }
+ end
+
+ def max_retries(config, method)
+ config.fetch("max_retries") { default_max_retries(method) }.to_i.clamp(0, 5)
+ end
+
+ def default_max_retries(_method)
+ DEFAULT_MAX_RETRIES
+ end
+
+ def retry_statuses(config)
+ statuses = config["retry_statuses"]
+ return DEFAULT_RETRY_STATUSES if statuses.blank?
+
+ Set.new(Array(statuses).map(&:to_i))
+ end
+ end
+ end
+end
diff --git a/plugins/discourse-workflows/lib/discourse_workflows/executor/node_execution_context.rb b/plugins/discourse-workflows/lib/discourse_workflows/executor/node_execution_context.rb
new file mode 100644
index 00000000000..661eed54a65
--- /dev/null
+++ b/plugins/discourse-workflows/lib/discourse_workflows/executor/node_execution_context.rb
@@ -0,0 +1,507 @@
+# frozen_string_literal: true
+
+module DiscourseWorkflows
+ class Executor
+ class NodeExecutionContext
+ MISSING = ParameterResolver::MISSING
+ RUN_CODE = CodeRunner::RUN_CODE
+ RUN_ONCE_FOR_ALL_ITEMS = CodeRunner::RUN_ONCE_FOR_ALL_ITEMS
+ RUN_ONCE_FOR_EACH_ITEM = CodeRunner::RUN_ONCE_FOR_EACH_ITEM
+ JAVASCRIPT_UNDEFINED = CodeRunner::JAVASCRIPT_UNDEFINED
+ JobResult = Data.define(:ok, :result, :error)
+ WaitRequest = Data.define(:waiting_until)
+
+ class RuntimeState
+ attr_reader :condition_step_details, :execution_hints, :log, :metadata, :wait_request
+
+ def initialize
+ @condition_step_details = []
+ @execution_hints = []
+ @log = StepLog.new
+ @metadata = {}
+ @wait_request = nil
+ end
+
+ def request_wait(waiting_until)
+ @wait_request = WaitRequest.new(waiting_until)
+ end
+
+ def add_condition_details(details)
+ @condition_step_details.concat(details)
+ end
+
+ def add_execution_hints(hints)
+ @execution_hints.concat(hints.map(&:deep_stringify_keys))
+ end
+
+ def merge_metadata(metadata)
+ @metadata.merge!(metadata.deep_stringify_keys)
+ end
+
+ def step_metadata
+ metadata = @metadata.dup
+ metadata["conditions"] = @condition_step_details if @condition_step_details.any?
+ metadata["hints"] = @execution_hints if @execution_hints.any?
+ metadata
+ end
+ end
+
+ attr_reader :user, :vars, :execution_id, :node_id, :webhook_ctx
+
+ def initialize(
+ input_items:,
+ input_groups: nil,
+ parameters: nil,
+ credentials: {},
+ node_settings: {},
+ webhook_id: nil,
+ property_schema: {},
+ credential_schema: [],
+ node_context: {},
+ user: nil,
+ resolver: nil,
+ vars: nil,
+ workflow: nil,
+ execution_id: nil,
+ resume_token: nil,
+ node_id: nil,
+ node_name: nil,
+ node_identifier: nil,
+ execution_mode: :normal,
+ flow_context: nil,
+ resolver_context: nil,
+ workflow_dependencies: nil,
+ workflow_snapshot: nil,
+ webhook_context: nil,
+ runtime_state: RuntimeState.new,
+ static_data_state: nil
+ )
+ @input_groups = normalize_input_groups(input_groups, input_items)
+ @input_items = @input_groups[0] || []
+ split =
+ NodeData.split(
+ parameters: parameters || {},
+ credentials: credentials,
+ webhook_id: webhook_id,
+ )
+ @parameters = split["parameters"]
+ @credentials = split["credentials"]
+ @node_settings = node_settings.deep_stringify_keys
+ @property_schema = property_schema
+ @credential_schema = NodeData.normalize_credential_definitions(credential_schema)
+ @node_context = node_context
+ @user = user
+ @resolver = resolver
+ @vars = vars
+ @workflow = workflow
+ @execution_id = execution_id
+ @resume_token = resume_token
+ @node_id = node_id
+ @node_name = node_name.presence&.to_s
+ @node_identifier = node_identifier.presence&.to_s
+ @webhook_id = split[DiscourseWorkflows::WorkflowDocument.node_webhook_id_key]
+ @execution_mode = execution_mode
+ @flow_context = flow_context || {}
+ @resolver_context = resolver_context || {}
+ @runtime_state = runtime_state
+ @workflow_dependencies = workflow_dependencies
+ @workflow_snapshot = workflow_snapshot
+ @webhook_ctx = webhook_context
+ @static_data_state = static_data_state
+ end
+
+ # Static data access.
+ #
+ # `get_workflow_static_data(:global)` returns the workflow-wide hash.
+ # `get_workflow_static_data(:node)` returns the per-node hash for the
+ # *current* node, keyed by node name. Mutations are persisted at the
+ # end of the execution by `Executor#commit_static_data!`.
+ def get_workflow_static_data(scope = :node)
+ raise "static data is not available in this context" if @static_data_state.nil?
+
+ case scope.to_s
+ when "node"
+ raise "static data node scope requires a node name" if @node_name.blank?
+ @static_data_state.fetch_node(@node_name)
+ when "global"
+ @static_data_state.fetch(:global)
+ else
+ raise ArgumentError, "Unknown static data scope: #{scope.inspect}. Use :node or :global"
+ end
+ end
+
+ def get_context(scope = :node)
+ case scope
+ when :node
+ @node_context
+ when :flow
+ @flow_context
+ else
+ raise ArgumentError, "Unknown context scope: #{scope}. Use :node or :flow"
+ end
+ end
+
+ def input_items(input_key = nil)
+ return @input_items if input_key.nil?
+
+ @input_groups.fetch(input_index(input_key)) { [] }
+ end
+
+ def inputs
+ max_index = @input_groups.keys.max || 0
+ Array.new(max_index + 1) { |index| @input_groups[index] || [] }
+ end
+
+ def input_context
+ InputContext.from_node_context(get_context(:node))
+ end
+
+ def get_mode
+ @execution_mode.to_s
+ end
+
+ def get_node
+ DiscourseWorkflows::NodeView.from_snapshot_node(
+ current_snapshot_node,
+ include_node_parameters: true,
+ include_credentials: true,
+ include_webhook_id: true,
+ ) ||
+ DiscourseWorkflows::NodeView.new(
+ id: node_id,
+ name: nil,
+ type: @node_identifier,
+ type_version: nil,
+ webhook_id: @webhook_id,
+ parameters: @parameters,
+ credentials: @credentials,
+ )
+ end
+
+ def get_workflow
+ DiscourseWorkflows::WorkflowView.from_workflow(
+ @workflow,
+ name: @workflow_snapshot&.workflow_name,
+ )
+ end
+
+ def get_input_data(input_index = 0, _connection_type = nil)
+ input_items(input_index)
+ end
+
+ def continue_on_fail
+ on_error = @node_settings["onError"]
+ return %w[continueRegularOutput continueErrorOutput].include?(on_error) if on_error.present?
+
+ ActiveModel::Type::Boolean.new.cast(@node_settings["continueOnFail"]) == true
+ end
+
+ def start_job(job_type, settings, item_index)
+ raise ArgumentError, "Unsupported job type: #{job_type}" unless job_type == "javascript"
+
+ JobResult.new(
+ ok: true,
+ result: code_runner.run(settings.deep_stringify_keys, item_index),
+ error: nil,
+ )
+ rescue => e
+ JobResult.new(ok: false, result: nil, error: e)
+ end
+
+ def get_node_parameter(path, item_index = 0, default: nil, options: {})
+ parameter_resolver.resolve(path, item_index, default:, options:)
+ end
+
+ def helpers
+ @helpers ||=
+ ContextHelpers.new(
+ node_identifier: @node_identifier,
+ data_table_access_validator: ->(data_table_id) do
+ ensure_data_table_access!(data_table_id)
+ end,
+ )
+ end
+
+ def get_credentials(slot, item_index = 0)
+ fetch_credentials(slot, item_index)
+ end
+
+ def actor_from_parameter(path, item_index = 0, default: "system")
+ username = get_node_parameter(path, item_index, default: default)
+ actor_from(username: username.presence || default, field: path.to_s, item_index: item_index)
+ end
+
+ def actor_from(username: nil, id: nil, field: nil, item_index: nil)
+ actor = find_user(username: username.presence, id: id)
+ ensure_actor_allowed!(actor, field: field, item_index: item_index)
+ actor
+ end
+
+ def find_user(username: nil, id: nil)
+ if username.present? == id.present?
+ raise ArgumentError, "Provide exactly one of username or id"
+ end
+
+ if username.present?
+ user = User.find_by(username: username)
+ raise DiscourseWorkflows::NodeError, "User '#{username}' not found" if user.nil?
+ else
+ user = User.find_by(id: id)
+ raise DiscourseWorkflows::NodeError, "User with id #{id} not found" if user.nil?
+ end
+
+ user
+ end
+
+ def http_request(method:, url:, headers: {}, body: nil, options: {}, item_index: 0)
+ HttpClient.new(self, item_index).request(method:, url:, headers:, body:, options:)
+ end
+
+ def put_execution_to_wait(waiting_until = nil)
+ @runtime_state.request_wait(waiting_until)
+ end
+
+ def resume_action_id(action)
+ DiscourseWorkflows::InteractiveResume.action_id(
+ execution_id: execution_id,
+ resume_token: @resume_token,
+ action: action,
+ )
+ end
+
+ def set_metadata(metadata)
+ @runtime_state.merge_metadata(metadata)
+ end
+
+ def add_execution_hints(*hints)
+ @runtime_state.add_execution_hints(hints)
+ end
+
+ def evaluate_expression(expression, item_index = 0)
+ with_item_index(item_index) { @resolver.resolve(expression) }
+ end
+
+ def log
+ @runtime_state.log
+ end
+
+ def execution_hints
+ @runtime_state.execution_hints
+ end
+
+ def metadata
+ @runtime_state.metadata
+ end
+
+ def get_child_nodes(node_name, options = {})
+ graph_nodes(
+ @workflow_snapshot&.child_nodes(node_name, connection_type: "main", depth: -1),
+ include_node_parameters: graph_option(options, :include_node_parameters, false),
+ )
+ end
+
+ def get_parent_nodes(node_name, options = {})
+ graph_nodes(
+ @workflow_snapshot&.parent_nodes(
+ node_name,
+ connection_type: graph_option(options, :connection_type, "main"),
+ depth: graph_option(options, :depth, -1),
+ ),
+ include_node_parameters: graph_option(options, :include_node_parameters, false),
+ )
+ end
+
+ def paired_item_for(item, input: 0)
+ input_index = input_index(input)
+ paired_item = { "item" => item_index_for(item, input_index:) }
+ paired_item["input"] = input_index if input_index != 0
+ paired_item
+ end
+
+ private
+
+ def fetch_credentials(slot, item_index)
+ raise ArgumentError, "credential slot is required" if slot.blank?
+
+ credential_id = credential_id_for(slot)
+ ensure_credential_access!(slot, credential_id)
+ credential = DiscourseWorkflows::Credential.find_by(id: credential_id)
+ raise Discourse::InvalidAccess if credential.nil?
+ unless credential_type_allowed?(slot, credential.credential_type)
+ raise Discourse::InvalidAccess
+ end
+
+ with_item_index(item_index) { @resolver.resolve_hash(credential.data || {}) }
+ end
+
+ def ensure_actor_allowed!(actor, field:, item_index:)
+ actor_policy.ensure_allowed!(
+ actor,
+ field: field,
+ item_index: item_index,
+ source: actor_source(field, item_index),
+ purpose: @node_identifier,
+ )
+ end
+
+ def actor_policy
+ @actor_policy ||= ActorPolicy.new(self)
+ end
+
+ def actor_source(field, item_index)
+ return :direct if field.blank?
+
+ raw_value = get_node_parameter(field, item_index || 0, options: { raw_expressions: true })
+ return :default if raw_value.nil?
+ return :expression if raw_value.is_a?(String) && raw_value.start_with?("=")
+
+ :static_config
+ end
+
+ def current_snapshot_node
+ @workflow_snapshot&.find_node(node_id)
+ end
+
+ def graph_nodes(nodes, include_node_parameters:)
+ Array
+ .wrap(nodes)
+ .filter_map do |node|
+ DiscourseWorkflows::NodeView.from_snapshot_node(
+ node,
+ include_node_parameters: include_node_parameters,
+ )
+ end
+ end
+
+ def graph_option(options, key, default)
+ options = {} unless options.respond_to?(:[])
+ options[key] || options[key.to_s] || default
+ end
+
+ def with_item_index(item_index = 0)
+ normalized_item_index = normalize_item_index(item_index)
+ item = input_items.fetch(normalized_item_index) { { "json" => {} } }
+
+ @resolver.with_item(item, item_index: normalized_item_index) { yield item }
+ end
+
+ def ensure_data_table_access!(data_table_id)
+ if @workflow && @node_id
+ return if workflow_references_dependency?("data_table_id", data_table_id)
+ elsif @parameters["data_table_id"].to_s == data_table_id
+ return
+ end
+
+ raise Discourse::InvalidAccess
+ end
+
+ def ensure_credential_access!(slot, credential_id)
+ raise Discourse::InvalidAccess if credential_id.blank? || !declared_credential_slot?(slot)
+
+ if @workflow && @node_id
+ return if workflow_references_dependency?("credential_id", credential_id)
+ elsif credential_id_for(slot) == credential_id
+ return
+ end
+
+ raise Discourse::InvalidAccess
+ end
+
+ def workflow_references_dependency?(type, key)
+ if @workflow_dependencies
+ @workflow_dependencies[@node_id].include?("#{type}:#{key}")
+ else
+ DiscourseWorkflows::WorkflowDependency.exists?(
+ workflow_id: @workflow.id,
+ node_id: @node_id,
+ dependency_type: type,
+ dependency_key: key,
+ )
+ end
+ end
+
+ def item_index_for(item, input_index: 0)
+ @item_indexes_by_input_object_id ||=
+ @input_groups.each_with_object({}) do |(index, items), result|
+ result[index] = items.each_with_index.to_h do |entry, item_index|
+ [entry.object_id, item_index]
+ end
+ end
+ @item_indexes_by_input_object_id.fetch(input_index) { {} }.fetch(item.object_id, 0)
+ end
+
+ def normalize_input_groups(input_groups, input_items)
+ groups = input_groups || { 0 => input_items }
+ has_indexed_inputs =
+ groups.keys.any? { |key| key.to_s.match?(/\Ainput_\d+\z/) || key.is_a?(Integer) }
+ groups.each_with_object({}) do |(key, items), result|
+ next if has_indexed_inputs && key.to_s == "main"
+
+ result[input_index(key)] = items || []
+ end
+ end
+
+ def input_index(input_key)
+ return input_key if input_key.is_a?(Integer)
+
+ value = input_key.to_s
+ return 0 if value == "main"
+
+ match = value.match(/\Ainput_(\d+)\z/)
+ return match[1].to_i - 1 if match
+
+ value.to_i
+ end
+
+ def normalize_item_index(item_index)
+ return 0 if item_index.nil?
+ return item_index if item_index.is_a?(Integer)
+
+ raise ArgumentError, "item_index must be an Integer"
+ end
+
+ def credential_id_for(slot)
+ credential = @credentials[slot.to_s]
+ credential["id"].to_s if credential
+ end
+
+ def declared_credential_slot?(slot)
+ credential_definition(slot).present?
+ end
+
+ def credential_type_allowed?(slot, credential_type)
+ credential_types = NodeData.credential_types_for(credential_definition(slot))
+ credential_types.include?(credential_type.to_s)
+ end
+
+ def credential_definition(slot)
+ @credential_schema.find { |definition| definition["name"] == slot.to_s }
+ end
+
+ def code_runner
+ @code_runner ||=
+ CodeRunner.new(
+ input_items: input_items,
+ parameters: @parameters,
+ input_context: -> { input_context },
+ resolver_context: @resolver_context,
+ user: @user,
+ vars: @vars,
+ flow_context: @flow_context,
+ runtime_state: @runtime_state,
+ )
+ end
+
+ def parameter_resolver
+ @parameter_resolver ||=
+ ParameterResolver.new(
+ parameters: @parameters,
+ property_schema: @property_schema,
+ resolver: @resolver,
+ input_items: input_items,
+ runtime_state: @runtime_state,
+ )
+ end
+ end
+ end
+end
diff --git a/plugins/discourse-workflows/lib/discourse_workflows/executor/parameter_resolver.rb b/plugins/discourse-workflows/lib/discourse_workflows/executor/parameter_resolver.rb
new file mode 100644
index 00000000000..3f153b850e5
--- /dev/null
+++ b/plugins/discourse-workflows/lib/discourse_workflows/executor/parameter_resolver.rb
@@ -0,0 +1,194 @@
+# frozen_string_literal: true
+
+module DiscourseWorkflows
+ class Executor
+ class ParameterResolver
+ MISSING = Object.new.freeze
+
+ def initialize(parameters:, property_schema:, resolver:, input_items:, runtime_state:)
+ @parameters = parameters
+ @property_schema = property_schema
+ @resolver = resolver
+ @input_items = input_items
+ @runtime_state = runtime_state
+ end
+
+ def resolve(path, item_index = 0, default: nil, options: {})
+ path_str = path.to_s
+ if raw_expressions?(options)
+ raw_value = raw_parameter_path(path_str)
+ return raw_value.equal?(MISSING) ? default : raw_value
+ end
+
+ with_item_index(item_index) do
+ resolved = resolve_parameter_path(path_str)
+ resolved.equal?(MISSING) ? default : resolved
+ end
+ end
+
+ private
+
+ def with_item_index(item_index = 0)
+ normalized_item_index = normalize_item_index(item_index)
+ item = @input_items.fetch(normalized_item_index) { { "json" => {} } }
+
+ @resolver.with_item(item, item_index: normalized_item_index) { yield item }
+ end
+
+ def normalize_item_index(item_index)
+ return 0 if item_index.nil?
+ return item_index if item_index.is_a?(Integer)
+
+ raise ArgumentError, "item_index must be an Integer"
+ end
+
+ def raw_expressions?(options)
+ options&.fetch(:raw_expressions, false)
+ end
+
+ def raw_parameter_path(path)
+ segments = path.split(".").reject(&:blank?)
+ return MISSING if segments.empty?
+ return MISSING unless @parameters.key?(segments.first)
+
+ if segments.one?
+ @parameters[segments.first]
+ else
+ dig_parameter_path(@parameters[segments.first], segments.drop(1))
+ end
+ end
+
+ def resolve_parameter(name, schema)
+ return @parameters[name] if no_data_expression?(schema)
+
+ if condition_builder_schema?(schema)
+ conditions = @parameters.fetch("conditions") { [] }
+ combinator = @parameters.fetch("combinator") { "and" }
+ options = @parameters.fetch("options") { {} }
+ result =
+ Executor::FilterParameter.execute_filter(conditions, combinator, options, @resolver)
+ @runtime_state.add_condition_details(result["details"])
+ result["passed"]
+ else
+ resolve_parameter_value(@parameters[name], schema)
+ end
+ end
+
+ def resolve_parameter_value(value, schema = nil)
+ return value if no_data_expression?(schema)
+ return resolve_fixed_collection_value(value, schema) if fixed_collection_schema?(schema)
+
+ case value
+ when Hash
+ resolve_hash_parameter_value(value, schema)
+ when Array
+ item_schema = schema_value(schema, :item_schema)
+ value.map { |entry| resolve_parameter_value(entry, item_schema) }
+ else
+ @resolver.resolve(value)
+ end
+ end
+
+ def resolve_hash_parameter_value(value, schema)
+ fields = schema_value(schema, :fields) || {}
+
+ value.transform_values.with_index do |nested_value, index|
+ key = value.keys[index]
+ nested_schema = fields[key.to_sym] || fields[key.to_s]
+ resolve_parameter_value(nested_value, nested_schema)
+ end
+ end
+
+ def resolve_fixed_collection_value(value, schema)
+ unless value.is_a?(Hash)
+ return(
+ resolve_fixed_collection_group_value(value, first_fixed_collection_row_schema(schema))
+ )
+ end
+
+ value.transform_values.with_index do |group_value, index|
+ group_name = value.keys[index]
+ row_schema = fixed_collection_row_schema(schema, group_name)
+ resolve_fixed_collection_group_value(group_value, row_schema)
+ end
+ end
+
+ def resolve_fixed_collection_group_value(value, row_schema)
+ case value
+ when Array
+ value.map { |row| resolve_parameter_value(row, { type: :object, fields: row_schema }) }
+ when Hash
+ resolve_parameter_value(value, { type: :object, fields: row_schema })
+ else
+ resolve_parameter_value(value)
+ end
+ end
+
+ def fixed_collection_row_schema(schema, group_name)
+ group =
+ Array(schema_value(schema, :options)).find do |option|
+ (schema_value(option, :name) || "").to_s == group_name.to_s
+ end
+
+ schema_value(group, :values) || {}
+ end
+
+ def first_fixed_collection_row_schema(schema)
+ schema_value(Array(schema_value(schema, :options)).first, :values) || {}
+ end
+
+ def resolve_parameter_path(path)
+ segments = path.split(".").reject(&:blank?)
+ return MISSING if segments.empty?
+
+ name = segments.first
+ schema = @property_schema[name.to_sym] || @property_schema[name]
+ if [email protected]?(name)
+ return resolve_parameter(name, schema) if condition_builder_schema?(schema)
+
+ return MISSING
+ end
+
+ resolved = resolve_parameter(name, schema)
+ return resolved if segments.one?
+
+ dig_parameter_path(resolved, segments.drop(1))
+ end
+
+ def dig_parameter_path(value, segments)
+ segments.reduce(value) do |current, segment|
+ case current
+ when Hash
+ return MISSING unless current.key?(segment)
+
+ current[segment]
+ when Array
+ return MISSING unless segment.match?(/\A\d+\z/)
+
+ current.fetch(segment.to_i) { return MISSING }
+ else
+ return MISSING
+ end
+ end
+ end
+
+ def condition_builder_schema?(schema)
+ schema.is_a?(Hash) && schema.dig(:ui, :control) == :condition_builder
+ end
+
+ def fixed_collection_schema?(schema)
+ schema_value(schema, :type) == :fixed_collection
+ end
+
+ def no_data_expression?(schema)
+ schema_value(schema, :no_data_expression) == true
+ end
+
+ def schema_value(schema, key)
+ return nil unless schema.respond_to?(:[])
+
+ schema[key] || schema[key.to_s]
+ end
+ end
+ end
+end
diff --git a/plugins/discourse-workflows/lib/discourse_workflows/executor/static_data_state.rb b/plugins/discourse-workflows/lib/discourse_workflows/executor/static_data_state.rb
new file mode 100644
index 00000000000..8ded191e851
--- /dev/null
+++ b/plugins/discourse-workflows/lib/discourse_workflows/executor/static_data_state.rb
@@ -0,0 +1,60 @@
+# frozen_string_literal: true
+
+module DiscourseWorkflows
+ class Executor
+ # Shared mutable static-data state for a single workflow execution.
+ #
+ # Lifecycle:
+ # 1. Snapshotted from the workflow row at execution start (`from_workflow`).
+ # 2. Read/mutated through `get_workflow_static_data` from any node's
+ # execution context during the run.
+ # 3. Committed back to the workflow row at execution end via
+ # `Executor#commit_static_data!`. Commits are skipped when no node
+ # ever accessed the data (`dirty?` stays false).
+ #
+ # Concurrency: commits take a row lock and reload the workflow, then
+ # overwrite `global` (last-write-wins) and merge `node` by
+ # name, persisted as flat `node:<name>` keys, so concurrent executions
+ # writing to different nodes don't clobber each other.
+ class StaticDataState
+ attr_reader :global, :node
+
+ def self.from_workflow(workflow)
+ normalized = workflow.normalized_static_data
+ new(
+ global: normalized[DiscourseWorkflows::Workflow::STATIC_DATA_GLOBAL_KEY].deep_dup,
+ node: workflow.node_static_data_entries.deep_dup,
+ )
+ end
+
+ def initialize(global: {}, node: {})
+ @global = global || {}
+ @node = node || {}
+ @dirty = false
+ end
+
+ def dirty?
+ @dirty
+ end
+
+ def fetch(scope)
+ @dirty = true
+ case scope.to_s
+ when DiscourseWorkflows::Workflow::STATIC_DATA_GLOBAL_KEY
+ @global
+ when "node"
+ raise ArgumentError, "Node scope requires a node name (use fetch_node(name))"
+ else
+ raise ArgumentError, "Unknown static data scope: #{scope.inspect}. Use :node or :global"
+ end
+ end
+
+ def fetch_node(node_name)
+ @dirty = true
+ key = node_name.to_s
+ @node[key] = {} unless @node.key?(key)
+ @node[key]
+ end
+ end
+ end
+end
diff --git a/plugins/discourse-workflows/lib/discourse_workflows/executor/step.rb b/plugins/discourse-workflows/lib/discourse_workflows/executor/step.rb
new file mode 100644
index 00000000000..1efa20b1618
--- /dev/null
+++ b/plugins/discourse-workflows/lib/discourse_workflows/executor/step.rb
@@ -0,0 +1,144 @@
+# frozen_string_literal: true
+
+module DiscourseWorkflows
+ class Executor
+ class Step
+ SUCCESS = "success"
+ ERROR = "error"
+ WAITING = "waiting"
+ FILTERED = "filtered"
+ RUNNING = "running"
+ SKIPPED = "skipped"
+
+ attr_reader :node_id,
+ :node_name,
+ :node_type,
+ :position,
+ :status,
+ :input,
+ :started_at,
+ :output,
+ :error,
+ :finished_at
+ attr_accessor :metadata
+
+ def initialize(
+ node_id:,
+ node_name:,
+ node_type:,
+ position:,
+ input:,
+ status: RUNNING,
+ output: nil,
+ error: nil,
+ started_at: nil,
+ finished_at: nil,
+ metadata: nil
+ )
+ @node_id = node_id.to_s
+ @node_name = node_name
+ @node_type = node_type
+ @position = position
+ @input = input
+ @status = status
+ @output = output
+ @error = error
+ @started_at = started_at || Time.current.iso8601(3)
+ @finished_at = finished_at || (status != RUNNING ? @started_at : nil)
+ @metadata = metadata
+ end
+
+ def success? = status == SUCCESS
+ def error? = status == ERROR
+ def waiting? = status == WAITING
+ def filtered? = status == FILTERED
+ def running? = status == RUNNING
+ def skipped? = status == SKIPPED
+
+ def succeed!(output:)
+ @status = SUCCESS
+ @output = output
+ @finished_at = Time.current.iso8601(3)
+ end
+
+ def filter!(output:)
+ @status = FILTERED
+ @output = output
+ @finished_at = Time.current.iso8601(3)
+ end
+
+ def fail!(message)
+ @status = ERROR
+ @error = message
+ @finished_at = Time.current.iso8601(3)
+ end
+
+ def mark_waiting!
+ @status = WAITING
+ end
+
+ def skip!(output:, reason:)
+ @status = SKIPPED
+ @output = output
+ @error = reason
+ @finished_at = Time.current.iso8601(3)
+ end
+
+ def apply_updates!(updates)
+ @status = updates["status"] if updates.key?("status")
+ @output = updates["output"] if updates.key?("output")
+ @finished_at = updates["finished_at"] if updates.key?("finished_at")
+ @error = updates["error"] if updates.key?("error")
+ end
+
+ def add_metadata(key, value)
+ @metadata ||= {}
+ @metadata[key] = value
+ end
+
+ def to_h
+ h = {
+ "node_id" => node_id,
+ "node_name" => node_name,
+ "node_type" => node_type,
+ "position" => position,
+ "status" => status,
+ "input" => input,
+ "started_at" => started_at,
+ }
+ h["output"] = output if output
+ h["finished_at"] = finished_at if finished_at
+ h["error"] = error if error
+ h["metadata"] = metadata if metadata
+ h
+ end
+
+ def self.from_h(hash)
+ new(
+ node_id: hash["node_id"],
+ node_name: hash["node_name"],
+ node_type: hash["node_type"],
+ position: hash["position"] || 0,
+ input: hash["input"],
+ status: hash["status"] || RUNNING,
+ output: hash["output"],
+ error: hash["error"],
+ started_at: hash["started_at"],
+ finished_at: hash["finished_at"],
+ metadata: hash["metadata"],
+ )
+ end
+
+ def self.build(node:, position:, input:, **kwargs)
+ new(
+ node_id: node.id,
+ node_name: node.name,
+ node_type: node.type,
+ position: position,
+ input: input,
+ **kwargs,
+ )
+ end
+ end
+ end
+end
diff --git a/plugins/discourse-workflows/lib/discourse_workflows/executor/step_log.rb b/plugins/discourse-workflows/lib/discourse_workflows/executor/step_log.rb
new file mode 100644
index 00000000000..61fd7f92533
--- /dev/null
+++ b/plugins/discourse-workflows/lib/discourse_workflows/executor/step_log.rb
@@ -0,0 +1,96 @@
+# frozen_string_literal: true
+
+module DiscourseWorkflows
+ class Executor
+ class StepLog
+ MAX_ENTRIES = 200
+
+ attr_reader :entries
+
+ def initialize
+ @entries = []
+ @has_errors = false
+ @truncated = false
+ end
+
+ def info(message)
+ append("info", message: message)
+ end
+
+ def warn(message)
+ append("warn", message: message)
+ end
+
+ def error(message)
+ @has_errors = true
+ append("error", message: message)
+ end
+
+ def kv(key, value, level: "info")
+ @has_errors = true if level == "error"
+ append(level, key: key, value: value.to_s)
+ end
+
+ def errors?
+ @has_errors
+ end
+
+ def empty?
+ @entries.empty?
+ end
+
+ def present?
+ @entries.present?
+ end
+
+ def merge(other)
+ return unless other
+ other.entries.each do |entry|
+ if @entries.size >= MAX_ENTRIES - 1
+ unless @truncated
+ @truncated = true
+ @entries << {
+ "level" => "warn",
+ "at" => Time.current.utc.iso8601,
+ "message" => "Log truncated at #{MAX_ENTRIES} entries",
+ }
+ end
+ break
+ end
+ @has_errors = true if entry["level"] == "error"
+ @entries << entry
+ end
+ end
+
+ def as_json(*)
+ @entries
+ end
+
+ def error_summary
+ errors = @entries.select { |e| e["level"] == "error" }
+ return if errors.empty?
+ messages = errors.first(3).map { |e| e["message"] || "#{e["key"]}: #{e["value"]}" }
+ messages.join("; ").truncate(500)
+ end
+
+ private
+
+ def append(level, **fields)
+ if @entries.size >= MAX_ENTRIES - 1
+ unless @truncated
+ @truncated = true
+ @entries << {
+ "level" => "warn",
+ "at" => Time.current.utc.iso8601,
+ "message" => "Log truncated at #{MAX_ENTRIES} entries",
+ }
+ end
+ return
+ end
+ @entries << { "level" => level, "at" => Time.current.utc.iso8601 }.merge(
+ fields.transform_keys(&:to_s),
+ )
+ end
+ end
+ end
+end
diff --git a/plugins/discourse-workflows/lib/discourse_workflows/executor/trigger_execution_context.rb b/plugins/discourse-workflows/lib/discourse_workflows/executor/trigger_execution_context.rb
new file mode 100644
index 00000000000..172306aa9e9
--- /dev/null
+++ b/plugins/discourse-workflows/lib/discourse_workflows/executor/trigger_execution_context.rb
@@ -0,0 +1,236 @@
+# frozen_string_literal: true
+
+module DiscourseWorkflows
+ class Executor
+ class TriggerExecutionContext
+ MISSING = Object.new.freeze
+ MAX_DEDUPLICATION_KEYS = 200
+
+ class RuntimeState
+ attr_reader :collected_trigger_data, :trigger_state, :static_data_global, :static_data_node
+
+ def initialize(trigger_state:, static_data_global: {}, static_data_node: {}, tick: false)
+ @collected_trigger_data = []
+ @trigger_state = trigger_state || {}
+ @static_data_global = static_data_global || {}
+ @static_data_node = static_data_node || {}
+ @tick = tick
+ end
+
+ def tick?
+ @tick
+ end
+
+ def deduplicated?(deduplication_key)
+ deduplication_key.present? &&
+ Array.wrap(@trigger_state["triggered_occurrences"]).include?(deduplication_key)
+ end
+
+ def record_deduplication_key(deduplication_key, now:)
+ keys = Array.wrap(@trigger_state["triggered_occurrences"])
+ @trigger_state["triggered_occurrences"] = keys.last(MAX_DEDUPLICATION_KEYS - 1) +
+ [deduplication_key]
+ @trigger_state["last_triggered_at"] = now.utc.iso8601
+ end
+
+ def collect_trigger_data(trigger_data)
+ @collected_trigger_data << trigger_data
+ end
+ end
+
+ attr_reader :now, :node_id
+
+ def initialize(
+ published_trigger:,
+ mode: :normal,
+ activation_mode: :init,
+ now: Time.current.utc,
+ dispatch: :enqueue,
+ user: nil,
+ runtime_state:
+ )
+ @published_trigger = published_trigger
+ @mode = mode.to_s
+ @activation_mode = activation_mode.to_s
+ @now = now
+ @dispatch = dispatch
+ @user = user
+ @node_id = published_trigger.trigger_node_id.to_s
+ @snapshot = WorkflowSnapshot.from_version(workflow, workflow_version)
+ @runtime_state = runtime_state
+ end
+
+ def get_node_parameter(parameter_name, default = nil, _options = {})
+ value = parameter_value(parameter_name)
+ value.equal?(MISSING) ? default : value
+ end
+
+ def get_timezone
+ DiscourseWorkflows::WorkflowTimezone.for(workflow:, workflow_version:)
+ end
+
+ def get_workflow_static_data(type)
+ case type.to_s
+ when "node"
+ @runtime_state.static_data_node
+ when "global"
+ @runtime_state.static_data_global
+ else
+ raise ArgumentError, "Unknown static data scope: #{type.inspect}. Use :node or :global"
+ end
+ end
+
+ def get_mode
+ @mode
+ end
+
+ def get_activation_mode
+ @activation_mode
+ end
+
+ def get_workflow
+ WorkflowView.from_workflow(workflow, name: workflow_version.name)
+ end
+
+ def get_node
+ NodeView.from_snapshot_node(
+ @snapshot.find_node(node_id),
+ include_node_parameters: true,
+ include_credentials: true,
+ include_webhook_id: true,
+ )
+ end
+
+ def get_child_nodes(node_name, options = {})
+ graph_nodes(
+ @snapshot.child_nodes(node_name, connection_type: "main", depth: -1),
+ include_node_parameters: graph_option(options, :include_node_parameters, false),
+ )
+ end
+
+ def get_parent_nodes(node_name, options = {})
+ graph_nodes(
+ @snapshot.parent_nodes(
+ node_name,
+ connection_type: graph_option(options, :connection_type, "main"),
+ depth: graph_option(options, :depth, -1),
+ ),
+ include_node_parameters: graph_option(options, :include_node_parameters, false),
+ )
+ end
+
+ def workflow_id
+ workflow.id
+ end
+
+ def helpers
+ @helpers ||= Helpers.new(self, @runtime_state)
+ end
+
+ def emit(data, deduplication_key: nil)
+ trigger_data = trigger_data_from(data)
+ return if trigger_data.blank?
+ return if @runtime_state.deduplicated?(deduplication_key)
+
+ if deduplication_key.present?
+ @runtime_state.record_deduplication_key(deduplication_key, now: now)
+ end
+
+ case @dispatch
+ when :enqueue
+ DiscourseWorkflows::TriggerDispatcher.enqueue(@published_trigger, trigger_data:)
+ when :execute
+ DiscourseWorkflows::TriggerDispatcher.execute(
+ @published_trigger,
+ trigger_data:,
+ user: @user,
+ )
+ when :collect
+ @runtime_state.collect_trigger_data(trigger_data)
+ when :none
+ nil
+ end
+ end
+
+ private
+
+ def workflow
+ @published_trigger.workflow
+ end
+
+ def workflow_version
+ @published_trigger.workflow_version
+ end
+
+ def graph_nodes(nodes, include_node_parameters:)
+ Array
+ .wrap(nodes)
+ .filter_map do |node|
+ NodeView.from_snapshot_node(node, include_node_parameters: include_node_parameters)
+ end
+ end
+
+ def graph_option(options, key, default)
+ options = {} unless options.respond_to?(:[])
+ options[key] || options[key.to_s] || default
+ end
+
+ def parameters
+ @parameters ||= DiscourseWorkflows::NodeData.parameters(@published_trigger.trigger_node)
+ end
+
+ def parameter_value(parameter_name)
+ segments = parameter_name.to_s.split(".").reject(&:blank?)
+ return MISSING if segments.empty?
+
+ segments.reduce(parameters) do |current, segment|
+ case current
+ when Hash
+ current.fetch(segment) { current.fetch(segment.to_sym, MISSING) }
+ when Array
+ return MISSING unless segment.match?(/\A\d+\z/)
+
+ current.fetch(segment.to_i) { return MISSING }
+ else
+ return MISSING
+ end
+ end
+ end
+
+ def trigger_data_from(data)
+ output_arrays = Array.wrap(data)
+ first_output = output_arrays.first
+ first_item = Array.wrap(first_output).first
+
+ if first_item.is_a?(Hash) && first_item.key?("json")
+ first_item["json"]
+ elsif first_item.is_a?(Hash)
+ first_item.deep_stringify_keys
+ else
+ {}
+ end
+ end
+
+ class Helpers
+ def initialize(context, runtime_state)
+ @context = context
+ @runtime_state = runtime_state
+ end
+
+ def return_json_array(json_data)
+ Array.wrap(json_data).map { |data| DiscourseWorkflows::Item.wrap(data) }
+ end
+
+ def register_cron(cron)
+ return unless @runtime_state.tick?
+
+ expression = cron[:expression] || cron["expression"]
+ scheduled_time = @context.now.in_time_zone(@context.get_timezone)
+ return unless DiscourseWorkflows::CronParser.matches?(expression, scheduled_time)
+
+ yield @context.now if block_given?
+ end
+ end
+ end
+ end
+end
diff --git a/plugins/discourse-workflows/lib/discourse_workflows/executor/webhook_execution_context.rb b/plugins/discourse-workflows/lib/discourse_workflows/executor/webhook_execution_context.rb
new file mode 100644
index 00000000000..33c7d6b426e
--- /dev/null
+++ b/plugins/discourse-workflows/lib/discourse_workflows/executor/webhook_execution_context.rb
@@ -0,0 +1,188 @@
+# frozen_string_literal: true
+
+module DiscourseWorkflows
+ class Executor
+ class WebhookExecutionContext
+ attr_reader :http_method, :path, :params, :webhook, :user, :node_id
+
+ delegate :input_items,
+ :get_node_parameter,
+ :get_node,
+ :get_workflow,
+ :get_child_nodes,
+ :get_parent_nodes,
+ :helpers,
+ to: :@node_execution_context
+
+ def initialize(
+ execution:,
+ node:,
+ node_type_class:,
+ webhook:,
+ http_method:,
+ path:,
+ params: {},
+ service_params: {}
+ )
+ @execution = execution
+ @node = node
+ @node_type_class = node_type_class
+ @webhook = webhook
+ @http_method = http_method.to_s
+ @path = path.to_s
+ @params = params || {}
+ @service_params = service_params || {}
+ @guardian = @service_params[:guardian] || @service_params["guardian"]
+ @user = @guardian&.user
+ @node_id = node_value("id").to_s
+ @node_identifier = node_value("type").to_s
+ @snapshot = execution_snapshot
+
+ build_context!
+ end
+
+ def trigger_data
+ @execution.trigger_data || {}
+ end
+
+ def get_request_object
+ {
+ "method" => http_method,
+ "path" => path,
+ "body" => get_body_data,
+ "query" => get_query_data,
+ "headers" => get_header_data,
+ }
+ end
+
+ def get_body_data
+ params
+ end
+
+ def get_query_data
+ params[:query] || params["query"] || {}
+ end
+
+ def get_header_data
+ params[:headers] || params["headers"] || {}
+ end
+
+ def resolve(value, item_index = 0)
+ @node_execution_context.evaluate_expression(value, item_index)
+ end
+
+ def dispose
+ @resolver&.dispose
+ @sandbox&.dispose
+ end
+
+ private
+
+ def build_context!
+ @execution_context =
+ ExecutionContext.new(
+ workflow: @execution.workflow,
+ trigger_data: trigger_data,
+ user: user,
+ execution: @execution,
+ workflow_nodes: @snapshot.to_h["nodes"],
+ workflow_name: @snapshot.workflow_name,
+ )
+ @execution_context.restore!(
+ context: @execution.execution_data&.context_data || {},
+ node_contexts: @execution.execution_data&.node_contexts || {},
+ resume_token: @execution.resume_token,
+ )
+
+ current_item = waiting_input_items.first || { "json" => {} }
+ node_context = @execution_context.node_context_for(snapshot_node(@node_id))
+ resolver_context =
+ @execution_context.resolver_context(
+ "__input_item" => current_item,
+ "__input_items" => waiting_input_items,
+ "__input_params" => parameters,
+ "__input_context" => DiscourseWorkflows::InputContext.from_node_context(node_context),
+ "__current_node_id" => @node_id,
+ "__node_parameters_by_name" => node_parameters_by_name,
+ "$itemIndex" => 0,
+ )
+ resolver_context.merge!("$json" => current_item.fetch("json") { {} })
+
+ @sandbox = DiscourseWorkflows::JsSandbox.new(resolver_context, user: user)
+ @resolver =
+ DiscourseWorkflows::ExpressionResolver.new(
+ resolver_context,
+ user: user,
+ sandbox: @sandbox,
+ )
+ @node_execution_context =
+ NodeExecutionContext.new(
+ input_items: waiting_input_items,
+ parameters: parameters,
+ credentials: credentials,
+ node_settings: DiscourseWorkflows::NodeData.direct_settings(@node),
+ webhook_id: webhook_id,
+ property_schema: @node_type_class.property_schema,
+ credential_schema: @node_type_class.credentials,
+ node_context: node_context,
+ user: user,
+ resolver: @resolver,
+ workflow: @execution.workflow,
+ execution_id: @execution.id,
+ resume_token: @execution.resume_token,
+ node_id: @node_id,
+ node_identifier: @node_identifier,
+ execution_mode: @execution.execution_mode.to_sym,
+ flow_context: @execution_context.context,
+ resolver_context: resolver_context,
+ workflow_snapshot: @snapshot,
+ )
+ end
+
+ def execution_snapshot
+ if @execution.execution_data&.workflow_data.present?
+ WorkflowSnapshot.new(@execution.execution_data.workflow_data)
+ else
+ WorkflowSnapshot.from_workflow(@execution.workflow, published: true)
+ end
+ end
+
+ def waiting_input_items
+ @waiting_input_items ||= @execution.waiting_step_input_items
+ end
+
+ def node_parameters_by_name
+ @node_parameters_by_name ||=
+ @snapshot
+ .nodes
+ .each_with_object({}) do |node, by_name|
+ name = node.name.to_s
+ next if name.blank?
+
+ by_name[name] = by_name.key?(name) ? nil : node.parameters
+ end
+ .compact
+ end
+
+ def snapshot_node(node_id)
+ @snapshot.find_node(node_id)
+ end
+
+ def parameters
+ @parameters ||= DiscourseWorkflows::NodeData.parameters(@node)
+ end
+
+ def credentials
+ @credentials ||= DiscourseWorkflows::NodeData.credentials(@node)
+ end
+
+ def webhook_id
+ DiscourseWorkflows::NodeData.webhook_id(@node)
+ end
+
+ def node_value(key)
+ DiscourseWorkflows::NodeData.read(@node, key)
+ end
+ end
+ end
+end
diff --git a/plugins/discourse-workflows/lib/discourse_workflows/expression_context_schema.rb b/plugins/discourse-workflows/lib/discourse_workflows/expression_context_schema.rb
new file mode 100644
index 00000000000..c40a3b83a69
--- /dev/null
+++ b/plugins/discourse-workflows/lib/discourse_workflows/expression_context_schema.rb
@@ -0,0 +1,80 @@
+# frozen_string_literal: true
+
+module DiscourseWorkflows
+ class ExpressionContextSchema
+ ENVIRONMENT_SYMBOLS = {
+ "$site_settings" => {
+ type: :object,
+ },
+ "$vars" => {
+ type: :object,
+ },
+ "$current_user" => {
+ type: :object,
+ provided_by_trigger: true,
+ fields: {
+ "id" => {
+ type: :integer,
+ },
+ "username" => {
+ type: :string,
+ },
+ },
+ },
+ "$execution" => {
+ type: :object,
+ fields: {
+ "id" => {
+ type: :integer,
+ },
+ "workflow_id" => {
+ type: :integer,
+ },
+ "workflow_name" => {
+ type: :string,
+ },
+ "resume_url" => {
+ type: :string,
+ display_options: {
+ show: {
+ node_present: [{ type: "flow:wait", parameters: { resume: "webhook" } }],
+ },
+ },
+ },
+ "resumeFormUrl" => {
+ type: :string,
+ display_options: {
+ show: {
+ node_present: [{ type: "action:form", parameters: { page_type: "page" } }],
+ },
+ },
+ },
+ },
+ },
+ }.freeze
+
+ NODE_REFERENCE_SHAPE = { item: { json: :object }, context: :object }.freeze
+
+ ITEM_PREFIX = "$json"
+
+ def self.environment_symbols
+ ENVIRONMENT_SYMBOLS
+ end
+
+ def self.node_reference_shape
+ NODE_REFERENCE_SHAPE
+ end
+
+ def self.item_prefix
+ ITEM_PREFIX
+ end
+
+ def self.to_hash
+ {
+ environment: ENVIRONMENT_SYMBOLS,
+ node_reference_shape: NODE_REFERENCE_SHAPE,
+ item_prefix: ITEM_PREFIX,
+ }
+ end
+ end
+end
diff --git a/plugins/discourse-workflows/lib/discourse_workflows/expression_resolver.rb b/plugins/discourse-workflows/lib/discourse_workflows/expression_resolver.rb
new file mode 100644
index 00000000000..3c9c7d32cd2
--- /dev/null
+++ b/plugins/discourse-workflows/lib/discourse_workflows/expression_resolver.rb
@@ -0,0 +1,485 @@
+# frozen_string_literal: true
+
+module DiscourseWorkflows
+ class ExpressionResolver
+ WHOLE_EXPRESSION_REGEX = /\A\{\{\s*([^{}]*?)\s*\}\}\z/
+
+ def self.find_matching_close(template, start)
+ depth = 1
+ cursor = start
+
+ while cursor < template.length - 1 && depth > 0
+ if template[cursor] == "{" && template[cursor + 1] == "{"
+ depth += 1
+ cursor += 2
+ elsif template[cursor] == "}" && template[cursor + 1] == "}"
+ depth -= 1
+ return cursor if depth == 0
+ cursor += 2
+ else
+ cursor += 1
+ end
+ end
+
+ nil
+ end
+
+ def self.resolve(value, context: {}, user: nil)
+ with_owned_sandbox(context, user: user) { |resolver| resolver.resolve(value) }
+ end
+
+ def self.resolve_hash(hash, context: {}, user: nil)
+ with_owned_sandbox(context, user: user) { |resolver| resolver.resolve_hash(hash) }
+ end
+
+ def self.resolve_segments(template, context: {}, user: nil)
+ with_owned_sandbox(context, user: user) { |resolver| resolver.resolve_segments(template) }
+ rescue MiniRacer::Error, JsSandbox::BudgetExceededError, JsSandbox::SandboxError => e
+ Rails.logger.warn("Expression evaluation failed: #{e.message}")
+ []
+ end
+
+ def self.with_owned_sandbox(context, user: nil)
+ sandbox = JsSandbox.new(context, user: user)
+ resolver = new(context, user: user, sandbox: sandbox)
+ yield resolver
+ ensure
+ resolver&.dispose
+ sandbox&.dispose
+ end
+
+ def initialize(context, sandbox:, user: nil, **_)
+ @context = context
+ @user = user
+ @sandbox = sandbox
+ end
+
+ def resolve(value)
+ return value unless resolvable_string?(value)
+
+ expression_body = value[1..].strip
+ whole_expression = expression_body.match(WHOLE_EXPRESSION_REGEX)&.captures&.first
+
+ whole_expression ? js_evaluator.evaluate(whole_expression) : render_template(expression_body)
+ end
+
+ def resolve_hash(hash)
+ resolve_tree(hash)
+ end
+
+ def dispose
+ @js_evaluator&.dispose
+ @js_evaluator = nil
+ end
+
+ def expression_errors
+ @js_evaluator&.expression_errors || []
+ end
+
+ def evaluate_expression(expression)
+ result = js_evaluator.evaluate(expression)
+ last_error = js_evaluator.expression_errors.last
+
+ if last_error && last_error[:expression] == expression
+ { result: nil, error: last_error[:error], error_type: last_error[:type] }
+ else
+ { result:, error: nil, error_type: nil }
+ end
+ end
+
+ def resolve_segments(template)
+ segments = []
+
+ scan_template(template) do |kind, content, from, to|
+ if kind == :plaintext
+ segments << { kind: "plaintext", text: content }
+ next
+ end
+
+ segment = { kind: "resolved", from:, to: }
+
+ if content.empty?
+ segment.merge!(text: "", state: "empty")
+ else
+ segment.merge!(classify_eval_result(evaluate_expression(content)))
+ end
+
+ segments << segment
+ end
+
+ segments
+ end
+
+ def with_item(item, item_index: 0)
+ input_item = normalize_input_item(item)
+ previous_json = @context["$json"]
+ previous_input_item = @context["__input_item"]
+ previous_item_index = @context["$itemIndex"]
+
+ @context["$json"] = input_item.fetch("json") { {} }
+ @context["__input_item"] = input_item
+ @context["$itemIndex"] = item_index
+ @js_evaluator&.rebind_input_item(input_item, item_index:)
+ yield
+ ensure
+ restore_context_value("$json", previous_json)
+ restore_context_value("__input_item", previous_input_item)
+ restore_context_value("$itemIndex", previous_item_index)
+ @js_evaluator&.rebind_input_item(
+ previous_input_item || { "json" => previous_json || {} },
+ item_index: previous_item_index || 0,
+ )
+ end
+
+ private
+
+ def normalize_input_item(item)
+ if item.is_a?(Hash)
+ stringified_item = item.deep_stringify_keys
+ return stringified_item if stringified_item.key?("json")
+ end
+
+ { "json" => item.deep_stringify_keys }
+ end
+
+ def restore_context_value(key, value)
+ if value.nil?
+ @context.delete(key)
+ else
+ @context[key] = value
+ end
+ end
+
+ def classify_eval_result(eval_result)
+ if eval_result[:error]
+ state = eval_result[:error_type] == :undefined ? "undefined" : "invalid"
+ return { text: "", state: }
+ end
+
+ result = eval_result[:result]
+ return { text: "", state: "undefined" } if result.nil?
+ return { text: "", state: "warning" } if result.is_a?(MiniRacer::JavaScriptFunction)
+
+ { text: format_value(result), state: "valid" }
+ end
+
+ def resolve_tree(value)
+ case value
+ when Hash
+ value.transform_values { |nested_value| resolve_tree(nested_value) }
+ when Array
+ value.map { |item| resolve_tree(item) }
+ else
+ resolve(value)
+ end
+ end
+
+ def resolvable_string?(value)
+ value.is_a?(String) && value.start_with?("=")
+ end
+
+ def render_template(template)
+ result = +""
+
+ scan_template(template) do |kind, content, _from, _to|
+ if kind == :expression
+ result << format_value(js_evaluator.evaluate(content))
+ else
+ result << content
+ end
+ end
+
+ result
+ end
+
+ def scan_template(template)
+ pos = 0
+
+ while pos < template.length
+ open = template.index("{{", pos)
+
+ if open.nil?
+ yield :plaintext, template[pos..], pos, template.length if pos < template.length
+ break
+ end
+
+ yield :plaintext, template[pos...open], pos, open if open > pos
+
+ close = self.class.find_matching_close(template, open + 2)
+
+ unless close
+ yield :plaintext, template[open..], open, template.length
+ break
+ end
+
+ yield :expression, template[(open + 2)...close].strip, open, close + 2
+ pos = close + 2
+ end
+ end
+
+ def js_evaluator
+ @js_evaluator ||= JsEvaluator.new(@context, user: @user, sandbox: @sandbox)
+ end
+
+ def format_value(value)
+ return "" if value.nil?
+ Array(value).join(", ")
+ end
+
+ class JsEvaluator
+ BLOCKED_NODE_NAMES = %w[constructor prototype eval].freeze
+
+ def initialize(context, sandbox:, user: nil)
+ @context = context
+ @user = user
+ @sandbox = sandbox
+ @initialized = false
+ @expression_errors = []
+ @callback_prefix = "__dwExpr#{object_id.abs}"
+ end
+
+ attr_reader :expression_errors
+
+ def evaluate(expression)
+ ensure_initialized!
+ @sandbox.eval("(#{expression})")
+ rescue JsSandbox::BudgetExceededError
+ raise
+ rescue JsSandbox::SandboxError, MiniRacer::Error => e
+ if e.message.include?(NodeOutputProxy::MULTIPLE_MATCHING_ITEMS_MESSAGE)
+ raise RuntimeError, NodeOutputProxy::MULTIPLE_MATCHING_ITEMS_MESSAGE
+ end
+
+ @expression_errors << { expression: expression, error: e.message, type: classify_error(e) }
+ nil
+ end
+
+ def classify_error(error)
+ msg = error.message
+ if msg.include?("is not defined") || msg.include?("Cannot read properties")
+ :undefined
+ else
+ :invalid
+ end
+ end
+
+ def dispose
+ @sandbox = nil
+ end
+
+ def rebind_input_item(item, item_index: 0)
+ ensure_initialized!
+ @sandbox.rebind_expression_item(item, item_index:)
+ end
+
+ private
+
+ def ensure_initialized!
+ return if @initialized
+ inject_expression_data!
+ @initialized = true
+ end
+
+ def inject_expression_data!
+ data = build_expression_data
+ @sandbox.attach(fetch_node_item_callback, method(:fetch_node_item_for_expression))
+ @sandbox.attach(fetch_node_items_callback, method(:fetch_node_items_for_expression))
+ @sandbox.attach(fetch_node_params_callback, method(:fetch_node_params_for_expression))
+ @sandbox.attach(node_executed_callback, method(:node_executed_for_expression?))
+ @sandbox.attach(fetch_input_items_callback, method(:fetch_input_items))
+ @sandbox.declare_json("__data", data)
+ @sandbox.eval(expression_setup_js)
+ end
+
+ def fetch_node_item_callback
+ "#{@callback_prefix}FetchNodeItem"
+ end
+
+ def fetch_node_items_callback
+ "#{@callback_prefix}FetchNodeItems"
+ end
+
+ def fetch_node_params_callback
+ "#{@callback_prefix}FetchNodeParams"
+ end
+
+ def node_executed_callback
+ "#{@callback_prefix}NodeExecuted"
+ end
+
+ def fetch_input_items_callback
+ "#{@callback_prefix}FetchInputItems"
+ end
+
+ def build_expression_data
+ {
+ "$json" => @context.fetch("$json") { {} },
+ "$trigger" => @context.fetch("$trigger") { {} },
+ "$execution" => @context.fetch("__execution") { {} },
+ "$itemIndex" => @context.fetch("$itemIndex") { 0 },
+ "__inputItem" =>
+ @context.fetch("__input_item") { { "json" => @context.fetch("$json") { {} } } },
+ "__inputParams" => @context.fetch("__input_params") { {} },
+ "__inputContext" => @context.fetch("__input_context") { {} },
+ "__node_contexts" => @context.fetch("__node_contexts") { {} },
+ "__nodeParametersByName" => @context.fetch("__node_parameters_by_name") { {} },
+ }
+ end
+
+ def fetch_node_item_for_expression(name, item_index = nil)
+ name_str = name.to_s
+ return {}.to_json if name_str.start_with?("_") || BLOCKED_NODE_NAMES.include?(name_str)
+
+ JsSandbox.serialize_json_payload(
+ node_output_proxy.item(name_str, item_index: item_index),
+ label: "$().item",
+ )
+ end
+
+ def fetch_node_items_for_expression(name, branch_index = nil, run_index = nil)
+ name_str = name.to_s
+ return [].to_json if name_str.start_with?("_") || BLOCKED_NODE_NAMES.include?(name_str)
+
+ JsSandbox.serialize_json_payload(
+ node_output_proxy.all(name_str, branch_index:, run_index:),
+ label: "$().all()",
+ )
+ end
+
+ def fetch_node_params_for_expression(name)
+ name_str = name.to_s
+ return {}.to_json if name_str.start_with?("_") || BLOCKED_NODE_NAMES.include?(name_str)
+
+ JsSandbox.serialize_json_payload(node_output_proxy.params(name_str), label: "$().params")
+ end
+
+ def node_executed_for_expression?(name)
+ name_str = name.to_s
+ return false if name_str.start_with?("_") || BLOCKED_NODE_NAMES.include?(name_str)
+
+ node_output_proxy.executed?(name_str)
+ end
+
+ def fetch_input_items
+ JsSandbox.serialize_json_payload(
+ @context.fetch("__input_items") { [] },
+ label: "$input.all()",
+ )
+ end
+
+ def expression_setup_js
+ <<~JS
+ function __WorkflowExpressionInput(item) {
+ this.item = item;
+ this.params = __data["__inputParams"];
+ this.context = __data["__inputContext"];
+ }
+
+ __WorkflowExpressionInput.prototype.all = function() {
+ return JSON.parse(#{fetch_input_items_callback}());
+ };
+
+ __WorkflowExpressionInput.prototype.first = function() {
+ var items = this.all();
+ return items[0] || { json: {} };
+ };
+
+ __WorkflowExpressionInput.prototype.last = function() {
+ var items = this.all();
+ return items[items.length - 1] || { json: {} };
+ };
+
+ var $input = new __WorkflowExpressionInput(__data["__inputItem"]);
+ Object.defineProperty(this, '$json', {
+ get: function() { return $input.item.json; },
+ set: function(value) {
+ $input.item.json = value;
+ __data["$json"] = value;
+ },
+ configurable: true
+ });
+ Object.defineProperty(this, '$itemIndex', {
+ get: function() { return __data["$itemIndex"]; },
+ set: function(value) { __data["$itemIndex"] = value; },
+ configurable: true
+ });
+ var $trigger = __data["$trigger"];
+ var $execution = __data["$execution"];
+ function __WorkflowExpressionNode(name) {
+ this.name = name;
+ }
+
+ Object.defineProperty(__WorkflowExpressionNode.prototype, 'item', {
+ get: function() {
+ return JSON.parse(#{fetch_node_item_callback}(this.name, __data["$itemIndex"]));
+ },
+ configurable: true
+ });
+
+ __WorkflowExpressionNode.prototype.itemMatching = function(itemIndex) {
+ if (itemIndex === undefined) {
+ throw new Error("Missing item index for .itemMatching()");
+ }
+ return JSON.parse(#{fetch_node_item_callback}(this.name, itemIndex));
+ };
+
+ __WorkflowExpressionNode.prototype.pairedItem = function(itemIndex) {
+ return JSON.parse(
+ #{fetch_node_item_callback}(
+ this.name,
+ itemIndex === undefined ? __data["$itemIndex"] : itemIndex
+ )
+ );
+ };
+
+ Object.defineProperty(__WorkflowExpressionNode.prototype, 'context', {
+ get: function() {
+ return __data.__node_contexts[this.name] || {};
+ },
+ configurable: true
+ });
+
+ Object.defineProperty(__WorkflowExpressionNode.prototype, 'params', {
+ get: function() {
+ return JSON.parse(#{fetch_node_params_callback}(this.name));
+ },
+ configurable: true
+ });
+
+ Object.defineProperty(__WorkflowExpressionNode.prototype, 'isExecuted', {
+ get: function() {
+ return #{node_executed_callback}(this.name);
+ },
+ configurable: true
+ });
+
+ __WorkflowExpressionNode.prototype.all = function(branchIndex, runIndex) {
+ return JSON.parse(#{fetch_node_items_callback}(this.name, branchIndex, runIndex));
+ };
+
+ __WorkflowExpressionNode.prototype.first = function(branchIndex, runIndex) {
+ var items = this.all(branchIndex, runIndex);
+ return items[0] || { json: {} };
+ };
+
+ __WorkflowExpressionNode.prototype.last = function(branchIndex, runIndex) {
+ var items = this.all(branchIndex, runIndex);
+ return items[items.length - 1] || { json: {} };
+ };
+
+ Object.defineProperty(this, '$', {
+ value: function(name) {
+ return new __WorkflowExpressionNode(name);
+ },
+ configurable: true,
+ writable: false
+ });
+ JS
+ end
+
+ def node_output_proxy
+ @node_output_proxy ||= NodeOutputProxy.new(@context)
+ end
+ end
+ end
+end
diff --git a/plugins/discourse-workflows/lib/discourse_workflows/form_completion.rb b/plugins/discourse-workflows/lib/discourse_workflows/form_completion.rb
new file mode 100644
index 00000000000..2959d2e7c82
--- /dev/null
+++ b/plugins/discourse-workflows/lib/discourse_workflows/form_completion.rb
@@ -0,0 +1,54 @@
+# frozen_string_literal: true
+
+module DiscourseWorkflows
+ class FormCompletion
+ NODE_TYPE = "action:form"
+ COMPLETION_PAGE_TYPE = "completion"
+ DEFAULT_ON_SUBMISSION = "completion_screen"
+ METADATA_KEY = "form_completion"
+
+ def self.from_execution(execution)
+ execution
+ .execution_data
+ &.steps_array
+ .to_a
+ .select do |step|
+ step["status"] == Executor::Step::SUCCESS && step.dig("metadata", METADATA_KEY).present?
+ end
+ .last
+ &.dig("metadata", METADATA_KEY)
+ end
+
+ def self.for_node(node, resolver:)
+ completion_payload(resolver.resolve_hash(parameters_for(node)))
+ end
+
+ def self.completion_node?(node)
+ node.present? && NodeData.read(node, "type") == NODE_TYPE &&
+ parameters_for(node).fetch("page_type") { "page" } == COMPLETION_PAGE_TYPE
+ end
+
+ def self.completion_payload(config)
+ {
+ "on_submission" => config.fetch("on_submission") { DEFAULT_ON_SUBMISSION },
+ "completion_title" => sanitize_html(config["completion_title"]),
+ "completion_message" => sanitize_html(config["completion_message"]),
+ "redirect_url" => config["redirect_url"],
+ "completion_text" => sanitize_html(config["completion_text"]),
+ }
+ end
+ private_class_method :completion_payload
+
+ def self.sanitize_html(value)
+ return if value.nil?
+
+ DiscourseWorkflows::Forms::Schema.sanitize_html(value)
+ end
+ private_class_method :sanitize_html
+
+ def self.parameters_for(node)
+ NodeData.parameters(node).deep_stringify_keys
+ end
+ private_class_method :parameters_for
+ end
+end
diff --git a/plugins/discourse-workflows/lib/discourse_workflows/form_response.rb b/plugins/discourse-workflows/lib/discourse_workflows/form_response.rb
new file mode 100644
index 00000000000..2ca751bd9f7
--- /dev/null
+++ b/plugins/discourse-workflows/lib/discourse_workflows/form_response.rb
@@ -0,0 +1,89 @@
+# frozen_string_literal: true
+
+module DiscourseWorkflows
+ module FormResponse
+ WORKFLOW_FINISHES_RESPONSE_MODE = "workflow_finishes"
+
+ module_function
+
+ def initial_submission(execution, response_metadata)
+ response_mode = response_metadata[:response_mode]
+ payload = {
+ has_downstream_form: response_metadata[:has_downstream_form],
+ response_mode: response_mode,
+ status: execution&.status,
+ }
+
+ if DiscourseWorkflows::WaitingWebhookRunner.waiting_for?(execution, node_type: "form")
+ payload.merge!(DiscourseWorkflows::WaitingExecution.form_urls(execution))
+ elsif execution&.success?
+ form_completion = DiscourseWorkflows::FormCompletion.from_execution(execution)
+ return if no_data_response?(execution, response_mode, form_completion)
+
+ payload[:form_completion] = form_completion
+ elsif execution&.error?
+ payload[:errors] = [workflow_error_message]
+ elsif no_data_response?(execution, response_mode)
+ return
+ end
+
+ payload.compact
+ end
+
+ def initial_submission_status(execution, response_metadata)
+ if response_metadata[:response_mode] == WORKFLOW_FINISHES_RESPONSE_MODE && execution&.error?
+ return :internal_server_error
+ end
+
+ :ok
+ end
+
+ def resumed_submission(execution)
+ response_mode = trigger_response_mode(execution)
+ body = { status: execution.status }
+
+ if DiscourseWorkflows::WaitingWebhookRunner.waiting_for?(execution, node_type: "form")
+ body.merge!(DiscourseWorkflows::WaitingExecution.form_urls(execution))
+ elsif execution.success?
+ form_completion = DiscourseWorkflows::FormCompletion.from_execution(execution)
+ return if no_data_response?(execution, response_mode, form_completion)
+
+ body[:form_completion] = form_completion
+ elsif execution.error?
+ body[:errors] = [workflow_error_message]
+ elsif no_data_response?(execution, response_mode)
+ return
+ end
+
+ body.compact
+ end
+
+ def resumed_submission_status(execution)
+ return :internal_server_error if execution.error?
+
+ :ok
+ end
+
+ def workflow_error_message
+ I18n.t("discourse_workflows.errors.workflow_failed")
+ end
+
+ def no_data_response?(execution, response_mode, form_completion = nil)
+ return false unless response_mode == WORKFLOW_FINISHES_RESPONSE_MODE
+ if DiscourseWorkflows::WaitingWebhookRunner.waiting_for?(execution, node_type: "form")
+ return false
+ end
+
+ execution&.waiting? || (execution&.success? && form_completion.blank?)
+ end
+
+ def trigger_response_mode(execution)
+ return if execution.blank?
+
+ trigger_node = execution.workflow_node(execution.trigger_node_id)
+ return if trigger_node.blank?
+
+ DiscourseWorkflows::NodeData.parameters(trigger_node)["response_mode"]
+ end
+ end
+end
diff --git a/plugins/discourse-workflows/lib/discourse_workflows/form_test_session.rb b/plugins/discourse-workflows/lib/discourse_workflows/form_test_session.rb
new file mode 100644
index 00000000000..994a1c45068
--- /dev/null
+++ b/plugins/discourse-workflows/lib/discourse_workflows/form_test_session.rb
@@ -0,0 +1,51 @@
+# frozen_string_literal: true
+
+module DiscourseWorkflows
+ class FormTestSession
+ TTL = 120.seconds
+ CACHE_PREFIX = "discourse_workflows:form_test_session"
+
+ def self.create!(workflow:, user:, trigger_node_id:)
+ token = SecureRandom.uuid
+ payload = {
+ "workflow_id" => workflow.id,
+ "user_id" => user.id,
+ "trigger_node_id" => trigger_node_id.to_s,
+ "workflow_data" => WorkflowSnapshot.from_workflow(workflow).to_h,
+ }
+
+ Discourse.cache.write(cache_key(token), payload, expires_in: TTL)
+ token
+ end
+
+ def self.find(token)
+ payload = Discourse.cache.read(cache_key(token))
+ return if payload.blank?
+
+ new(token:, payload: payload.deep_stringify_keys)
+ end
+
+ attr_reader :token, :workflow_id, :user_id, :trigger_node_id, :workflow_snapshot
+
+ def initialize(token:, payload:)
+ @token = token
+ @workflow_id = payload["workflow_id"].to_i
+ @user_id = payload["user_id"].to_i
+ @trigger_node_id = payload["trigger_node_id"].to_s
+ @workflow_snapshot = WorkflowSnapshot.new(payload["workflow_data"])
+ end
+
+ def trigger_node
+ workflow_snapshot.find_node(trigger_node_id)
+ end
+
+ def owned_by?(user)
+ user.present? && user.id == user_id
+ end
+
+ def self.cache_key(token)
+ "#{CACHE_PREFIX}:#{token}"
+ end
+ private_class_method :cache_key
+ end
+end
diff --git a/plugins/discourse-workflows/lib/discourse_workflows/form_trigger_token.rb b/plugins/discourse-workflows/lib/discourse_workflows/form_trigger_token.rb
new file mode 100644
index 00000000000..598cab33ecb
--- /dev/null
+++ b/plugins/discourse-workflows/lib/discourse_workflows/form_trigger_token.rb
@@ -0,0 +1,68 @@
+# frozen_string_literal: true
+
+module DiscourseWorkflows
+ class FormTriggerToken
+ PURPOSE = "discourse-workflows-form-trigger"
+ SALT = "discourse-workflows-form-trigger"
+ KEY_LENGTH = 32
+ TTL = 1.hour
+
+ def self.generate(workflow_id:, trigger_node_id:, uuid:, form_query_parameters: nil)
+ payload = {
+ "workflow_id" => workflow_id,
+ "trigger_node_id" => trigger_node_id.to_s,
+ "uuid" => uuid,
+ "nonce" => SecureRandom.hex(16),
+ }
+
+ normalized_query_parameters =
+ DiscourseWorkflows::Forms::Payload.normalize_query_parameters(form_query_parameters)
+ if normalized_query_parameters.present?
+ payload["form_query_parameters"] = normalized_query_parameters
+ end
+
+ encryptor.encrypt_and_sign(JSON.generate(payload), purpose: PURPOSE, expires_in: TTL)
+ end
+
+ def self.valid?(token, workflow_id:, trigger_node_id:, uuid:)
+ payload(
+ token,
+ workflow_id: workflow_id,
+ trigger_node_id: trigger_node_id,
+ uuid: uuid,
+ ).present?
+ end
+
+ def self.payload(token, workflow_id:, trigger_node_id:, uuid:)
+ payload = verify(token)
+ return if payload.blank?
+
+ if payload["workflow_id"].to_s == workflow_id.to_s &&
+ payload["trigger_node_id"].to_s == trigger_node_id.to_s &&
+ payload["uuid"].to_s == uuid.to_s
+ payload
+ end
+ end
+
+ def self.verify(token)
+ decrypted = encryptor.decrypt_and_verify(token, purpose: PURPOSE)
+ return if decrypted.blank?
+
+ JSON.parse(decrypted)
+ rescue ActiveSupport::MessageEncryptor::InvalidMessage, JSON::ParserError
+ nil
+ end
+
+ def self.encryptor
+ @encryptor ||=
+ ActiveSupport::MessageEncryptor.new(
+ ActiveSupport::KeyGenerator.new(Rails.application.secret_key_base).generate_key(
+ SALT,
+ KEY_LENGTH,
+ ),
+ cipher: "aes-256-gcm",
+ )
+ end
+ private_class_method :encryptor
+ end
+end
diff --git a/plugins/discourse-workflows/lib/discourse_workflows/forms/payload.rb b/plugins/discourse-workflows/lib/discourse_workflows/forms/payload.rb
new file mode 100644
index 00000000000..eed2e35eaf8
--- /dev/null
+++ b/plugins/discourse-workflows/lib/discourse_workflows/forms/payload.rb
@@ -0,0 +1,40 @@
+# frozen_string_literal: true
+
+module DiscourseWorkflows
+ module Forms
+ module Payload
+ DEFAULT_MODE = "production"
+
+ module_function
+
+ def build(
+ form_data,
+ submitted_at: Time.current.utc.iso8601(3),
+ form_mode: DEFAULT_MODE,
+ query_parameters: nil
+ )
+ payload = (form_data || {}).deep_stringify_keys
+ payload["submitted_at"] = submitted_at
+ payload["form_mode"] = form_mode.presence || DEFAULT_MODE
+
+ if (query_parameters = normalize_query_parameters(query_parameters)).present?
+ payload["form_query_parameters"] = query_parameters
+ end
+
+ payload
+ end
+
+ def normalize_query_parameters(query_parameters)
+ query_parameters.present? ? query_parameters.to_h.deep_stringify_keys : {}
+ end
+
+ def form_mode_from(trigger_data)
+ trigger_data.to_h["form_mode"].presence || DEFAULT_MODE
+ end
+
+ def query_parameters_from(trigger_data)
+ trigger_data.to_h["form_query_parameters"] || {}
+ end
+ end
+ end
+end
diff --git a/plugins/discourse-workflows/lib/discourse_workflows/forms/schema.rb b/plugins/discourse-workflows/lib/discourse_workflows/forms/schema.rb
new file mode 100644
index 00000000000..8c9eec4b9e6
--- /dev/null
+++ b/plugins/discourse-workflows/lib/discourse_workflows/forms/schema.rb
@@ -0,0 +1,171 @@
+# frozen_string_literal: true
+
+module DiscourseWorkflows
+ module Forms
+ module Schema
+ HTML_SANITIZE_CONFIG = {
+ elements: %w[
+ a
+ b
+ br
+ code
+ div
+ em
+ h1
+ h2
+ h3
+ h4
+ h5
+ h6
+ i
+ img
+ li
+ ol
+ p
+ pre
+ source
+ span
+ strong
+ sub
+ sup
+ table
+ tbody
+ td
+ th
+ thead
+ tr
+ u
+ ul
+ video
+ ],
+ attributes: {
+ "a" => %w[href target title],
+ "img" => %w[alt height src title width],
+ "source" => %w[src type],
+ "video" => %w[controls height poster src width],
+ },
+ protocols: {
+ "a" => {
+ "href" => %w[http https mailto],
+ },
+ "img" => {
+ "src" => %w[http https],
+ },
+ "source" => {
+ "src" => %w[http https],
+ },
+ "video" => {
+ "poster" => %w[http https],
+ "src" => %w[http https],
+ },
+ },
+ }.freeze
+
+ module_function
+
+ def build(fields)
+ form_fields = DiscourseWorkflows::Schemas::FormFields.with_keys(fields)
+
+ {
+ data: initial_data(form_fields),
+ fields: form_fields.map { |field| field_schema(field) }.compact,
+ }
+ end
+
+ def initial_data(fields)
+ fields.each_with_object({}) do |field, data|
+ next if field["field_type"] == "html"
+ next if field["field_type"] == "hiddenField"
+
+ data[field["key"]] = initial_value(field)
+ end
+ end
+
+ def initial_value(field)
+ default_value = field["default_value"]
+
+ case field["field_type"]
+ when "checkbox"
+ ActiveModel::Type::Boolean.new.cast(default_value)
+ when "password"
+ ""
+ else
+ default_value.presence || ""
+ end
+ end
+
+ def field_schema(field)
+ type = field["field_type"].presence || "text"
+ return if type == "hiddenField"
+
+ schema = {
+ name: field["key"],
+ title: field["field_label"],
+ description: field["description"],
+ type: form_kit_type(type),
+ validation: validation_for(field),
+ placeholder: field["placeholder"],
+ autofocus: false,
+ }.compact
+
+ case type
+ when "dropdown", "radio"
+ schema[:options] = options_for(field)
+ when "html"
+ schema[:html] = sanitize_html(field["html"])
+ end
+
+ schema
+ end
+
+ def form_kit_type(field_type)
+ case field_type
+ when "textarea"
+ "textarea"
+ when "checkbox"
+ "checkbox"
+ when "dropdown"
+ "select"
+ when "number"
+ "input-number"
+ when "email"
+ "input-email"
+ when "password"
+ "password"
+ when "date"
+ "input-date"
+ when "radio"
+ "radio-group"
+ when "html"
+ "html"
+ else
+ "input"
+ end
+ end
+
+ def validation_for(field)
+ return if %w[checkbox hiddenField html].include?(field["field_type"])
+
+ "required" if field["required"]
+ end
+
+ def options_for(field)
+ options = field["options"]
+ values = options.is_a?(Hash) ? options["values"] : options
+
+ Array
+ .wrap(values)
+ .filter_map do |option|
+ value = option.is_a?(Hash) ? option["value"] || option[:value] : option
+ next if value.blank?
+
+ { value: value, label: value }
+ end
+ end
+
+ def sanitize_html(html)
+ Sanitize.fragment(html.to_s, HTML_SANITIZE_CONFIG)
+ end
+ end
+ end
+end
diff --git a/plugins/discourse-workflows/lib/discourse_workflows/forms/view_model.rb b/plugins/discourse-workflows/lib/discourse_workflows/forms/view_model.rb
new file mode 100644
index 00000000000..d4b39b8157b
--- /dev/null
+++ b/plugins/discourse-workflows/lib/discourse_workflows/forms/view_model.rb
@@ -0,0 +1,40 @@
+# frozen_string_literal: true
+
+module DiscourseWorkflows
+ module Forms
+ module ViewModel
+ module_function
+
+ def build(
+ fields:,
+ form_title:,
+ form_description:,
+ response_mode:,
+ has_downstream_form:,
+ form_submit_url: nil,
+ form_waiting_url: nil,
+ form_status_url: nil,
+ form_channel: nil,
+ resume_token: nil,
+ form_mode: nil
+ )
+ schema = DiscourseWorkflows::Forms::Schema.build(fields)
+
+ {
+ form_title: form_title,
+ form_description: form_description,
+ data: schema[:data],
+ fields: schema[:fields],
+ response_mode: response_mode,
+ has_downstream_form: has_downstream_form,
+ form_submit_url: form_submit_url,
+ form_waiting_url: form_waiting_url,
+ form_status_url: form_status_url,
+ form_channel: form_channel,
+ resume_token: resume_token,
+ form_mode: form_mode,
+ }.compact
+ end
+ end
+ end
+end
diff --git a/plugins/discourse-workflows/lib/discourse_workflows/input_context.rb b/plugins/discourse-workflows/lib/discourse_workflows/input_context.rb
new file mode 100644
index 00000000000..779a515b62f
--- /dev/null
+++ b/plugins/discourse-workflows/lib/discourse_workflows/input_context.rb
@@ -0,0 +1,9 @@
+# frozen_string_literal: true
+
+module DiscourseWorkflows
+ class InputContext
+ def self.from_node_context(node_context)
+ node_context&.key?("no_items_left") ? { "noItemsLeft" => node_context["no_items_left"] } : {}
+ end
+ end
+end
diff --git a/plugins/discourse-workflows/lib/discourse_workflows/interactive_resume.rb b/plugins/discourse-workflows/lib/discourse_workflows/interactive_resume.rb
new file mode 100644
index 00000000000..3ba830a6926
--- /dev/null
+++ b/plugins/discourse-workflows/lib/discourse_workflows/interactive_resume.rb
@@ -0,0 +1,73 @@
+# frozen_string_literal: true
+
+module DiscourseWorkflows
+ class InteractiveResume
+ class Request
+ attr_reader :action
+
+ def initialize(execution:, action:)
+ @execution = execution
+ @action = action
+ end
+
+ def claim
+ claimed_execution =
+ DiscourseWorkflows::Execution.claim_for_resume(
+ @execution,
+ resume_token: @execution.resume_token,
+ )
+ return if claimed_execution.blank?
+
+ ClaimedRequest.new(execution: claimed_execution, action: action)
+ end
+ end
+
+ class ClaimedRequest
+ attr_reader :action
+
+ def initialize(execution:, action:)
+ @execution = execution
+ @action = action
+ end
+
+ def resume!(response_items, user: nil)
+ DiscourseWorkflows::WaitingExecution.resume_claimed(@execution, response_items, user: user)
+ end
+ end
+
+ def self.action_id(execution_id:, resume_token:, action:)
+ DiscourseWorkflows::WaitingExecution.action_token(
+ execution_id: execution_id,
+ resume_token: resume_token,
+ action: action,
+ )
+ end
+
+ def self.action_payload(action_id)
+ DiscourseWorkflows::WaitingExecution.action_token_payload(action_id)
+ end
+
+ def self.action_id?(action_id, expected_node_type:, allowed_actions:)
+ from_action_id(
+ action_id,
+ expected_node_type: expected_node_type,
+ allowed_actions: allowed_actions,
+ ).present?
+ end
+
+ def self.from_action_id(action_id, expected_node_type:, allowed_actions:)
+ payload = action_payload(action_id)
+ return if payload.blank?
+ return if allowed_actions.exclude?(payload["action"])
+
+ execution =
+ DiscourseWorkflows::WaitingExecution.find_by_action_token(
+ action_id,
+ expected_node_type: expected_node_type,
+ )
+ return if execution.blank?
+
+ Request.new(execution: execution, action: payload["action"])
+ end
+ end
+end
diff --git a/plugins/discourse-workflows/lib/discourse_workflows/item.rb b/plugins/discourse-workflows/lib/discourse_workflows/item.rb
new file mode 100644
index 00000000000..867b7c1259c
--- /dev/null
+++ b/plugins/discourse-workflows/lib/discourse_workflows/item.rb
@@ -0,0 +1,90 @@
+# frozen_string_literal: true
+
+module DiscourseWorkflows
+ module Item
+ PAIRED_ITEM_KEY = "pairedItem"
+ INCONSISTENT_ITEM_FORMAT_MESSAGE = "Every returned item must use the same format."
+
+ class InconsistentItemFormatError < ArgumentError
+ end
+
+ def self.wrap(data = nil, paired_item: nil, **keyword_data)
+ data = keyword_data if data.nil? && keyword_data.present?
+
+ case data
+ when Array
+ data.map { |d| wrap(d) }
+ when Hash
+ item = { "json" => data.deep_stringify_keys.freeze }
+ item[PAIRED_ITEM_KEY] = normalize_paired_item(paired_item) if paired_item.present?
+ item
+ else
+ raise ArgumentError, "Item.wrap expects Hash or Array<Hash>, got #{data.class}"
+ end
+ end
+
+ def self.normalize_items(execution_data)
+ execution_data = stringify_result(execution_data)
+
+ if execution_data.is_a?(Hash)
+ return [normalize_item_result(execution_data)] if execution_data.key?("json")
+
+ return [wrap(execution_data)]
+ end
+
+ if execution_data.all? { |item| item.is_a?(Hash) && item.key?("json") }
+ return execution_data.map { |item| normalize_item_result(item) }
+ end
+
+ if execution_data.any? { |item| item.is_a?(Hash) && item.key?("json") }
+ raise InconsistentItemFormatError, INCONSISTENT_ITEM_FORMAT_MESSAGE
+ end
+
+ execution_data.map { |item| wrap(item) }
+ end
+
+ def self.paired_item(item)
+ item[PAIRED_ITEM_KEY]
+ end
+
+ def self.with_paired_item(item, paired_item)
+ item.except(PAIRED_ITEM_KEY).merge(PAIRED_ITEM_KEY => normalize_paired_item(paired_item))
+ end
+
+ def self.normalize_paired_item(paired_item)
+ case paired_item
+ when Array
+ paired_item.map { |entry| normalize_paired_item_entry(entry) }
+ when Hash
+ normalize_paired_item_entry(paired_item)
+ when Integer
+ { "item" => paired_item }
+ else
+ paired_item
+ end
+ end
+
+ def self.normalize_paired_item_entry(entry)
+ entry.deep_stringify_keys.compact
+ end
+
+ def self.normalize_item_result(result)
+ if result.key?(PAIRED_ITEM_KEY)
+ result[PAIRED_ITEM_KEY] = normalize_paired_item(result[PAIRED_ITEM_KEY])
+ end
+
+ result
+ end
+
+ def self.stringify_result(value)
+ case value
+ when Hash
+ value.deep_stringify_keys
+ when Array
+ value.map { |item| stringify_result(item) }
+ else
+ value
+ end
+ end
+ end
+end
diff --git a/plugins/discourse-workflows/lib/discourse_workflows/item_contract.rb b/plugins/discourse-workflows/lib/discourse_workflows/item_contract.rb
new file mode 100644
index 00000000000..6366e88ec93
--- /dev/null
+++ b/plugins/discourse-workflows/lib/discourse_workflows/item_contract.rb
@@ -0,0 +1,64 @@
+# frozen_string_literal: true
+
+module DiscourseWorkflows
+ module ItemContract
+ VALID_ITEM_KEYS = %w[json pairedItem error index].freeze
+
+ class Error < StandardError
+ end
+
+ def self.validate_items!(items, source:)
+ unless items.is_a?(Array) &&
+ items.all? { |item| item.is_a?(Hash) && item["json"].is_a?(Hash) }
+ raise Error,
+ "Invalid items from #{source}: expected Array<{ 'json' => Hash }>, got #{items.inspect.truncate(200)}"
+ end
+
+ items.each do |item|
+ validate_item_keys!(item, source:)
+ validate_paired_item!(item, source:)
+ end
+ end
+
+ def self.validate_output_arrays!(result, source:, ports: nil)
+ unless result.is_a?(Array) && result.all? { |inner| inner.is_a?(Array) }
+ raise Error, "#{source}: execute must return Array<Array<Item>>, got #{result.class}"
+ end
+
+ if ports && result.length > ports.length
+ raise Error,
+ "#{source}: execute returned #{result.length} outputs, but node declares #{ports.length}"
+ end
+
+ result.each { |inner| validate_items!(inner, source: source) }
+ end
+
+ def self.validate_paired_item!(item, source:)
+ paired_item = Item.paired_item(item)
+ return if paired_item.nil?
+
+ entries = paired_item.is_a?(Array) ? paired_item : [paired_item]
+ unless entries.all? { |entry| valid_paired_item_entry?(entry) }
+ raise Error,
+ "Invalid pairedItem from #{source}: expected Integer or { 'item' => Integer, 'input' => Integer? }, got #{paired_item.inspect.truncate(200)}"
+ end
+ end
+
+ def self.validate_item_keys!(item, source:)
+ unknown_keys = item.keys - VALID_ITEM_KEYS
+ return if unknown_keys.empty?
+
+ raise Error,
+ "Invalid item keys from #{source}: expected #{VALID_ITEM_KEYS.inspect}, got #{unknown_keys.inspect.truncate(200)}"
+ end
+
+ def self.valid_paired_item_entry?(entry)
+ return true if entry.is_a?(Integer)
+ return false unless entry.is_a?(Hash)
+
+ item_index = entry["item"]
+ input_index = entry["input"]
+ item_index.is_a?(Integer) && (input_index.nil? || input_index.is_a?(Integer))
+ end
+ end
+end
diff --git a/plugins/discourse-workflows/lib/discourse_workflows/js_sandbox.rb b/plugins/discourse-workflows/lib/discourse_workflows/js_sandbox.rb
new file mode 100644
index 00000000000..befc5946b50
--- /dev/null
+++ b/plugins/discourse-workflows/lib/discourse_workflows/js_sandbox.rb
@@ -0,0 +1,296 @@
+# frozen_string_literal: true
+
+module DiscourseWorkflows
+ class JsSandbox
+ EVAL_TIMEOUT_MS = 100
+ MAX_INJECTED_JSON_BYTES = 1.megabyte
+ MAX_MEMORY_BYTES = 10.megabytes
+ MARSHAL_STACK_DEPTH = 20
+
+ attr_reader :js_context, :log
+
+ class BudgetExceededError < StandardError
+ end
+
+ class SandboxError < StandardError
+ end
+
+ class PayloadTooLargeError < StandardError
+ end
+
+ def initialize(workflow_context, user: nil, vars: nil, capture_logs: false, budget_tracker: nil)
+ @workflow_context = workflow_context
+ @user = user
+ @vars = vars || DiscourseWorkflows::Variable.pluck(:key, :value).to_h
+ @budget_tracker = budget_tracker
+ @site_setting_store = SiteSettingStore.new
+ @js_context = create_js_context
+ setup_core_environment!
+ setup_console_capture! if capture_logs
+ end
+
+ def eval(code)
+ started_at = Process.clock_gettime(Process::CLOCK_MONOTONIC)
+ @js_context.eval(code)
+ rescue MiniRacer::ScriptTerminatedError
+ raise BudgetExceededError, "JavaScript evaluation exceeded #{EVAL_TIMEOUT_MS}ms time limit"
+ rescue MiniRacer::Error => e
+ raise SandboxError, "Sandbox execution failed: #{e.message}"
+ rescue SandboxError, PayloadTooLargeError
+ raise
+ rescue StandardError => e
+ raise SandboxError, "Sandbox execution failed: #{e.message}"
+ ensure
+ finish_eval!(started_at)
+ end
+
+ def rebind_code_item(item, item_index: 0)
+ item_js = serialize_json_payload(item, label: "$input.item")
+ self.eval("$input.item = #{item_js}; __itemIndex = #{item_index};")
+ end
+
+ def rebind_expression_item(item, item_index: 0)
+ item_js = serialize_json_payload(item, label: "$input.item")
+ self.eval(
+ "$input.item = #{item_js}; " \
+ "__data[\"__inputItem\"] = $input.item; " \
+ "__data[\"$json\"] = $input.item.json; " \
+ "__data[\"$itemIndex\"] = #{item_index};",
+ )
+ end
+
+ def declare_json(name, value)
+ value_js = serialize_json_payload(value, label: name)
+ self.eval("var #{name} = #{value_js};")
+ end
+
+ def attach(name, callable)
+ @js_context.attach(name, callable)
+ end
+
+ def self.serialize_json_payload(value, label:)
+ payload = value.to_json
+
+ return payload if payload.bytesize <= MAX_INJECTED_JSON_BYTES
+
+ raise PayloadTooLargeError,
+ "Sandbox payload '#{label}' exceeds #{MAX_INJECTED_JSON_BYTES} bytes"
+ end
+
+ def dispose
+ @js_context&.dispose
+ @js_context = nil
+ end
+
+ class SiteSettingStore
+ def initialize
+ @values_by_name = {}
+ end
+
+ def fetch(name)
+ return @values_by_name[name] if @values_by_name.key?(name)
+
+ sym = name.to_s.to_sym
+ @values_by_name[name] = if SiteSetting.secret_settings.include?(sym) ||
+ SiteSetting.hidden_settings.include?(sym)
+ "[FILTERED]"
+ else
+ SiteSetting.get(name)
+ end
+ end
+ end
+
+ private
+
+ def create_js_context
+ MiniRacer::Context.new(
+ timeout: EVAL_TIMEOUT_MS,
+ max_memory: MAX_MEMORY_BYTES,
+ marshal_stack_depth: MARSHAL_STACK_DEPTH,
+ )
+ end
+
+ def setup_core_environment!
+ @js_context.attach("__getSiteSetting", method(:fetch_site_setting))
+ @js_context.attach("__getNodeItem", method(:fetch_node_item))
+ @js_context.attach("__getNodeItems", method(:fetch_node_items))
+ @js_context.attach("__getNodeContext", method(:fetch_node_context))
+ @js_context.attach("__getNodeParams", method(:fetch_node_params))
+ @js_context.attach("__isNodeExecuted", method(:node_executed?))
+
+ execution = @workflow_context.fetch("__execution") { {} }
+ declare_json("__vars", @vars)
+ declare_json("__executionData", execution)
+ declare_json("__currentUser", build_current_user)
+
+ eval(<<~JS)
+ Object.defineProperty(this, '$vars', {
+ value: Object.freeze(__vars)
+ });
+ Object.defineProperty(this, '$execution', {
+ value: Object.freeze(__executionData)
+ });
+ Object.defineProperty(this, '$current_user', {
+ value: Object.freeze(__currentUser)
+ });
+ Object.defineProperty(this, '$site_settings', {
+ value: new Proxy({}, {
+ get: function(target, prop) {
+ if (prop in target) return target[prop];
+ target[prop] = __getSiteSetting(prop);
+ return target[prop];
+ },
+ set: function() { return false; }
+ })
+ });
+ function __WorkflowNodeOutput(name) {
+ this.name = name;
+ }
+
+ function __workflowItemIndex() {
+ return typeof __itemIndex === "undefined" ? 0 : __itemIndex;
+ }
+
+ Object.defineProperty(__WorkflowNodeOutput.prototype, 'item', {
+ get: function() {
+ return JSON.parse(__getNodeItem(this.name, __workflowItemIndex()));
+ },
+ configurable: true
+ });
+
+ Object.defineProperty(__WorkflowNodeOutput.prototype, 'context', {
+ get: function() {
+ return JSON.parse(__getNodeContext(this.name));
+ },
+ configurable: true
+ });
+
+ Object.defineProperty(__WorkflowNodeOutput.prototype, 'params', {
+ get: function() {
+ return JSON.parse(__getNodeParams(this.name));
+ },
+ configurable: true
+ });
+
+ Object.defineProperty(__WorkflowNodeOutput.prototype, 'isExecuted', {
+ get: function() {
+ return __isNodeExecuted(this.name);
+ },
+ configurable: true
+ });
+
+ __WorkflowNodeOutput.prototype.itemMatching = function(itemIndex) {
+ if (itemIndex === undefined) {
+ throw new Error("Missing item index for .itemMatching()");
+ }
+ return JSON.parse(__getNodeItem(this.name, itemIndex));
+ };
+
+ __WorkflowNodeOutput.prototype.pairedItem = function(itemIndex) {
+ return JSON.parse(
+ __getNodeItem(
+ this.name,
+ itemIndex === undefined ? __workflowItemIndex() : itemIndex
+ )
+ );
+ };
+
+ __WorkflowNodeOutput.prototype.all = function(branchIndex, runIndex) {
+ return JSON.parse(__getNodeItems(this.name, branchIndex, runIndex));
+ };
+
+ __WorkflowNodeOutput.prototype.first = function(branchIndex, runIndex) {
+ var items = this.all(branchIndex, runIndex);
+ return items[0] || { json: {} };
+ };
+
+ __WorkflowNodeOutput.prototype.last = function(branchIndex, runIndex) {
+ var items = this.all(branchIndex, runIndex);
+ return items[items.length - 1] || { json: {} };
+ };
+
+ Object.defineProperty(this, '$', {
+ value: function(name) {
+ return new __WorkflowNodeOutput(name);
+ },
+ configurable: true,
+ writable: false
+ });
+ JS
+ end
+
+ def fetch_site_setting(name)
+ @site_setting_store.fetch(name)&.to_s
+ rescue StandardError
+ nil
+ end
+
+ def fetch_node_item(name, item_index = nil)
+ serialize_json_payload(
+ node_output_proxy.item(name, item_index: item_index),
+ label: "$().item",
+ )
+ end
+
+ def fetch_node_items(name, branch_index = nil, run_index = nil)
+ serialize_json_payload(
+ node_output_proxy.all(name, branch_index:, run_index:),
+ label: "$().all()",
+ )
+ end
+
+ def fetch_node_context(name)
+ serialize_json_payload(node_output_proxy.context(name), label: "$().context")
+ end
+
+ def fetch_node_params(name)
+ serialize_json_payload(node_output_proxy.params(name), label: "$().params")
+ end
+
+ def node_executed?(name)
+ node_output_proxy.executed?(name)
+ end
+
+ def node_output_proxy
+ @node_output_proxy ||= NodeOutputProxy.new(@workflow_context)
+ end
+
+ def build_current_user
+ return {} unless @user
+ ExpressionContextSchema
+ .environment_symbols
+ .dig("$current_user", :fields)
+ .to_h { |field_name, _| [field_name, @user.public_send(field_name)] }
+ end
+
+ def setup_console_capture!
+ @log = Executor::StepLog.new
+ capture = proc { |level, *args| @log.public_send(level, args.map(&:to_s).join(" ")) }
+ @js_context.attach("__captureLog", proc { |*args| capture.call(:info, *args) })
+ @js_context.attach("__captureWarn", proc { |*args| capture.call(:warn, *args) })
+ @js_context.attach("__captureError", proc { |*args| capture.call(:error, *args) })
+
+ eval(<<~JS)
+ Object.defineProperty(this, 'console', {
+ value: Object.freeze({
+ log: function() { __captureLog(...arguments); },
+ info: function() { __captureLog(...arguments); },
+ warn: function() { __captureWarn(...arguments); },
+ error: function() { __captureError(...arguments); }
+ })
+ });
+ JS
+ end
+
+ def finish_eval!(started_at)
+ return unless started_at
+
+ elapsed_ms = (Process.clock_gettime(Process::CLOCK_MONOTONIC) - started_at) * 1000.0
+ @budget_tracker&.charge!(elapsed_ms)
+ end
+
+ def serialize_json_payload(value, label:)
+ self.class.serialize_json_payload(value, label:)
+ end
+ end
+end
diff --git a/plugins/discourse-workflows/lib/discourse_workflows/load_options_context.rb b/plugins/discourse-workflows/lib/discourse_workflows/load_options_context.rb
new file mode 100644
index 00000000000..648960e0330
--- /dev/null
+++ b/plugins/discourse-workflows/lib/discourse_workflows/load_options_context.rb
@@ -0,0 +1,166 @@
+# frozen_string_literal: true
+
+module DiscourseWorkflows
+ class LoadOptionsContext
+ attr_reader :method_name,
+ :property_name,
+ :node_identifier,
+ :node_version,
+ :node_id,
+ :node_name,
+ :workflow_id,
+ :credentials,
+ :filter,
+ :input_context,
+ :execution_context,
+ :user,
+ :guardian,
+ :node_class
+
+ def initialize(
+ method_name:,
+ property_name: nil,
+ node_identifier: nil,
+ node_version: nil,
+ node_id: nil,
+ node_name: nil,
+ workflow_id: nil,
+ parameters: {},
+ credentials: {},
+ filter: nil,
+ input_context: {},
+ execution_context: {},
+ user: nil,
+ guardian: nil,
+ node_class: nil
+ )
+ @method_name = method_name.to_s
+ @property_name = property_name.presence&.to_s
+ @node_identifier = node_identifier.presence&.to_s || node_class&.identifier
+ @node_version = node_version.presence&.to_s || node_class&.version
+ @node_id = node_id.presence&.to_s
+ @node_name = node_name.presence&.to_s
+ @workflow_id = workflow_id.presence&.to_s
+ @parameters = normalize_hash(parameters)
+ @node_class = node_class
+ @credentials = filter_credentials(credentials)
+ @filter = filter.presence&.to_s
+ @input_context = normalize_hash(input_context)
+ @execution_context = normalize_hash(execution_context)
+ @user = user
+ @guardian = guardian
+ end
+
+ def get_current_node_parameter(path = nil, fallback = nil)
+ return @parameters if path.blank?
+
+ value = dig_path(@parameters, path)
+ value.nil? ? fallback : value
+ end
+
+ def get_current_node_parameters
+ @parameters
+ end
+
+ def matches_filter?(value)
+ filter.blank? || value.downcase.include?(filter.downcase)
+ end
+
+ def get_credentials(slot)
+ definition = credential_definition(slot)
+ credential = credential_for_slot(slot)
+ raise Discourse::InvalidAccess if definition.blank? || credential.blank?
+
+ credential_record = DiscourseWorkflows::Credential.find_by(id: credential["id"])
+ raise Discourse::InvalidAccess if credential_record.blank?
+ unless credential_type_allowed?(definition, credential_record.credential_type)
+ raise Discourse::InvalidAccess
+ end
+
+ DiscourseWorkflows::ExpressionResolver.resolve_hash(
+ credential_record.data || {},
+ context: credential_resolver_context,
+ user: user,
+ )
+ end
+
+ def helpers
+ @helpers ||= ContextHelpers.new(node_identifier: node_identifier, guardian: guardian)
+ end
+
+ def to_h
+ {
+ method_name: method_name,
+ property_name: property_name,
+ node_identifier: node_identifier,
+ node_version: node_version,
+ node_id: node_id,
+ node_name: node_name,
+ workflow_id: workflow_id,
+ parameters: @parameters,
+ credentials: credentials,
+ filter: filter,
+ input_context: input_context,
+ execution_context: execution_context,
+ }.compact
+ end
+
+ private
+
+ def normalize_hash(value)
+ value = value.to_unsafe_h if value.respond_to?(:to_unsafe_h)
+ value = value.to_h if value.respond_to?(:to_h)
+ value.is_a?(Hash) ? value.deep_stringify_keys : {}
+ end
+
+ def filter_credentials(credentials)
+ NodeData.filter_declared_credentials(
+ NodeData.normalize_credentials(normalize_hash(credentials)),
+ node_class,
+ @parameters,
+ )
+ end
+
+ def credential_definitions
+ @credential_definitions ||= NodeData.normalize_credential_definitions(node_class&.credentials)
+ end
+
+ def credential_definition(slot)
+ credential_definitions.find { |definition| definition["name"] == slot.to_s } ||
+ credential_definitions.find do |definition|
+ NodeData.credential_types_for(definition).include?(slot.to_s)
+ end
+ end
+
+ def credential_for_slot(slot)
+ credentials[slot.to_s].presence || credentials[credential_definition(slot)&.fetch("name")]
+ end
+
+ def credential_type_allowed?(definition, credential_type)
+ NodeData.credential_types_for(definition).include?(credential_type.to_s)
+ end
+
+ def credential_resolver_context
+ execution_context.merge(input_context).merge(
+ "$json" => input_context.dig("item", "json") || {},
+ "__input_item" => input_context["item"] || {},
+ )
+ end
+
+ def dig_path(hash, path)
+ path
+ .to_s
+ .split(".")
+ .reject(&:blank?)
+ .reduce(hash) do |value, key|
+ break nil unless value.respond_to?(:[])
+
+ if value.respond_to?(:key?) && value.key?(key)
+ value[key]
+ elsif value.respond_to?(:key?) && value.key?(key.to_sym)
+ value[key.to_sym]
+ end
+ end
+ end
+ end
+end
diff --git a/plugins/discourse-workflows/lib/discourse_workflows/node_data.rb b/plugins/discourse-workflows/lib/discourse_workflows/node_data.rb
new file mode 100644
index 00000000000..a8b154f667d
--- /dev/null
+++ b/plugins/discourse-workflows/lib/discourse_workflows/node_data.rb
@@ -0,0 +1,160 @@
+# frozen_string_literal: true
+
+module DiscourseWorkflows
+ module NodeData
+ NODE_DIRECT_SETTING_KEYS = NodeDataShape::NODE_DIRECT_SETTING_KEYS
+
+ module_function
+
+ def parameters(node)
+ read(node, "parameters") || {}
+ end
+
+ def credentials(node)
+ read(node, "credentials") || {}
+ end
+
+ def resolved_parameters(node)
+ parameters(node).deep_dup
+ end
+
+ def type_version(node)
+ WorkflowDocument.node_type_version(node) || Registry::DEFAULT_VERSION
+ end
+
+ def webhook_id(node)
+ WorkflowDocument.node_webhook_id(node)
+ end
+
+ def split(parameters:, credentials: {}, webhook_id: nil, node_type: nil)
+ parameters = (parameters || {}).deep_stringify_keys
+ credentials = normalize_credentials(credentials)
+
+ credentials = filter_declared_credentials(credentials, node_type, parameters)
+
+ {
+ "parameters" => parameters,
+ "credentials" => credentials,
+ WorkflowDocument.node_webhook_id_key => webhook_id,
+ }
+ end
+
+ def direct_settings(node)
+ NODE_DIRECT_SETTING_KEYS.each_with_object({}) do |(json_key, _attribute), settings|
+ value = read(node, json_key)
+ settings[json_key] = value unless value.nil?
+ end
+ end
+
+ def normalize_credentials(credentials_hash)
+ (credentials_hash || {}).each_with_object({}) do |(slot, credential), result|
+ next unless credential.is_a?(Hash)
+
+ credential = credential.deep_stringify_keys
+ next if credential["id"].blank?
+
+ result[slot.to_s] = credential.slice("id", "credential_type").merge(
+ "id" => credential["id"].to_s,
+ )
+ end
+ end
+
+ def read(node, key)
+ return node.public_send(key) if node.respond_to?(key)
+
+ attribute = NODE_DIRECT_SETTING_KEYS[key.to_s]
+ return node.public_send(attribute) if attribute && node.respond_to?(attribute)
+
+ if node.respond_to?(:key?)
+ return node[key] if node.key?(key)
+ key_symbol = key.to_sym
+ return node[key_symbol] if node.key?(key_symbol)
+ end
+
+ node[key] || node[key.to_sym]
+ end
+
+ def filter_declared_credentials(credentials, node_type, parameters)
+ return credentials if node_type.blank?
+
+ definitions = credential_definitions_for(node_type)
+ return {} if definitions.blank?
+
+ definitions.each_with_object({}) do |definition, result|
+ slot = definition["name"]
+ credential = credentials[slot]
+ next if credential.blank? || !credential_slot_visible?(definition, parameters)
+
+ credential_type = credential["credential_type"].presence
+ credential_types = credential_types_for(definition)
+ credential_type ||= credential_types.first if credential_types.one?
+ next if credential_type.blank? || credential_types.exclude?(credential_type)
+
+ result[slot] = credential.merge("credential_type" => credential_type)
+ end
+ end
+
+ def credential_definitions_for(node_type)
+ normalize_credential_definitions(node_class(node_type)&.credentials)
+ end
+
+ def normalize_credential_definitions(definitions)
+ Array(definitions).filter_map do |definition|
+ definition = definition.deep_stringify_keys
+ name = definition["name"].presence
+ next if name.blank?
+
+ definition.merge("name" => name)
+ end
+ end
+
+ def credential_types_for(definition)
+ Array(definition["credential_types"] || definition["credential_type"]).map(&:to_s)
+ end
+
+ def credential_slot_visible?(definition, parameters)
+ display_options = definition["display_options"] || {}
+
+ visible_for_conditions?(display_options["show"], parameters) &&
+ !hidden_by_conditions?(display_options["hide"], parameters)
+ end
+
+ def visible_for_conditions?(conditions, parameters)
+ return true if conditions.blank?
+
+ conditions.all? { |key, expected| matches_display_rule?(expected, parameters[key]) }
+ end
+
+ def hidden_by_conditions?(conditions, parameters)
+ conditions.present? && visible_for_conditions?(conditions, parameters)
+ end
+
+ def matches_display_rule?(expected, value)
+ return false unless expected.is_a?(Array)
+
+ expected.any? { |condition| matches_display_condition?(condition, value) }
+ end
+
+ def matches_display_condition?(condition, value)
+ operator = condition.is_a?(Hash) ? condition["_cnd"] : nil
+ return condition == value if operator.blank?
+
+ return value != operator["not"] if operator.key?("not")
+ if operator.key?("exists")
+ return operator["exists"] ? !empty_display_value?(value) : empty_display_value?(value)
+ end
+
+ false
+ end
+
+ def empty_display_value?(value)
+ return true if value.nil? || value == ""
+ return value.empty? if value.is_a?(Array)
+ false
+ end
+
+ def node_class(node_type)
+ node_type.respond_to?(:identifier) ? node_type : Registry.find_node_type(node_type)
+ end
+ end
+end
diff --git a/plugins/discourse-workflows/lib/discourse_workflows/node_data_shape.rb b/plugins/discourse-workflows/lib/discourse_workflows/node_data_shape.rb
new file mode 100644
index 00000000000..c5b3cd0b8bd
--- /dev/null
+++ b/plugins/discourse-workflows/lib/discourse_workflows/node_data_shape.rb
@@ -0,0 +1,23 @@
+# frozen_string_literal: true
+
+module DiscourseWorkflows
+ module NodeDataShape
+ NODE_DIRECT_SETTING_KEYS = {
+ "notes" => :notes,
+ "notesInFlow" => :notes_in_flow,
+ "alwaysOutputData" => :always_output_data,
+ "onError" => :on_error,
+ "continueOnFail" => :continue_on_fail,
+ }.freeze
+
+ FORM_TRIGGER_TYPE = "trigger:form"
+ FORM_TRIGGER_WEBHOOK_ID_KEY = "webhookId"
+
+ module_function
+
+ def form_trigger?(node_type)
+ node_type == FORM_TRIGGER_TYPE ||
+ (node_type.respond_to?(:identifier) && node_type.identifier == FORM_TRIGGER_TYPE)
+ end
+ end
+end
diff --git a/plugins/discourse-workflows/lib/discourse_workflows/node_error.rb b/plugins/discourse-workflows/lib/discourse_workflows/node_error.rb
new file mode 100644
index 00000000000..a3e442d9ff7
--- /dev/null
+++ b/plugins/discourse-workflows/lib/discourse_workflows/node_error.rb
@@ -0,0 +1,6 @@
+# frozen_string_literal: true
+
+module DiscourseWorkflows
+ class NodeError < StandardError
+ end
+end
diff --git a/plugins/discourse-workflows/lib/discourse_workflows/node_error_handling.rb b/plugins/discourse-workflows/lib/discourse_workflows/node_error_handling.rb
new file mode 100644
index 00000000000..7edafffbc61
--- /dev/null
+++ b/plugins/discourse-workflows/lib/discourse_workflows/node_error_handling.rb
@@ -0,0 +1,19 @@
+# frozen_string_literal: true
+
+module DiscourseWorkflows
+ module NodeErrorHandling
+ private
+
+ def raise_node_error!(message, description: nil, item_index: nil, line_number: nil)
+ suffix = +""
+ suffix << " [line #{line_number}" if line_number
+ suffix << (line_number ? ", for item #{item_index}" : " [item #{item_index}") if item_index
+ suffix.presence&.<<("]")
+
+ full_message = +"#{message}#{suffix}"
+ full_message << ": #{description}" if description.present?
+
+ raise DiscourseWorkflows::NodeError, full_message
+ end
+ end
+end
diff --git a/plugins/discourse-workflows/lib/discourse_workflows/node_issues.rb b/plugins/discourse-workflows/lib/discourse_workflows/node_issues.rb
new file mode 100644
index 00000000000..7775e0d0662
--- /dev/null
+++ b/plugins/discourse-workflows/lib/discourse_workflows/node_issues.rb
@@ -0,0 +1,151 @@
+# frozen_string_literal: true
+
+module DiscourseWorkflows
+ class NodeIssues
+ class << self
+ def for_node(node, node_type_class)
+ return [] unless node_type_class.respond_to?(:property_schema)
+ schema = node_type_class.property_schema || {}
+ config = NodeData.resolved_parameters(node)
+ walk(schema, config.deep_stringify_keys, "")
+ end
+
+ private
+
+ def walk(schema, config, path_prefix)
+ effective = apply_defaults(schema, config)
+ issues = []
+
+ schema.each do |name, field|
+ next unless field_visible?(field, effective)
+
+ name_s = name.to_s
+ path = path_prefix.empty? ? name_s : "#{path_prefix}.#{name_s}"
+ value = effective[name_s]
+
+ if field[:required] && blank_value?(value)
+ issues << { path: path, name: name_s, message: "required" }
+ end
+
+ case field[:type]
+ when :collection
+ if value.is_a?(Hash)
+ field[:options].to_a.each do |option|
+ option_name = option[:name].to_s
+ next unless value.key?(option_name)
+
+ option_schema = { option_name => option.except(:name, :display_name) }
+ issues.concat(walk(option_schema, value, path))
+ end
+ elsif value.is_a?(Array)
+ item_schema = (field[:item_schema] || {}).merge(field[:extra_item_schema] || {})
+ value.each_with_index do |item, index|
+ item_hash = item.is_a?(Hash) ? item.deep_stringify_keys : {}
+ issues.concat(walk(item_schema, item_hash, "#{path}.#{index}"))
+ end
+ end
+ when :fixed_collection
+ field[:options].to_a.each do |group|
+ group_name = group[:name].to_s
+ rows = CollectionParameters.rows_from_value(value, group: group_name)
+ if field[:required] && !blank_value?(value) && blank_value?(rows)
+ issues << { path: "#{path}.#{group_name}", name: name_s, message: "required" }
+ end
+
+ rows.each_with_index do |item, index|
+ item_hash = item.is_a?(Hash) ? item.deep_stringify_keys : {}
+ issues.concat(
+ walk(group[:values] || {}, item_hash, "#{path}.#{group_name}.#{index}"),
+ )
+ end
+ end
+ when :assignment_collection
+ assignments = CollectionParameters.rows_from_value(value, group: "assignments")
+ if field[:required] && !blank_value?(value) && blank_value?(assignments)
+ issues << { path: "#{path}.assignments", name: name_s, message: "required" }
+ end
+
+ assignment_schema = {
+ name: {
+ type: :string,
+ required: true,
+ },
+ type: {
+ type: :options,
+ required: true,
+ },
+ value: {
+ type: :string,
+ required: true,
+ },
+ }
+
+ assignments.each_with_index do |item, index|
+ item_hash = item.is_a?(Hash) ? item.deep_stringify_keys : {}
+ issues.concat(walk(assignment_schema, item_hash, "#{path}.assignments.#{index}"))
+ end
+ end
+ end
+ issues
+ end
+
+ def apply_defaults(schema, config)
+ result = config.dup
+ schema.each do |name, field|
+ name_s = name.to_s
+ result[name_s] = field[:default] if result[name_s].nil? && !field[:default].nil?
+ end
+ result
+ end
+
+ def field_visible?(field, config)
+ ui = field[:ui] || {}
+ return false if ui[:hidden]
+ display_options = field[:display_options] || {}
+ return false if display_options[:show] && !matches_rules?(display_options[:show], config)
+ return false if display_options[:hide] && matches_rules?(display_options[:hide], config)
+ true
+ end
+
+ def matches_rules?(rules, config)
+ rules.all? { |field_name, expected| matches_rule?(expected, config[field_name.to_s]) }
+ end
+
+ def matches_rule?(expected, value)
+ return false unless expected.is_a?(Array)
+
+ expected.any? { |condition| matches_condition?(condition, value) }
+ end
+
+ def matches_condition?(condition, value)
+ operator = condition.is_a?(Hash) ? condition[:_cnd] || condition["_cnd"] : nil
+ return condition == value if operator.blank?
+
+ if operator.key?(:not) || operator.key?("not")
+ expected = operator.key?(:not) ? operator[:not] : operator["not"]
+ return value != expected
+ end
+
+ if operator.key?(:exists) || operator.key?("exists")
+ exists = operator.key?(:exists) ? operator[:exists] : operator["exists"]
+ return exists ? !empty_value?(value) : empty_value?(value)
+ end
+
+ false
+ end
+
+ def empty_value?(value)
+ return true if value.nil? || value == ""
+ return value.empty? if value.is_a?(Array)
+ false
+ end
+
+ def blank_value?(value)
+ return true if value.nil?
+ return value.strip.empty? if value.is_a?(String)
+ return value.empty? if value.is_a?(Array)
+ false
+ end
+ end
+ end
+end
diff --git a/plugins/discourse-workflows/lib/discourse_workflows/node_output_proxy.rb b/plugins/discourse-workflows/lib/discourse_workflows/node_output_proxy.rb
new file mode 100644
index 00000000000..2efda510a77
--- /dev/null
+++ b/plugins/discourse-workflows/lib/discourse_workflows/node_output_proxy.rb
@@ -0,0 +1,190 @@
+# frozen_string_literal: true
+
+module DiscourseWorkflows
+ class NodeOutputProxy
+ BLOCKED_NODE_NAMES = %w[constructor prototype eval].freeze
+ MISSING_ITEM_LINK_MESSAGE = "Info for expression missing from previous node"
+ MULTIPLE_MATCHING_ITEMS_MESSAGE = "Multiple matching items for expression"
+
+ def initialize(context)
+ @context = context || {}
+ end
+
+ def item(name, item_index: nil)
+ name_str = name.to_s
+ return { "json" => {} } if blocked_node_name?(name_str)
+
+ linked_item_for_expression(name_str, item_index: item_index_for(item_index))
+ end
+
+ def all(name, branch_index: nil, run_index: nil)
+ name_str = name.to_s
+ return [] if blocked_node_name?(name_str)
+
+ branch_index = default_branch_index_for(name_str) if branch_index.nil?
+ node_items_for_expression(name_str, branch_index:, run_index:)
+ end
+
+ def first(name, branch_index: nil, run_index: nil)
+ all(name, branch_index:, run_index:).first || { "json" => {} }
+ end
+
+ def last(name, branch_index: nil, run_index: nil)
+ items = all(name, branch_index:, run_index:)
+ items[items.length - 1] || { "json" => {} }
+ end
+
+ def context(name)
+ @context.dig("__node_contexts", name.to_s) || {}
+ end
+
+ def params(name)
+ @context.dig("__node_parameters_by_name", name.to_s) || {}
+ end
+
+ def executed?(name)
+ name_str = name.to_s
+ return false if blocked_node_name?(name_str)
+
+ return true if Array(@context.dig("__node_runs", name_str)).present?
+
+ @context.key?(name_str)
+ end
+
+ private
+
+ def blocked_node_name?(name)
+ name.start_with?("_") || BLOCKED_NODE_NAMES.include?(name)
+ end
+
+ def item_index_for(item_index)
+ return item_index.to_i unless item_index.nil?
+
+ @context.fetch("$itemIndex") { 0 }.to_i
+ end
+
+ def linked_item_for_expression(name, item_index:)
+ target_runs = @context.dig("__node_runs", name)
+ target_items = node_items_for_expression(name)
+ return { "json" => {} } if target_items.blank?
+
+ raise MISSING_ITEM_LINK_MESSAGE unless target_runs && @context["__current_node_id"]
+
+ input_source = current_input_source
+ raise MISSING_ITEM_LINK_MESSAGE if input_source.blank?
+
+ matches =
+ trace_linked_items(
+ input_source["node_name"],
+ input_source["output_index"].to_i,
+ item_index,
+ name,
+ Set.new,
+ )
+
+ raise MISSING_ITEM_LINK_MESSAGE if matches.blank?
+
+ distinct_matches =
+ matches.uniq { |match| [match[:node_name], match[:output_index], match[:item_index]] }
+ raise MULTIPLE_MATCHING_ITEMS_MESSAGE if distinct_matches.length > 1
+
+ distinct_matches.first[:item]
+ end
+
+ def node_items_for_expression(name, branch_index: nil, run_index: nil)
+ if @context.dig("__node_runs", name)
+ run = node_run(name, run_index)
+ if run
+ output_index = branch_index.nil? ? default_branch_index_for(name) : branch_index.to_i
+ output_items = run.dig("outputs", output_index)
+ return output_items if output_items.is_a?(Array)
+ return []
+ end
+ end
+
+ items = @context[name]
+ return items if items.is_a?(Array)
+ return [{ "json" => items }] if items.is_a?(Hash)
+
+ []
+ end
+
+ def default_branch_index_for(name)
+ input_source = current_input_source
+ return input_source["output_index"].to_i if input_source && input_source["node_name"] == name
+
+ 0
+ end
+
+ def trace_linked_items(node_name, output_index, item_index, target_node_name, visited)
+ key = [node_name, output_index.to_i, item_index.to_i]
+ return [] if visited.include?(key)
+
+ visited.add(key)
+ output_item = output_item_for(node_name, output_index, item_index)
+ return [] unless output_item
+
+ if node_name == target_node_name
+ return [
+ {
+ node_name: node_name,
+ output_index: output_index.to_i,
+ item_index: item_index.to_i,
+ item: output_item,
+ },
+ ]
+ end
+
+ paired_items = normalized_paired_items(output_item)
+ raise MISSING_ITEM_LINK_MESSAGE if paired_items.blank?
+
+ paired_items.flat_map do |paired_item|
+ source = input_source_for(node_name, paired_item.fetch("input") { 0 })
+ next [] if source.blank?
+
+ trace_linked_items(
+ source["node_name"],
+ source["output_index"].to_i,
+ paired_item.fetch("item").to_i,
+ target_node_name,
+ visited.dup,
+ )
+ end
+ end
+
+ def output_item_for(node_name, output_index, item_index)
+ node_run(node_name)&.dig("outputs", output_index.to_i, item_index.to_i)
+ end
+
+ def input_source_for(node_name, input_index)
+ node_run(node_name)&.dig("input_sources", input_index.to_i)
+ end
+
+ def node_run(node_name, run_index = nil)
+ runs = Array(@context.dig("__node_runs", node_name))
+ return if runs.blank?
+
+ return runs.last if run_index.nil?
+
+ runs[run_index.to_i] || runs.last
+ end
+
+ def normalized_paired_items(item)
+ paired_item = Item.paired_item(item)
+ return [] if paired_item.blank?
+
+ paired_items = paired_item.is_a?(Array) ? paired_item : [paired_item]
+ paired_items.filter_map do |entry|
+ next { "item" => entry, "input" => 0 } if entry.is_a?(Integer)
+ next unless entry.is_a?(Hash) && entry["item"].is_a?(Integer)
+
+ { "item" => entry["item"], "input" => entry["input"] || 0 }
+ end
+ end
+
+ def current_input_source
+ input_index = @context.fetch("__current_input_index") { 0 }.to_i
+ Array(@context["__input_sources"] || @context[:__input_sources])[input_index]
+ end
+ end
+end
diff --git a/plugins/discourse-workflows/lib/discourse_workflows/node_type.rb b/plugins/discourse-workflows/lib/discourse_workflows/node_type.rb
new file mode 100644
index 00000000000..5075b4b8b5d
--- /dev/null
+++ b/plugins/discourse-workflows/lib/discourse_workflows/node_type.rb
@@ -0,0 +1,195 @@
+# frozen_string_literal: true
+
+module DiscourseWorkflows
+ class NodeType
+ include NodeErrorHandling
+ extend NodeTypeDescriptor
+
+ DESCRIPTION_DEFAULTS = {
+ version: "1.0",
+ defaults: {
+ },
+ inputs: [:main],
+ required_inputs: nil,
+ outputs: [:main],
+ properties: {
+ },
+ credentials: [],
+ webhooks: [],
+ events: [],
+ max_nodes: nil,
+ capabilities: {
+ },
+ palette_visible: true,
+ available: true,
+ }.freeze
+
+ def self.inherited(subclass)
+ super
+ DiscourseWorkflows::NodeType.registered_nodes << subclass
+ end
+
+ def self.registered_nodes
+ @registered_nodes ||= []
+ end
+
+ def self.waiting_identifiers
+ registered_nodes.select(&:waits_for_resume?).map(&:identifier)
+ end
+
+ def self.description(value = nil)
+ if value
+ @description = DESCRIPTION_DEFAULTS.deep_merge(value.deep_symbolize_keys).freeze
+ else
+ @description || DESCRIPTION_DEFAULTS
+ end
+ end
+
+ def self.identifier
+ description.fetch(:name) { raise NotImplementedError }
+ end
+
+ def self.version
+ description.fetch(:version)
+ end
+
+ def self.icon
+ description.dig(:defaults, :icon)
+ end
+
+ def self.color
+ description.dig(:defaults, :color)
+ end
+
+ def self.palette_visible?
+ description_value(:palette_visible)
+ end
+
+ def self.available?
+ description_value(:available)
+ end
+
+ def self.unavailable_reason_key(configuration = nil)
+ return nil unless description.key?(:unavailable_reason_key)
+
+ description_value(:unavailable_reason_key, configuration: configuration)
+ end
+
+ def self.inputs(configuration = {})
+ description_value(:inputs, configuration: configuration)
+ end
+
+ def self.outputs(configuration = {})
+ description_value(:outputs, configuration: configuration)
+ end
+
+ def self.properties
+ description_value(:properties)
+ end
+
+ def self.credentials
+ description_value(:credentials)
+ end
+
+ def self.webhooks(configuration = {})
+ Array(description_value(:webhooks, configuration: configuration)).map do |webhook|
+ webhook.deep_symbolize_keys
+ end
+ end
+
+ def self.waiting_webhook_for(http_method:, path:, node_type:)
+ webhooks.find do |webhook|
+ webhook[:restart_webhook] == true && webhook[:node_type].to_s == node_type.to_s &&
+ webhook[:http_method].to_s.casecmp?(http_method.to_s) &&
+ webhook.fetch(:path) { "" }.to_s == path.to_s
+ end
+ end
+
+ def self.property_schema
+ properties
+ end
+
+ def self.event_name
+ Array(description[:events]).first
+ end
+
+ def self.manually_triggerable?
+ capability_enabled?(:manually_triggerable)
+ end
+
+ def self.provides_current_user?
+ capability_enabled?(:provides_current_user)
+ end
+
+ def self.waits_for_resume?
+ capability_enabled?(:waits_for_resume)
+ end
+
+ def self.max_nodes
+ description_value(:max_nodes)
+ end
+
+ def self.description_value(key, configuration: nil)
+ value = description.fetch(key)
+ return value unless value.respond_to?(:call)
+
+ configuration.nil? ? value.call : value.call(configuration)
+ end
+
+ def self.capability_enabled?(key)
+ description.dig(:capabilities, key) == true
+ end
+
+ def self.normalize_tag_names(value)
+ Array
+ .wrap(value)
+ .flat_map { |name| name.to_s.split(",") }
+ .filter_map { |name| name.strip.presence }
+ end
+
+ def initialize(**)
+ end
+
+ def execute(exec_ctx)
+ raise NotImplementedError
+ end
+
+ def trigger(trigger_ctx)
+ raise NotImplementedError
+ end
+
+ def webhook(webhook_ctx)
+ raise NotImplementedError
+ end
+
+ def valid?
+ true
+ end
+
+ def matches?(_trigger_ctx)
+ true
+ end
+
+ def output
+ raise NotImplementedError
+ end
+
+ private
+
+ def normalize_tag_names(value)
+ self.class.normalize_tag_names(value)
+ end
+
+ def wrap(data, paired_item: nil)
+ Item.wrap(data, paired_item:)
+ end
+
+ def serialize_record(record, serializer, scope: Discourse.system_user.guardian, root: false)
+ MultiJson.load(serializer.new(record, scope:, root:).to_json).deep_symbolize_keys
+ end
+
+ def with_paired_item(item, paired_item)
+ Item.with_paired_item(item, paired_item)
+ end
+ end
+end
diff --git a/plugins/discourse-workflows/lib/discourse_workflows/node_type_descriptor.rb b/plugins/discourse-workflows/lib/discourse_workflows/node_type_descriptor.rb
new file mode 100644
index 00000000000..48f15cb6249
--- /dev/null
+++ b/plugins/discourse-workflows/lib/discourse_workflows/node_type_descriptor.rb
@@ -0,0 +1,170 @@
+# frozen_string_literal: true
+
+module DiscourseWorkflows
+ module NodeTypeDescriptor
+ DEFAULT_I18N_PREFIX = "discourse_workflows"
+
+ GROUPS = {
+ "discourse_triggers" => {
+ icon: "discourse-other-tab",
+ label_key: "discourse_workflows.add_node.categories.discourse_triggers",
+ order: 10,
+ },
+ "triggers" => {
+ icon: "bolt",
+ label_key: "discourse_workflows.add_node.categories.triggers",
+ order: 20,
+ },
+ "discourse_actions" => {
+ icon: "discourse-other-tab",
+ label_key: "discourse_workflows.add_node.categories.discourse_actions",
+ order: 30,
+ },
+ "data" => {
+ icon: "table",
+ label_key: "discourse_workflows.add_node.categories.data",
+ order: 50,
+ },
+ "utilities" => {
+ icon: "code",
+ label_key: "discourse_workflows.add_node.categories.utilities",
+ order: 60,
+ },
+ "flow" => {
+ icon: "arrows-split-up-and-left",
+ label_key: "discourse_workflows.add_node.categories.flow",
+ order: 70,
+ },
+ "human_review" => {
+ icon: "user-check",
+ label_key: "discourse_workflows.add_node.categories.human_review",
+ order: 80,
+ },
+ }.freeze
+
+ def kind
+ identifier.split(":").first
+ end
+
+ def label_key
+ description[:displayName] || description[:display_name_key] ||
+ "#{DEFAULT_I18N_PREFIX}.nodes.#{identifier}"
+ end
+
+ def description_key
+ description[:description_key] || "#{DEFAULT_I18N_PREFIX}.node_descriptions.#{identifier}"
+ end
+
+ def group
+ description[:group] || default_group
+ end
+
+ def palette_group
+ group_definition.merge(id: group)
+ end
+
+ def i18n_prefix
+ description[:i18n_prefix] || DEFAULT_I18N_PREFIX
+ end
+
+ def i18n_scope
+ description[:i18n_scope] || identifier.split(":").last
+ end
+
+ def operation_label_key(operation)
+ "#{i18n_prefix}.#{i18n_scope}.operations.#{operation}"
+ end
+
+ def operations
+ operation_field = property_schema[:operation]
+ options = Array(operation_field&.dig(:options))
+
+ return [] unless operation_field&.dig(:type) == :options
+ return [] if options.length <= 1
+
+ options.map { |value| { value: value, label_key: operation_label_key(value) } }
+ end
+
+ def ports(configuration = {})
+ normalize_ports(output_port_definitions(configuration))
+ end
+
+ def input_ports(configuration = {})
+ normalize_ports(input_port_definitions(configuration), primary: false, required: true)
+ end
+
+ def required_inputs(configuration = {})
+ description_value(:required_inputs, configuration: configuration)
+ end
+
+ def branching?
+ ports.length > 1
+ end
+
+ def capabilities
+ description.fetch(:capabilities, {}).merge(
+ branching: branching?,
+ manually_triggerable: manually_triggerable?,
+ provides_current_user: provides_current_user?,
+ result_mode: branching? ? "ports" : "items",
+ )
+ end
+
+ def ui_metadata
+ {
+ icon: icon,
+ color: color,
+ defaults: description[:defaults],
+ label_key: label_key,
+ description_key: description_key,
+ palette_group: palette_group,
+ i18n_prefix: i18n_prefix,
+ i18n_scope: i18n_scope,
+ }.compact
+ end
+
+ private
+
+ def group_definition
+ GROUPS.fetch(group)
+ end
+
+ def default_group
+ case kind
+ when "trigger"
+ "triggers"
+ when "condition", "flow"
+ "flow"
+ else
+ "utilities"
+ end
+ end
+
+ def output_port_definitions(configuration = {})
+ return call_port_definition(:outputs, configuration) if respond_to?(:outputs)
+ []
+ end
+
+ def input_port_definitions(configuration = {})
+ return call_port_definition(:inputs, configuration) if respond_to?(:inputs)
+ [:main]
+ end
+
+ def call_port_definition(method_name, configuration)
+ method = public_method(method_name)
+ Array(method.arity.zero? ? method.call : method.call(configuration))
+ end
+
+ def normalize_ports(definitions, primary: true, required: nil)
+ definitions.map.with_index do |definition, index|
+ port = definition.is_a?(Hash) ? definition.deep_symbolize_keys : { key: definition.to_s }
+ port[:key] = port[:key].presence&.to_s || index.to_s
+ port[:type] = port.fetch(:type, "main").to_s
+ port[:index] = index
+ port[:primary] = index.zero? if primary && !port.key?(:primary)
+ port[:required] = required if !required.nil? && !port.key?(:required)
+ port.compact
+ end
+ end
+ end
+end
diff --git a/plugins/discourse-workflows/lib/discourse_workflows/node_type_serializer.rb b/plugins/discourse-workflows/lib/discourse_workflows/node_type_serializer.rb
new file mode 100644
index 00000000000..02e591534e1
--- /dev/null
+++ b/plugins/discourse-workflows/lib/discourse_workflows/node_type_serializer.rb
@@ -0,0 +1,74 @@
+# frozen_string_literal: true
+
+module DiscourseWorkflows
+ class NodeTypeSerializer
+ def initialize(identifier:, available_versions:)
+ @identifier = identifier
+ @available_versions = available_versions
+ @latest_version = available_versions.last
+ end
+
+ def to_h
+ versions = version_descriptions
+ latest = versions.fetch(@latest_version)
+
+ latest.merge(
+ latest: latest,
+ versions: versions,
+ icon: latest.dig(:ui, :icon),
+ color: latest.dig(:ui, :color),
+ branching: latest.dig(:capabilities, :branching),
+ manually_triggerable: latest.dig(:capabilities, :manually_triggerable),
+ ).compact
+ end
+
+ private
+
+ def version_descriptions
+ @available_versions.index_with do |version|
+ serializable_version(Registry.find_node_type(@identifier, version: version), version)
+ end
+ end
+
+ def serializable_version(klass, version)
+ properties = klass.property_schema
+ webhooks = serializable_webhooks(klass)
+ description =
+ klass.description.merge(
+ displayName: klass.label_key,
+ descriptionKey: klass.description_key,
+ name: @identifier,
+ version: version,
+ inputs: klass.input_ports,
+ outputs: klass.ports,
+ properties: properties,
+ webhooks: webhooks,
+ )
+
+ {
+ displayName: description[:displayName],
+ name: @identifier,
+ version: version,
+ defaults: description[:defaults],
+ inputs: description[:inputs],
+ outputs: description[:outputs],
+ properties: properties,
+ credentials: description[:credentials],
+ webhooks: webhooks,
+ description: description,
+ identifier: @identifier,
+ kind: klass.kind,
+ ui: klass.ui_metadata,
+ capabilities: klass.capabilities,
+ ports: klass.ports,
+ operations: klass.operations,
+ available: klass.available?,
+ unavailable_reason_key: (klass.unavailable_reason_key unless klass.available?),
+ }.compact
+ end
+
+ def serializable_webhooks(klass)
+ klass.webhooks.map { |webhook| webhook.except(:handler) }
+ end
+ end
+end
diff --git a/plugins/discourse-workflows/lib/discourse_workflows/node_view.rb b/plugins/discourse-workflows/lib/discourse_workflows/node_view.rb
new file mode 100644
index 00000000000..275fb94006c
--- /dev/null
+++ b/plugins/discourse-workflows/lib/discourse_workflows/node_view.rb
@@ -0,0 +1,103 @@
+# frozen_string_literal: true
+
+module DiscourseWorkflows
+ class NodeView
+ attr_reader :id,
+ :name,
+ :type,
+ :type_version,
+ :position,
+ :webhook_id,
+ :notes,
+ :notes_in_flow,
+ :always_output_data,
+ :on_error,
+ :continue_on_fail
+
+ def self.from_snapshot_node(
+ node,
+ include_node_parameters: false,
+ include_credentials: false,
+ include_webhook_id: false
+ )
+ return if node.blank?
+
+ direct_settings =
+ DiscourseWorkflows::NodeData
+ .direct_settings(node)
+ .transform_keys { |key| DiscourseWorkflows::NodeData::NODE_DIRECT_SETTING_KEYS[key] }
+
+ new(
+ id: node.id,
+ name: node.name,
+ type: node.type,
+ type_version: node.type_version,
+ position: node.position,
+ webhook_id: include_webhook_id ? node.webhook_id : nil,
+ parameters: include_node_parameters ? node.parameters : nil,
+ credentials: include_credentials ? node.credentials : nil,
+ **direct_settings,
+ )
+ end
+
+ def initialize(
+ id:,
+ name:,
+ type:,
+ type_version:,
+ position: nil,
+ webhook_id: nil,
+ parameters: nil,
+ credentials: nil,
+ notes: nil,
+ notes_in_flow: nil,
+ always_output_data: nil,
+ on_error: nil,
+ continue_on_fail: nil
+ )
+ @id = id.to_s
+ @name = name.to_s
+ @type = type.to_s
+ @type_version = numeric_version(type_version)
+ @position = position || [0, 0]
+ @webhook_id = webhook_id
+ @parameters = parameters&.deep_dup
+ @credentials = credentials&.deep_dup
+ @notes = notes
+ @notes_in_flow = notes_in_flow
+ @always_output_data = always_output_data
+ @on_error = on_error
+ @continue_on_fail = continue_on_fail
+ freeze
+ end
+
+ def parameters
+ @parameters&.deep_dup
+ end
+
+ def credentials
+ @credentials&.deep_dup
+ end
+
+ def to_h
+ {
+ "id" => id,
+ "name" => name,
+ "type" => type,
+ "typeVersion" => type_version,
+ "position" => position,
+ "webhookId" => webhook_id,
+ "parameters" => parameters,
+ "credentials" => credentials,
+ }.merge(DiscourseWorkflows::NodeData.direct_settings(self)).compact
+ end
+
+ private
+
+ def numeric_version(version)
+ Float(version)
+ rescue ArgumentError, TypeError
+ version
+ end
+ end
+end
diff --git a/plugins/discourse-workflows/lib/discourse_workflows/nodes/badge/v1.rb b/plugins/discourse-workflows/lib/discourse_workflows/nodes/badge/v1.rb
new file mode 100644
index 00000000000..eb60b839f0f
--- /dev/null
+++ b/plugins/discourse-workflows/lib/discourse_workflows/nodes/badge/v1.rb
@@ -0,0 +1,113 @@
+# frozen_string_literal: true
+
+module DiscourseWorkflows
+ module Nodes
+ module Badge
+ class V1 < NodeType
+ OPERATIONS = %w[grant revoke].freeze
+
+ description(
+ name: "action:badge",
+ version: "1.0",
+ defaults: {
+ icon: "certificate",
+ color: "yellow",
+ },
+ group: "discourse_actions",
+ capabilities: {
+ run_scope: "per_item",
+ },
+ properties: {
+ operation: {
+ type: :options,
+ required: true,
+ options: OPERATIONS,
+ default: "grant",
+ ui: {
+ expression: true,
+ },
+ },
+ username: {
+ type: :string,
+ required: true,
+ ui: {
+ control: :user,
+ },
+ },
+ badge_id: {
+ type: :integer,
+ required: true,
+ type_options: {
+ load_options_method: "badges",
+ },
+ ui: {
+ control: :combo_box,
+ dynamic_value: :badge_id,
+ },
+ control_options: {
+ value_property: "id",
+ name_property: "name",
+ filterable: true,
+ none: "discourse_workflows.badge.badge_id_placeholder",
+ },
+ },
+ actor_username: {
+ type: :string,
+ required: false,
+ default: "system",
+ ui: {
+ control: :user,
+ },
+ },
+ },
+ )
+
+ def self.load_options_context(context)
+ case context.method_name
+ when "badges"
+ ::Badge
+ .where(enabled: true)
+ .order(:name)
+ .pluck(:id, :name)
+ .select { |_, name| context.matches_filter?(name) }
+ .map { |id, name| { id:, name: } }
+ end
+ end
+
+ def execute(exec_ctx)
+ items =
+ exec_ctx.input_items.map.with_index do |_item, item_index|
+ config = {
+ "operation" =>
+ exec_ctx.get_node_parameter("operation", item_index, default: "grant"),
+ "username" => exec_ctx.get_node_parameter("username", item_index),
+ "badge_id" => exec_ctx.get_node_parameter("badge_id", item_index),
+ }
+
+ wrap(process(exec_ctx, config, item_index))
+ end
+
+ [items]
+ end
+
+ private
+
+ def process(exec_ctx, config, item_index)
+ user = exec_ctx.find_user(username: config["username"])
+ badge = ::Badge.find(config["badge_id"])
+ actor = exec_ctx.actor_from_parameter("actor_username", item_index)
+
+ case config["operation"]
+ when "revoke"
+ user_badge = UserBadge.find_by(user: user, badge: badge)
+ BadgeGranter.revoke(user_badge, revoked_by: actor) if user_badge
+ else
+ BadgeGranter.grant(badge, user, granted_by: actor)
+ end
+
+ { user_id: user.id, username: user.username, badge_id: badge.id, badge_name: badge.name }
+ end
+ end
+ end
+ end
+end
diff --git a/plugins/discourse-workflows/lib/discourse_workflows/nodes/code/js_task_runner_sandbox.rb b/plugins/discourse-workflows/lib/discourse_workflows/nodes/code/js_task_runner_sandbox.rb
new file mode 100644
index 00000000000..36a921b6437
--- /dev/null
+++ b/plugins/discourse-workflows/lib/discourse_workflows/nodes/code/js_task_runner_sandbox.rb
@@ -0,0 +1,292 @@
+# frozen_string_literal: true
+
+module DiscourseWorkflows
+ module Nodes
+ module Code
+ class JsTaskRunnerSandbox
+ include NodeErrorHandling
+
+ RUN_CODE = "runCode"
+ RUN_ONCE_FOR_ALL_ITEMS = "runOnceForAllItems"
+ RUN_ONCE_FOR_EACH_ITEM = "runOnceForEachItem"
+ JS_TEXT_KEYS = { object: { singular: "object", plural: "objects" } }.freeze
+ RESERVED_ITEM_KEYS = %w[json pairedItem error index].freeze
+
+ def initialize(
+ workflow_mode,
+ execute_functions,
+ chunk_size = 1000,
+ additional_properties = {}
+ )
+ @workflow_mode = workflow_mode
+ @execute_functions = execute_functions
+ @chunk_size = chunk_size || 1000
+ @additional_properties = additional_properties || {}
+ end
+
+ def run_code_all_items(code)
+ execution_result =
+ @execute_functions.start_job(
+ "javascript",
+ {
+ code: code,
+ nodeMode: RUN_ONCE_FOR_ALL_ITEMS,
+ workflowMode: @workflow_mode,
+ continueOnFail: @execute_functions.continue_on_fail,
+ additionalProperties: @additional_properties,
+ },
+ 0,
+ )
+ raise_execution_error!(execution_result) unless execution_result.ok
+
+ result = execution_result.result
+ return [] if result.nil?
+
+ validate_run_code_all_items(result)
+ end
+
+ def run_code_for_tool(code)
+ execution_result =
+ @execute_functions.start_job(
+ "javascript",
+ {
+ code: code,
+ nodeMode: RUN_ONCE_FOR_ALL_ITEMS,
+ workflowMode: @workflow_mode,
+ continueOnFail: @execute_functions.continue_on_fail,
+ additionalProperties: @additional_properties,
+ },
+ 0,
+ )
+ raise_execution_error!(execution_result) unless execution_result.ok
+
+ execution_result.result
+ end
+
+ def run_code_for_each_item(code, num_input_items)
+ validate_no_disallowed_methods_in_run_for_each(code, 0)
+
+ chunk_input_items(num_input_items).flat_map do |chunk|
+ execution_result =
+ @execute_functions.start_job(
+ "javascript",
+ {
+ code: code,
+ nodeMode: RUN_ONCE_FOR_EACH_ITEM,
+ workflowMode: @workflow_mode,
+ continueOnFail: @execute_functions.continue_on_fail,
+ chunk: {
+ startIndex: chunk[:start_index],
+ count: chunk[:count],
+ },
+ additionalProperties: @additional_properties,
+ },
+ 0,
+ )
+ raise_execution_error!(execution_result) unless execution_result.ok
+
+ execution_result.result.map.with_index do |result, index|
+ validate_run_code_each_item(result, item_index: chunk[:start_index] + index)
+ end
+ end
+ end
+
+ def run_code(code)
+ execution_result =
+ @execute_functions.start_job(
+ "javascript",
+ {
+ code: code,
+ nodeMode: RUN_CODE,
+ workflowMode: @workflow_mode,
+ continueOnFail: @execute_functions.continue_on_fail,
+ additionalProperties: @additional_properties,
+ },
+ 0,
+ )
+ raise_execution_error!(execution_result) unless execution_result.ok
+
+ execution_result.result
+ end
+
+ private
+
+ def chunk_input_items(num_input_items)
+ num_chunks = (num_input_items.to_f / @chunk_size).ceil
+ Array.new(num_chunks) do |index|
+ start_index = index * @chunk_size
+ count = index == num_chunks - 1 ? num_input_items - start_index : @chunk_size
+ { start_index: start_index, count: count }
+ end
+ end
+
+ def raise_execution_error!(execution_result)
+ error = execution_result.error
+ raise error if error.is_a?(Exception)
+
+ raise_node_error!(
+ I18n.t("discourse_workflows.errors.javascript_execution_failed"),
+ description: error.to_s,
+ )
+ end
+
+ def validate_no_disallowed_methods_in_run_for_each(code, item_index)
+ match = code.match(/\$input\.(?<disallowed_method>first|last|all|itemMatching)/)
+ return if match.blank?
+
+ disallowed_method = match[:disallowed_method]
+ line_number =
+ code
+ .split("\n")
+ .find_index do |line|
+ stripped = line.strip
+ line.include?(disallowed_method) && !stripped.start_with?("//", "/*", "*")
+ end
+ return if line_number.nil?
+
+ raise_node_error!(
+ "Can't use .#{disallowed_method}() here",
+ description: "This is only available in 'Run Once for All Items' mode.",
+ item_index: item_index,
+ line_number: line_number + 1,
+ )
+ end
+
+ def validate_run_code_each_item(value, item_index:)
+ unless value.is_a?(Hash) || value.is_a?(Array)
+ raise_node_error!(
+ "Code doesn't return #{text_key(:object, include_article: true)}",
+ description:
+ "Please return #{text_key(:object, include_article: true)} representing the output " \
+ "item. ('#{value}' was returned instead.)",
+ item_index: item_index,
+ )
+ end
+
+ if value.is_a?(Array)
+ first_sentence =
+ if value.length > 0
+ "An array of #{value.first.class.name.downcase}s was returned."
+ else
+ "An empty array was returned."
+ end
+ raise_node_error!(
+ "Code doesn't return a single #{text_key(:object)}",
+ description:
+ "#{first_sentence} If you need to output multiple items, please use the " \
+ "'Run Once for All Items' mode instead.",
+ item_index: item_index,
+ )
+ end
+
+ return_data = normalize_items!([value]).first
+ validate_item!(return_data, item_index: item_index)
+ validate_top_level_keys!(return_data, item_index: item_index)
+ return_data["pairedItem"] ||= { "item" => item_index }
+ return_data
+ end
+
+ def validate_run_code_all_items(value)
+ unless value.is_a?(Hash) || value.is_a?(Array)
+ raise_node_error!(
+ "Code doesn't return items properly",
+ description:
+ "Please return an array of #{text_key(:object, plural: true)}, one for each item " \
+ "you would like to output.",
+ )
+ end
+
+ if value.is_a?(Array)
+ unless value.all? { |item| item.is_a?(Hash) }
+ raise_node_error!(
+ "Code doesn't return items properly",
+ description:
+ "Please return an array of #{text_key(:object, plural: true)}, one for each " \
+ "item you would like to output.",
+ )
+ end
+
+ if value.any? { |item| item.keys.any? { |key| reserved_item_key?(key) } }
+ value.each_with_index do |item, index|
+ validate_top_level_keys!(item, item_index: index)
+ end
+ end
+ elsif !value.is_a?(Hash)
+ raise_node_error!(
+ "Code doesn't return items properly",
+ description:
+ "Please return an array of #{text_key(:object, plural: true)}, one for each item " \
+ "you would like to output.",
+ )
+ end
+
+ normalize_items!(value).tap do |return_data|
+ return_data.each_with_index do |item, index|
+ validate_item!(item, item_index: index)
+ validate_top_level_keys!(item, item_index: index)
+ end
+ end
+ end
+
+ def normalize_items!(value)
+ @execute_functions.helpers.normalize_items(value)
+ end
+
+ def validate_item!(item, item_index:)
+ unless item["json"].is_a?(Hash)
+ raise_node_error!(
+ "A 'json' property isn't #{text_key(:object, include_article: true)}",
+ description:
+ "In the returned data, every key named 'json' must point to " \
+ "#{text_key(:object, include_article: true)}.",
+ item_index: item_index,
+ )
+ end
+ end
+
+ def validate_top_level_keys!(item, item_index:)
+ found_reserved_key = nil
+ unknown_keys = []
+
+ item.each_key do |key|
+ if reserved_item_key?(key)
+ found_reserved_key ||= key
+ else
+ unknown_keys << key
+ end
+ end
+
+ return if unknown_keys.empty?
+
+ if found_reserved_key
+ raise_node_error!(
+ "Invalid output format",
+ description:
+ "An output item contains the reserved key #{found_reserved_key}. Wrap each item " \
+ "in an object under a key called json.",
+ item_index: item_index,
+ )
+ end
+
+ raise_node_error!(
+ "Unknown top-level item key: #{unknown_keys.first}",
+ description: "Access the properties of an item under .json, e.g. item.json",
+ item_index: item_index,
+ )
+ end
+
+ def text_key(key, include_article: false, plural: false)
+ response = JS_TEXT_KEYS.fetch(key).fetch(plural ? :plural : :singular)
+ return response unless include_article
+
+ article = response.match?(/\A[aeiou]/) ? "an" : "a"
+ "#{article} #{response}"
+ end
+
+ def reserved_item_key?(key)
+ RESERVED_ITEM_KEYS.include?(key.to_s)
+ end
+ end
+ end
+ end
+end
diff --git a/plugins/discourse-workflows/lib/discourse_workflows/nodes/code/v1.rb b/plugins/discourse-workflows/lib/discourse_workflows/nodes/code/v1.rb
new file mode 100644
index 00000000000..76bc87cfd3d
--- /dev/null
+++ b/plugins/discourse-workflows/lib/discourse_workflows/nodes/code/v1.rb
@@ -0,0 +1,105 @@
+# frozen_string_literal: true
+
+module DiscourseWorkflows
+ module Nodes
+ module Code
+ class V1 < NodeType
+ DEFAULT_CODE = <<~JS
+ // Available variables:
+ // $input.item.json - current item's JSON data
+ // $input.all() - array of all input items
+ // $json - shortcut for $input.item.json
+ // $("NodeName").item - access the paired item from another node
+ // $vars.KEY - workflow variables
+ // $site_settings.NAME - site settings
+ // $execution - execution metadata (id, workflow_name, ...)
+ // $current_user - user running the workflow
+ // console.log/warn/error - logging
+
+ // Example: add a new field called 'foo' to every input item
+ var items = $input.all();
+ items.forEach(function(item) {
+ item.json.foo = 1;
+ });
+
+ return items;
+ JS
+ RUN_ONCE_FOR_ALL_ITEMS = "runOnceForAllItems"
+ RUN_ONCE_FOR_EACH_ITEM = "runOnceForEachItem"
+
+ description(
+ name: "action:code",
+ version: "1.0",
+ defaults: {
+ icon: "code",
+ color: "red",
+ },
+ capabilities: {
+ run_scope: {
+ parameter: "mode",
+ values: {
+ RUN_ONCE_FOR_EACH_ITEM => "per_item",
+ RUN_ONCE_FOR_ALL_ITEMS => "all_items",
+ },
+ },
+ },
+ properties: {
+ mode: {
+ type: :options,
+ default: RUN_ONCE_FOR_ALL_ITEMS,
+ options: [RUN_ONCE_FOR_EACH_ITEM, RUN_ONCE_FOR_ALL_ITEMS],
+ no_data_expression: true,
+ },
+ code: {
+ type: :string,
+ required: true,
+ default: DEFAULT_CODE,
+ no_data_expression: true,
+ ui: {
+ control: :code,
+ },
+ control_options: {
+ height: 300,
+ lang: :javascript,
+ },
+ },
+ },
+ )
+
+ def execute(exec_ctx)
+ code =
+ exec_ctx.get_node_parameter(
+ "code",
+ 0,
+ default: DEFAULT_CODE,
+ options: {
+ raw_expressions: true,
+ },
+ ).to_s
+ mode = exec_ctx.get_node_parameter("mode", 0, default: RUN_ONCE_FOR_ALL_ITEMS)
+ validate_mode!(mode)
+
+ sandbox = JsTaskRunnerSandbox.new(exec_ctx.get_mode, exec_ctx)
+ [
+ if mode == RUN_ONCE_FOR_ALL_ITEMS
+ sandbox.run_code_all_items(code)
+ else
+ sandbox.run_code_for_each_item(code, exec_ctx.get_input_data.length)
+ end,
+ ]
+ end
+
+ private
+
+ def validate_mode!(mode)
+ return if [RUN_ONCE_FOR_ALL_ITEMS, RUN_ONCE_FOR_EACH_ITEM].include?(mode)
+
+ raise_node_error!(
+ "Invalid Code mode",
+ description: "#{mode.inspect} is not a supported Code execution mode.",
+ )
+ end
+ end
+ end
+ end
+end
diff --git a/plugins/discourse-workflows/lib/discourse_workflows/nodes/create_post/v1.rb b/plugins/discourse-workflows/lib/discourse_workflows/nodes/create_post/v1.rb
new file mode 100644
index 00000000000..97b902bba07
--- /dev/null
+++ b/plugins/discourse-workflows/lib/discourse_workflows/nodes/create_post/v1.rb
@@ -0,0 +1,91 @@
+# frozen_string_literal: true
+
+module DiscourseWorkflows
+ module Nodes
+ module CreatePost
+ class V1 < NodeType
+ description(
+ name: "action:create_post",
+ version: "1.0",
+ defaults: {
+ icon: "reply",
+ color: "teal",
+ },
+ group: "discourse_actions",
+ capabilities: {
+ run_scope: "per_item",
+ },
+ properties: {
+ topic_id: {
+ type: :string,
+ required: true,
+ },
+ raw: {
+ type: :string,
+ required: true,
+ ui: {
+ control: :textarea,
+ },
+ },
+ reply_to_post_number: {
+ type: :integer,
+ required: false,
+ },
+ author_username: {
+ type: :string,
+ required: false,
+ default: "system",
+ ui: {
+ control: :user,
+ },
+ },
+ },
+ )
+
+ def execute(exec_ctx)
+ items =
+ exec_ctx.input_items.map.with_index do |_item, item_index|
+ config = {
+ "topic_id" => exec_ctx.get_node_parameter("topic_id", item_index),
+ "raw" => exec_ctx.get_node_parameter("raw", item_index),
+ "reply_to_post_number" =>
+ exec_ctx.get_node_parameter("reply_to_post_number", item_index),
+ }
+
+ wrap(process(exec_ctx, config, item_index))
+ end
+
+ [items]
+ end
+
+ private
+
+ def process(exec_ctx, config, item_index)
+ topic = ::Topic.find(config["topic_id"])
+ author = exec_ctx.actor_from_parameter("author_username", item_index)
+ author.guardian.ensure_can_see!(topic)
+
+ if topic.closed? || topic.archived?
+ raise_node_error!(
+ I18n.t("discourse_workflows.errors.create_post.topic_closed_or_archived"),
+ )
+ end
+
+ post_args = {
+ topic_id: topic.id,
+ raw: config["raw"],
+ reply_to_post_number: config["reply_to_post_number"].presence,
+ skip_workflows: true,
+ }.compact
+ post = PostCreator.new(author, post_args).create!
+
+ { post: post_data(post) }
+ end
+
+ def post_data(post)
+ serialize_record(post, WebHookPostSerializer)
+ end
+ end
+ end
+ end
+end
diff --git a/plugins/discourse-workflows/lib/discourse_workflows/nodes/data_table/v1.rb b/plugins/discourse-workflows/lib/discourse_workflows/nodes/data_table/v1.rb
new file mode 100644
index 00000000000..d671f0a5d99
--- /dev/null
+++ b/plugins/discourse-workflows/lib/discourse_workflows/nodes/data_table/v1.rb
@@ -0,0 +1,320 @@
+# frozen_string_literal: true
+
+module DiscourseWorkflows
+ module Nodes
+ module DataTable
+ class V1 < NodeType
+ OPERATIONS = %w[insert get update delete upsert row_exists row_not_exists].freeze
+ MAPPING_MODES = %w[manual auto].freeze
+ DEFAULT_LIMIT = DiscourseWorkflows::DataTables::Facade::MAX_LIMIT
+ CONDITION_OVERRIDES =
+ {
+ "equals" => "eq",
+ "notEquals" => "neq",
+ "contains" => "ilike",
+ "notContains" => "not_ilike",
+ "gt" => "gt",
+ "gte" => "gte",
+ "lt" => "lt",
+ "lte" => "lte",
+ }.transform_values { |condition| { "condition" => condition } }
+ .merge(
+ "empty" => {
+ "condition" => "eq",
+ "value" => nil,
+ },
+ "notEmpty" => {
+ "condition" => "neq",
+ "value" => nil,
+ },
+ "true" => {
+ "condition" => "eq",
+ "value" => true,
+ },
+ "false" => {
+ "condition" => "eq",
+ "value" => false,
+ },
+ )
+ .freeze
+
+ description(
+ name: "action:data_table",
+ version: "1.0",
+ defaults: {
+ icon: "table",
+ color: "violet",
+ },
+ group: "data",
+ i18n_scope: "data_table_node",
+ capabilities: {
+ run_scope: "per_item",
+ },
+ properties: {
+ operation: {
+ type: :options,
+ required: true,
+ options: OPERATIONS,
+ default: "insert",
+ },
+ data_table_id: {
+ type: :integer,
+ required: true,
+ type_options: {
+ load_options_method: "data_tables",
+ },
+ ui: {
+ control: :data_table_select,
+ },
+ control_options: {
+ value_property: "id",
+ name_property: "name",
+ filterable: true,
+ none: "discourse_workflows.data_table_node.data_table_id_placeholder",
+ resets: %w[filter columns sort_column],
+ },
+ },
+ mapping_mode: {
+ type: :options,
+ required: true,
+ options: MAPPING_MODES,
+ default: "manual",
+ display_options: {
+ show: {
+ operation: ["insert"],
+ },
+ },
+ no_data_expression: true,
+ },
+ columns_case_sensitive_hint: {
+ type: :notice,
+ display_options: {
+ show: {
+ operation: ["insert"],
+ mapping_mode: ["manual"],
+ },
+ },
+ },
+ columns: {
+ type: :object,
+ required: false,
+ default: {
+ },
+ display_options: {
+ show: {
+ operation: %w[insert update upsert],
+ },
+ hide: {
+ mapping_mode: ["auto"],
+ },
+ },
+ ui: {
+ control: :data_table_columns,
+ },
+ },
+ filter_combinator: {
+ type: :options,
+ options: %w[and or],
+ default: "and",
+ required: false,
+ display_options: {
+ show: {
+ operation: %w[get update delete upsert row_exists row_not_exists],
+ },
+ },
+ no_data_expression: true,
+ },
+ filter: {
+ type: :array,
+ required: false,
+ display_options: {
+ show: {
+ operation: %w[get update delete upsert row_exists row_not_exists],
+ },
+ },
+ ui: {
+ control: :data_table_condition_builder,
+ },
+ },
+ limit: {
+ type: :integer,
+ required: false,
+ display_options: {
+ show: {
+ operation: ["get"],
+ },
+ },
+ },
+ sort_column: {
+ type: :string,
+ required: false,
+ display_options: {
+ show: {
+ operation: ["get"],
+ },
+ },
+ ui: {
+ control: :data_table_column_select,
+ format: :full,
+ },
+ control_options: {
+ none: "discourse_workflows.data_table_node.sort_column_placeholder",
+ },
+ },
+ sort_direction: {
+ type: :options,
+ required: false,
+ options: %w[asc desc],
+ default: "asc",
+ display_options: {
+ show: {
+ operation: ["get"],
+ },
+ },
+ },
+ },
+ )
+
+ def self.load_options_context(context)
+ case context.method_name
+ when "data_tables"
+ result =
+ context.helpers.get_data_table_aggregate_proxy.get_many_and_count(
+ filter: {
+ name: context.filter,
+ },
+ sort_by: "name:asc",
+ )
+
+ result[:data]
+ end
+ end
+
+ def execute(exec_ctx)
+ items =
+ exec_ctx.input_items.flat_map.with_index do |item, item_index|
+ config = {
+ "operation" =>
+ exec_ctx.get_node_parameter("operation", item_index, default: "insert"),
+ "data_table_id" => exec_ctx.get_node_parameter("data_table_id", item_index),
+ "mapping_mode" =>
+ exec_ctx.get_node_parameter("mapping_mode", item_index, default: "manual"),
+ "columns" => exec_ctx.get_node_parameter("columns", item_index, default: {}),
+ "filter_combinator" =>
+ exec_ctx.get_node_parameter("filter_combinator", item_index, default: "and"),
+ "filter" => exec_ctx.get_node_parameter("filter", item_index),
+ "limit" => exec_ctx.get_node_parameter("limit", item_index),
+ "sort_column" => exec_ctx.get_node_parameter("sort_column", item_index),
+ "sort_direction" =>
+ exec_ctx.get_node_parameter("sort_direction", item_index, default: "asc"),
+ }
+ begin
+ pair_output_items(execute_with_config(config, item, exec_ctx), exec_ctx, item)
+ rescue ArgumentError => e
+ raise_node_error!(e.message)
+ end
+ end
+
+ [items]
+ end
+
+ private
+
+ def pair_output_items(output_items, exec_ctx, item)
+ paired_item = exec_ctx.paired_item_for(item)
+
+ Array.wrap(output_items).map { |output_item| with_paired_item(output_item, paired_item) }
+ end
+
+ def execute_with_config(config, item, exec_ctx)
+ node_proxy = exec_ctx.helpers.get_data_table_proxy(config.fetch("data_table_id"))
+ operation_name = config.fetch("operation", "insert")
+
+ if operation_name == "insert" && config["mapping_mode"] == "auto"
+ json = item["json"] || {}
+ config = config.merge("columns" => json.slice(*column_names(node_proxy)))
+ end
+
+ case operation_name
+ when "insert"
+ wrap(node_proxy.insert_rows([config["columns"] || {}], "all"))
+ when "get"
+ wrap(node_proxy.get_many_rows_and_count(row_query_options(config))[:data])
+ when "update"
+ wrap(node_proxy.update_rows(row_mutation_options(config)))
+ when "delete"
+ wrap(node_proxy.delete_rows(row_delete_options(config)))
+ when "upsert"
+ wrap(node_proxy.upsert_row(row_mutation_options(config)))
+ when "row_exists", "row_not_exists"
+ row_existence_items(config, item, operation_name, node_proxy)
+ else
+ raise_node_error!(
+ I18n.t(
+ "discourse_workflows.errors.data_table.unknown_operation",
+ operation: operation_name,
+ ),
+ )
+ end
+ end
+
+ def row_existence_items(config, item, operation_name, node_proxy)
+ filter = normalized_filter(config)
+ if filter.blank?
+ raise_node_error!(I18n.t("discourse_workflows.errors.data_table.filter_required"))
+ end
+
+ count = node_proxy.get_many_rows_and_count(filter: filter, take: 1)[:count].to_i
+ matched = count > 0
+ emit = operation_name == "row_exists" ? matched : !matched
+ emit ? [item] : []
+ end
+
+ def column_names(node_proxy)
+ node_proxy.get_columns.map { |column| column[:name] }
+ end
+
+ def row_query_options(config)
+ options = {}
+ filter = normalized_filter(config)
+ options[:filter] = filter if filter.present?
+ options[:take] = config["limit"].present? ? config["limit"].to_i : DEFAULT_LIMIT
+ options[:sort_by] = normalized_sort_by(config) if config["sort_column"].present?
+ options
+ end
+
+ def row_mutation_options(config)
+ { filter: normalized_filter(config), data: config["columns"] || {} }
+ end
+
+ def row_delete_options(config)
+ { filter: normalized_filter(config) }
+ end
+
+ def normalized_filter(config)
+ filter = config["filter"]
+ return if filter.blank?
+
+ {
+ "type" => config["filter_combinator"] || "and",
+ "filters" => filter.map { |condition| normalized_condition(condition) },
+ }
+ end
+
+ def normalized_condition(condition)
+ operation = condition.dig("operator", "operation")
+ override =
+ CONDITION_OVERRIDES.fetch(operation) do
+ raise_node_error!("Unsupported data table operator: #{operation.inspect}")
+ end
+
+ { "columnName" => condition["columnName"], "value" => condition["value"] }.merge(override)
+ end
+
+ def normalized_sort_by(config)
+ [config["sort_column"], config["sort_direction"].to_s.casecmp?("desc") ? "DESC" : "ASC"]
+ end
+ end
+ end
+ end
+end
diff --git a/plugins/discourse-workflows/lib/discourse_workflows/nodes/error/v1.rb b/plugins/discourse-workflows/lib/discourse_workflows/nodes/error/v1.rb
new file mode 100644
index 00000000000..0599351db03
--- /dev/null
+++ b/plugins/discourse-workflows/lib/discourse_workflows/nodes/error/v1.rb
@@ -0,0 +1,33 @@
+# frozen_string_literal: true
+
+module DiscourseWorkflows
+ module Nodes
+ module Error
+ class V1 < NodeType
+ description(
+ name: "trigger:error",
+ version: "1.0",
+ defaults: {
+ icon: "triangle-exclamation",
+ color: "red",
+ },
+ inputs: [],
+ max_nodes: 1,
+ )
+
+ def initialize(error_data = {}, *)
+ super(parameters: {})
+ @error_data = error_data.is_a?(Hash) ? error_data : {}
+ end
+
+ def valid?
+ true
+ end
+
+ def output
+ @error_data
+ end
+ end
+ end
+ end
+end
diff --git a/plugins/discourse-workflows/lib/discourse_workflows/nodes/filter/v1.rb b/plugins/discourse-workflows/lib/discourse_workflows/nodes/filter/v1.rb
new file mode 100644
index 00000000000..7b253158ac8
--- /dev/null
+++ b/plugins/discourse-workflows/lib/discourse_workflows/nodes/filter/v1.rb
@@ -0,0 +1,53 @@
+# frozen_string_literal: true
+
+module DiscourseWorkflows
+ module Nodes
+ module Filter
+ class V1 < NodeType
+ description(
+ name: "condition:filter",
+ version: "1.0",
+ defaults: {
+ icon: "filter",
+ color: "violet",
+ },
+ outputs: [
+ { key: "true", label_key: "discourse_workflows.executions.statuses.kept" },
+ { key: "false", label_key: "discourse_workflows.executions.statuses.rejected" },
+ ],
+ capabilities: {
+ run_scope: "per_item",
+ },
+ properties: {
+ combinator: {
+ type: :options,
+ options: %w[and or],
+ default: "and",
+ no_data_expression: true,
+ },
+ conditions: {
+ type: :array,
+ ui: {
+ control: :condition_builder,
+ },
+ },
+ options: {
+ type: :object,
+ ui: {
+ hidden: true,
+ },
+ },
+ },
+ )
+
+ def execute(exec_ctx)
+ exec_ctx
+ .input_items
+ .each_with_index
+ .partition { |_item, item_index| exec_ctx.get_node_parameter(:conditions, item_index) }
+ .map { |items| items.map(&:first) }
+ end
+ end
+ end
+ end
+end
diff --git a/plugins/discourse-workflows/lib/discourse_workflows/nodes/form/v1.rb b/plugins/discourse-workflows/lib/discourse_workflows/nodes/form/v1.rb
new file mode 100644
index 00000000000..11ca326b613
--- /dev/null
+++ b/plugins/discourse-workflows/lib/discourse_workflows/nodes/form/v1.rb
@@ -0,0 +1,246 @@
+# frozen_string_literal: true
+
+module DiscourseWorkflows
+ module Nodes
+ module Form
+ class V1 < NodeType
+ description(
+ name: "action:form",
+ version: "1.0",
+ defaults: {
+ icon: "rectangle-list",
+ color: "blue",
+ },
+ group: "human_review",
+ properties: {
+ page_type: {
+ type: :options,
+ default: "page",
+ options: %w[page completion],
+ no_data_expression: true,
+ },
+ form_title: {
+ type: :string,
+ display_options: {
+ show: {
+ page_type: %w[page],
+ },
+ },
+ },
+ form_description: {
+ type: :string,
+ display_options: {
+ show: {
+ page_type: %w[page],
+ },
+ },
+ ui: {
+ control: :textarea,
+ },
+ },
+ form_fields:
+ Schemas::FormFields::SCHEMA.merge(display_options: { show: { page_type: %w[page] } }),
+ on_submission: {
+ type: :options,
+ default: "completion_screen",
+ options: %w[completion_screen redirect show_text],
+ display_options: {
+ show: {
+ page_type: %w[completion],
+ },
+ },
+ no_data_expression: true,
+ },
+ completion_title: {
+ type: :string,
+ display_options: {
+ show: {
+ page_type: %w[completion],
+ on_submission: %w[completion_screen],
+ },
+ },
+ },
+ completion_message: {
+ type: :string,
+ display_options: {
+ show: {
+ page_type: %w[completion],
+ on_submission: %w[completion_screen],
+ },
+ },
+ ui: {
+ control: :textarea,
+ },
+ },
+ redirect_url: {
+ type: :string,
+ display_options: {
+ show: {
+ page_type: %w[completion],
+ on_submission: %w[redirect],
+ },
+ },
+ },
+ completion_text: {
+ type: :string,
+ display_options: {
+ show: {
+ page_type: %w[completion],
+ on_submission: %w[show_text],
+ },
+ },
+ ui: {
+ control: :textarea,
+ },
+ },
+ },
+ capabilities: {
+ waits_for_resume: true,
+ },
+ webhooks: [
+ {
+ name: "setup",
+ path: "",
+ http_method: "GET",
+ response_mode: "on_received",
+ restart_webhook: true,
+ node_type: "form",
+ },
+ {
+ name: "default",
+ path: "",
+ http_method: "POST",
+ response_mode: "response_node",
+ restart_webhook: true,
+ node_type: "form",
+ },
+ {
+ name: "status",
+ path: "status",
+ http_method: "GET",
+ response_mode: "on_received",
+ restart_webhook: true,
+ node_type: "form",
+ },
+ ],
+ )
+
+ def execute(exec_ctx)
+ page_type = exec_ctx.get_node_parameter("page_type", 0, default: "page")
+
+ return [exec_ctx.input_items] if page_type == "completion"
+
+ exec_ctx.put_execution_to_wait(nil)
+ [exec_ctx.input_items]
+ end
+
+ def webhook(webhook_ctx)
+ if webhook_ctx.http_method == "GET" && webhook_ctx.path == "status"
+ return status_response(webhook_ctx)
+ end
+ return show_response(webhook_ctx) if webhook_ctx.http_method == "GET"
+ return submit_response(webhook_ctx) if webhook_ctx.http_method == "POST"
+
+ DiscourseWorkflows::WebhookResponse.respond(
+ status: :not_found,
+ body: {
+ error: "not_found",
+ },
+ )
+ end
+
+ private
+
+ def status_response(webhook_ctx)
+ DiscourseWorkflows::WebhookResponse.respond(status: :ok, body: { status: "form_waiting" })
+ end
+
+ def show_response(webhook_ctx)
+ DiscourseWorkflows::WebhookResponse.respond(status: :ok, body: form_data(webhook_ctx))
+ end
+
+ def submit_response(webhook_ctx)
+ form_validation =
+ Schemas::FormFields.validate_submission(
+ form_fields(webhook_ctx),
+ form_data_param(webhook_ctx),
+ query_parameters: form_query_parameters(webhook_ctx),
+ )
+
+ unless form_validation.valid?
+ return(
+ DiscourseWorkflows::WebhookResponse.respond(
+ status: :unprocessable_entity,
+ body: {
+ errors: form_validation.errors.map(&:to_h),
+ },
+ )
+ )
+ end
+
+ DiscourseWorkflows::WebhookResponse.resume(
+ workflow_data: [
+ [
+ {
+ "json" =>
+ DiscourseWorkflows::Forms::Payload.build(
+ form_validation.data,
+ submitted_at: Time.current.utc.iso8601(3),
+ form_mode: form_mode(webhook_ctx),
+ query_parameters: form_query_parameters(webhook_ctx),
+ ),
+ "pairedItem" => {
+ "item" => 0,
+ },
+ },
+ ],
+ ],
+ status: :ok,
+ body: {
+ },
+ )
+ end
+
+ def form_data_param(webhook_ctx)
+ body_data = webhook_ctx.get_body_data
+ body_data[:form_data] || body_data["form_data"] || {}
+ end
+
+ def form_data(webhook_ctx)
+ fields =
+ Schemas::FormFields.apply_query_defaults(
+ form_fields(webhook_ctx),
+ form_query_parameters(webhook_ctx),
+ )
+
+ DiscourseWorkflows::Forms::ViewModel.build(
+ fields: fields,
+ form_title: webhook_ctx.get_node_parameter("form_title", 0),
+ form_description: webhook_ctx.get_node_parameter("form_description", 0),
+ response_mode: "on_received",
+ has_downstream_form:
+ webhook_ctx
+ .get_child_nodes(webhook_ctx.get_node.name)
+ .any? { |node| node.type == "action:form" },
+ )
+ end
+
+ def form_fields(webhook_ctx)
+ Schemas::FormFields.with_keys(
+ DiscourseWorkflows::CollectionParameters.rows_from_value(
+ webhook_ctx.get_node_parameter("form_fields", 0, default: []),
+ ),
+ )
+ end
+
+ def form_mode(webhook_ctx)
+ DiscourseWorkflows::Forms::Payload.form_mode_from(webhook_ctx.trigger_data)
+ end
+
+ def form_query_parameters(webhook_ctx)
+ DiscourseWorkflows::Forms::Payload.query_parameters_from(webhook_ctx.trigger_data)
+ end
+ end
+ end
+ end
+end
diff --git a/plugins/discourse-workflows/lib/discourse_workflows/nodes/form_trigger/v1.rb b/plugins/discourse-workflows/lib/discourse_workflows/nodes/form_trigger/v1.rb
new file mode 100644
index 00000000000..a75a0448bd1
--- /dev/null
+++ b/plugins/discourse-workflows/lib/discourse_workflows/nodes/form_trigger/v1.rb
@@ -0,0 +1,80 @@
+# frozen_string_literal: true
+
+module DiscourseWorkflows
+ module Nodes
+ module FormTrigger
+ class V1 < NodeType
+ description(
+ name: NodeDataShape::FORM_TRIGGER_TYPE,
+ version: "1.0",
+ defaults: {
+ icon: "rectangle-list",
+ color: "teal",
+ },
+ properties: {
+ url_preview: {
+ type: :custom,
+ required: false,
+ ui: {
+ control: :url_preview,
+ },
+ },
+ form_title: {
+ type: :string,
+ },
+ form_description: {
+ type: :string,
+ ui: {
+ control: :textarea,
+ },
+ },
+ form_fields: Schemas::FormFields::SCHEMA,
+ authentication: {
+ type: :options,
+ required: true,
+ default: "none",
+ options: %w[none login_required],
+ no_data_expression: true,
+ },
+ response_mode: {
+ type: :options,
+ required: true,
+ default: "on_received",
+ options: %w[on_received workflow_finishes],
+ no_data_expression: true,
+ },
+ },
+ capabilities: {
+ manually_triggerable: true,
+ provides_current_user: true,
+ },
+ webhooks: [
+ { name: "default", path: WorkflowDocument.node_webhook_id_key, http_method: "GET" },
+ ],
+ )
+
+ def initialize(
+ form_data:,
+ submitted_at: Time.current.utc.iso8601(3),
+ form_mode: nil,
+ query_parameters: nil
+ )
+ super(parameters: {})
+ @form_data = form_data
+ @submitted_at = submitted_at
+ @form_mode = form_mode
+ @query_parameters = query_parameters
+ end
+
+ def output
+ DiscourseWorkflows::Forms::Payload.build(
+ @form_data,
+ submitted_at: @submitted_at,
+ form_mode: @form_mode,
+ query_parameters: @query_parameters,
+ )
+ end
+ end
+ end
+ end
+end
diff --git a/plugins/discourse-workflows/lib/discourse_workflows/nodes/group/v1.rb b/plugins/discourse-workflows/lib/discourse_workflows/nodes/group/v1.rb
new file mode 100644
index 00000000000..6c030ccab4c
--- /dev/null
+++ b/plugins/discourse-workflows/lib/discourse_workflows/nodes/group/v1.rb
@@ -0,0 +1,138 @@
+# frozen_string_literal: true
+
+module DiscourseWorkflows
+ module Nodes
+ module Group
+ class V1 < NodeType
+ OPERATIONS = %w[add remove get].freeze
+
+ description(
+ name: "action:group",
+ version: "1.0",
+ defaults: {
+ icon: "user-plus",
+ color: "indigo",
+ },
+ group: "discourse_actions",
+ capabilities: {
+ run_scope: "per_item",
+ },
+ properties: {
+ operation: {
+ type: :options,
+ required: true,
+ options: OPERATIONS,
+ default: "add",
+ ui: {
+ expression: true,
+ },
+ },
+ username: {
+ type: :string,
+ required: true,
+ display_options: {
+ show: {
+ operation: %w[add remove],
+ },
+ },
+ ui: {
+ control: :user,
+ },
+ },
+ group_id: {
+ type: :integer,
+ required: true,
+ type_options: {
+ load_options_method: "groups",
+ },
+ ui: {
+ control: :group_select,
+ },
+ control_options: {
+ value_property: "id",
+ name_property: "name",
+ filterable: true,
+ none: "discourse_workflows.group.group_id_placeholder",
+ },
+ },
+ actor_username: {
+ type: :string,
+ required: false,
+ default: "system",
+ ui: {
+ control: :user,
+ },
+ },
+ },
+ )
+
+ def self.load_options_context(context)
+ case context.method_name
+ when "groups"
+ scope = ::Group.order(:name)
+ scope = scope.where(automatic: false) unless context.get_current_node_parameter(
+ "operation",
+ ) == "get"
+
+ scope
+ .pluck(:id, :name)
+ .select { |_, name| context.matches_filter?(name) }
+ .map { |id, name| { id:, name: } }
+ end
+ end
+
+ def execute(exec_ctx)
+ items =
+ exec_ctx.input_items.map.with_index do |_item, item_index|
+ config = {
+ "operation" => exec_ctx.get_node_parameter("operation", item_index, default: "add"),
+ "username" => exec_ctx.get_node_parameter("username", item_index),
+ "group_id" => exec_ctx.get_node_parameter("group_id", item_index),
+ }
+
+ wrap(process(exec_ctx, config, item_index))
+ end
+
+ [items]
+ end
+
+ private
+
+ def process(exec_ctx, config, item_index)
+ group = ::Group.find(config["group_id"])
+ actor = exec_ctx.actor_from_parameter("actor_username", item_index)
+ guardian = actor.guardian
+ guardian.ensure_can_see_group!(group)
+ serialized_group = group_data(group, guardian)
+
+ return { group: serialized_group } if config["operation"] == "get"
+
+ guardian.ensure_can_edit_group!(group)
+
+ user = exec_ctx.find_user(username: config["username"])
+
+ logger = GroupActionLogger.new(actor, group)
+
+ case config["operation"]
+ when "remove"
+ group.remove(user)
+ logger.log_remove_user_from_group(user)
+ else
+ group.add(user)
+ logger.log_add_user_to_group(user)
+ end
+
+ { group: serialized_group, user: user_data(user, guardian) }
+ end
+
+ def group_data(group, guardian)
+ serialize_record(group, WebHookGroupSerializer, scope: guardian)
+ end
+
+ def user_data(user, guardian)
+ serialize_record(user, BasicUserSerializer, scope: guardian)
+ end
+ end
+ end
+ end
+end
diff --git a/plugins/discourse-workflows/lib/discourse_workflows/nodes/http_helpers.rb b/plugins/discourse-workflows/lib/discourse_workflows/nodes/http_helpers.rb
new file mode 100644
index 00000000000..d8c9ba66e02
--- /dev/null
+++ b/plugins/discourse-workflows/lib/discourse_workflows/nodes/http_helpers.rb
@@ -0,0 +1,59 @@
+# frozen_string_literal: true
+
+module DiscourseWorkflows
+ module Nodes
+ module HttpHelpers
+ BODY_METHODS = %i[post put patch].freeze
+ FILTERED_QUERY_VALUE = "[FILTERED]"
+
+ def normalize_headers(rows)
+ rows.each_with_object({}) do |h, headers|
+ headers[h["key"]] = h["value"] if h["key"].present?
+ end
+ end
+
+ def build_body(method, config, headers, form_params: nil)
+ return nil if BODY_METHODS.exclude?(method)
+
+ content_type = config.fetch("content_type") { "json" }
+
+ case content_type
+ when "form_urlencoded"
+ return nil if form_params.blank?
+ headers["Content-Type"] = "application/x-www-form-urlencoded"
+ URI.encode_www_form(
+ form_params.filter_map { |p| [p["key"], p["value"]] if p["key"].present? },
+ )
+ when "raw"
+ body = config["body_raw"]
+ return nil if body.blank?
+ headers["Content-Type"] = config.fetch("raw_content_type") { "text/plain" }
+ body
+ else
+ body = config["body_json"]
+ return nil if body.blank?
+ headers["Content-Type"] ||= "application/json"
+ body
+ end
+ end
+
+ def filtered_url_for_logging(url, query_params = [])
+ uri = URI.parse(url.to_s)
+ params = URI.decode_www_form(uri.query || "")
+ Array(query_params).each do |param|
+ params << [param["key"], param["value"]] if param["key"].present?
+ end
+
+ uri.query =
+ if params.any?
+ params
+ .map { |key, _| "#{URI.encode_www_form_component(key)}=#{FILTERED_QUERY_VALUE}" }
+ .join("&")
+ end
+ uri.to_s
+ rescue URI::InvalidURIError
+ "[invalid URL]"
+ end
+ end
+ end
+end
diff --git a/plugins/discourse-workflows/lib/discourse_workflows/nodes/http_request/authenticator.rb b/plugins/discourse-workflows/lib/discourse_workflows/nodes/http_request/authenticator.rb
new file mode 100644
index 00000000000..f0f5eb19ff1
--- /dev/null
+++ b/plugins/discourse-workflows/lib/discourse_workflows/nodes/http_request/authenticator.rb
@@ -0,0 +1,47 @@
+# frozen_string_literal: true
+
+module DiscourseWorkflows
+ module Nodes
+ module HttpRequest
+ class Authenticator
+ extend NodeErrorHandling
+
+ def self.apply(config, headers, exec_ctx, item_index: 0)
+ auth_mode = config.fetch("authentication") { "none" }
+ return if auth_mode == "none"
+
+ cred_data = fetch_credential_data(exec_ctx, auth_mode, item_index)
+
+ case auth_mode
+ when "basic_auth"
+ apply_basic_auth(headers, cred_data)
+ when "bearer_token"
+ apply_bearer_token(headers, cred_data)
+ end
+ end
+
+ def self.fetch_credential_data(exec_ctx, auth_mode, item_index)
+ if exec_ctx.nil?
+ raise_node_error!(
+ I18n.t("discourse_workflows.errors.http_request.exec_ctx_required", mode: auth_mode),
+ )
+ end
+ exec_ctx.get_credentials("auth", item_index)
+ end
+
+ def self.apply_basic_auth(headers, cred_data)
+ user = cred_data["user"]
+ password = cred_data["password"]
+ headers["Authorization"] = "Basic #{Base64.strict_encode64("#{user}:#{password}")}"
+ end
+
+ def self.apply_bearer_token(headers, cred_data)
+ token = cred_data["token"]
+ headers["Authorization"] = "Bearer #{token}"
+ end
+
+ private_class_method :fetch_credential_data, :apply_basic_auth, :apply_bearer_token
+ end
+ end
+ end
+end
diff --git a/plugins/discourse-workflows/lib/discourse_workflows/nodes/http_request/request_builder.rb b/plugins/discourse-workflows/lib/discourse_workflows/nodes/http_request/request_builder.rb
new file mode 100644
index 00000000000..ca434747d47
--- /dev/null
+++ b/plugins/discourse-workflows/lib/discourse_workflows/nodes/http_request/request_builder.rb
@@ -0,0 +1,56 @@
+# frozen_string_literal: true
+
+module DiscourseWorkflows
+ module Nodes
+ module HttpRequest
+ class RequestBuilder
+ include HttpHelpers
+ include NodeErrorHandling
+
+ def initialize(config, exec_ctx = nil, item_index = 0)
+ @config = config
+ @exec_ctx = exec_ctx
+ @item_index = item_index
+ end
+
+ def build
+ method = @config.fetch("method") { "GET" }.downcase.to_sym
+ if @config["url"].blank?
+ raise_node_error!(I18n.t("discourse_workflows.errors.http_request.url_required"))
+ end
+
+ uri = build_uri(@config["url"], @config["query_params"])
+ headers = (@config["headers"] || {}).to_h.compact
+ Authenticator.apply(@config, headers, @exec_ctx, item_index: @item_index)
+ body = @config.key?("body") ? @config["body"] : build_body(method, @config, headers)
+ [method, uri, headers, body]
+ end
+
+ private
+
+ def build_uri(url, query_params)
+ uri = URI.parse(url)
+ if %w[http https].exclude?(uri.scheme&.downcase)
+ raise_node_error!(I18n.t("discourse_workflows.errors.http_request.unsupported_scheme"))
+ end
+ if uri.host.blank?
+ raise_node_error!(I18n.t("discourse_workflows.errors.http_request.host_required"))
+ end
+
+ append_query_params(uri, query_params)
+ uri
+ rescue URI::InvalidURIError => e
+ raise_node_error!("Invalid URL", description: e.message)
+ end
+
+ def append_query_params(uri, query_params)
+ return if query_params.blank?
+
+ existing = URI.decode_www_form(uri.query || "")
+ query_params.each { |qp| existing << [qp["key"], qp["value"]] if qp["key"].present? }
+ uri.query = URI.encode_www_form(existing) if existing.any?
+ end
+ end
+ end
+ end
+end
diff --git a/plugins/discourse-workflows/lib/discourse_workflows/nodes/http_request/response_parser.rb b/plugins/discourse-workflows/lib/discourse_workflows/nodes/http_request/response_parser.rb
new file mode 100644
index 00000000000..91f029f64ab
--- /dev/null
+++ b/plugins/discourse-workflows/lib/discourse_workflows/nodes/http_request/response_parser.rb
@@ -0,0 +1,53 @@
+# frozen_string_literal: true
+
+module DiscourseWorkflows
+ module Nodes
+ module HttpRequest
+ class ResponseParser
+ MAX_RESPONSE_BODY_SIZE = 1.megabyte
+ MAX_ALLOWED_SIZE = 10.megabytes
+
+ def self.parse(response, max_size_kb: nil, log: nil)
+ max_size =
+ if max_size_kb
+ max_size_kb.to_i.kilobytes.clamp(1.kilobyte, MAX_ALLOWED_SIZE)
+ else
+ MAX_RESPONSE_BODY_SIZE
+ end
+ {
+ status: response.status,
+ status_message: response.respond_to?(:reason_phrase) ? response.reason_phrase : nil,
+ headers: response.headers.to_h,
+ body: parse_body(response, max_size, log),
+ }
+ end
+
+ def self.parse_body(response, max_size, log)
+ content_type = response.headers["content-type"] || ""
+ body = truncate_body(response.body, max_size, log)
+
+ if content_type.include?("application/json")
+ JSON.parse(body)
+ else
+ { "data" => body }
+ end
+ rescue JSON::ParserError
+ { "data" => body }
+ end
+
+ def self.truncate_body(raw_body, max_size, log)
+ if raw_body.is_a?(String) && raw_body.bytesize > max_size
+ log&.warn(
+ "Response body truncated from #{raw_body.bytesize} bytes to #{max_size} bytes",
+ )
+ raw_body.scrub("").byteslice(0, max_size).scrub("")
+ else
+ raw_body.to_s
+ end
+ end
+
+ private_class_method :parse_body, :truncate_body
+ end
+ end
+ end
+end
diff --git a/plugins/discourse-workflows/lib/discourse_workflows/nodes/http_request/v1.rb b/plugins/discourse-workflows/lib/discourse_workflows/nodes/http_request/v1.rb
new file mode 100644
index 00000000000..cc50353afd1
--- /dev/null
+++ b/plugins/discourse-workflows/lib/discourse_workflows/nodes/http_request/v1.rb
@@ -0,0 +1,301 @@
+# frozen_string_literal: true
+
+module DiscourseWorkflows
+ module Nodes
+ module HttpRequest
+ class V1 < NodeType
+ include HttpHelpers
+
+ description(
+ name: "action:http_request",
+ version: "1.0",
+ defaults: {
+ icon: "globe",
+ color: "indigo",
+ },
+ capabilities: {
+ run_scope: "per_item",
+ },
+ properties: {
+ method: {
+ type: :options,
+ required: true,
+ options: %w[GET POST PUT DELETE PATCH],
+ default: "GET",
+ ui: {
+ expression: true,
+ },
+ },
+ url: {
+ type: :string,
+ required: true,
+ },
+ authentication: {
+ type: :options,
+ options: %w[none basic_auth bearer_token],
+ default: "none",
+ no_data_expression: true,
+ },
+ headers: {
+ type: :fixed_collection,
+ type_options: {
+ multiple_values: true,
+ },
+ options: [
+ {
+ name: "values",
+ values: {
+ key: {
+ type: :string,
+ required: true,
+ },
+ value: {
+ type: :string,
+ required: true,
+ },
+ },
+ },
+ ],
+ },
+ query_params: {
+ type: :fixed_collection,
+ type_options: {
+ multiple_values: true,
+ },
+ options: [
+ {
+ name: "values",
+ values: {
+ key: {
+ type: :string,
+ required: true,
+ },
+ value: {
+ type: :string,
+ required: true,
+ },
+ },
+ },
+ ],
+ },
+ content_type: {
+ type: :options,
+ required: false,
+ options: %w[json form_urlencoded raw],
+ default: "json",
+ display_options: {
+ show: {
+ method: %w[POST PUT PATCH],
+ },
+ },
+ },
+ body_json: {
+ type: :string,
+ required: false,
+ display_options: {
+ show: {
+ method: %w[POST PUT PATCH],
+ content_type: ["json"],
+ },
+ },
+ ui: {
+ control: :textarea,
+ },
+ },
+ body_raw: {
+ type: :string,
+ required: false,
+ display_options: {
+ show: {
+ method: %w[POST PUT PATCH],
+ content_type: ["raw"],
+ },
+ },
+ ui: {
+ control: :textarea,
+ },
+ },
+ body_form: {
+ type: :fixed_collection,
+ required: false,
+ display_options: {
+ show: {
+ method: %w[POST PUT PATCH],
+ content_type: ["form_urlencoded"],
+ },
+ },
+ type_options: {
+ multiple_values: true,
+ },
+ options: [
+ {
+ name: "values",
+ values: {
+ key: {
+ type: :string,
+ required: true,
+ },
+ value: {
+ type: :string,
+ required: true,
+ },
+ },
+ },
+ ],
+ },
+ raw_content_type: {
+ type: :string,
+ required: false,
+ default: "text/plain",
+ display_options: {
+ show: {
+ method: %w[POST PUT PATCH],
+ content_type: ["raw"],
+ },
+ },
+ },
+ never_error: {
+ type: :boolean,
+ required: false,
+ default: false,
+ },
+ full_response: {
+ type: :boolean,
+ required: false,
+ default: false,
+ },
+ max_response_size_kb: {
+ type: :integer,
+ required: false,
+ default: 1024,
+ },
+ },
+ credentials: [
+ {
+ name: "auth",
+ credential_types: %w[basic_auth bearer_token],
+ required: false,
+ display_options: {
+ show: {
+ authentication: %w[basic_auth bearer_token],
+ },
+ },
+ label_key: "discourse_workflows.http_request.credential",
+ },
+ ],
+ )
+
+ def execute(exec_ctx)
+ items =
+ exec_ctx.input_items.flat_map.with_index do |item, item_index|
+ config = {
+ "method" => exec_ctx.get_node_parameter("method", item_index, default: "GET"),
+ "url" => exec_ctx.get_node_parameter("url", item_index),
+ "authentication" =>
+ exec_ctx.get_node_parameter("authentication", item_index, default: "none"),
+ "content_type" =>
+ exec_ctx.get_node_parameter("content_type", item_index, default: "json"),
+ "body_json" => exec_ctx.get_node_parameter("body_json", item_index),
+ "body_raw" => exec_ctx.get_node_parameter("body_raw", item_index),
+ "raw_content_type" =>
+ exec_ctx.get_node_parameter(
+ "raw_content_type",
+ item_index,
+ default: "text/plain",
+ ),
+ "never_error" =>
+ exec_ctx.get_node_parameter("never_error", item_index, default: false),
+ "full_response" =>
+ exec_ctx.get_node_parameter("full_response", item_index, default: false),
+ "max_response_size_kb" =>
+ exec_ctx.get_node_parameter("max_response_size_kb", item_index, default: 1024),
+ }
+ result = process(config, item_index, exec_ctx)
+ wrap_result(result, paired_item: exec_ctx.paired_item_for(item))
+ end
+ [items]
+ end
+
+ private
+
+ def process(config, item_index, exec_ctx)
+ method = config.fetch("method") { "GET" }.downcase.to_sym
+ headers =
+ normalize_headers(
+ exec_ctx.get_node_parameter("headers.values", item_index, default: []),
+ )
+ body =
+ build_body(
+ method,
+ config,
+ headers,
+ form_params: exec_ctx.get_node_parameter("body_form.values", item_index, default: []),
+ )
+ query_params = exec_ctx.get_node_parameter("query_params.values", item_index, default: [])
+ log_request(exec_ctx.log, method, config["url"], headers, body, query_params:)
+ response =
+ exec_ctx.http_request(
+ method: method,
+ url: config["url"],
+ headers: headers,
+ body: body,
+ item_index: item_index,
+ options: request_options(config, query_params),
+ )
+ if full_response?(config)
+ {
+ body: response.body,
+ headers: response.headers,
+ status_code: response.status,
+ status_message: response.status_message,
+ }
+ else
+ response.body
+ end
+ end
+
+ def full_response?(config)
+ config["full_response"] == true
+ end
+
+ def wrap_result(result, paired_item:)
+ if result.is_a?(Array)
+ result.map { |entry| wrap_response_body(entry, paired_item:) }
+ else
+ [wrap_response_body(result, paired_item:)]
+ end
+ end
+
+ def wrap_response_body(body, paired_item:)
+ wrap(body.is_a?(Hash) ? body : { data: body }, paired_item:)
+ end
+
+ def log_request(log, method, uri, headers, body, query_params: [])
+ log.info("#{method.to_s.upcase} #{filtered_url_for_logging(uri, query_params)}")
+ if headers.present?
+ filtered =
+ ActiveSupport::ParameterFilter.new(Rails.application.config.filter_parameters).filter(
+ headers,
+ )
+ filtered.each { |k, v| log.info("#{k}: #{v}") }
+ end
+ if body.is_a?(Hash)
+ filtered_body =
+ ActiveSupport::ParameterFilter.new(Rails.application.config.filter_parameters).filter(
+ body,
+ )
+ log.info(filtered_body.to_json)
+ elsif body.present?
+ log.info("[body omitted]")
+ end
+ end
+
+ def request_options(config, query_params)
+ config.slice("authentication", "never_error", "max_response_size_kb").merge(
+ "query_params" => query_params,
+ )
+ end
+ end
+ end
+ end
+end
diff --git a/plugins/discourse-workflows/lib/discourse_workflows/nodes/if/v1.rb b/plugins/discourse-workflows/lib/discourse_workflows/nodes/if/v1.rb
new file mode 100644
index 00000000000..2010b869e5e
--- /dev/null
+++ b/plugins/discourse-workflows/lib/discourse_workflows/nodes/if/v1.rb
@@ -0,0 +1,53 @@
+# frozen_string_literal: true
+
+module DiscourseWorkflows
+ module Nodes
+ module If
+ class V1 < NodeType
+ description(
+ name: "condition:if",
+ version: "1.0",
+ defaults: {
+ icon: "arrows-split-up-and-left",
+ color: "blue",
+ },
+ outputs: [
+ { key: "true", label_key: "discourse_workflows.branch.true" },
+ { key: "false", label_key: "discourse_workflows.branch.false" },
+ ],
+ capabilities: {
+ run_scope: "per_item",
+ },
+ properties: {
+ combinator: {
+ type: :options,
+ options: %w[and or],
+ default: "and",
+ no_data_expression: true,
+ },
+ conditions: {
+ type: :array,
+ ui: {
+ control: :condition_builder,
+ },
+ },
+ options: {
+ type: :object,
+ ui: {
+ hidden: true,
+ },
+ },
+ },
+ )
+
+ def execute(exec_ctx)
+ exec_ctx
+ .input_items
+ .each_with_index
+ .partition { |_item, item_index| exec_ctx.get_node_parameter(:conditions, item_index) }
+ .map { |items| items.map(&:first) }
+ end
+ end
+ end
+ end
+end
diff --git a/plugins/discourse-workflows/lib/discourse_workflows/nodes/limit/v1.rb b/plugins/discourse-workflows/lib/discourse_workflows/nodes/limit/v1.rb
new file mode 100644
index 00000000000..51048701849
--- /dev/null
+++ b/plugins/discourse-workflows/lib/discourse_workflows/nodes/limit/v1.rb
@@ -0,0 +1,43 @@
+# frozen_string_literal: true
+
+module DiscourseWorkflows
+ module Nodes
+ module Limit
+ class V1 < NodeType
+ description(
+ name: "action:limit",
+ version: "1.0",
+ defaults: {
+ icon: "magnifying-glass-minus",
+ color: "yellow",
+ },
+ group: "flow",
+ capabilities: {
+ run_scope: "all_items",
+ },
+ properties: {
+ max_items: {
+ type: :integer,
+ required: false,
+ default: 10,
+ min: 1,
+ },
+ keep: {
+ type: :options,
+ required: false,
+ options: %w[first last],
+ default: "first",
+ },
+ },
+ )
+
+ def execute(exec_ctx)
+ max = [exec_ctx.get_node_parameter("max_items", 0, default: 10).to_i, 1].max
+ keep = exec_ctx.get_node_parameter("keep", 0, default: "first")
+
+ [keep == "last" ? exec_ctx.input_items.last(max) : exec_ctx.input_items.first(max)]
+ end
+ end
+ end
+ end
+end
diff --git a/plugins/discourse-workflows/lib/discourse_workflows/nodes/log/v1.rb b/plugins/discourse-workflows/lib/discourse_workflows/nodes/log/v1.rb
new file mode 100644
index 00000000000..c2bc0ea9970
--- /dev/null
+++ b/plugins/discourse-workflows/lib/discourse_workflows/nodes/log/v1.rb
@@ -0,0 +1,83 @@
+# frozen_string_literal: true
+
+module DiscourseWorkflows
+ module Nodes
+ module Log
+ class V1 < NodeType
+ RUN_ONCE_FOR_ALL_ITEMS = "runOnceForAllItems"
+ RUN_ONCE_FOR_EACH_ITEM = "runOnceForEachItem"
+
+ description(
+ name: "action:log",
+ version: "1.0",
+ defaults: {
+ icon: "scroll",
+ color: "purple",
+ },
+ capabilities: {
+ produces_data: false,
+ run_scope: {
+ parameter: "mode",
+ values: {
+ RUN_ONCE_FOR_EACH_ITEM => "per_item",
+ RUN_ONCE_FOR_ALL_ITEMS => "all_items",
+ },
+ },
+ },
+ properties: {
+ mode: {
+ type: :options,
+ default: RUN_ONCE_FOR_EACH_ITEM,
+ options: [RUN_ONCE_FOR_EACH_ITEM, RUN_ONCE_FOR_ALL_ITEMS],
+ no_data_expression: true,
+ },
+ entries: {
+ type: :fixed_collection,
+ required: false,
+ type_options: {
+ multiple_values: true,
+ },
+ options: [
+ {
+ name: "values",
+ values: {
+ key: {
+ type: :string,
+ required: true,
+ no_data_expression: true,
+ },
+ value: {
+ type: :string,
+ required: true,
+ },
+ },
+ },
+ ],
+ },
+ },
+ )
+
+ def execute(exec_ctx)
+ mode = exec_ctx.get_node_parameter("mode", 0, default: RUN_ONCE_FOR_EACH_ITEM)
+
+ if mode == RUN_ONCE_FOR_ALL_ITEMS || exec_ctx.input_items.empty?
+ log_entries(exec_ctx, 0)
+ else
+ exec_ctx.input_items.each_with_index do |_item, item_index|
+ log_entries(exec_ctx, item_index)
+ end
+ end
+
+ [[]]
+ end
+
+ private
+
+ def log_entries(exec_ctx, item_index)
+ entries = exec_ctx.get_node_parameter("entries.values", item_index, default: [])
+ entries.each { |entry| exec_ctx.log.kv(entry["key"].to_s, entry["value"].to_s) }
+ end
+ end
+ end
+ end
+end
diff --git a/plugins/discourse-workflows/lib/discourse_workflows/nodes/loop_over_items/v1.rb b/plugins/discourse-workflows/lib/discourse_workflows/nodes/loop_over_items/v1.rb
new file mode 100644
index 00000000000..c737fa66940
--- /dev/null
+++ b/plugins/discourse-workflows/lib/discourse_workflows/nodes/loop_over_items/v1.rb
@@ -0,0 +1,76 @@
+# frozen_string_literal: true
+
+module DiscourseWorkflows
+ module Nodes
+ module LoopOverItems
+ class V1 < NodeType
+ description(
+ name: "flow:loop_over_items",
+ version: "1.0",
+ defaults: {
+ icon: "arrow-rotate-right",
+ color: "brown",
+ },
+ palette_visible: false,
+ outputs: [
+ { key: "done", label_key: "discourse_workflows.branch.done" },
+ { key: "loop", label_key: "discourse_workflows.branch.loop" },
+ ],
+ properties: {
+ batch_size: {
+ type: :integer,
+ required: true,
+ default: 1,
+ min: 1,
+ },
+ },
+ )
+
+ def execute(exec_ctx)
+ batch_size = exec_ctx.get_node_parameter("batch_size", 0, default: 1).to_i
+ batch_size = 1 if batch_size < 1
+
+ if exec_ctx.get_context(:node)["items"].nil?
+ execute_first(exec_ctx, batch_size)
+ else
+ execute_subsequent(exec_ctx, batch_size)
+ end
+ end
+
+ private
+
+ def execute_first(exec_ctx, batch_size)
+ node_context = exec_ctx.get_context(:node)
+ all_items = exec_ctx.input_items.dup
+ node_context["current_run_index"] = 0
+ node_context["max_run_index"] = (all_items.length.to_f / batch_size).ceil
+ node_context["processed_items"] = []
+
+ batch = all_items.shift(batch_size)
+ node_context["items"] = all_items
+ node_context["no_items_left"] = false
+ node_context["done"] = false
+
+ [[], batch]
+ end
+
+ def execute_subsequent(exec_ctx, batch_size)
+ node_context = exec_ctx.get_context(:node)
+ node_context["processed_items"].concat(exec_ctx.input_items)
+ node_context["current_run_index"] += 1
+
+ remaining = node_context["items"]
+ batch = remaining.shift(batch_size)
+
+ if batch.empty?
+ node_context["done"] = true
+ node_context["no_items_left"] = true
+ [node_context["processed_items"], []]
+ else
+ [[], batch]
+ end
+ end
+ end
+ end
+ end
+end
diff --git a/plugins/discourse-workflows/lib/discourse_workflows/nodes/manual/v1.rb b/plugins/discourse-workflows/lib/discourse_workflows/nodes/manual/v1.rb
new file mode 100644
index 00000000000..382bcdb9de5
--- /dev/null
+++ b/plugins/discourse-workflows/lib/discourse_workflows/nodes/manual/v1.rb
@@ -0,0 +1,29 @@
+# frozen_string_literal: true
+
+module DiscourseWorkflows
+ module Nodes
+ module Manual
+ class V1 < NodeType
+ description(
+ name: "trigger:manual",
+ version: "1.0",
+ defaults: {
+ icon: "arrow-pointer",
+ },
+ capabilities: {
+ manually_triggerable: true,
+ provides_current_user: true,
+ },
+ )
+
+ def initialize(*)
+ super(parameters: {})
+ end
+
+ def output
+ {}
+ end
+ end
+ end
+ end
+end
diff --git a/plugins/discourse-workflows/lib/discourse_workflows/nodes/markdown_table/v1.rb b/plugins/discourse-workflows/lib/discourse_workflows/nodes/markdown_table/v1.rb
new file mode 100644
index 00000000000..9e280382c73
--- /dev/null
+++ b/plugins/discourse-workflows/lib/discourse_workflows/nodes/markdown_table/v1.rb
@@ -0,0 +1,122 @@
+# frozen_string_literal: true
+
+module DiscourseWorkflows
+ module Nodes
+ module MarkdownTable
+ class V1 < NodeType
+ MAPPING_MODES = %w[manual auto].freeze
+
+ description(
+ name: "action:markdown_table",
+ version: "1.0",
+ defaults: {
+ icon: "table-cells",
+ color: "green",
+ },
+ group: "data",
+ capabilities: {
+ run_scope: "all_items",
+ },
+ properties: {
+ mapping_mode: {
+ type: :options,
+ required: true,
+ options: MAPPING_MODES,
+ default: "manual",
+ no_data_expression: true,
+ },
+ columns: {
+ type: :fixed_collection,
+ required: false,
+ display_options: {
+ show: {
+ mapping_mode: ["manual"],
+ },
+ },
+ type_options: {
+ multiple_values: true,
+ },
+ options: [
+ {
+ name: "values",
+ values: {
+ header: {
+ type: :string,
+ required: true,
+ no_data_expression: true,
+ },
+ value: {
+ type: :string,
+ required: true,
+ },
+ },
+ },
+ ],
+ },
+ },
+ )
+
+ def execute(exec_ctx)
+ headers, rows =
+ if exec_ctx.get_node_parameter("mapping_mode", 0, default: "manual") == "auto"
+ auto_table(exec_ctx.input_items)
+ else
+ configured_table(exec_ctx)
+ end
+
+ return [[wrap({ "markdown" => "" })]] if headers.empty?
+
+ [[wrap({ "markdown" => render_table(headers, rows) })]]
+ end
+
+ private
+
+ def auto_table(input_items)
+ headers = input_items.flat_map { |item| (item["json"] || {}).keys }.uniq
+ rows =
+ input_items.map do |item|
+ json = item["json"] || {}
+ headers.map { |key| format_cell(json[key]) }
+ end
+ [headers, rows]
+ end
+
+ def configured_table(exec_ctx)
+ columns = exec_ctx.get_node_parameter("columns.values", 0, default: [])
+ headers = columns.map { |c| c["header"].to_s }
+ rows =
+ exec_ctx.input_items.each_with_index.map do |_item, item_index|
+ resolved = exec_ctx.get_node_parameter("columns.values", item_index, default: [])
+ resolved.map { |c| format_cell(c["value"]) }
+ end
+ [headers, rows]
+ end
+
+ def render_table(headers, rows)
+ ([headers, headers.map { "---" }] + rows).map { |cells| row_line(cells) }.join("\n")
+ end
+
+ def row_line(cells)
+ "| #{cells.join(" | ")} |"
+ end
+
+ def format_cell(value)
+ raw =
+ if value.nil?
+ ""
+ elsif value.is_a?(Hash) || value.is_a?(Array)
+ JSON.generate(value)
+ else
+ value.to_s
+ end
+
+ sanitize_cell(raw)
+ end
+
+ def sanitize_cell(str)
+ str.gsub("|", "\\|").gsub(/\r\n|\n/, "<br>")
+ end
+ end
+ end
+ end
+end
diff --git a/plugins/discourse-workflows/lib/discourse_workflows/nodes/merge/v1.rb b/plugins/discourse-workflows/lib/discourse_workflows/nodes/merge/v1.rb
new file mode 100644
index 00000000000..f04a5f67614
--- /dev/null
+++ b/plugins/discourse-workflows/lib/discourse_workflows/nodes/merge/v1.rb
@@ -0,0 +1,596 @@
+# frozen_string_literal: true
+
+module DiscourseWorkflows
+ module Nodes
+ module Merge
+ class V1 < NodeType
+ description(
+ name: "flow:merge",
+ version: "1.0",
+ defaults: {
+ icon: "arrows-turn-to-dots",
+ color: "blue",
+ },
+ palette_visible: false,
+ capabilities: {
+ run_scope: "all_items",
+ },
+ inputs:
+ lambda do |configuration = {}|
+ mode = configuration.fetch("mode") { "append" }
+ if mode == "append"
+ count = [configuration.fetch("number_inputs") { 2 }.to_i, 2].max
+ count.times.map { |index| input_port(index, required: false) }
+ else
+ [input_port(0, required: false), input_port(1, required: false)]
+ end
+ end,
+ required_inputs:
+ lambda do |configuration = {}|
+ configuration.fetch("mode") { "append" } == "choose_branch" ? [0, 1] : 1
+ end,
+ properties: {
+ mode: {
+ type: :options,
+ required: true,
+ options: %w[append combine choose_branch],
+ default: "append",
+ },
+ number_inputs: {
+ type: :integer,
+ required: false,
+ default: 2,
+ min: 2,
+ display_options: {
+ show: {
+ mode: ["append"],
+ },
+ },
+ },
+ combine_by: {
+ type: :options,
+ required: false,
+ options: %w[matching_fields position all],
+ default: "matching_fields",
+ display_options: {
+ show: {
+ mode: ["combine"],
+ },
+ },
+ },
+ fields_to_match: {
+ type: :fixed_collection,
+ required: false,
+ display_options: {
+ show: {
+ mode: ["combine"],
+ combine_by: ["matching_fields"],
+ },
+ },
+ type_options: {
+ multiple_values: true,
+ },
+ options: [
+ {
+ name: "values",
+ values: {
+ field_1: {
+ type: :string,
+ required: true,
+ no_data_expression: true,
+ },
+ field_2: {
+ type: :string,
+ required: true,
+ no_data_expression: true,
+ },
+ },
+ },
+ ],
+ },
+ join_mode: {
+ type: :options,
+ required: false,
+ options: %w[
+ keep_matches
+ keep_non_matches
+ keep_everything
+ enrich_input_1
+ enrich_input_2
+ ],
+ default: "keep_matches",
+ display_options: {
+ show: {
+ mode: ["combine"],
+ combine_by: ["matching_fields"],
+ },
+ },
+ },
+ output_data_from: {
+ type: :options,
+ required: false,
+ options: %w[both input_1 input_2],
+ default: "both",
+ display_options: {
+ show: {
+ mode: ["combine"],
+ combine_by: ["matching_fields"],
+ },
+ },
+ },
+ multiple_matches: {
+ type: :options,
+ required: false,
+ options: %w[all first],
+ default: "all",
+ display_options: {
+ show: {
+ mode: ["combine"],
+ combine_by: ["matching_fields"],
+ },
+ },
+ },
+ use_data_of_input: {
+ type: :options,
+ required: false,
+ options: %w[input_1 input_2],
+ default: "input_1",
+ display_options: {
+ show: {
+ mode: ["choose_branch"],
+ },
+ },
+ },
+ choose_output: {
+ type: :options,
+ required: false,
+ options: %w[specified_input empty],
+ default: "specified_input",
+ display_options: {
+ show: {
+ mode: ["choose_branch"],
+ },
+ },
+ },
+ include_unpaired: {
+ type: :boolean,
+ required: false,
+ default: false,
+ display_options: {
+ show: {
+ mode: ["combine"],
+ combine_by: ["position"],
+ },
+ },
+ },
+ resolve_clash: {
+ type: :options,
+ required: false,
+ options: %w[prefer_last prefer_input_1 prefer_input_2 add_suffix],
+ default: "prefer_last",
+ display_options: {
+ show: {
+ mode: ["combine"],
+ },
+ },
+ },
+ merge_mode: {
+ type: :options,
+ required: false,
+ options: %w[deep_merge shallow_merge],
+ default: "deep_merge",
+ display_options: {
+ show: {
+ mode: ["combine"],
+ },
+ },
+ },
+ override_empty: {
+ type: :boolean,
+ required: false,
+ default: false,
+ display_options: {
+ show: {
+ mode: ["combine"],
+ },
+ },
+ },
+ fuzzy_compare: {
+ type: :boolean,
+ required: false,
+ default: false,
+ display_options: {
+ show: {
+ mode: ["combine"],
+ },
+ },
+ },
+ },
+ )
+
+ def execute(exec_ctx)
+ config = {
+ "mode" => exec_ctx.get_node_parameter("mode", 0, default: "append"),
+ "number_inputs" => exec_ctx.get_node_parameter("number_inputs", 0, default: 2),
+ "combine_by" =>
+ exec_ctx.get_node_parameter("combine_by", 0, default: "matching_fields"),
+ "join_mode" => exec_ctx.get_node_parameter("join_mode", 0, default: "keep_matches"),
+ "output_data_from" =>
+ exec_ctx.get_node_parameter("output_data_from", 0, default: "both"),
+ "multiple_matches" =>
+ exec_ctx.get_node_parameter("multiple_matches", 0, default: "all"),
+ "use_data_of_input" =>
+ exec_ctx.get_node_parameter("use_data_of_input", 0, default: "input_1"),
+ "choose_output" =>
+ exec_ctx.get_node_parameter("choose_output", 0, default: "specified_input"),
+ "include_unpaired" =>
+ exec_ctx.get_node_parameter("include_unpaired", 0, default: false),
+ "resolve_clash" =>
+ exec_ctx.get_node_parameter("resolve_clash", 0, default: "prefer_last"),
+ "merge_mode" => exec_ctx.get_node_parameter("merge_mode", 0, default: "deep_merge"),
+ "override_empty" => exec_ctx.get_node_parameter("override_empty", 0, default: false),
+ "fuzzy_compare" => exec_ctx.get_node_parameter("fuzzy_compare", 0, default: false),
+ }
+ fields_to_match = exec_ctx.get_node_parameter("fields_to_match.values", 0, default: [])
+ @input_item_indexes = item_indexes_by_input(exec_ctx.inputs)
+
+ items =
+ case config.fetch("mode") { "append" }
+ when "append"
+ append_inputs(exec_ctx)
+ when "choose_branch"
+ choose_branch(two_inputs(exec_ctx), config)
+ when "combine"
+ combine(two_inputs(exec_ctx), config, fields_to_match)
+ else
+ exec_ctx.input_items("main")
+ end
+
+ [items]
+ end
+
+ private
+
+ def self.input_port(index, required: true)
+ input_number = index + 1
+ {
+ key: "input_#{input_number}",
+ type: "main",
+ display_name: "Input #{input_number}",
+ label_key: "discourse_workflows.merge.input_#{input_number}",
+ required: required,
+ }
+ end
+
+ def append_inputs(exec_ctx)
+ indexed_items = exec_ctx.inputs.flatten(1)
+ return indexed_items if indexed_items.present?
+
+ exec_ctx.input_items("main")
+ end
+
+ def two_inputs(exec_ctx)
+ [exec_ctx.input_items(0), exec_ctx.input_items(1)]
+ end
+
+ def choose_branch(inputs, config)
+ return [wrap({})] if config.fetch("choose_output") { "specified_input" } == "empty"
+
+ selected_input_index(config) == 0 ? inputs[0] : inputs[1]
+ end
+
+ def combine(inputs, config, fields_to_match)
+ case config.fetch("combine_by") { "matching_fields" }
+ when "position"
+ combine_by_position(inputs, config)
+ when "all"
+ combine_all(inputs, config)
+ else
+ combine_by_fields(inputs, config, fields_to_match)
+ end
+ end
+
+ def combine_by_position(inputs, config)
+ preferred_index = preferred_input_index(config, inputs.length)
+ count =
+ if config["include_unpaired"]
+ inputs.map(&:length).max || 0
+ else
+ inputs.map(&:length).min || 0
+ end
+
+ count.times.map do |index|
+ entries = inputs.map { |input| input[index] || { "json" => {} } }
+ merge_entries(entries, config, preferred_index:)
+ end
+ end
+
+ def combine_all(inputs, config)
+ input_1, input_2 = inputs
+ return [] if input_1.blank? || input_2.blank?
+
+ preferred_index = preferred_input_index(config, inputs.length)
+ input_1.flat_map do |entry_1|
+ input_2.map { |entry_2| merge_entries([entry_1, entry_2], config, preferred_index:) }
+ end
+ end
+
+ def combine_by_fields(inputs, config, fields_to_match)
+ input_1, input_2 = inputs
+ join_mode = config.fetch("join_mode") { "keep_matches" }
+ output_data_from = config.fetch("output_data_from") { "both" }
+ fields = match_fields(fields_to_match)
+ validate_match_fields!(fields)
+ if input_1.blank? || input_2.blank?
+ return combine_by_fields_with_empty_input(input_1, input_2, join_mode, output_data_from)
+ end
+
+ matches = find_matches(input_1, input_2, fields, config)
+
+ case join_mode
+ when "keep_non_matches"
+ non_matches(matches, output_data_from)
+ when "keep_everything"
+ matched_output(matches, output_data_from, config) + matches[:unmatched_1] +
+ matches[:unmatched_2]
+ when "enrich_input_1"
+ merge_matched(matches[:matched], config) + matches[:unmatched_1]
+ when "enrich_input_2"
+ merge_matched(matches[:matched], config, preferred_index: 1) + matches[:unmatched_2]
+ else
+ matched_output(matches, output_data_from, config)
+ end
+ end
+
+ def combine_by_fields_with_empty_input(input_1, input_2, join_mode, output_data_from)
+ case join_mode
+ when "keep_non_matches"
+ case output_data_from
+ when "input_1"
+ input_1
+ when "input_2"
+ input_2
+ else
+ input_1 + input_2
+ end
+ when "keep_everything"
+ input_1 + input_2
+ when "enrich_input_1"
+ input_1.presence || []
+ when "enrich_input_2"
+ input_2.presence || []
+ else
+ []
+ end
+ end
+
+ def match_fields(fields_to_match)
+ fields_to_match.map.with_index do |field, index|
+ field_1 = field["field_1"].presence
+ field_2 = field["field_2"].presence || field_1
+ if field_1.blank? || field_2.blank?
+ raise_node_error!(
+ I18n.t("discourse_workflows.errors.merge.invalid_fields_to_match"),
+ description:
+ I18n.t(
+ "discourse_workflows.errors.merge.fields_to_match_pair_missing_fields",
+ index: index + 1,
+ ),
+ )
+ end
+
+ [field_1, field_2]
+ end
+ end
+
+ def validate_match_fields!(fields)
+ if fields.blank?
+ raise_node_error!(
+ I18n.t("discourse_workflows.errors.merge.missing_fields_to_match"),
+ description: I18n.t("discourse_workflows.errors.merge.fields_to_match_required"),
+ )
+ end
+ end
+
+ def find_matches(input_1, input_2, fields, config)
+ matched_input_2_indexes = Set.new
+ result = { matched: [], matched_2: [], unmatched_1: [], unmatched_2: [] }
+
+ input_1.each do |entry_1|
+ matches =
+ input_2.each_with_index.filter_map do |entry_2, index|
+ next unless fields_match?(entry_1, entry_2, fields, config)
+
+ matched_input_2_indexes << index
+ entry_2
+ end
+ matches = matches.first(1) if config.fetch("multiple_matches") { "all" } == "first"
+
+ if matches.any?
+ result[:matched] << [entry_1, matches]
+ else
+ result[:unmatched_1] << entry_1
+ end
+ end
+
+ input_2.each_with_index do |entry, index|
+ if matched_input_2_indexes.include?(index)
+ result[:matched_2] << entry
+ else
+ result[:unmatched_2] << entry
+ end
+ end
+
+ result
+ end
+
+ def fields_match?(entry_1, entry_2, fields, config)
+ fields.all? do |field_1, field_2|
+ present_1, value_1 = field_lookup(entry_1, field_1)
+ present_2, value_2 = field_lookup(entry_2, field_2)
+ next false if !present_1 || !present_2
+
+ compare_values(value_1, value_2, fuzzy: config["fuzzy_compare"])
+ end
+ end
+
+ def compare_values(value_1, value_2, fuzzy:)
+ fuzzy ? value_1.to_s == value_2.to_s : value_1 == value_2
+ end
+
+ def matched_output(matches, output_data_from, config)
+ case output_data_from
+ when "input_1"
+ matches[:matched].map(&:first)
+ when "input_2"
+ matches[:matched_2]
+ else
+ merge_matched(matches[:matched], config)
+ end
+ end
+
+ def non_matches(matches, output_data_from)
+ case output_data_from
+ when "input_1"
+ matches[:unmatched_1]
+ when "input_2"
+ matches[:unmatched_2]
+ else
+ matches[:unmatched_1].map { |item| add_source(item, "input_1") } +
+ matches[:unmatched_2].map { |item| add_source(item, "input_2") }
+ end
+ end
+
+ def merge_matched(matched, config, preferred_index: nil)
+ preferred_index ||= preferred_input_index(config, 2)
+ matched.flat_map do |entry_1, matches|
+ matches.map { |entry_2| merge_entries([entry_1, entry_2], config, preferred_index:) }
+ end
+ end
+
+ def merge_entries(entries, config, preferred_index:)
+ paired_items = paired_items(entries)
+ entries = suffix_entries(entries) if config["resolve_clash"] == "add_suffix"
+ ordered_entries = entries.dup
+ preferred = ordered_entries.delete_at(preferred_index) || { "json" => {} }
+ ordered_entries << preferred
+
+ wrap(
+ merge_hashes(ordered_entries.map { |entry| entry.fetch("json") { {} } }, config),
+ ).merge("pairedItem" => paired_items)
+ end
+
+ def merge_hashes(hashes, config)
+ hashes.each_with_object({}) do |hash, result|
+ if config.fetch("merge_mode") { "deep_merge" } == "shallow_merge"
+ merge_shallow!(result, hash, config)
+ else
+ merge_deep!(result, hash, config)
+ end
+ end
+ end
+
+ def merge_shallow!(target, source, config)
+ source.each { |key, value| target[key] = merged_value(target[key], value, config) }
+ target
+ end
+
+ def merge_deep!(target, source, config)
+ source.each do |key, value|
+ target[key] = if target[key].is_a?(Hash) && value.is_a?(Hash)
+ merge_deep!(target[key].dup, value, config)
+ else
+ merged_value(target[key], value, config)
+ end
+ end
+ target
+ end
+
+ def merged_value(existing, incoming, config)
+ return existing if config["override_empty"] && blank_merge_value?(incoming)
+
+ incoming
+ end
+
+ def blank_merge_value?(value)
+ value.nil? || value == ""
+ end
+
+ def suffix_entries(entries)
+ entries.map.with_index do |entry, index|
+ json =
+ entry
+ .fetch("json") { {} }
+ .each_with_object({}) do |(key, value), result|
+ result["#{key}_#{index + 1}"] = value
+ end
+ entry.merge("json" => json)
+ end
+ end
+
+ def add_source(item, source)
+ wrap(item.fetch("json") { {} }.merge("_source" => source)).merge(
+ "pairedItem" => paired_item_for_entry(item, input_index(source)),
+ ).compact
+ end
+
+ def paired_items(entries)
+ entries.each_with_index.filter_map do |entry, input_index|
+ paired_item_for_entry(entry, input_index)
+ end
+ end
+
+ def paired_item_for_entry(entry, input_index)
+ item_index = @input_item_indexes&.dig(input_index, entry.object_id)
+ return unless item_index
+
+ { "input" => input_index, "item" => item_index }
+ end
+
+ def item_indexes_by_input(inputs)
+ inputs
+ .each_with_index
+ .each_with_object({}) do |(items, input_index), indexes|
+ indexes[input_index] = items.each_with_index.to_h do |item, item_index|
+ [item.object_id, item_index]
+ end
+ end
+ end
+
+ def preferred_input_index(config, input_count)
+ case config["resolve_clash"]
+ when "prefer_input_1"
+ 0
+ when "prefer_input_2"
+ 1
+ else
+ input_count - 1
+ end
+ end
+
+ def input_index(input_name)
+ input_name.to_s == "input_2" ? 1 : 0
+ end
+
+ def selected_input_index(config)
+ config["use_data_of_input_index"] ||
+ input_index(config.fetch("use_data_of_input") { "input_1" })
+ end
+
+ def field_lookup(item, field)
+ value = item.fetch("json") { {} }
+ field
+ .to_s
+ .split(".")
+ .each do |key|
+ return false, nil unless value.is_a?(Hash) && value.key?(key)
+
+ value = value[key]
+ end
+
+ [true, value]
+ end
+ end
+ end
+ end
+end
diff --git a/plugins/discourse-workflows/lib/discourse_workflows/nodes/post_created/v1.rb b/plugins/discourse-workflows/lib/discourse_workflows/nodes/post_created/v1.rb
new file mode 100644
index 00000000000..34045c7bd27
--- /dev/null
+++ b/plugins/discourse-workflows/lib/discourse_workflows/nodes/post_created/v1.rb
@@ -0,0 +1,80 @@
+# frozen_string_literal: true
+
+module DiscourseWorkflows
+ module Nodes
+ module PostCreated
+ class V1 < NodeType
+ description(
+ name: "trigger:post_created",
+ version: "1.0",
+ defaults: {
+ icon: "comment",
+ color: "indigo",
+ },
+ group: "discourse_triggers",
+ events: [:post_created],
+ properties: {
+ category_id: {
+ type: :integer,
+ required: false,
+ ui: {
+ control: :category,
+ },
+ },
+ tag_names: {
+ type: :string,
+ required: false,
+ ui: {
+ control: :tags,
+ },
+ },
+ },
+ )
+
+ def initialize(post, opts = nil, *)
+ super(parameters: {})
+ @post = post
+ @opts = opts
+ end
+
+ def valid?
+ @post.present? && @post.topic.present? && @post.post_type == Post.types[:regular] &&
+ !@opts&.dig(:skip_workflows)
+ end
+
+ def output
+ { post: post_data(@post), topic: topic_data(@post.topic) }
+ end
+
+ def matches?(trigger_ctx)
+ topic = @post.topic
+
+ matches_category?(topic, trigger_ctx.get_node_parameter("category_id")) &&
+ matches_tags?(topic, normalize_tag_names(trigger_ctx.get_node_parameter("tag_names")))
+ end
+
+ private
+
+ def post_data(post)
+ serialize_record(post, WebHookPostSerializer)
+ end
+
+ def topic_data(topic)
+ serialize_record(topic, TopicListItemSerializer)
+ end
+
+ def matches_category?(topic, category_id)
+ category_id.blank? || topic.category_id == category_id.to_i
+ end
+
+ def matches_tags?(topic, tag_names)
+ tag_names.empty? || (topic_tag_names(topic) & tag_names).any?
+ end
+
+ def topic_tag_names(topic)
+ @topic_tag_names ||= topic.tags.pluck(:name)
+ end
+ end
+ end
+ end
+end
diff --git a/plugins/discourse-workflows/lib/discourse_workflows/nodes/respond_to_webhook/v1.rb b/plugins/discourse-workflows/lib/discourse_workflows/nodes/respond_to_webhook/v1.rb
new file mode 100644
index 00000000000..c3ee99eaaa8
--- /dev/null
+++ b/plugins/discourse-workflows/lib/discourse_workflows/nodes/respond_to_webhook/v1.rb
@@ -0,0 +1,202 @@
+# frozen_string_literal: true
+
+module DiscourseWorkflows
+ module Nodes
+ module RespondToWebhook
+ class V1 < NodeType
+ include Nodes::HttpHelpers
+
+ DEFAULT_STATUS_CODES = {
+ "redirect" => 302,
+ "json" => 200,
+ "text" => 200,
+ "no_data" => 204,
+ "first_incoming_item" => 200,
+ "all_incoming_items" => 200,
+ }
+
+ description(
+ name: "action:respond_to_webhook",
+ version: "1.0",
+ defaults: {
+ icon: "reply",
+ color: "purple",
+ },
+ properties: {
+ response_type: {
+ type: :options,
+ required: true,
+ default: "json",
+ options: %w[json redirect text no_data first_incoming_item all_incoming_items],
+ },
+ status_code: {
+ type: :string,
+ required: false,
+ default: "200",
+ display_options: {
+ show: {
+ response_type: %w[json text no_data first_incoming_item all_incoming_items],
+ },
+ },
+ },
+ redirect_url: {
+ type: :string,
+ required: true,
+ display_options: {
+ show: {
+ response_type: %w[redirect],
+ },
+ },
+ },
+ allowed_redirect_domains: {
+ type: :fixed_collection,
+ display_options: {
+ show: {
+ response_type: %w[redirect],
+ },
+ },
+ type_options: {
+ multiple_values: true,
+ },
+ options: [{ name: "values", values: { domain: { type: :string, required: true } } }],
+ },
+ response_body: {
+ type: :string,
+ required: false,
+ display_options: {
+ show: {
+ response_type: %w[json text],
+ },
+ },
+ ui: {
+ control: :textarea,
+ },
+ },
+ response_key: {
+ type: :string,
+ required: false,
+ display_options: {
+ show: {
+ response_type: %w[first_incoming_item all_incoming_items],
+ },
+ },
+ },
+ response_headers: {
+ type: :fixed_collection,
+ type_options: {
+ multiple_values: true,
+ },
+ options: [
+ {
+ name: "values",
+ values: {
+ key: {
+ type: :string,
+ required: true,
+ },
+ value: {
+ type: :string,
+ required: true,
+ },
+ },
+ },
+ ],
+ },
+ },
+ )
+
+ def execute(exec_ctx)
+ raise_node_error!("No webhook response context available") unless exec_ctx.webhook_ctx
+
+ exec_ctx.webhook_ctx.respond(build_response(exec_ctx))
+ [exec_ctx.input_items]
+ end
+
+ private
+
+ def build_response(exec_ctx)
+ item_index = 0
+ config = {
+ "response_type" =>
+ exec_ctx.get_node_parameter("response_type", item_index, default: "json"),
+ "status_code" => exec_ctx.get_node_parameter("status_code", item_index),
+ "redirect_url" => exec_ctx.get_node_parameter("redirect_url", item_index),
+ "response_body" => exec_ctx.get_node_parameter("response_body", item_index),
+ "response_key" => exec_ctx.get_node_parameter("response_key", item_index),
+ }
+
+ response_type = config.fetch("response_type") { "json" }
+ status_code = (config["status_code"].presence || DEFAULT_STATUS_CODES[response_type]).to_i
+ status_code = DEFAULT_STATUS_CODES[response_type] if response_type == "redirect"
+ headers =
+ normalize_headers(
+ exec_ctx.get_node_parameter("response_headers.values", item_index, default: []),
+ )
+
+ body =
+ case response_type
+ when "redirect"
+ redirect_url = config["redirect_url"]
+ allowed_redirect_domains =
+ normalize_allowed_redirect_domains(
+ exec_ctx.get_node_parameter(
+ "allowed_redirect_domains.values",
+ item_index,
+ default: [],
+ ),
+ )
+ unless RedirectUrlValidator.valid?(redirect_url, allowed_redirect_domains)
+ return(
+ WebhookResponse.new(body: { error: "invalid_redirect_url" }, status_code: 400)
+ )
+ end
+ headers["Location"] = redirect_url
+ nil
+ when "json"
+ parse_json_body(config["response_body"])
+ when "text"
+ headers["Content-Type"] ||= "text/plain; charset=utf-8"
+ config["response_body"].to_s
+ when "no_data"
+ nil
+ when "all_incoming_items"
+ maybe_wrap_response_key(
+ config["response_key"],
+ exec_ctx.input_items.map { |item| item["json"] || {} },
+ )
+ when "first_incoming_item"
+ maybe_wrap_response_key(
+ config["response_key"],
+ exec_ctx.input_items.dig(0, "json") || {},
+ )
+ end
+
+ WebhookResponse.new(
+ body: body,
+ headers: headers,
+ no_body: response_type == "no_data",
+ status_code: status_code,
+ )
+ end
+
+ def normalize_allowed_redirect_domains(domain_rows)
+ domain_rows.filter_map do |domain_config|
+ domain_config["domain"].to_s.strip.downcase.presence
+ end
+ end
+
+ def parse_json_body(body)
+ return body unless body.is_a?(String)
+
+ JSON.parse(body)
+ rescue JSON::ParserError
+ raise_node_error!("Invalid JSON in response_body")
+ end
+
+ def maybe_wrap_response_key(response_key, body)
+ response_key.present? ? { response_key => body } : body
+ end
+ end
+ end
+ end
+end
diff --git a/plugins/discourse-workflows/lib/discourse_workflows/nodes/schedule/payload.rb b/plugins/discourse-workflows/lib/discourse_workflows/nodes/schedule/payload.rb
new file mode 100644
index 00000000000..d6ca736075a
--- /dev/null
+++ b/plugins/discourse-workflows/lib/discourse_workflows/nodes/schedule/payload.rb
@@ -0,0 +1,33 @@
+# frozen_string_literal: true
+
+module DiscourseWorkflows
+ module Nodes
+ module Schedule
+ module Payload
+ module_function
+
+ def build(time: Time.current, timezone:)
+ local_time = time.in_time_zone(timezone)
+ hour = local_time.hour % 12
+ hour = 12 if hour.zero?
+ readable_time = "#{hour}:#{local_time.strftime("%M:%S %P")}"
+
+ {
+ "timestamp" => local_time.iso8601(3),
+ "readable_date" =>
+ "#{local_time.strftime("%B")} #{local_time.day.ordinalize} #{local_time.year}, #{readable_time}",
+ "readable_time" => readable_time,
+ "day_of_week" => local_time.strftime("%A"),
+ "year" => local_time.strftime("%Y"),
+ "month" => local_time.strftime("%B"),
+ "day_of_month" => local_time.strftime("%d"),
+ "hour" => local_time.strftime("%H"),
+ "minute" => local_time.strftime("%M"),
+ "second" => local_time.strftime("%S"),
+ "timezone" => "#{timezone} (UTC#{local_time.formatted_offset})",
+ }
+ end
+ end
+ end
+ end
+end
diff --git a/plugins/discourse-workflows/lib/discourse_workflows/nodes/schedule/recurrence.rb b/plugins/discourse-workflows/lib/discourse_workflows/nodes/schedule/recurrence.rb
new file mode 100644
index 00000000000..30eb38ba6bf
--- /dev/null
+++ b/plugins/discourse-workflows/lib/discourse_workflows/nodes/schedule/recurrence.rb
@@ -0,0 +1,81 @@
+# frozen_string_literal: true
+
+module DiscourseWorkflows
+ module Nodes
+ module Schedule
+ module Recurrence
+ module_function
+
+ def inactive
+ { activated: false }
+ end
+
+ def for_rule(interval_size:, index:, type_interval:)
+ return inactive if interval_size == 1
+
+ {
+ activated: true,
+ index: index,
+ interval_size: interval_size,
+ type_interval: type_interval,
+ }
+ end
+
+ def due?(recurrence, recurrence_rules, scheduled_at, timezone)
+ return true if !recurrence[:activated]
+
+ index = recurrence[:index]
+ current_value = value(recurrence, scheduled_at, timezone)
+ last_value = recurrence_rules[index]
+
+ return update!(recurrence_rules, index, current_value) if last_value.nil?
+
+ last_value = last_value.to_i
+ interval_size = recurrence[:interval_size]
+ due =
+ case recurrence[:type_interval]
+ when "hours"
+ exact_interval_match?(current_value, last_value, interval_size, 24)
+ when "days"
+ exact_interval_match?(current_value, last_value, interval_size, 365)
+ when "weeks"
+ exact_interval_match?(current_value, last_value, interval_size, 52) ||
+ current_value == last_value
+ when "months"
+ exact_interval_match?(current_value, last_value, interval_size, 12)
+ else
+ false
+ end
+
+ update!(recurrence_rules, index, current_value) if due
+ due
+ end
+
+ def value(recurrence, scheduled_at, timezone)
+ local_time = scheduled_at.in_time_zone(timezone)
+
+ case recurrence[:type_interval]
+ when "hours"
+ local_time.hour
+ when "days"
+ local_time.yday
+ when "weeks"
+ local_time.to_date.strftime("%U").to_i + 1
+ when "months"
+ local_time.month - 1
+ end
+ end
+
+ def update!(recurrence_rules, index, value)
+ recurrence_rules[index] = value
+ true
+ end
+
+ def exact_interval_match?(current_value, last_value, interval_size, modulus)
+ expected_difference = interval_size % modulus
+ (current_value - last_value + modulus) % modulus == expected_difference
+ end
+ end
+ end
+ end
+end
diff --git a/plugins/discourse-workflows/lib/discourse_workflows/nodes/schedule/rules.rb b/plugins/discourse-workflows/lib/discourse_workflows/nodes/schedule/rules.rb
new file mode 100644
index 00000000000..8d835fc82a4
--- /dev/null
+++ b/plugins/discourse-workflows/lib/discourse_workflows/nodes/schedule/rules.rb
@@ -0,0 +1,175 @@
+# frozen_string_literal: true
+
+require "digest"
+
+module DiscourseWorkflows
+ module Nodes
+ module Schedule
+ module Rules
+ module_function
+
+ VALID_FIELDS = %w[minutes hours days weeks months cronExpression].freeze
+
+ class Rule
+ attr_reader :data
+
+ def initialize(data)
+ @data = data.is_a?(Hash) ? data.with_indifferent_access : {}
+ end
+
+ def field
+ data[:field]
+ end
+
+ def expression
+ data[:expression]
+ end
+
+ def [](key)
+ data[key]
+ end
+ end
+
+ def validate(rules, errors)
+ if rules.empty?
+ errors.add(:base, I18n.t("discourse_workflows.errors.schedule_rules_required"))
+ return
+ end
+
+ rules.each do |rule|
+ next if valid?(rule)
+
+ errors.add(:base, I18n.t("discourse_workflows.errors.invalid_schedule_rule"))
+ break
+ end
+ end
+
+ def valid?(rule)
+ rule = wrap(rule)
+ return false if VALID_FIELDS.exclude?(rule.field)
+
+ case rule.field
+ when "minutes"
+ valid_range?(rule[:minutesInterval], 1..59, allow_nil: true)
+ when "hours"
+ valid_range?(rule[:hoursInterval], 1..23, allow_nil: true) &&
+ valid_range?(rule[:triggerAtMinute], 0..59, allow_nil: true)
+ when "days"
+ valid_range?(rule[:daysInterval], 1..31, allow_nil: true) &&
+ valid_range?(rule[:triggerAtHour], 0..23, allow_nil: true) &&
+ valid_range?(rule[:triggerAtMinute], 0..59, allow_nil: true)
+ when "weeks"
+ valid_range?(rule[:weeksInterval], 1..52, allow_nil: true) &&
+ valid_range?(rule[:triggerAtHour], 0..23, allow_nil: true) &&
+ valid_range?(rule[:triggerAtMinute], 0..59, allow_nil: true) &&
+ valid_weekdays?(rule[:triggerAtDay])
+ when "months"
+ valid_range?(rule[:monthsInterval], 1..12, allow_nil: true) &&
+ valid_range?(rule[:triggerAtDayOfMonth], 1..31, allow_nil: true) &&
+ valid_range?(rule[:triggerAtHour], 0..23, allow_nil: true) &&
+ valid_range?(rule[:triggerAtMinute], 0..59, allow_nil: true)
+ when "cronExpression"
+ CronParser.valid?(rule.expression) && CronParser.minute_granularity?(rule.expression)
+ end
+ end
+
+ def to_cron_expression(rule, node_key = "")
+ rule = wrap(rule)
+
+ case rule.field
+ when "minutes"
+ "*/#{integer_or_default(rule[:minutesInterval], 5).clamp(1, 59)} * * * *"
+ when "hours"
+ hours = integer_or_default(rule[:hoursInterval], 1).clamp(1, 23)
+ minute = integer_or_stable(rule[:triggerAtMinute], node_key, "minute", 0, 60)
+ return "#{minute} */#{hours} * * *" if (24 % hours).zero?
+
+ "#{minute} * * * *"
+ when "days"
+ minute = integer_or_stable(rule[:triggerAtMinute], node_key, "minute", 0, 60)
+ hour = integer_or_stable(rule[:triggerAtHour], node_key, "hour", 0, 24)
+ "#{minute} #{hour} * * *"
+ when "weeks"
+ minute = integer_or_stable(rule[:triggerAtMinute], node_key, "minute", 0, 60)
+ hour = integer_or_stable(rule[:triggerAtHour], node_key, "hour", 0, 24)
+ weekdays = Array.wrap(rule[:triggerAtDay]).map(&:to_i)
+ days_of_week = weekdays.empty? ? "*" : weekdays.join(",")
+ "#{minute} #{hour} * * #{days_of_week}"
+ when "months"
+ minute = integer_or_stable(rule[:triggerAtMinute], node_key, "minute", 0, 60)
+ hour = integer_or_stable(rule[:triggerAtHour], node_key, "hour", 0, 24)
+ day = integer_or_stable(rule[:triggerAtDayOfMonth], node_key, "dayOfMonth", 1, 29)
+ months = integer_or_default(rule[:monthsInterval], 1).clamp(1, 12)
+ "#{minute} #{hour} #{day} */#{months} *"
+ when "cronExpression"
+ rule.expression
+ end
+ end
+
+ def recurrence(rule, index)
+ rule = wrap(rule)
+
+ case rule.field
+ when "hours"
+ DiscourseWorkflows::Nodes::Schedule::Recurrence.for_rule(
+ interval_size: integer_or_default(rule[:hoursInterval], 1),
+ index:,
+ type_interval: "hours",
+ )
+ when "days"
+ DiscourseWorkflows::Nodes::Schedule::Recurrence.for_rule(
+ interval_size: integer_or_default(rule[:daysInterval], 1),
+ index:,
+ type_interval: "days",
+ )
+ when "weeks"
+ DiscourseWorkflows::Nodes::Schedule::Recurrence.for_rule(
+ interval_size: integer_or_default(rule[:weeksInterval], 1),
+ index:,
+ type_interval: "weeks",
+ )
+ when "months"
+ DiscourseWorkflows::Nodes::Schedule::Recurrence.for_rule(
+ interval_size: integer_or_default(rule[:monthsInterval], 1),
+ index:,
+ type_interval: "months",
+ )
+ else
+ DiscourseWorkflows::Nodes::Schedule::Recurrence.inactive
+ end
+ end
+
+ def wrap(rule)
+ rule.is_a?(Rule) ? rule : Rule.new(rule)
+ end
+
+ def valid_range?(value, range, allow_nil: false)
+ return true if allow_nil && value.nil?
+
+ range.cover?(Integer(value))
+ rescue ArgumentError, TypeError
+ false
+ end
+
+ def valid_weekdays?(days)
+ days.blank? || Array.wrap(days).all? { |day| valid_range?(day, 0..6) }
+ end
+
+ def integer_or_default(value, default)
+ value.nil? ? default : value.to_i
+ end
+
+ def integer_or_stable(value, node_key, label, min, max)
+ return value.to_i.clamp(min, max - 1) unless value.nil?
+
+ stable_int(node_key, label, min, max)
+ end
+
+ def stable_int(seed, label, min, max)
+ hash = Digest::SHA256.digest("#{seed}:#{label}")
+ min + (hash.unpack1("N") % (max - min))
+ end
+ end
+ end
+ end
+end
diff --git a/plugins/discourse-workflows/lib/discourse_workflows/nodes/schedule/v1.rb b/plugins/discourse-workflows/lib/discourse_workflows/nodes/schedule/v1.rb
new file mode 100644
index 00000000000..89306b49cd8
--- /dev/null
+++ b/plugins/discourse-workflows/lib/discourse_workflows/nodes/schedule/v1.rb
@@ -0,0 +1,270 @@
+# frozen_string_literal: true
+
+module DiscourseWorkflows
+ module Nodes
+ module Schedule
+ class V1 < NodeType
+ HOUR_OPTIONS = (0..23).to_a.freeze
+ WEEKDAY_OPTIONS = [1, 2, 3, 4, 5, 6, 0].freeze
+
+ description(
+ name: "trigger:schedule",
+ version: "1.0",
+ defaults: {
+ icon: "calendar-days",
+ color: "orange",
+ },
+ properties: {
+ rule: {
+ type: :fixed_collection,
+ required: true,
+ type_options: {
+ multiple_values: true,
+ },
+ ui: {
+ flat: true,
+ },
+ options: [
+ {
+ name: "interval",
+ values: {
+ field: {
+ type: :options,
+ required: true,
+ default: "days",
+ options: %w[minutes hours days weeks months cronExpression],
+ no_data_expression: true,
+ },
+ minutesInterval: {
+ type: :integer,
+ default: 5,
+ min: 1,
+ max: 59,
+ display_options: {
+ show: {
+ field: %w[minutes],
+ },
+ },
+ no_data_expression: true,
+ },
+ hoursInterval: {
+ type: :integer,
+ default: 1,
+ min: 1,
+ max: 23,
+ display_options: {
+ show: {
+ field: %w[hours],
+ },
+ },
+ no_data_expression: true,
+ },
+ daysInterval: {
+ type: :integer,
+ default: 1,
+ min: 1,
+ max: 31,
+ display_options: {
+ show: {
+ field: %w[days],
+ },
+ },
+ no_data_expression: true,
+ },
+ weeksInterval: {
+ type: :integer,
+ default: 1,
+ min: 1,
+ max: 52,
+ display_options: {
+ show: {
+ field: %w[weeks],
+ },
+ },
+ no_data_expression: true,
+ },
+ monthsInterval: {
+ type: :integer,
+ default: 1,
+ min: 1,
+ max: 12,
+ display_options: {
+ show: {
+ field: %w[months],
+ },
+ },
+ no_data_expression: true,
+ },
+ triggerAtDay: {
+ type: :multi_options,
+ default: [0],
+ options: WEEKDAY_OPTIONS,
+ display_options: {
+ show: {
+ field: %w[weeks],
+ },
+ },
+ control_options: {
+ option_format: :weekday,
+ },
+ },
+ triggerAtDayOfMonth: {
+ type: :integer,
+ default: 1,
+ min: 1,
+ max: 31,
+ display_options: {
+ show: {
+ field: %w[months],
+ },
+ },
+ no_data_expression: true,
+ },
+ triggerAtHour: {
+ type: :options,
+ default: 0,
+ options: HOUR_OPTIONS,
+ display_options: {
+ show: {
+ field: %w[days weeks months],
+ },
+ },
+ no_data_expression: true,
+ ui: {
+ control: :combo_box,
+ },
+ control_options: {
+ option_format: :hour_of_day,
+ },
+ },
+ triggerAtMinute: {
+ type: :integer,
+ default: 0,
+ min: 0,
+ max: 59,
+ display_options: {
+ show: {
+ field: %w[hours days weeks months],
+ },
+ },
+ no_data_expression: true,
+ },
+ expression: {
+ type: :string,
+ validate: :cron,
+ display_options: {
+ show: {
+ field: %w[cronExpression],
+ },
+ },
+ },
+ },
+ },
+ ],
+ },
+ },
+ capabilities: {
+ activation_trigger: true,
+ manually_triggerable: true,
+ synthesizes_manual_data: true,
+ },
+ )
+
+ def initialize(*)
+ super(parameters: {})
+ end
+
+ def self.validate_configuration(configuration, errors)
+ Rules.validate(CollectionParameters.rows(configuration, :rule, group: "interval"), errors)
+ end
+
+ def trigger(trigger_ctx)
+ rules = trigger_ctx.get_node_parameter("rule.interval", [])
+ timezone = trigger_ctx.get_timezone
+ node_key = "#{trigger_ctx.workflow_id}:#{trigger_ctx.node_id}"
+ schedules =
+ rules.map.with_index do |rule, index|
+ {
+ rule: rule,
+ rule_index: index,
+ cron_expression: Rules.to_cron_expression(rule, node_key),
+ recurrence: Rules.recurrence(rule, index),
+ }
+ end
+
+ if trigger_ctx.get_mode == "manual"
+ return(
+ {
+ manual_trigger_function:
+ lambda do
+ schedule = schedules.first
+ if schedule
+ execute_trigger(
+ trigger_ctx,
+ schedule[:recurrence],
+ rule_index: schedule[:rule_index],
+ timezone:,
+ skip_recurrence_check: true,
+ deduplicate: false,
+ )
+ end
+ end,
+ }
+ )
+ end
+
+ schedules.each do |schedule|
+ trigger_ctx
+ .helpers
+ .register_cron(
+ { expression: schedule[:cron_expression], recurrence: schedule[:recurrence] },
+ ) do |scheduled_time|
+ execute_trigger(
+ trigger_ctx,
+ schedule[:recurrence],
+ rule_index: schedule[:rule_index],
+ timezone:,
+ scheduled_time:,
+ )
+ end
+ end
+
+ {}
+ end
+
+ private
+
+ def execute_trigger(
+ trigger_ctx,
+ recurrence,
+ rule_index:,
+ timezone:,
+ scheduled_time: Time.current.utc,
+ skip_recurrence_check: false,
+ deduplicate: true
+ )
+ static_data = trigger_ctx.get_workflow_static_data(:node)
+ recurrence_rules = static_data["recurrenceRules"] ||= []
+ if !skip_recurrence_check &&
+ !Recurrence.due?(recurrence, recurrence_rules, scheduled_time, timezone)
+ return
+ end
+
+ trigger_ctx.emit(
+ [
+ trigger_ctx.helpers.return_json_array(
+ [Payload.build(time: scheduled_time, timezone:)],
+ ),
+ ],
+ deduplication_key:
+ (
+ if deduplicate
+ "#{trigger_ctx.workflow_id}:#{trigger_ctx.node_id}:#{rule_index}:#{scheduled_time.utc.iso8601}"
+ end
+ ),
+ )
+ end
+ end
+ end
+ end
+end
diff --git a/plugins/discourse-workflows/lib/discourse_workflows/nodes/set_fields/v1.rb b/plugins/discourse-workflows/lib/discourse_workflows/nodes/set_fields/v1.rb
new file mode 100644
index 00000000000..14e8dea8b97
--- /dev/null
+++ b/plugins/discourse-workflows/lib/discourse_workflows/nodes/set_fields/v1.rb
@@ -0,0 +1,289 @@
+# frozen_string_literal: true
+
+module DiscourseWorkflows
+ module Nodes
+ module SetFields
+ class V1 < NodeType
+ description(
+ name: "action:set_fields",
+ version: "1.0",
+ defaults: {
+ icon: "list",
+ color: "green",
+ },
+ group: "data",
+ capabilities: {
+ run_scope: "per_item",
+ },
+ properties: {
+ mode: {
+ type: :options,
+ required: false,
+ options: %w[manual raw],
+ default: "manual",
+ },
+ assignments: {
+ type: :assignment_collection,
+ required: false,
+ default: {
+ assignments: [],
+ },
+ type_options: {
+ assignment_types: %w[string number boolean array object],
+ },
+ display_options: {
+ show: {
+ mode: ["manual"],
+ },
+ },
+ },
+ json_output: {
+ type: :string,
+ required: false,
+ display_options: {
+ show: {
+ mode: ["raw"],
+ },
+ },
+ no_data_expression: true,
+ ui: {
+ control: :code,
+ },
+ control_options: {
+ height: 200,
+ lang: :json,
+ },
+ },
+ include_other_fields: {
+ type: :boolean,
+ required: false,
+ default: true,
+ },
+ include: {
+ type: :options,
+ required: false,
+ options: %w[all selected except],
+ default: "all",
+ display_options: {
+ show: {
+ include_other_fields: [true],
+ },
+ },
+ },
+ include_fields: {
+ type: :string,
+ required: false,
+ display_options: {
+ show: {
+ include_other_fields: [true],
+ include: ["selected"],
+ },
+ },
+ },
+ exclude_fields: {
+ type: :string,
+ required: false,
+ display_options: {
+ show: {
+ include_other_fields: [true],
+ include: ["except"],
+ },
+ },
+ },
+ options: {
+ type: :collection,
+ required: false,
+ options: [
+ { name: "dot_notation", type: :boolean, default: true },
+ { name: "ignore_conversion_errors", type: :boolean, default: false },
+ ],
+ },
+ },
+ )
+
+ def execute(exec_ctx)
+ items =
+ exec_ctx.input_items.map.with_index do |item, item_index|
+ config = {
+ "mode" => exec_ctx.get_node_parameter("mode", item_index, default: "manual"),
+ "json_output" => exec_ctx.get_node_parameter("json_output", item_index),
+ "include_other_fields" =>
+ exec_ctx.get_node_parameter("include_other_fields", item_index, default: true),
+ "include" => exec_ctx.get_node_parameter("include", item_index, default: "all"),
+ "include_fields" => exec_ctx.get_node_parameter("include_fields", item_index),
+ "exclude_fields" => exec_ctx.get_node_parameter("exclude_fields", item_index),
+ }
+
+ wrap(process(exec_ctx, item, item_index, config))
+ end
+
+ [items]
+ end
+
+ private
+
+ def process(exec_ctx, item, item_index, config)
+ item_json = item.fetch("json") { {} }
+ options = exec_ctx.get_node_parameter("options", item_index, default: {})
+ result = included_fields(item_json, config, options)
+
+ if config["mode"] == "raw"
+ result.merge(parse_json_fields(config))
+ else
+ apply_assignments(
+ result,
+ exec_ctx.get_node_parameter("assignments.assignments", item_index, default: []),
+ options,
+ )
+ end
+ end
+
+ def included_fields(item_json, config, options)
+ return {} unless config.fetch("include_other_fields", true)
+
+ dot_notation = dot_notation?(options)
+ fields =
+ case config.fetch("include") { "all" }
+ when "selected"
+ selected_fields(item_json, config["include_fields"], dot_notation)
+ when "except"
+ except_fields(item_json, config["exclude_fields"], dot_notation)
+ else
+ item_json.deep_dup
+ end
+
+ fields || {}
+ end
+
+ def parse_json_fields(config)
+ raw_json = config["json_output"]
+ if raw_json.blank?
+ raise_node_error!(I18n.t("discourse_workflows.errors.set_fields.json_blank"))
+ end
+
+ parsed = JSON.parse(raw_json)
+ unless parsed.is_a?(Hash)
+ raise_node_error!(I18n.t("discourse_workflows.errors.set_fields.json_must_be_object"))
+ end
+
+ parsed
+ rescue JSON::ParserError => e
+ raise_node_error!("Invalid JSON", description: e.message)
+ end
+
+ def apply_assignments(result, assignments, options)
+ dot_notation = dot_notation?(options)
+ ignore_errors = options.fetch("ignore_conversion_errors", false)
+
+ assignments.each do |field|
+ key = field["name"].to_s
+ next if key.blank?
+
+ value = cast_value(field["value"], field.fetch("type") { "string" }, ignore_errors)
+ set_field(result, key, value, dot_notation)
+ end
+
+ result
+ end
+
+ def selected_fields(item_json, field_list, dot_notation)
+ split_fields(field_list).each_with_object({}) do |field, result|
+ value = get_field(item_json, field, dot_notation)
+ next if value.nil?
+
+ output_field = dot_notation && field.include?(".") ? field.split(".").last : field
+ set_field(result, output_field, value, dot_notation)
+ end
+ end
+
+ def except_fields(item_json, field_list, dot_notation)
+ result = item_json.deep_dup
+ split_fields(field_list).each { |field| unset_field(result, field, dot_notation) }
+ result
+ end
+
+ def split_fields(field_list)
+ field_list.to_s.split(",").map(&:strip).reject(&:blank?)
+ end
+
+ def dot_notation?(options)
+ options.fetch("dot_notation", true)
+ end
+
+ def cast_value(value, type, ignore_errors)
+ cast_value!(value, type, ignore_errors)
+ rescue JSON::ParserError, ArgumentError => e
+ return value if ignore_errors
+
+ raise_node_error!("Invalid field value", description: e.message)
+ end
+
+ def cast_value!(value, type, ignore_errors)
+ case type
+ when "integer"
+ Integer(value)
+ when "float"
+ Float(value)
+ when "number"
+ Float(value)
+ when "boolean"
+ return value if value == true || value == false
+
+ %w[true 1].include?(value.to_s.downcase)
+ when "array"
+ cast_json_value(value, Array, ignore_errors)
+ when "object"
+ cast_json_value(value, Hash, ignore_errors)
+ else
+ value.to_s
+ end
+ end
+
+ def cast_json_value(value, expected_class, ignore_errors)
+ return value if value.is_a?(expected_class)
+
+ parsed = JSON.parse(value.to_s)
+ return parsed if parsed.is_a?(expected_class)
+ return value if ignore_errors
+
+ expected_type = expected_class == Array ? "array" : "object"
+ raise_node_error!("Invalid field value", description: "Expected #{expected_type}")
+ end
+
+ def set_field(result, field, value, dot_notation)
+ unless dot_notation && field.include?(".")
+ result[field] = value
+ return
+ end
+
+ keys = field.split(".")
+ leaf = keys.pop
+ target = result
+ keys.each do |key|
+ target[key] = {} unless target[key].is_a?(Hash)
+ target = target[key]
+ end
+ target[leaf] = value
+ end
+
+ def get_field(hash, field, dot_notation)
+ return hash[field] unless dot_notation && field.include?(".")
+
+ field.split(".").reduce(hash) { |value, key| value.is_a?(Hash) ? value[key] : nil }
+ end
+
+ def unset_field(hash, field, dot_notation)
+ unless dot_notation && field.include?(".")
+ hash.delete(field)
+ return
+ end
+
+ keys = field.split(".")
+ leaf = keys.pop
+ target = keys.reduce(hash) { |value, key| value.is_a?(Hash) ? value[key] : nil }
+ target.delete(leaf) if target.is_a?(Hash)
+ end
+ end
+ end
+ end
+end
diff --git a/plugins/discourse-workflows/lib/discourse_workflows/nodes/sort/v1.rb b/plugins/discourse-workflows/lib/discourse_workflows/nodes/sort/v1.rb
new file mode 100644
index 00000000000..5967462657a
--- /dev/null
+++ b/plugins/discourse-workflows/lib/discourse_workflows/nodes/sort/v1.rb
@@ -0,0 +1,190 @@
+# frozen_string_literal: true
+
+module DiscourseWorkflows
+ module Nodes
+ module Sort
+ class V1 < NodeType
+ RUN_CODE = "runCode"
+
+ description(
+ name: "action:sort",
+ version: "1.0",
+ defaults: {
+ icon: "arrow-down-a-z",
+ color: "yellow",
+ },
+ group: "flow",
+ capabilities: {
+ run_scope: "all_items",
+ },
+ properties: {
+ type: {
+ type: :options,
+ required: true,
+ options: %w[simple random code],
+ default: "simple",
+ },
+ sort_fields: {
+ type: :fixed_collection,
+ required: false,
+ display_options: {
+ show: {
+ type: ["simple"],
+ },
+ },
+ type_options: {
+ multiple_values: true,
+ },
+ options: [
+ {
+ name: "values",
+ values: {
+ field_name: {
+ type: :string,
+ required: true,
+ no_data_expression: true,
+ },
+ order: {
+ type: :options,
+ required: true,
+ options: %w[ascending descending],
+ default: "ascending",
+ },
+ },
+ },
+ ],
+ },
+ code: {
+ type: :string,
+ required: false,
+ display_options: {
+ show: {
+ type: ["code"],
+ },
+ },
+ no_data_expression: true,
+ default: <<~JS.strip,
+ // The two items to compare are in the variables a and b
+ // Access the fields via a.json and b.json
+ // Return -1 if a should go before b
+ // Return 1 if b should go before a
+ // Return 0 if there's no difference
+
+ if (a.json.myField < b.json.myField) {
+ return -1;
+ }
+ if (a.json.myField > b.json.myField) {
+ return 1;
+ }
+ return 0;
+ JS
+ ui: {
+ control: :code,
+ },
+ control_options: {
+ height: 200,
+ lang: :javascript,
+ },
+ },
+ },
+ )
+
+ def execute(exec_ctx)
+ type = exec_ctx.get_node_parameter("type", 0, default: "simple")
+ config = { "type" => type, "code" => exec_ctx.get_node_parameter("code", 0) }
+
+ items =
+ case type
+ when "simple"
+ sort_simple(exec_ctx)
+ when "random"
+ sort_random(exec_ctx.input_items)
+ when "code"
+ sort_code(exec_ctx, config)
+ else
+ exec_ctx.input_items.dup
+ end
+ [items]
+ end
+
+ private
+
+ def sort_simple(exec_ctx)
+ sort_fields = exec_ctx.get_node_parameter("sort_fields.values", 0, default: [])
+ return exec_ctx.input_items.dup if sort_fields.blank?
+
+ exec_ctx.input_items.sort { |a, b| compare_items(a, b, sort_fields) }
+ end
+
+ def compare_items(a, b, sort_fields)
+ sort_fields.each do |field|
+ field_name = field["field_name"]
+ direction = field["order"] == "descending" ? -1 : 1
+
+ val_a = dig_field(a.fetch("json") { {} }, field_name)
+ val_b = dig_field(b.fetch("json") { {} }, field_name)
+
+ val_a = val_a.downcase if val_a.is_a?(String)
+ val_b = val_b.downcase if val_b.is_a?(String)
+
+ cmp = (val_a <=> val_b)
+
+ cmp = nil_aware_compare(val_a, val_b) if cmp.nil?
+
+ return cmp * direction unless cmp == 0
+ end
+
+ 0
+ end
+
+ def nil_aware_compare(a, b)
+ return 0 if a.nil? && b.nil?
+ return -1 if a.nil?
+ return 1 if b.nil?
+ 0
+ end
+
+ def dig_field(hash, field_name)
+ field_name.split(".").reduce(hash) { |obj, key| obj.is_a?(Hash) ? obj[key] : nil }
+ end
+
+ def sort_random(input_items)
+ input_items.shuffle
+ end
+
+ def sort_code(exec_ctx, config)
+ code = config["code"].to_s
+ unless code.match?(/\breturn\b/)
+ raise_node_error!(I18n.t("discourse_workflows.errors.sort.code_missing_return"))
+ end
+
+ items = exec_ctx.input_items.map(&:deep_dup)
+ execution_result =
+ exec_ctx.start_job(
+ "javascript",
+ {
+ code: "return items.sort(function(a, b) { #{code} });",
+ nodeMode: RUN_CODE,
+ workflowMode: exec_ctx.get_mode,
+ continueOnFail: exec_ctx.continue_on_fail,
+ additionalProperties: {
+ "items" => items,
+ },
+ },
+ 0,
+ )
+
+ raise execution_result.error if execution_result.error.is_a?(Exception)
+ unless execution_result.ok
+ raise_node_error!(
+ I18n.t("discourse_workflows.errors.javascript_execution_failed"),
+ description: execution_result.error.to_s,
+ )
+ end
+
+ execution_result.result
+ end
+ end
+ end
+ end
+end
diff --git a/plugins/discourse-workflows/lib/discourse_workflows/nodes/split_out/v1.rb b/plugins/discourse-workflows/lib/discourse_workflows/nodes/split_out/v1.rb
new file mode 100644
index 00000000000..d6469f484be
--- /dev/null
+++ b/plugins/discourse-workflows/lib/discourse_workflows/nodes/split_out/v1.rb
@@ -0,0 +1,261 @@
+# frozen_string_literal: true
+
+module DiscourseWorkflows
+ module Nodes
+ module SplitOut
+ class V1 < NodeType
+ MAX_SPLIT_ITEMS = 1_000
+
+ description(
+ name: "action:split_out",
+ version: "1.0",
+ defaults: {
+ icon: "arrows-turn-to-dots",
+ color: "yellow",
+ },
+ group: "flow",
+ palette_visible: false,
+ capabilities: {
+ run_scope: "per_item",
+ },
+ properties: {
+ field: {
+ type: :string,
+ required: true,
+ },
+ include: {
+ type: :options,
+ required: false,
+ options: %w[no_other_fields all_other_fields selected_other_fields],
+ default: "no_other_fields",
+ ui: {
+ expression: true,
+ },
+ },
+ fields_to_include: {
+ type: :string,
+ required: false,
+ },
+ destination_field_name: {
+ type: :string,
+ required: false,
+ },
+ },
+ )
+
+ def execute(exec_ctx)
+ field_tracker = {}
+ items =
+ exec_ctx.input_items.flat_map.with_index do |item, item_index|
+ config =
+ split_config(
+ {
+ "field" => exec_ctx.get_node_parameter("field", item_index),
+ "include" =>
+ exec_ctx.get_node_parameter(
+ "include",
+ item_index,
+ default: "no_other_fields",
+ ),
+ "fields_to_include" =>
+ exec_ctx.get_node_parameter("fields_to_include", item_index),
+ "destination_field_name" =>
+ exec_ctx.get_node_parameter("destination_field_name", item_index),
+ "disable_dot_notation" =>
+ exec_ctx.get_node_parameter("disable_dot_notation", item_index),
+ },
+ )
+
+ split_item(item, config, exec_ctx.paired_item_for(item), field_tracker)
+ end
+
+ add_missing_field_hints(exec_ctx, field_tracker)
+
+ [items]
+ end
+
+ private
+
+ def split_config(config)
+ field_names = parse_field_names(config["field"])
+ dest_names = parse_field_names(config["destination_field_name"])
+
+ if dest_names.present? && dest_names.length != field_names.length
+ raise_node_error!(
+ I18n.t("discourse_workflows.errors.split_out.destination_count_mismatch"),
+ )
+ end
+
+ {
+ field_names: field_names,
+ include_mode: config.fetch("include") { "no_other_fields" },
+ dest_names: dest_names,
+ fields_to_include: parse_field_names(config["fields_to_include"]),
+ disable_dot_notation: truthy?(config["disable_dot_notation"]),
+ }
+ end
+
+ def parse_field_names(value)
+ return [] if value.blank?
+ value.to_s.split(",").filter_map { |v| v.strip.sub(/\A\$json\./, "").presence }
+ end
+
+ def truthy?(value)
+ value == true || value.to_s == "true"
+ end
+
+ def fetch_field(hash, field_name, disable_dot_notation)
+ return hash.key?(field_name), hash[field_name] if disable_dot_notation
+
+ current = hash
+ field_name
+ .split(".")
+ .each do |key|
+ return false, nil unless current.is_a?(Hash) && current.key?(key)
+
+ current = current[key]
+ end
+
+ [true, current]
+ end
+
+ def unset_field(hash, field_name, disable_dot_notation)
+ if disable_dot_notation
+ hash.delete(field_name)
+ return
+ end
+
+ keys = field_name.split(".")
+ current = hash
+ keys[0..-2].each do |key|
+ current = current.is_a?(Hash) ? current[key] : nil
+ break unless current
+ end
+ current.delete(keys.last) if current.is_a?(Hash)
+ end
+
+ def coerce_to_array(value)
+ return value if value.is_a?(Array)
+ return value.values if value.is_a?(Hash)
+
+ [value]
+ end
+
+ def split_item(item, config, paired_item, field_tracker)
+ item_json = item.fetch("json") { {} }
+ field_names = config[:field_names]
+ multi_split = field_names.length > 1
+ entries = []
+
+ field_names.each_with_index do |field_name, field_index|
+ field_tracker[field_name] = false unless field_tracker.key?(field_name)
+ exists, value = fetch_field(item_json, field_name, config[:disable_dot_notation])
+ field_tracker[field_name] = true if exists
+ next unless exists
+
+ elements = coerce_to_array(value)
+
+ next if elements.empty?
+
+ if elements.length > MAX_SPLIT_ITEMS
+ raise_node_error!(
+ I18n.t(
+ "discourse_workflows.errors.split_out.too_many_items",
+ max: MAX_SPLIT_ITEMS,
+ count: elements.length,
+ ),
+ )
+ end
+
+ elements.each_with_index do |element, element_index|
+ entries[element_index] ||= { "json" => {} }
+ write_split_element(
+ entries[element_index]["json"],
+ element,
+ field_name,
+ config[:dest_names][field_index],
+ config[:include_mode],
+ multi_split,
+ )
+ end
+ end
+
+ entries.map do |entry|
+ json =
+ apply_include_mode(
+ entry["json"],
+ item_json,
+ config[:include_mode],
+ field_names,
+ config[:fields_to_include],
+ config[:disable_dot_notation],
+ )
+ wrap(json, paired_item:)
+ end
+ end
+
+ def write_split_element(
+ entry,
+ element,
+ field_name,
+ destination_field_name,
+ include_mode,
+ multi_split
+ )
+ output_field_name = destination_field_name.presence || field_name
+
+ if element.is_a?(Hash) && include_mode == "no_other_fields" &&
+ destination_field_name.blank? && !multi_split
+ entry.merge!(element.deep_stringify_keys)
+ else
+ entry[output_field_name] = element
+ end
+ end
+
+ def apply_include_mode(
+ entry,
+ item_json,
+ include_mode,
+ field_names,
+ fields_to_include,
+ disable_dot_notation
+ )
+ case include_mode
+ when "all_other_fields"
+ base = item_json.deep_dup
+ field_names.each { |f| unset_field(base, f, disable_dot_notation) }
+ base.merge(entry)
+ when "selected_other_fields"
+ if fields_to_include.empty?
+ raise_node_error!(
+ I18n.t("discourse_workflows.errors.split_out.fields_to_include_required"),
+ )
+ end
+
+ fields_to_include.each do |f|
+ _, val = fetch_field(item_json, f, disable_dot_notation)
+ entry[f] = val
+ end
+ entry
+ else
+ entry
+ end
+ end
+
+ def add_missing_field_hints(exec_ctx, field_tracker)
+ field_tracker.each do |field, found|
+ next if found
+
+ exec_ctx.add_execution_hints(
+ {
+ message:
+ I18n.t("discourse_workflows.hints.split_out.field_not_found", field: field),
+ location: "outputPane",
+ },
+ )
+ end
+ end
+ end
+ end
+ end
+end
diff --git a/plugins/discourse-workflows/lib/discourse_workflows/nodes/stale_topic/v1.rb b/plugins/discourse-workflows/lib/discourse_workflows/nodes/stale_topic/v1.rb
new file mode 100644
index 00000000000..575afa4e857
--- /dev/null
+++ b/plugins/discourse-workflows/lib/discourse_workflows/nodes/stale_topic/v1.rb
@@ -0,0 +1,85 @@
+# frozen_string_literal: true
+
+module DiscourseWorkflows
+ module Nodes
+ module StaleTopic
+ class V1 < NodeType
+ description(
+ name: "trigger:stale_topic",
+ version: "1.0",
+ defaults: {
+ icon: "clock",
+ color: "deep-orange",
+ },
+ group: "discourse_triggers",
+ properties: {
+ hours: {
+ type: :integer,
+ required: true,
+ default: 24,
+ min: 1,
+ },
+ category_id: {
+ type: :integer,
+ required: false,
+ ui: {
+ control: :category,
+ },
+ },
+ tag_names: {
+ type: :string,
+ required: false,
+ ui: {
+ control: :tags,
+ },
+ },
+ },
+ capabilities: {
+ manually_triggerable: true,
+ },
+ )
+
+ MAX_TOPICS_PER_RUN = 100
+
+ def self.trigger_data_for(trigger_ctx)
+ hours = trigger_ctx.get_node_parameter("hours", 24)
+ category_id = trigger_ctx.get_node_parameter("category_id").presence&.to_i
+ tag_names = normalize_tag_names(trigger_ctx.get_node_parameter("tag_names"))
+
+ stale_topics(
+ hours: hours,
+ category_id: category_id,
+ tag_names: tag_names,
+ limit: MAX_TOPICS_PER_RUN,
+ ).map { |topic| { topic: topic_data(topic) } }
+ end
+
+ def self.stale_topics(hours:, category_id: nil, tag_names: [], limit:)
+ threshold = hours.to_i.clamp(1..).hours.ago
+
+ scope =
+ ::Topic
+ .where("GREATEST(topics.created_at, topics.last_posted_at) < ?", threshold)
+ .where(closed: false, archived: false, visible: true)
+ .where("topics.archetype = ?", Archetype.default)
+ .includes(first_post: :user)
+
+ scope = scope.where(category_id: category_id) if category_id
+ scope = scope.joins(:tags).where(tags: { name: tag_names }).distinct if tag_names.any?
+
+ scope.limit(limit).to_a
+ end
+
+ def self.topic_data(topic)
+ MultiJson.load(
+ TopicListItemSerializer.new(
+ topic,
+ scope: Discourse.system_user.guardian,
+ root: false,
+ ).to_json,
+ ).deep_symbolize_keys
+ end
+ end
+ end
+ end
+end
diff --git a/plugins/discourse-workflows/lib/discourse_workflows/nodes/sticky_note/v1.rb b/plugins/discourse-workflows/lib/discourse_workflows/nodes/sticky_note/v1.rb
new file mode 100644
index 00000000000..5b58fb0c8d4
--- /dev/null
+++ b/plugins/discourse-workflows/lib/discourse_workflows/nodes/sticky_note/v1.rb
@@ -0,0 +1,43 @@
+# frozen_string_literal: true
+
+module DiscourseWorkflows
+ module Nodes
+ module StickyNote
+ class V1 < NodeType
+ description(
+ name: "flow:sticky_note",
+ version: "1.0",
+ defaults: {
+ icon: "note-sticky",
+ color: "yellow",
+ },
+ palette_visible: false,
+ inputs: [],
+ outputs: [],
+ properties: {
+ content: {
+ type: :string,
+ required: false,
+ },
+ height: {
+ type: :integer,
+ required: false,
+ },
+ width: {
+ type: :integer,
+ required: false,
+ },
+ color: {
+ type: :string,
+ required: false,
+ },
+ },
+ )
+
+ def execute(exec_ctx)
+ [exec_ctx.input_items]
+ end
+ end
+ end
+ end
+end
diff --git a/plugins/discourse-workflows/lib/discourse_workflows/nodes/topic/v1.rb b/plugins/discourse-workflows/lib/discourse_workflows/nodes/topic/v1.rb
new file mode 100644
index 00000000000..8251d91d3fb
--- /dev/null
+++ b/plugins/discourse-workflows/lib/discourse_workflows/nodes/topic/v1.rb
@@ -0,0 +1,215 @@
+# frozen_string_literal: true
+
+module DiscourseWorkflows
+ module Nodes
+ module Topic
+ class V1 < NodeType
+ OPERATIONS = %w[create get list].freeze
+ MAX_LIMIT = 100
+ DEFAULT_LIMIT = 30
+
+ description(
+ name: "action:topic",
+ version: "1.0",
+ defaults: {
+ icon: "comments",
+ color: "light-blue",
+ },
+ group: "discourse_actions",
+ capabilities: {
+ run_scope: "per_item",
+ },
+ properties: {
+ operation: {
+ type: :options,
+ required: true,
+ options: OPERATIONS,
+ default: "create",
+ },
+ topic_id: {
+ type: :string,
+ required: true,
+ display_options: {
+ show: {
+ operation: ["get"],
+ },
+ },
+ },
+ title: {
+ type: :string,
+ required: true,
+ display_options: {
+ show: {
+ operation: ["create"],
+ },
+ },
+ },
+ raw: {
+ type: :string,
+ required: true,
+ ui: {
+ control: :textarea,
+ },
+ display_options: {
+ show: {
+ operation: ["create"],
+ },
+ },
+ },
+ category_id: {
+ type: :integer,
+ required: false,
+ ui: {
+ control: :category,
+ },
+ display_options: {
+ show: {
+ operation: ["create"],
+ },
+ },
+ },
+ tag_names: {
+ type: :string,
+ required: false,
+ ui: {
+ control: :tags,
+ },
+ display_options: {
+ show: {
+ operation: ["create"],
+ },
+ },
+ },
+ query: {
+ type: :string,
+ required: true,
+ ui: {
+ control: :filter_query,
+ },
+ display_options: {
+ show: {
+ operation: ["list"],
+ },
+ },
+ },
+ limit: {
+ type: :integer,
+ required: false,
+ default: DEFAULT_LIMIT,
+ display_options: {
+ show: {
+ operation: ["list"],
+ },
+ },
+ },
+ actor_username: {
+ type: :string,
+ required: false,
+ default: "system",
+ ui: {
+ control: :user,
+ },
+ },
+ },
+ )
+
+ def execute(exec_ctx)
+ items =
+ exec_ctx.input_items.flat_map.with_index do |_item, item_index|
+ config = {
+ "operation" =>
+ exec_ctx.get_node_parameter("operation", item_index, default: "create"),
+ "topic_id" => exec_ctx.get_node_parameter("topic_id", item_index),
+ "title" => exec_ctx.get_node_parameter("title", item_index),
+ "raw" => exec_ctx.get_node_parameter("raw", item_index),
+ "category_id" => exec_ctx.get_node_parameter("category_id", item_index),
+ "tag_names" => exec_ctx.get_node_parameter("tag_names", item_index),
+ "query" => exec_ctx.get_node_parameter("query", item_index),
+ "limit" => exec_ctx.get_node_parameter("limit", item_index, default: DEFAULT_LIMIT),
+ }
+
+ Array.wrap(execute_with_config(exec_ctx, config, item_index))
+ end
+
+ [items]
+ end
+
+ private
+
+ def execute_with_config(exec_ctx, config, item_index)
+ case config["operation"]
+ when "create"
+ wrap(create_topic(exec_ctx, config, item_index))
+ when "get"
+ wrap(get_topic(exec_ctx, config, item_index))
+ when "list"
+ list_topics(exec_ctx, config, item_index).map { |data| wrap(data) }
+ else
+ raise_node_error!(
+ I18n.t(
+ "discourse_workflows.errors.topic.unknown_operation",
+ operation: config["operation"],
+ ),
+ )
+ end
+ end
+
+ def create_topic(exec_ctx, config, item_index)
+ author = exec_ctx.actor_from_parameter("actor_username", item_index)
+ guardian = author.guardian
+ category_id = config["category_id"].presence&.to_i
+ category = Category.find_by(id: category_id) if category_id
+ tag_names = normalize_tag_names(config["tag_names"])
+
+ unless guardian.can_create?(Topic, category)
+ raise_node_error!(I18n.t("discourse_workflows.errors.topic.create_failed"))
+ end
+
+ args = {
+ title: config["title"],
+ raw: config["raw"],
+ guardian: guardian,
+ skip_workflows: true,
+ }
+ args[:category] = category.id if category
+ args[:tags] = tag_names if tag_names.present?
+
+ post_creator = PostCreator.new(author, **args)
+ post = post_creator.create
+ if post_creator.errors.present?
+ raise_node_error!(post_creator.errors.full_messages.join(", "))
+ end
+
+ topic = post.topic
+
+ { topic: topic_data(topic, guardian), post_id: post.id, post_number: post.post_number }
+ end
+
+ def get_topic(exec_ctx, config, item_index)
+ topic = ::Topic.find(config["topic_id"])
+ actor = exec_ctx.actor_from_parameter("actor_username", item_index)
+ actor.guardian.ensure_can_see!(topic)
+ { topic: topic_data(topic, actor.guardian) }
+ end
+
+ def list_topics(exec_ctx, config, item_index)
+ limit = [[Integer(config["limit"] || DEFAULT_LIMIT), 1].max, MAX_LIMIT].min
+ actor = exec_ctx.actor_from_parameter("actor_username", item_index)
+ topic_query = TopicQuery.new(actor, q: config["query"], per_page: limit)
+ topic_list = topic_query.list_filter
+
+ posts = topic_list.topics.map(&:first_post).compact
+ if posts.any?
+ ActiveRecord::Associations::Preloader.new(records: posts, associations: :user).call
+ end
+
+ topic_list.topics.map { |topic| { topic: topic_data(topic, actor.guardian) } }
+ end
+
+ def topic_data(topic, guardian)
+ serialize_record(topic, TopicListItemSerializer, scope: guardian)
+ end
+ end
+ end
+ end
+end
diff --git a/plugins/discourse-workflows/lib/discourse_workflows/nodes/topic_admin_button/v1.rb b/plugins/discourse-workflows/lib/discourse_workflows/nodes/topic_admin_button/v1.rb
new file mode 100644
index 00000000000..2ad011cf20f
--- /dev/null
+++ b/plugins/discourse-workflows/lib/discourse_workflows/nodes/topic_admin_button/v1.rb
@@ -0,0 +1,52 @@
+# frozen_string_literal: true
+
+module DiscourseWorkflows
+ module Nodes
+ module TopicAdminButton
+ class V1 < NodeType
+ description(
+ name: "trigger:topic_admin_button",
+ version: "1.0",
+ defaults: {
+ icon: "gear",
+ color: "cyan",
+ },
+ group: "discourse_triggers",
+ properties: {
+ label: {
+ type: :string,
+ required: true,
+ },
+ icon: {
+ type: :icon,
+ required: false,
+ },
+ },
+ capabilities: {
+ manually_triggerable: true,
+ provides_current_user: true,
+ },
+ )
+
+ def initialize(topic)
+ super(parameters: {})
+ @topic = topic
+ end
+
+ def valid?
+ @topic.present?
+ end
+
+ def output
+ { topic: topic_data(@topic) }
+ end
+
+ private
+
+ def topic_data(topic)
+ serialize_record(topic, TopicListItemSerializer)
+ end
+ end
+ end
+ end
+end
diff --git a/plugins/discourse-workflows/lib/discourse_workflows/nodes/topic_category_changed/v1.rb b/plugins/discourse-workflows/lib/discourse_workflows/nodes/topic_category_changed/v1.rb
new file mode 100644
index 00000000000..3ed15fb0ccf
--- /dev/null
+++ b/plugins/discourse-workflows/lib/discourse_workflows/nodes/topic_category_changed/v1.rb
@@ -0,0 +1,40 @@
+# frozen_string_literal: true
+
+module DiscourseWorkflows
+ module Nodes
+ module TopicCategoryChanged
+ class V1 < NodeType
+ description(
+ name: "trigger:topic_category_changed",
+ version: "1.0",
+ defaults: {
+ icon: "folder-open",
+ color: "deep-orange",
+ },
+ group: "discourse_triggers",
+ events: [:topic_category_changed],
+ )
+
+ def initialize(topic, old_category)
+ super(parameters: {})
+ @topic = topic
+ @old_category = old_category
+ end
+
+ def valid?
+ @topic.present? && @old_category.present?
+ end
+
+ def output
+ { topic: topic_data(@topic), old_category_id: @old_category.id }
+ end
+
+ private
+
+ def topic_data(topic)
+ serialize_record(topic, TopicListItemSerializer)
+ end
+ end
+ end
+ end
+end
diff --git a/plugins/discourse-workflows/lib/discourse_workflows/nodes/topic_closed/v1.rb b/plugins/discourse-workflows/lib/discourse_workflows/nodes/topic_closed/v1.rb
new file mode 100644
index 00000000000..567f8a994f5
--- /dev/null
+++ b/plugins/discourse-workflows/lib/discourse_workflows/nodes/topic_closed/v1.rb
@@ -0,0 +1,74 @@
+# frozen_string_literal: true
+
+module DiscourseWorkflows
+ module Nodes
+ module TopicClosed
+ class V1 < NodeType
+ description(
+ name: "trigger:topic_closed",
+ version: "1.0",
+ defaults: {
+ icon: "lock",
+ color: "grey",
+ },
+ group: "discourse_triggers",
+ events: [:topic_status_updated],
+ properties: {
+ category_id: {
+ type: :integer,
+ required: false,
+ ui: {
+ control: :category,
+ },
+ },
+ tag_names: {
+ type: :string,
+ required: false,
+ ui: {
+ control: :tags,
+ },
+ },
+ },
+ )
+
+ def initialize(topic, status, enabled)
+ super(parameters: {})
+ @topic = topic
+ @status = status
+ @enabled = enabled
+ end
+
+ def valid?
+ @status.to_s == "closed" && @enabled
+ end
+
+ def output
+ { topic: topic_data(@topic) }
+ end
+
+ def matches?(trigger_ctx)
+ matches_category?(trigger_ctx.get_node_parameter("category_id")) &&
+ matches_tags?(normalize_tag_names(trigger_ctx.get_node_parameter("tag_names")))
+ end
+
+ private
+
+ def topic_data(topic)
+ serialize_record(topic, TopicListItemSerializer)
+ end
+
+ def matches_category?(category_id)
+ category_id.blank? || @topic.category_id == category_id.to_i
+ end
+
+ def matches_tags?(tag_names)
+ tag_names.empty? || (topic_tag_names & tag_names).any?
+ end
+
+ def topic_tag_names
+ @topic_tag_names ||= @topic.tags.pluck(:name)
+ end
+ end
+ end
+ end
+end
diff --git a/plugins/discourse-workflows/lib/discourse_workflows/nodes/topic_created/v1.rb b/plugins/discourse-workflows/lib/discourse_workflows/nodes/topic_created/v1.rb
new file mode 100644
index 00000000000..120fcc13394
--- /dev/null
+++ b/plugins/discourse-workflows/lib/discourse_workflows/nodes/topic_created/v1.rb
@@ -0,0 +1,77 @@
+# frozen_string_literal: true
+
+module DiscourseWorkflows
+ module Nodes
+ module TopicCreated
+ class V1 < NodeType
+ description(
+ name: "trigger:topic_created",
+ version: "1.0",
+ defaults: {
+ icon: "plus",
+ color: "teal",
+ },
+ group: "discourse_triggers",
+ events: [:topic_created],
+ properties: {
+ category_id: {
+ type: :integer,
+ required: false,
+ ui: {
+ control: :category,
+ },
+ },
+ tag_names: {
+ type: :string,
+ required: false,
+ ui: {
+ control: :tags,
+ },
+ },
+ },
+ )
+
+ def initialize(topic, opts = nil, *)
+ super(parameters: {})
+ @topic = topic
+ @opts = opts
+ end
+
+ def valid?
+ @topic.present? && !@opts&.dig(:skip_workflows)
+ end
+
+ def output
+ { post: post_data(@topic.first_post), topic: topic_data(@topic) }
+ end
+
+ def matches?(trigger_ctx)
+ matches_category?(trigger_ctx.get_node_parameter("category_id")) &&
+ matches_tags?(normalize_tag_names(trigger_ctx.get_node_parameter("tag_names")))
+ end
+
+ private
+
+ def topic_data(topic)
+ serialize_record(topic, TopicListItemSerializer)
+ end
+
+ def post_data(post)
+ serialize_record(post, WebHookPostSerializer)
+ end
+
+ def matches_category?(category_id)
+ category_id.blank? || @topic.category_id == category_id.to_i
+ end
+
+ def matches_tags?(tag_names)
+ tag_names.empty? || (topic_tag_names & tag_names).any?
+ end
+
+ def topic_tag_names
+ @topic_tag_names ||= @topic.tags.pluck(:name)
+ end
+ end
+ end
+ end
+end
diff --git a/plugins/discourse-workflows/lib/discourse_workflows/nodes/topic_tag_changed/v1.rb b/plugins/discourse-workflows/lib/discourse_workflows/nodes/topic_tag_changed/v1.rb
new file mode 100644
index 00000000000..fc36dd58ed7
--- /dev/null
+++ b/plugins/discourse-workflows/lib/discourse_workflows/nodes/topic_tag_changed/v1.rb
@@ -0,0 +1,73 @@
+# frozen_string_literal: true
+
+module DiscourseWorkflows
+ module Nodes
+ module TopicTagChanged
+ class V1 < NodeType
+ description(
+ name: "trigger:topic_tag_changed",
+ version: "1.0",
+ defaults: {
+ icon: "tag",
+ color: "deep-orange",
+ },
+ group: "discourse_triggers",
+ events: [:topic_tags_changed],
+ properties: {
+ category_id: {
+ type: :integer,
+ required: false,
+ ui: {
+ control: :category,
+ },
+ },
+ },
+ )
+
+ def initialize(topic, payload = {})
+ super(parameters: {})
+ @topic = topic
+ @old_tag_names = payload[:old_tag_names] || []
+ @new_tag_names = payload[:new_tag_names] || []
+ @user = payload[:user]
+ end
+
+ def valid?
+ @topic.present? && (added_tags.present? || removed_tags.present?)
+ end
+
+ def output
+ {
+ topic: topic_data(@topic),
+ old_tags: @old_tag_names,
+ new_tags: @new_tag_names,
+ added_tags: added_tags,
+ removed_tags: removed_tags,
+ }
+ end
+
+ def matches?(trigger_ctx)
+ matches_category?(trigger_ctx.get_node_parameter("category_id"))
+ end
+
+ private
+
+ def added_tags
+ @new_tag_names - @old_tag_names
+ end
+
+ def removed_tags
+ @old_tag_names - @new_tag_names
+ end
+
+ def topic_data(topic)
+ serialize_record(topic, TopicListItemSerializer)
+ end
+
+ def matches_category?(category_id)
+ category_id.blank? || @topic.category_id == category_id.to_i
+ end
+ end
+ end
+ end
+end
diff --git a/plugins/discourse-workflows/lib/discourse_workflows/nodes/topic_tags/v1.rb b/plugins/discourse-workflows/lib/discourse_workflows/nodes/topic_tags/v1.rb
new file mode 100644
index 00000000000..96f175ecbc6
--- /dev/null
+++ b/plugins/discourse-workflows/lib/discourse_workflows/nodes/topic_tags/v1.rb
@@ -0,0 +1,105 @@
+# frozen_string_literal: true
+
+module DiscourseWorkflows
+ module Nodes
+ module TopicTags
+ class V1 < NodeType
+ OPERATIONS = %w[add remove].freeze
+
+ description(
+ name: "action:topic_tags",
+ version: "1.0",
+ defaults: {
+ icon: "tags",
+ color: "orange",
+ },
+ group: "discourse_actions",
+ capabilities: {
+ run_scope: "per_item",
+ },
+ properties: {
+ operation: {
+ type: :options,
+ required: true,
+ options: OPERATIONS,
+ default: "add",
+ ui: {
+ expression: true,
+ },
+ },
+ topic_id: {
+ type: :string,
+ required: true,
+ },
+ tag_names: {
+ type: :string,
+ required: false,
+ ui: {
+ control: :tags,
+ },
+ },
+ actor_username: {
+ type: :string,
+ required: false,
+ default: "system",
+ ui: {
+ control: :user,
+ },
+ },
+ },
+ )
+
+ def execute(exec_ctx)
+ items =
+ exec_ctx.input_items.map.with_index do |_item, item_index|
+ config = {
+ "operation" => exec_ctx.get_node_parameter("operation", item_index, default: "add"),
+ "topic_id" => exec_ctx.get_node_parameter("topic_id", item_index),
+ "tag_names" => exec_ctx.get_node_parameter("tag_names", item_index),
+ }
+
+ wrap(process(exec_ctx, config, item_index))
+ end
+
+ [items]
+ end
+
+ private
+
+ def process(exec_ctx, config, item_index)
+ topic = ::Topic.find(config["topic_id"])
+ actor = exec_ctx.actor_from_parameter("actor_username", item_index)
+ guardian = actor.guardian
+
+ names = normalize_tag_names(config["tag_names"])
+ if names.empty?
+ raise_node_error!(I18n.t("discourse_workflows.errors.topic_tags.no_tag_names"))
+ end
+
+ case config["operation"]
+ when "remove"
+ old_tag_names = topic.tags.pluck(:name)
+ desired_tag_names = old_tag_names - names
+ tag_topic!(topic, guardian, desired_tag_names)
+ { tag_names: old_tag_names & names, topic_id: topic.id }
+ else
+ tag_topic!(topic, guardian, names, append: true)
+ { tag_names: names, topic_id: topic.id }
+ end
+ end
+
+ def tag_topic!(topic, guardian, tag_names, append: false)
+ unless DiscourseTagging.tag_topic_by_names(topic, guardian, tag_names, append:)
+ raise_node_error!(
+ I18n.t(
+ "discourse_workflows.errors.topic_tags.operation_failed",
+ errors: topic.errors.full_messages.join(", "),
+ ),
+ )
+ end
+ topic.save!
+ end
+ end
+ end
+ end
+end
diff --git a/plugins/discourse-workflows/lib/discourse_workflows/nodes/wait/v1.rb b/plugins/discourse-workflows/lib/discourse_workflows/nodes/wait/v1.rb
new file mode 100644
index 00000000000..d32720b3523
--- /dev/null
+++ b/plugins/discourse-workflows/lib/discourse_workflows/nodes/wait/v1.rb
@@ -0,0 +1,157 @@
+# frozen_string_literal: true
+
+module DiscourseWorkflows
+ module Nodes
+ module Wait
+ class V1 < NodeType
+ WAIT_UNITS = %w[seconds minutes hours days].freeze
+
+ description(
+ name: "flow:wait",
+ version: "1.0",
+ defaults: {
+ icon: "pause",
+ color: "salmon",
+ },
+ outputs: %w[main],
+ properties:
+ lambda do
+ webhook_fields =
+ Schemas::Webhook::CONFIGURATION_FIELDS.transform_values do |field|
+ display_options = field[:display_options] || {}
+ show = (display_options[:show] || {}).merge(resume: ["webhook"])
+ field.merge(display_options: display_options.merge(show: show))
+ end
+
+ {
+ resume: {
+ type: :options,
+ required: true,
+ default: "time_interval",
+ options: %w[time_interval webhook],
+ },
+ wait_amount: {
+ type: :integer,
+ required: true,
+ default: 1,
+ display_options: {
+ show: {
+ resume: ["time_interval"],
+ },
+ },
+ },
+ wait_unit: {
+ type: :options,
+ required: true,
+ default: "hours",
+ options: WAIT_UNITS,
+ display_options: {
+ show: {
+ resume: ["time_interval"],
+ },
+ },
+ },
+ webhook_info: {
+ type: :notice,
+ display_options: {
+ show: {
+ resume: ["webhook"],
+ },
+ },
+ },
+ **webhook_fields,
+ webhook_suffix:
+ Schemas::Webhook::WEBHOOK_SUFFIX_FIELD.merge(
+ display_options: {
+ show: {
+ resume: ["webhook"],
+ },
+ },
+ ),
+ limit_wait_time: {
+ type: :boolean,
+ default: false,
+ display_options: {
+ show: {
+ resume: ["webhook"],
+ },
+ },
+ },
+ timeout_amount: {
+ type: :integer,
+ required: false,
+ display_options: {
+ show: {
+ resume: ["webhook"],
+ limit_wait_time: [true],
+ },
+ },
+ },
+ timeout_unit: {
+ type: :options,
+ required: false,
+ default: "hours",
+ options: WAIT_UNITS,
+ display_options: {
+ show: {
+ resume: ["webhook"],
+ limit_wait_time: [true],
+ },
+ },
+ },
+ }
+ end,
+ capabilities: {
+ waits_for_resume: true,
+ },
+ )
+
+ def execute(exec_ctx)
+ resume_mode = exec_ctx.get_node_parameter("resume", 0, default: "time_interval")
+
+ if resume_mode == "webhook"
+ waiting_until = webhook_waiting_until(exec_ctx)
+ else
+ amount = exec_ctx.get_node_parameter("wait_amount", 0, default: 1).to_i
+ unit = exec_ctx.get_node_parameter("wait_unit", 0, default: "hours")
+
+ if amount <= 0
+ raise_node_error!(I18n.t("discourse_workflows.errors.wait.amount_must_be_positive"))
+ end
+ if WAIT_UNITS.exclude?(unit)
+ raise_node_error!(I18n.t("discourse_workflows.errors.wait.invalid_unit", unit: unit))
+ end
+
+ waiting_until = amount.public_send(unit).from_now
+ end
+
+ exec_ctx.put_execution_to_wait(waiting_until)
+ [exec_ctx.input_items]
+ end
+
+ private
+
+ def webhook_waiting_until(exec_ctx)
+ return nil unless exec_ctx.get_node_parameter("limit_wait_time", 0, default: false)
+
+ timeout_amount = exec_ctx.get_node_parameter("timeout_amount", 0, default: nil).presence
+ timeout_amount = timeout_amount.to_i if timeout_amount
+ timeout_unit = exec_ctx.get_node_parameter("timeout_unit", 0, default: "hours").presence
+
+ if WAIT_UNITS.exclude?(timeout_unit)
+ raise_node_error!(
+ I18n.t("discourse_workflows.errors.wait.invalid_timeout_unit", unit: timeout_unit),
+ )
+ end
+ if timeout_amount && timeout_amount <= 0
+ raise_node_error!(
+ I18n.t("discourse_workflows.errors.wait.timeout_amount_must_be_positive"),
+ )
+ end
+
+ timeout_amount&.public_send(timeout_unit)&.from_now
+ end
+ end
+ end
+ end
+end
diff --git a/plugins/discourse-workflows/lib/discourse_workflows/nodes/webhook/v1.rb b/plugins/discourse-workflows/lib/discourse_workflows/nodes/webhook/v1.rb
new file mode 100644
index 00000000000..3de9f5ac853
--- /dev/null
+++ b/plugins/discourse-workflows/lib/discourse_workflows/nodes/webhook/v1.rb
@@ -0,0 +1,73 @@
+# frozen_string_literal: true
+
+module DiscourseWorkflows
+ module Nodes
+ module Webhook
+ class V1 < NodeType
+ description(
+ name: "trigger:webhook",
+ version: "1.0",
+ defaults: {
+ icon: "globe",
+ color: "purple",
+ },
+ properties: {
+ url_preview: {
+ type: :custom,
+ required: false,
+ ui: {
+ control: :url_preview,
+ },
+ },
+ **Schemas::Webhook::CONFIGURATION_FIELDS,
+ path: {
+ type: :string,
+ required: true,
+ },
+ },
+ capabilities: {
+ manually_triggerable: true,
+ },
+ credentials: [
+ {
+ name: "auth",
+ credential_types: %w[basic_auth bearer_token header_auth],
+ required: false,
+ display_options: {
+ show: {
+ authentication: %w[basic_auth bearer_auth header_auth],
+ },
+ },
+ label_key: "discourse_workflows.webhook.credential",
+ },
+ ],
+ webhooks: [{ name: "default", path: "path", http_method: "http_method" }],
+ )
+
+ def initialize(body:, headers:, params: {}, query:, method:, webhook_url:, raw_body: nil)
+ super(parameters: {})
+ @body = body
+ @headers = headers
+ @params = params
+ @query = query
+ @method = method
+ @webhook_url = webhook_url
+ @raw_body = raw_body
+ end
+
+ def output
+ data = {
+ body: @body,
+ headers: @headers,
+ params: @params,
+ query: @query,
+ method: @method,
+ webhook_url: @webhook_url,
+ }
+ data[:raw_body] = @raw_body if @raw_body.present?
+ data
+ end
+ end
+ end
+ end
+end
diff --git a/plugins/discourse-workflows/lib/discourse_workflows/pagination.rb b/plugins/discourse-workflows/lib/discourse_workflows/pagination.rb
new file mode 100644
index 00000000000..76edbb8f422
--- /dev/null
+++ b/plugins/discourse-workflows/lib/discourse_workflows/pagination.rb
@@ -0,0 +1,33 @@
+# frozen_string_literal: true
+
+module DiscourseWorkflows
+ module Pagination
+ DEFAULT_LIMIT = 25
+ MAX_LIMIT = 100
+
+ Page = Data.define(:records, :total_rows, :load_more_url)
+
+ def self.normalize_limit(limit)
+ (limit || DEFAULT_LIMIT).clamp(1, MAX_LIMIT)
+ end
+
+ def self.cursor_page(scope:, cursor:, limit:, path:, query: {})
+ paginated_scope = cursor ? scope.where("id < ?", cursor) : scope
+ records = paginated_scope.limit(limit + 1).to_a
+ has_more = records.size > limit
+ records = records.first(limit) if has_more
+
+ Page.new(
+ records: records,
+ total_rows: scope.count,
+ load_more_url: build_load_more_url(path, records, limit, query, has_more),
+ )
+ end
+
+ def self.build_load_more_url(path, records, limit, query, has_more)
+ return if !has_more || records.empty?
+
+ "#{path}?#{query.merge(cursor: records.last.id, limit: limit).compact_blank.to_query}"
+ end
+ end
+end
diff --git a/plugins/discourse-workflows/lib/discourse_workflows/plugin_enable_handler.rb b/plugins/discourse-workflows/lib/discourse_workflows/plugin_enable_handler.rb
new file mode 100644
index 00000000000..63e48c154f3
--- /dev/null
+++ b/plugins/discourse-workflows/lib/discourse_workflows/plugin_enable_handler.rb
@@ -0,0 +1,35 @@
+# frozen_string_literal: true
+
+module DiscourseWorkflows
+ module PluginEnableHandler
+ module_function
+
+ def handle!
+ reschedule_waiting_executions!
+ activate_published_triggers!
+ end
+
+ def reschedule_waiting_executions!
+ Execution
+ .where(status: :waiting)
+ .where.not(waiting_until: nil)
+ .find_each do |execution|
+ duration = [execution.waiting_until - Time.current, 0].max
+ Jobs.enqueue_in(
+ duration,
+ Jobs::DiscourseWorkflows::ResumeWaitingExecution,
+ execution_id: execution.id,
+ )
+ end
+ end
+
+ def activate_published_triggers!
+ Workflow
+ .published
+ .includes(:active_version)
+ .find_each do |workflow|
+ TriggerRuntime.activate_workflow!(workflow, workflow_version: workflow.active_version)
+ end
+ end
+ end
+end
diff --git a/plugins/discourse-workflows/lib/discourse_workflows/plugin_node_registration.rb b/plugins/discourse-workflows/lib/discourse_workflows/plugin_node_registration.rb
new file mode 100644
index 00000000000..ba35cfa85a0
--- /dev/null
+++ b/plugins/discourse-workflows/lib/discourse_workflows/plugin_node_registration.rb
@@ -0,0 +1,68 @@
+# frozen_string_literal: true
+
+module DiscourseWorkflows
+ class << self
+ attr_writer :node_registration_ready
+
+ def node_registration_ready?
+ @node_registration_ready == true
+ end
+
+ def register_plugin_node_registration(plugin, registration)
+ node_classes =
+ if registration.respond_to?(:call)
+ plugin.instance_exec(&registration)
+ else
+ registration
+ end
+
+ Array
+ .wrap(node_classes)
+ .each do |node_class|
+ DiscoursePluginRegistry.register_discourse_workflows_node(node_class, plugin)
+ end
+ end
+
+ def flush_plugin_node_registrations!
+ Discourse.plugins.each do |plugin|
+ next unless plugin.respond_to?(:discourse_workflows_node_registrations)
+
+ plugin.discourse_workflows_node_registrations.each do |registration|
+ register_plugin_node_registration(plugin, registration)
+ end
+ plugin.discourse_workflows_node_registrations.clear
+ end
+ end
+ end
+end
+
+class Plugin::Instance
+ def register_discourse_workflows_node(node_class = nil, &block)
+ raise ArgumentError, "Provide a node class or a block, not both" if node_class && block
+ raise ArgumentError, "Provide a node class or a block" if !node_class && !block
+
+ register_discourse_workflows_node_cache_reset!
+
+ registration = block || node_class
+ if DiscourseWorkflows.node_registration_ready?
+ DiscourseWorkflows.register_plugin_node_registration(self, registration)
+ else
+ discourse_workflows_node_registrations << registration
+ end
+ end
+
+ def discourse_workflows_node_registrations
+ @discourse_workflows_node_registrations ||= []
+ end
+
+ private
+
+ def register_discourse_workflows_node_cache_reset!
+ return if @discourse_workflows_node_cache_reset_registered
+ return if enabled_site_setting.blank?
+
+ @discourse_workflows_node_cache_reset_registered = true
+ @discourse_workflows_node_cache_reset_handler =
+ on_enabled_change { DiscourseWorkflows::Registry.reset_indexes! }
+ end
+end
diff --git a/plugins/discourse-workflows/lib/discourse_workflows/property_schema_validator.rb b/plugins/discourse-workflows/lib/discourse_workflows/property_schema_validator.rb
new file mode 100644
index 00000000000..0933d8164b7
--- /dev/null
+++ b/plugins/discourse-workflows/lib/discourse_workflows/property_schema_validator.rb
@@ -0,0 +1,374 @@
+# frozen_string_literal: true
+
+module DiscourseWorkflows
+ class PropertySchemaValidator
+ KNOWN_FIELD_TYPES = %i[
+ string
+ integer
+ number
+ float
+ boolean
+ options
+ multi_options
+ collection
+ fixed_collection
+ assignment_collection
+ array
+ object
+ notice
+ credential
+ icon
+ custom
+ ].freeze
+
+ KNOWN_FIELD_KEYS = %i[
+ type
+ required
+ default
+ options
+ min
+ max
+ max_items
+ validate
+ no_data_expression
+ display_options
+ item_schema
+ extra_item_schema
+ type_options
+ ui
+ control_options
+ ].freeze
+
+ TYPE_SPECIFIC_KEYS = { credential: %i[credential_type] }.freeze
+
+ KNOWN_TYPE_OPTIONS_KEYS = %i[
+ add_optional_field_button_text
+ assignment_types
+ hide_optional_fields
+ item_title
+ layout
+ load_options_depends_on
+ load_options_method
+ max_allowed_fields
+ min_required_fields
+ multiple_values
+ sortable
+ ].freeze
+
+ KNOWN_UI_KEYS = %i[
+ control
+ dynamic_value
+ expression
+ flat
+ format
+ hidden
+ show_description
+ show_label
+ singular_name
+ ].freeze
+
+ KNOWN_CONTROL_OPTIONS_KEYS = %i[
+ action_icon
+ action_label
+ action_route
+ action_route_models
+ filterable
+ height
+ lang
+ name_property
+ none
+ option_format
+ set_from_option
+ resets
+ value_property
+ ].freeze
+
+ KNOWN_UI_CONTROLS = %i[
+ boolean
+ category
+ code
+ combo_box
+ condition_builder
+ credential
+ data_table_column_select
+ data_table_columns
+ data_table_condition_builder
+ data_table_select
+ filter_query
+ group_select
+ icon
+ multi_combo_box
+ notice
+ password
+ query_params
+ select
+ tags
+ textarea
+ url_preview
+ user
+ user_or_group
+ ].freeze
+
+ TYPES_REQUIRING_OPTIONS = %i[options multi_options collection fixed_collection].freeze
+
+ Error =
+ Struct.new(:node, :path, :message) do
+ def to_s
+ "#{node} at #{path.map(&:to_s).join(".")}: #{message}"
+ end
+ end
+
+ def self.validate_all
+ DiscourseWorkflows::NodeType
+ .registered_nodes
+ .flat_map { |node_class| validate_node(node_class) }
+ .compact
+ end
+
+ def self.validate_node(node_class)
+ identifier =
+ begin
+ node_class.identifier
+ rescue NotImplementedError
+ return []
+ end
+ call(identifier, node_class.property_schema)
+ end
+
+ def self.call(identifier, schema)
+ new(identifier, schema).validate
+ end
+
+ def initialize(identifier, schema)
+ @identifier = identifier
+ @schema = schema
+ @errors = []
+ end
+
+ def validate
+ if @schema.is_a?(Hash)
+ validate_schema(@schema, path: [])
+ else
+ add_error([], "property_schema must be a Hash, got #{@schema.class}")
+ end
+ @errors
+ end
+
+ private
+
+ def validate_schema(schema, path:)
+ validate_schema_with_siblings(schema, path: path, siblings: schema.keys)
+ end
+
+ def validate_field(name, field, path:, sibling_keys:)
+ field_path = path + [name]
+
+ unless field.is_a?(Hash)
+ add_error(field_path, "expected field definition Hash, got #{field.class}")
+ return
+ end
+
+ validate_field_keys(field, path: field_path)
+ validate_field_type(field, path: field_path)
+ validate_field_options(field, path: field_path)
+ validate_ui(field, path: field_path)
+ validate_type_options(field, path: field_path)
+ validate_control_options(field, path: field_path)
+ validate_visibility(field, path: field_path, sibling_keys: sibling_keys)
+ validate_item_schemas(field, path: field_path)
+ validate_collection_options(field, path: field_path)
+ end
+
+ def validate_field_keys(field, path:)
+ allowed = KNOWN_FIELD_KEYS + TYPE_SPECIFIC_KEYS.fetch(field[:type], [])
+ unknown = field.keys - allowed
+ return if unknown.empty?
+ add_error(path, "unknown field key(s): #{unknown.sort.inspect}")
+ end
+
+ def validate_field_type(field, path:)
+ return if KNOWN_FIELD_TYPES.include?(field[:type])
+ add_error(path + [:type], "unknown type: #{field[:type].inspect}")
+ end
+
+ def validate_field_options(field, path:)
+ type = field[:type]
+ return if TYPES_REQUIRING_OPTIONS.exclude?(type)
+ return if field.dig(:type_options, :load_options_method)
+
+ options = field[:options]
+ return if options.is_a?(Array) && options.any?
+ add_error(path, "type #{type.inspect} requires a non-empty :options array")
+ end
+
+ def validate_ui(field, path:)
+ ui = field[:ui]
+ return if ui.nil?
+
+ ui_path = path + [:ui]
+
+ unless ui.is_a?(Hash)
+ add_error(ui_path, "expected Hash, got #{ui.class}")
+ return
+ end
+
+ unknown = ui.keys - KNOWN_UI_KEYS
+ add_error(ui_path, "unknown ui key(s): #{unknown.sort.inspect}") if unknown.any?
+
+ control = ui[:control]
+ return if control.nil? || KNOWN_UI_CONTROLS.include?(control)
+ add_error(ui_path + [:control], "unknown control: #{control.inspect}")
+ end
+
+ def validate_type_options(field, path:)
+ options = field[:type_options]
+ return if options.nil?
+
+ options_path = path + [:type_options]
+
+ unless options.is_a?(Hash)
+ add_error(options_path, "expected Hash, got #{options.class}")
+ return
+ end
+
+ unknown = options.keys - KNOWN_TYPE_OPTIONS_KEYS
+ return if unknown.empty?
+ add_error(options_path, "unknown type_options key(s): #{unknown.sort.inspect}")
+ end
+
+ def validate_control_options(field, path:)
+ options = field[:control_options]
+ return if options.nil?
+
+ options_path = path + [:control_options]
+
+ unless options.is_a?(Hash)
+ add_error(options_path, "expected Hash, got #{options.class}")
+ return
+ end
+
+ unknown = options.keys - KNOWN_CONTROL_OPTIONS_KEYS
+ return if unknown.empty?
+ add_error(options_path, "unknown control_options key(s): #{unknown.sort.inspect}")
+ end
+
+ def validate_visibility(field, path:, sibling_keys:)
+ display_options = field[:display_options]
+ return if display_options.nil?
+
+ display_options_path = path + [:display_options]
+ unless display_options.is_a?(Hash)
+ add_error(display_options_path, "expected Hash, got #{display_options.class}")
+ return
+ end
+
+ unknown = display_options.keys - %i[show hide]
+ if unknown.any?
+ add_error(display_options_path, "unknown display_options key(s): #{unknown.sort.inspect}")
+ end
+
+ %i[show hide].each do |key|
+ rules = display_options[key]
+ next if rules.nil?
+
+ rule_path = display_options_path + [key]
+ unless rules.is_a?(Hash)
+ add_error(rule_path, "expected Hash, got #{rules.class}")
+ next
+ end
+
+ rules.each do |ref, expected|
+ if sibling_keys.exclude?(ref)
+ add_error(rule_path, "references unknown sibling field: #{ref.inspect}")
+ end
+
+ next if expected.is_a?(Array)
+ add_error(rule_path + [ref], "expected Array, got #{expected.class}")
+ end
+ end
+ end
+
+ def validate_item_schemas(field, path:)
+ item_schema = field[:item_schema]
+
+ validate_schema(item_schema, path: path + [:item_schema]) if item_schema.is_a?(Hash)
+
+ extra = field[:extra_item_schema]
+ return unless extra.is_a?(Hash)
+
+ # Extra item fields are rendered inside the same row as item_schema fields,
+ # so visibility rules may reference either side.
+ extra_siblings = (item_schema.is_a?(Hash) ? item_schema.keys : []) + extra.keys
+ validate_schema_with_siblings(
+ extra,
+ path: path + [:extra_item_schema],
+ siblings: extra_siblings,
+ )
+ end
+
+ def validate_collection_options(field, path:)
+ case field[:type]
+ when :collection
+ validate_option_bag_options(field[:options], path: path + [:options])
+ when :fixed_collection
+ validate_fixed_collection_options(field[:options], path: path + [:options])
+ end
+ end
+
+ def validate_option_bag_options(options, path:)
+ return unless options.is_a?(Array)
+
+ siblings = options.filter_map { |option| option[:name]&.to_sym if option.is_a?(Hash) }
+ options.each_with_index do |option, index|
+ option_path = path + [index]
+ unless option.is_a?(Hash)
+ add_error(option_path, "expected option definition Hash, got #{option.class}")
+ next
+ end
+
+ name = option[:name]
+ if name.blank?
+ add_error(option_path, "collection option requires :name")
+ next
+ end
+
+ option_field = option.except(:name, :display_name)
+ validate_field(name.to_sym, option_field, path: path, sibling_keys: siblings)
+ end
+ end
+
+ def validate_fixed_collection_options(options, path:)
+ return unless options.is_a?(Array)
+
+ options.each_with_index do |group, index|
+ group_path = path + [index]
+ unless group.is_a?(Hash)
+ add_error(group_path, "expected fixed collection group Hash, got #{group.class}")
+ next
+ end
+
+ unknown = group.keys - %i[name display_name values]
+ if unknown.any?
+ add_error(group_path, "unknown fixed collection group key(s): #{unknown.sort.inspect}")
+ end
+
+ add_error(group_path, "fixed collection group requires :name") if group[:name].blank?
+ values = group[:values]
+ unless values.is_a?(Hash)
+ add_error(group_path + [:values], "expected Hash, got #{values.class}")
+ next
+ end
+
+ validate_schema(values, path: group_path + [:values])
+ end
+ end
+
+ def validate_schema_with_siblings(schema, path:, siblings:)
+ schema.each { |name, field| validate_field(name, field, path: path, sibling_keys: siblings) }
+ end
+
+ def add_error(path, message)
+ @errors << Error.new(@identifier, path, message)
+ end
+ end
+end
diff --git a/plugins/discourse-workflows/lib/discourse_workflows/published_trigger.rb b/plugins/discourse-workflows/lib/discourse_workflows/published_trigger.rb
new file mode 100644
index 00000000000..9dc52533a19
--- /dev/null
+++ b/plugins/discourse-workflows/lib/discourse_workflows/published_trigger.rb
@@ -0,0 +1,18 @@
+# frozen_string_literal: true
+
+module DiscourseWorkflows
+ PublishedTrigger =
+ Data.define(:workflow, :workflow_version, :trigger_node) do
+ def workflow_id
+ workflow.id
+ end
+
+ def workflow_version_id
+ workflow_version.id
+ end
+
+ def trigger_node_id
+ trigger_node["id"]
+ end
+ end
+end
diff --git a/plugins/discourse-workflows/lib/discourse_workflows/redirect_url_validator.rb b/plugins/discourse-workflows/lib/discourse_workflows/redirect_url_validator.rb
new file mode 100644
index 00000000000..06d90991ed3
--- /dev/null
+++ b/plugins/discourse-workflows/lib/discourse_workflows/redirect_url_validator.rb
@@ -0,0 +1,53 @@
+# frozen_string_literal: true
+
+module DiscourseWorkflows
+ class RedirectUrlValidator
+ def self.valid?(url, allowed_domains)
+ new(url, allowed_domains).valid?
+ end
+
+ def initialize(url, allowed_domains)
+ @url = url
+ @allowed_domains = allowed_domains
+ end
+
+ def valid?
+ return false if @url.blank?
+
+ uri = URI.parse(@url)
+ return true if uri.relative? && uri.host.blank?
+ return false unless uri.scheme.in?(%w[http https]) && uri.host.present?
+ return true if uri.host.casecmp?(Discourse.current_hostname)
+
+ allowed_host?(uri.host)
+ rescue URI::InvalidURIError
+ false
+ end
+
+ private
+
+ def allowed_host?(host)
+ host = host.to_s.downcase
+ Array(@allowed_domains).any? do |domain|
+ domain = domain.to_s.strip.downcase
+ valid_domain_entry?(domain) && domain_matches?(host, domain)
+ end
+ end
+
+ def valid_domain_entry?(domain)
+ return false if domain.blank? || domain == "*"
+ return false if domain.include?("/") || domain.include?(":")
+
+ domain.start_with?("*.") ? domain.length > 2 : !domain.include?("*")
+ end
+
+ def domain_matches?(host, domain)
+ if domain.start_with?("*.")
+ suffix = domain.delete_prefix("*.")
+ host.end_with?(".#{suffix}") && host != suffix
+ else
+ host == domain
+ end
+ end
+ end
+end
diff --git a/plugins/discourse-workflows/lib/discourse_workflows/registry.rb b/plugins/discourse-workflows/lib/discourse_workflows/registry.rb
new file mode 100644
index 00000000000..d849ab172a2
--- /dev/null
+++ b/plugins/discourse-workflows/lib/discourse_workflows/registry.rb
@@ -0,0 +1,86 @@
+# frozen_string_literal: true
+
+require_relative "plugin_node_registration"
+
+module DiscourseWorkflows
+ class Registry
+ DEFAULT_VERSION = "1.0"
+
+ class << self
+ def nodes(include_disabled_plugins: false)
+ if include_disabled_plugins
+ DiscoursePluginRegistry._raw_discourse_workflows_nodes.map { |entry| entry[:value] }.uniq
+ else
+ DiscoursePluginRegistry.discourse_workflows_nodes
+ end
+ end
+
+ def triggers
+ nodes.select { |n| n.identifier.start_with?("trigger:") }
+ end
+
+ def actions
+ nodes.select { |n| n.identifier.start_with?("action:") }
+ end
+
+ def conditions
+ nodes.select { |n| n.identifier.start_with?("condition:") }
+ end
+
+ def flows
+ nodes.select { |n| n.identifier.start_with?("flow:") }
+ end
+
+ def credential_types
+ DiscoursePluginRegistry.discourse_workflows_credential_types
+ end
+
+ def find_credential_type(identifier)
+ credential_type_index[identifier]
+ end
+
+ def find_node_type(identifier, version: nil, include_disabled_plugins: false)
+ version ||= DEFAULT_VERSION
+ node_type_index(include_disabled_plugins: include_disabled_plugins)[[identifier, version]]
+ end
+
+ def latest_version(identifier, include_disabled_plugins: false)
+ available_versions(identifier, include_disabled_plugins: include_disabled_plugins).last
+ end
+
+ def available_versions(identifier, include_disabled_plugins: false)
+ versions_by_identifier(include_disabled_plugins: include_disabled_plugins)[identifier] || []
+ end
+
+ def reset_indexes!
+ @credential_type_index = nil
+ end
+
+ private
+
+ def node_type_index(include_disabled_plugins: false)
+ nodes(include_disabled_plugins: include_disabled_plugins).each_with_object({}) do |klass, h|
+ version = klass.respond_to?(:version) ? klass.version : DEFAULT_VERSION
+ key = [klass.identifier, version]
+ if h.key?(key)
+ raise ArgumentError, "Duplicate workflow node type #{klass.identifier} v#{version}"
+ end
+ h[key] = klass
+ end
+ end
+
+ def versions_by_identifier(include_disabled_plugins: false)
+ node_type_index(include_disabled_plugins: include_disabled_plugins)
+ .keys
+ .group_by(&:first)
+ .transform_values do |keys|
+ keys.map(&:second).sort_by { |version| Gem::Version.new(version) }
+ end
+ end
+
+ def credential_type_index
+ @credential_type_index ||= credential_types.index_by(&:identifier)
+ end
+ end
+ end
+end
diff --git a/plugins/discourse-workflows/lib/discourse_workflows/sandbox_budget.rb b/plugins/discourse-workflows/lib/discourse_workflows/sandbox_budget.rb
new file mode 100644
index 00000000000..d87d18f3cdd
--- /dev/null
+++ b/plugins/discourse-workflows/lib/discourse_workflows/sandbox_budget.rb
@@ -0,0 +1,42 @@
+# frozen_string_literal: true
+
+module DiscourseWorkflows
+ class SandboxBudget
+ TOTAL_BUDGET_MS = 1_000
+ CONTEXT_KEY = "__sandbox_elapsed_ms"
+
+ def initialize(context = nil, budget_ms: TOTAL_BUDGET_MS)
+ @context = context
+ @budget_ms = budget_ms
+ @elapsed_ms = 0
+ end
+
+ def charge!(elapsed_ms)
+ total = elapsed_ms + current_elapsed_ms
+ persist_elapsed_ms(total)
+
+ return if total <= @budget_ms
+
+ raise JsSandbox::BudgetExceededError,
+ "Sandbox execution time exceeded #{@budget_ms}ms for this workflow"
+ end
+
+ def current_elapsed_ms
+ if @context
+ @context.fetch(CONTEXT_KEY, 0).to_f
+ else
+ @elapsed_ms
+ end
+ end
+
+ private
+
+ def persist_elapsed_ms(total)
+ if @context
+ @context[CONTEXT_KEY] = total.round(3)
+ else
+ @elapsed_ms = total
+ end
+ end
+ end
+end
diff --git a/plugins/discourse-workflows/lib/discourse_workflows/schemas/form_fields.rb b/plugins/discourse-workflows/lib/discourse_workflows/schemas/form_fields.rb
new file mode 100644
index 00000000000..20c422ce8fe
--- /dev/null
+++ b/plugins/discourse-workflows/lib/discourse_workflows/schemas/form_fields.rb
@@ -0,0 +1,255 @@
+# frozen_string_literal: true
+
+module DiscourseWorkflows
+ module Schemas
+ module FormFields
+ MAX_FIELD_VALUE_LENGTH = 10_000
+ EMAIL_REGEX = URI::MailTo::EMAIL_REGEXP
+
+ ValidationResult =
+ Struct.new(:errors, :data, keyword_init: true) do
+ def valid?
+ errors.empty?
+ end
+ end
+
+ ValidationError = Struct.new(:field_label, :code, keyword_init: true)
+
+ ITEM_SCHEMA = {
+ field_label: {
+ type: :string,
+ required: true,
+ },
+ field_type: {
+ type: :options,
+ required: true,
+ default: "text",
+ options: %w[
+ text
+ textarea
+ number
+ email
+ password
+ date
+ checkbox
+ dropdown
+ radio
+ hiddenField
+ html
+ ],
+ ui: {
+ expression: true,
+ },
+ },
+ }.freeze
+
+ EXTRA_ITEM_SCHEMA = {
+ field_name: {
+ type: :string,
+ },
+ required: {
+ type: :boolean,
+ default: false,
+ display_options: {
+ hide: {
+ field_type: %w[hiddenField html],
+ },
+ },
+ },
+ description: {
+ type: :string,
+ },
+ placeholder: {
+ type: :string,
+ display_options: {
+ show: {
+ field_type: %w[text textarea number email password],
+ },
+ },
+ },
+ default_value: {
+ type: :string,
+ display_options: {
+ hide: {
+ field_type: %w[password hiddenField html],
+ },
+ },
+ },
+ options: {
+ type: :fixed_collection,
+ display_options: {
+ show: {
+ field_type: %w[dropdown radio],
+ },
+ },
+ type_options: {
+ multiple_values: true,
+ },
+ options: [
+ {
+ name: "values",
+ values: {
+ value: {
+ type: :string,
+ required: true,
+ ui: {
+ show_label: false,
+ },
+ },
+ },
+ },
+ ],
+ },
+ field_value: {
+ type: :string,
+ display_options: {
+ show: {
+ field_type: %w[hiddenField],
+ },
+ },
+ },
+ html: {
+ type: :string,
+ display_options: {
+ show: {
+ field_type: %w[html],
+ },
+ },
+ ui: {
+ control: :textarea,
+ },
+ },
+ }.freeze
+
+ SCHEMA = {
+ type: :fixed_collection,
+ required: true,
+ type_options: {
+ multiple_values: true,
+ hide_optional_fields: true,
+ },
+ options: [{ name: "values", values: ITEM_SCHEMA.merge(EXTRA_ITEM_SCHEMA) }],
+ }.freeze
+
+ module_function
+
+ def field_key(field)
+ field["field_name"].presence || field["field_label"].to_s.parameterize(separator: "_")
+ end
+
+ def with_keys(fields)
+ Array.wrap(fields).map { |field| field.merge("key" => field_key(field)) }
+ end
+
+ def apply_query_defaults(fields, query_parameters)
+ normalized_query_parameters = (query_parameters || {}).to_h.with_indifferent_access
+
+ fields.map do |field|
+ key = field["key"] || field_key(field)
+ next field unless normalized_query_parameters.key?(key)
+
+ case field["field_type"]
+ when "hiddenField"
+ next field if field["field_value"].present?
+
+ field.merge("field_value" => normalized_query_parameters[key])
+ when "password", "html"
+ field
+ else
+ field.merge("default_value" => normalized_query_parameters[key])
+ end
+ end
+ end
+
+ def public_fields(fields)
+ fields.map do |field|
+ case field["field_type"]
+ when "hiddenField"
+ field.except("field_value", "default_value")
+ when "password"
+ field.except("default_value")
+ else
+ field
+ end
+ end
+ end
+
+ def validate_submission(fields, submitted_params, query_parameters: nil)
+ submitted = (submitted_params || {}).with_indifferent_access
+ query_parameters = (query_parameters || {}).to_h.with_indifferent_access
+ errors = []
+ data = {}
+
+ with_keys(fields).each do |field|
+ next if field["field_type"] == "html"
+
+ key = field["key"]
+
+ if field["field_type"] == "hiddenField"
+ data[key] = hidden_value(field, query_parameters)
+ next
+ end
+
+ value = submitted[key]
+
+ if missing?(field, value)
+ errors << build_error(field, :missing)
+ next
+ end
+
+ begin
+ coerced_value = coerce(value, field["field_type"])
+ if valid_value?(coerced_value, field)
+ data[key] = coerced_value
+ else
+ errors << build_error(field, :invalid_value)
+ end
+ rescue ArgumentError, TypeError
+ errors << build_error(field, :invalid_value)
+ end
+ end
+
+ ValidationResult.new(errors: errors, data: data)
+ end
+
+ def missing?(field, value)
+ return false unless field["required"]
+ return false if field["field_type"] == "checkbox"
+ return false if field["field_type"] == "hiddenField"
+ return false if field["field_type"] == "html"
+
+ value.blank?
+ end
+
+ def hidden_value(field, query_parameters)
+ value = field["field_value"].presence || query_parameters[field["key"]]
+
+ coerce(value.presence || "", "hiddenField")
+ end
+
+ def coerce(value, field_type)
+ case field_type
+ when "number"
+ return if value.blank?
+
+ value.to_s.include?(".") ? Float(value) : Integer(value)
+ when "checkbox"
+ ActiveModel::Type::Boolean.new.cast(value)
+ else
+ value.is_a?(String) ? value.truncate(MAX_FIELD_VALUE_LENGTH) : value
+ end
+ end
+
+ def valid_value?(value, field)
+ return true if value.blank?
+ return true unless field["field_type"] == "email"
+
+ EMAIL_REGEX.match?(value)
+ end
+
+ def build_error(field, code)
+ ValidationError.new(field_label: field["field_label"], code: code)
+ end
+ end
+ end
+end
diff --git a/plugins/discourse-workflows/lib/discourse_workflows/schemas/webhook.rb b/plugins/discourse-workflows/lib/discourse_workflows/schemas/webhook.rb
new file mode 100644
index 00000000000..da39676e806
--- /dev/null
+++ b/plugins/discourse-workflows/lib/discourse_workflows/schemas/webhook.rb
@@ -0,0 +1,126 @@
+# frozen_string_literal: true
+
+module DiscourseWorkflows
+ module Schemas::Webhook
+ HTTP_METHODS = %w[GET POST PUT DELETE PATCH HEAD].freeze
+
+ RESPONSE_MODE_ON_RECEIVED = "on_received"
+ RESPONSE_MODE_LAST_NODE = "last_node"
+ RESPONSE_MODE_RESPONSE_NODE = "response_node"
+ RESPONSE_MODES = [
+ RESPONSE_MODE_ON_RECEIVED,
+ RESPONSE_MODE_LAST_NODE,
+ RESPONSE_MODE_RESPONSE_NODE,
+ ].freeze
+
+ RESPONSE_DATA_FIRST_ENTRY_JSON = "first_entry_json"
+ RESPONSE_DATA_ALL_ENTRIES = "all_entries"
+ RESPONSE_DATA_NO_DATA = "no_data"
+ RESPONSE_DATA_MODES = [
+ RESPONSE_DATA_FIRST_ENTRY_JSON,
+ RESPONSE_DATA_ALL_ENTRIES,
+ RESPONSE_DATA_NO_DATA,
+ ].freeze
+
+ AUTH_MODES = %w[none basic_auth bearer_auth header_auth].freeze
+
+ CONFIGURATION_FIELDS = {
+ authentication: {
+ type: :options,
+ options: AUTH_MODES,
+ default: "none",
+ no_data_expression: true,
+ },
+ http_method: {
+ type: :options,
+ required: true,
+ default: "GET",
+ options: HTTP_METHODS,
+ ui: {
+ expression: true,
+ },
+ },
+ response_mode: {
+ type: :options,
+ required: true,
+ default: RESPONSE_MODE_ON_RECEIVED,
+ options: RESPONSE_MODES,
+ },
+ response_code: {
+ type: :string,
+ required: false,
+ default: "200",
+ display_options: {
+ show: {
+ response_mode: [RESPONSE_MODE_ON_RECEIVED, RESPONSE_MODE_LAST_NODE],
+ },
+ },
+ },
+ response_data: {
+ type: :options,
+ required: false,
+ default: RESPONSE_DATA_FIRST_ENTRY_JSON,
+ options: RESPONSE_DATA_MODES,
+ display_options: {
+ show: {
+ response_mode: [RESPONSE_MODE_LAST_NODE],
+ },
+ },
+ },
+ response_body: {
+ type: :string,
+ required: false,
+ display_options: {
+ show: {
+ response_mode: [RESPONSE_MODE_ON_RECEIVED],
+ },
+ },
+ ui: {
+ control: :textarea,
+ },
+ },
+ no_response_body: {
+ type: :boolean,
+ required: false,
+ default: false,
+ display_options: {
+ show: {
+ response_mode: [RESPONSE_MODE_ON_RECEIVED],
+ },
+ },
+ },
+ response_headers: {
+ type: :fixed_collection,
+ type_options: {
+ multiple_values: true,
+ },
+ options: [
+ {
+ name: "values",
+ values: {
+ key: {
+ type: :string,
+ required: true,
+ },
+ value: {
+ type: :string,
+ required: true,
+ },
+ },
+ },
+ ],
+ },
+ ip_allowlist: {
+ type: :string,
+ required: false,
+ },
+ ignore_bots: {
+ type: :boolean,
+ required: false,
+ default: false,
+ },
+ }.freeze
+
+ WEBHOOK_SUFFIX_FIELD = { type: :string, required: false }.freeze
+ end
+end
diff --git a/plugins/discourse-workflows/lib/discourse_workflows/trigger_dispatcher.rb b/plugins/discourse-workflows/lib/discourse_workflows/trigger_dispatcher.rb
new file mode 100644
index 00000000000..b7c6e10c2b4
--- /dev/null
+++ b/plugins/discourse-workflows/lib/discourse_workflows/trigger_dispatcher.rb
@@ -0,0 +1,37 @@
+# frozen_string_literal: true
+
+module DiscourseWorkflows
+ class TriggerDispatcher
+ def self.enqueue(published_trigger, trigger_data:, user_id: nil, run_at: nil)
+ args = {
+ workflow_id: published_trigger.workflow_id,
+ workflow_version_id: published_trigger.workflow_version_id,
+ trigger_node_id: published_trigger.trigger_node_id,
+ trigger_data: trigger_data,
+ }
+ args[:user_id] = user_id if user_id
+
+ if run_at.present? && run_at > Time.current
+ return Jobs.enqueue_at(run_at, Jobs::DiscourseWorkflows::ExecuteWorkflow, args)
+ end
+
+ Jobs.enqueue(Jobs::DiscourseWorkflows::ExecuteWorkflow, args)
+ end
+
+ def self.execute(published_trigger, trigger_data:, user: nil, webhook_context: nil)
+ options =
+ DiscourseWorkflows::Executor::ExecutionOptions.new(
+ user: user,
+ workflow_version: published_trigger.workflow_version,
+ webhook_context: webhook_context,
+ )
+
+ DiscourseWorkflows::Executor.new(
+ published_trigger.workflow,
+ published_trigger.trigger_node_id,
+ trigger_data,
+ options,
+ ).run
+ end
+ end
+end
diff --git a/plugins/discourse-workflows/lib/discourse_workflows/trigger_node_context.rb b/plugins/discourse-workflows/lib/discourse_workflows/trigger_node_context.rb
new file mode 100644
index 00000000000..ff30195ff08
--- /dev/null
+++ b/plugins/discourse-workflows/lib/discourse_workflows/trigger_node_context.rb
@@ -0,0 +1,44 @@
+# frozen_string_literal: true
+
+module DiscourseWorkflows
+ class TriggerNodeContext
+ MISSING = Object.new.freeze
+
+ def self.from_published_trigger(published_trigger)
+ new(published_trigger.trigger_node)
+ end
+
+ def initialize(trigger_node)
+ @trigger_node = trigger_node
+ end
+
+ def get_node_parameter(parameter_name, default = nil, _options = {})
+ value = parameter_value(parameter_name)
+ value.equal?(MISSING) ? default : value
+ end
+
+ private
+
+ def parameters
+ @parameters ||= DiscourseWorkflows::NodeData.parameters(@trigger_node)
+ end
+
+ def parameter_value(parameter_name)
+ segments = parameter_name.to_s.split(".").reject(&:blank?)
+ return MISSING if segments.empty?
+
+ segments.reduce(parameters) do |current, segment|
+ case current
+ when Hash
+ current.fetch(segment) { current.fetch(segment.to_sym, MISSING) }
+ when Array
+ return MISSING unless segment.match?(/\A\d+\z/)
+
+ current.fetch(segment.to_i) { return MISSING }
+ else
+ return MISSING
+ end
+ end
+ end
+ end
+end
diff --git a/plugins/discourse-workflows/lib/discourse_workflows/trigger_runtime.rb b/plugins/discourse-workflows/lib/discourse_workflows/trigger_runtime.rb
new file mode 100644
index 00000000000..58006bb86f5
--- /dev/null
+++ b/plugins/discourse-workflows/lib/discourse_workflows/trigger_runtime.rb
@@ -0,0 +1,157 @@
+# frozen_string_literal: true
+
+module DiscourseWorkflows
+ class TriggerRuntime
+ class << self
+ def tick!(now: Time.current.utc)
+ now = scheduled_minute(now)
+
+ published_triggers("trigger:schedule").each do |published_trigger|
+ run_trigger(published_trigger, mode: :normal, activation_mode: :trigger, now:, tick: true)
+ end
+ end
+
+ def activate_workflow!(workflow, workflow_version: workflow.active_version)
+ return if workflow_version.nil?
+
+ Webhook::Action::ActivateWebhooks.call(
+ workflow: workflow,
+ workflow_version: workflow_version,
+ )
+
+ activation_trigger_nodes(workflow_version).each do |node|
+ published_trigger = PublishedTrigger.new(workflow:, workflow_version:, trigger_node: node)
+ run_trigger(
+ published_trigger,
+ mode: :normal,
+ activation_mode: :init,
+ tick: false,
+ dispatch: :none,
+ )
+ end
+ end
+
+ def deactivate_workflow!(workflow)
+ Webhook::Action::DeactivateWebhooks.call(workflow: workflow)
+ end
+
+ def manual_trigger_data(workflow:, trigger_node:, user:)
+ workflow_version = workflow.workflow_versions.find_by(version_id: workflow.version_id)
+ node_type_class = node_type_for(trigger_node)
+ return {} unless node_type_class&.capability_enabled?(:synthesizes_manual_data)
+
+ published_trigger =
+ PublishedTrigger.new(workflow:, workflow_version:, trigger_node: trigger_node)
+ runtime_state = runtime_state_for(published_trigger)
+ ctx =
+ Executor::TriggerExecutionContext.new(
+ published_trigger:,
+ mode: :manual,
+ activation_mode: :manual,
+ dispatch: :collect,
+ user:,
+ runtime_state:,
+ )
+ result = instantiate(node_type_class, trigger_node).trigger(ctx)
+ result[:manual_trigger_function]&.call if result.is_a?(Hash)
+ commit_runtime_state!(published_trigger, runtime_state)
+ runtime_state.collected_trigger_data.first || {}
+ end
+
+ private
+
+ def published_triggers(trigger_type)
+ Workflow::Action::FindPublishedTriggers.call(trigger_type:)
+ end
+
+ def activation_trigger_nodes(workflow_version)
+ workflow_version.nodes.select { |node| activation_trigger_node?(node_type_for(node)) }
+ end
+
+ def run_trigger(
+ published_trigger,
+ mode:,
+ activation_mode:,
+ now: Time.current.utc,
+ tick: false,
+ dispatch: :enqueue
+ )
+ node_type_class = node_type_for(published_trigger.trigger_node)
+ return unless activation_trigger_node?(node_type_class)
+
+ published_trigger.workflow.with_lock do
+ runtime_state = runtime_state_for(published_trigger, tick:)
+ ctx =
+ Executor::TriggerExecutionContext.new(
+ published_trigger:,
+ mode:,
+ activation_mode:,
+ now:,
+ dispatch:,
+ runtime_state:,
+ )
+ instantiate(node_type_class, published_trigger.trigger_node).trigger(ctx)
+ commit_runtime_state!(published_trigger, runtime_state)
+ end
+ end
+
+ def runtime_state_for(published_trigger, tick: false)
+ workflow = published_trigger.workflow
+ trigger_node = published_trigger.trigger_node
+ node_name = trigger_node["name"].to_s
+
+ Executor::TriggerExecutionContext::RuntimeState.new(
+ trigger_state: workflow.node_trigger_state(published_trigger.trigger_node_id).deep_dup,
+ static_data_global: workflow.global_static_data.deep_dup,
+ static_data_node: workflow.node_static_data(node_name).deep_dup,
+ tick:,
+ )
+ end
+
+ def commit_runtime_state!(published_trigger, runtime_state)
+ workflow = published_trigger.workflow
+ node_name = published_trigger.trigger_node["name"].to_s
+
+ # trigger_state holds engine bookkeeping (dedup, last_triggered_at).
+ # static_data holds user-facing runtime state; we merge the trigger's
+ # flat `node:<name>` slot back without disturbing other nodes' entries.
+ # We skip writing the slot if it would be empty AND the slot didn't
+ # already exist, to avoid creating noise entries for triggers that
+ # never touched static data (e.g. activation-time runs).
+ workflow.transaction do
+ workflow.update_node_trigger_state!(
+ published_trigger.trigger_node_id,
+ runtime_state.trigger_state,
+ )
+
+ current_node_data = workflow.node_static_data_entries
+ merged_node = current_node_data.dup
+ if runtime_state.static_data_node.any? || current_node_data.key?(node_name)
+ merged_node[node_name] = runtime_state.static_data_node
+ end
+ workflow.commit_static_data!(global: runtime_state.static_data_global, node: merged_node)
+ end
+ end
+
+ def node_type_for(node)
+ Registry.find_node_type(node["type"], version: node["typeVersion"])
+ end
+
+ def activation_trigger_node?(node_type_class)
+ node_type_class&.capability_enabled?(:activation_trigger)
+ end
+
+ def instantiate(node_type_class, node)
+ node_type_class.new(
+ parameters: node["parameters"],
+ credentials: node["credentials"],
+ webhook_id: node["webhookId"],
+ )
+ end
+
+ def scheduled_minute(time)
+ time.utc.change(sec: 0, usec: 0)
+ end
+ end
+ end
+end
diff --git a/plugins/discourse-workflows/lib/discourse_workflows/waiting_execution.rb b/plugins/discourse-workflows/lib/discourse_workflows/waiting_execution.rb
new file mode 100644
index 00000000000..cf731234f27
--- /dev/null
+++ b/plugins/discourse-workflows/lib/discourse_workflows/waiting_execution.rb
@@ -0,0 +1,220 @@
+# frozen_string_literal: true
+
+module DiscourseWorkflows
+ class WaitingExecution
+ SIGNATURE_PARAM = "signature"
+ SIGNATURE_SALT = "discourse-workflows-waiting-signature"
+ ACTION_TOKEN_SALT = "discourse-workflows-waiting-action"
+ FORM_CHANNEL_SALT = "discourse-workflows-form-channel"
+ HMAC_KEY_LENGTH = 32
+
+ def self.find(execution_id:, signature:, expected_node_type: nil)
+ execution =
+ DiscourseWorkflows::Execution.includes(:workflow).find_by(
+ id: execution_id,
+ status: :waiting,
+ )
+ return unless execution
+ return unless valid_signature?(execution, signature)
+
+ if expected_node_type.present?
+ waiting_node = execution.find_waiting_node
+ return unless waiting_node&.dig("type") == expected_node_type
+ end
+
+ execution
+ end
+
+ def self.valid_signature?(execution, signature)
+ stored =
+ resume_signature(execution_id: execution.id, resume_token: execution.resume_token).to_s
+ provided = signature.to_s
+ return false if stored.blank? || provided.blank?
+ return false if stored.bytesize != provided.bytesize
+
+ ActiveSupport::SecurityUtils.secure_compare(stored, provided)
+ end
+
+ def self.claim(execution, signature:)
+ return unless valid_signature?(execution, signature)
+
+ DiscourseWorkflows::Execution.claim_for_resume(
+ execution,
+ resume_token: execution.resume_token,
+ )
+ end
+
+ def self.resume_claimed(execution, response_items, user: nil, webhook_context: nil)
+ DiscourseWorkflows::Executor.resume(
+ execution,
+ response_items,
+ user: user,
+ webhook_context: webhook_context,
+ )
+ end
+
+ def self.form_urls(execution)
+ {
+ form_channel: form_channel(execution),
+ form_waiting_url: form_waiting_url(execution),
+ form_submit_url: form_waiting_url(execution),
+ form_status_url: form_status_url(execution),
+ }
+ end
+
+ def self.form_waiting_url(execution, absolute: false)
+ form_waiting_url_for(
+ execution_id: execution.id,
+ resume_token: execution.resume_token,
+ absolute: absolute,
+ )
+ end
+
+ def self.form_waiting_url_for(execution_id:, resume_token:, absolute: false)
+ signed_url(
+ "/workflows/forms/waiting/#{execution_id.to_i}.json",
+ resume_signature(execution_id: execution_id, resume_token: resume_token),
+ absolute: absolute,
+ )
+ end
+
+ def self.form_status_url(execution, absolute: false)
+ form_status_url_for(
+ execution_id: execution.id,
+ resume_token: execution.resume_token,
+ absolute: absolute,
+ )
+ end
+
+ def self.form_status_url_for(execution_id:, resume_token:, absolute: false)
+ signed_url(
+ "/workflows/forms/waiting/#{execution_id.to_i}/status.json",
+ resume_signature(execution_id: execution_id, resume_token: resume_token),
+ absolute: absolute,
+ )
+ end
+
+ def self.form_channel(execution)
+ resume_token = execution.resume_token.to_s
+ return if resume_token.blank?
+
+ signature =
+ OpenSSL::HMAC.hexdigest("SHA256", form_channel_key, "#{execution.id}:#{resume_token}")
+ "/discourse-workflows/form-execution/#{execution.id}-#{signature}"
+ end
+
+ def self.webhook_url(execution_id:, resume_token:, suffix: nil, absolute: true)
+ webhook_url_with_signature(
+ execution_id: execution_id,
+ signature: resume_signature(execution_id: execution_id, resume_token: resume_token),
+ suffix: suffix,
+ absolute: absolute,
+ )
+ end
+
+ def self.webhook_url_with_signature(execution_id:, signature:, suffix: nil, absolute: true)
+ path = "/workflows/waiting/#{execution_id}/webhook"
+ path = "#{path}/#{suffix}" if suffix.present?
+ signed_url(path, signature, absolute: absolute)
+ end
+
+ def self.action_token(execution_id:, resume_token:, action:)
+ action = action.to_s
+ "#{execution_id.to_i}:#{action}:#{action_signature(execution_id:, resume_token:, action:)}"
+ end
+
+ def self.action_token_payload(token)
+ return if token.blank?
+
+ execution_id, action, signature = token.to_s.split(":", 3)
+ return if execution_id.blank? || action.blank? || signature.blank?
+ return unless execution_id.match?(/\A\d+\z/)
+
+ { "execution_id" => execution_id.to_i, "action" => action, "signature" => signature }
+ end
+
+ def self.find_by_action_token(token, expected_node_type:)
+ payload = action_token_payload(token)
+ return unless payload
+
+ execution =
+ DiscourseWorkflows::Execution.includes(:workflow).find_by(
+ id: payload["execution_id"],
+ status: :waiting,
+ )
+ return unless execution
+ return unless valid_action_signature?(execution, payload)
+
+ if expected_node_type.present?
+ waiting_node = execution.find_waiting_node
+ return unless waiting_node&.dig("type") == expected_node_type
+ end
+
+ execution
+ end
+
+ def self.signed_url(path, signature, absolute: false)
+ base = absolute ? Discourse.base_url : ""
+ separator = path.include?("?") ? "&" : "?"
+ "#{base}#{path}#{separator}#{SIGNATURE_PARAM}=#{Rack::Utils.escape(signature.to_s)}"
+ end
+ private_class_method :signed_url
+
+ def self.resume_signature(execution_id:, resume_token:)
+ resume_token = resume_token.to_s
+ return if resume_token.blank?
+
+ OpenSSL::HMAC.hexdigest("SHA256", signature_key, "#{execution_id.to_i}:#{resume_token}")
+ end
+
+ def self.valid_action_signature?(execution, payload)
+ signature = payload["signature"].to_s
+ expected =
+ action_signature(
+ execution_id: execution.id,
+ resume_token: execution.resume_token,
+ action: payload["action"],
+ )
+ return false if signature.bytesize != expected.bytesize
+
+ ActiveSupport::SecurityUtils.secure_compare(signature, expected)
+ end
+ private_class_method :valid_action_signature?
+
+ def self.action_signature(execution_id:, resume_token:, action:)
+ OpenSSL::HMAC.hexdigest(
+ "SHA256",
+ action_token_key,
+ "#{execution_id.to_i}:#{action}:#{resume_token}",
+ )
+ end
+ private_class_method :action_signature
+
+ def self.action_token_key
+ @action_token_key ||=
+ ActiveSupport::KeyGenerator.new(Rails.application.secret_key_base).generate_key(
+ ACTION_TOKEN_SALT,
+ HMAC_KEY_LENGTH,
+ )
+ end
+ private_class_method :action_token_key
+
+ def self.signature_key
+ @signature_key ||=
+ ActiveSupport::KeyGenerator.new(Rails.application.secret_key_base).generate_key(
+ SIGNATURE_SALT,
+ HMAC_KEY_LENGTH,
+ )
+ end
+ private_class_method :signature_key
+
+ def self.form_channel_key
+ @form_channel_key ||=
+ ActiveSupport::KeyGenerator.new(Rails.application.secret_key_base).generate_key(
+ FORM_CHANNEL_SALT,
+ HMAC_KEY_LENGTH,
+ )
+ end
+ private_class_method :form_channel_key
+ end
+end
diff --git a/plugins/discourse-workflows/lib/discourse_workflows/waiting_webhook_runner.rb b/plugins/discourse-workflows/lib/discourse_workflows/waiting_webhook_runner.rb
new file mode 100644
index 00000000000..e15848c949e
--- /dev/null
+++ b/plugins/discourse-workflows/lib/discourse_workflows/waiting_webhook_runner.rb
@@ -0,0 +1,154 @@
+# frozen_string_literal: true
+
+module DiscourseWorkflows
+ class WaitingWebhookRunner
+ Response = Struct.new(:status, :body, keyword_init: true)
+
+ def self.call(**kwargs)
+ new(**kwargs).call
+ end
+
+ def self.waiting_for?(execution, node_type:)
+ return false unless execution&.waiting?
+
+ node = execution.find_waiting_node
+ return false if node.blank?
+
+ node_class =
+ Registry.find_node_type(NodeData.read(node, "type"), version: NodeData.type_version(node))
+ return false unless node_class
+
+ node_class.waiting_webhook_for(http_method: "GET", path: "", node_type: node_type).present?
+ end
+
+ def initialize(
+ execution_id:,
+ signature:,
+ http_method:,
+ path:,
+ node_type:,
+ params: {},
+ service_params: {}
+ )
+ @execution_id = execution_id
+ @signature = signature
+ @http_method = http_method
+ @path = path.to_s
+ @node_type = node_type.to_s
+ @params = params || {}
+ @service_params = service_params || {}
+ end
+
+ def call
+ execution = WaitingExecution.find(execution_id: @execution_id, signature: @signature)
+ return not_found unless execution
+
+ node = execution.find_waiting_node
+ return not_found if node.blank?
+
+ node_class =
+ Registry.find_node_type(NodeData.read(node, "type"), version: NodeData.type_version(node))
+ return not_found unless node_class
+
+ webhook =
+ node_class.waiting_webhook_for(
+ http_method: @http_method,
+ path: @path,
+ node_type: @node_type,
+ )
+ return not_found unless webhook
+
+ webhook_context =
+ Executor::WebhookExecutionContext.new(
+ execution: execution,
+ node: node,
+ node_type_class: node_class,
+ webhook: webhook,
+ http_method: @http_method,
+ path: @path,
+ params: @params,
+ service_params: @service_params,
+ )
+ node_parameters = NodeData.parameters(node)
+ node =
+ node_class.new(
+ parameters: node_parameters,
+ credentials: NodeData.credentials(node),
+ webhook_id: NodeData.webhook_id(node),
+ )
+ response = node.webhook(webhook_context)
+ return response_from(response, execution) unless response.resume?
+
+ resume_execution(execution, response.workflow_data, node_class, node_parameters)
+ ensure
+ webhook_context&.dispose
+ end
+
+ private
+
+ def resume_execution(execution, workflow_data, node_class, node_parameters)
+ DiscourseWorkflows::ItemContract.validate_output_arrays!(
+ workflow_data,
+ source: "webhook:#{execution.waiting_node_id}",
+ ports: node_class.ports(node_parameters),
+ )
+ response_items = workflow_data.fetch(0) { [] }
+
+ claimed_execution = WaitingExecution.claim(execution, signature: @signature)
+ unless claimed_execution
+ return(
+ Response.new(
+ status: :conflict,
+ body: {
+ error: I18n.t("discourse_workflows.errors.already_resumed"),
+ },
+ )
+ )
+ end
+
+ resumed_execution =
+ WaitingExecution.resume_claimed(
+ claimed_execution,
+ response_items,
+ user: guardian_user,
+ ).reload
+
+ Response.new(
+ status: response_status_for(resumed_execution),
+ body: response_body_for(resumed_execution),
+ )
+ end
+
+ def response_body_for(execution)
+ return DiscourseWorkflows::FormResponse.resumed_submission(execution) if @node_type == "form"
+
+ { status: execution.status }
+ end
+
+ def response_status_for(execution)
+ if @node_type == "form"
+ return DiscourseWorkflows::FormResponse.resumed_submission_status(execution)
+ end
+
+ :ok
+ end
+
+ def response_from(response, execution)
+ body = response.body
+ if @node_type == "form" && @http_method == "GET" && @path.blank? && response.status == :ok
+ body = body.merge(DiscourseWorkflows::WaitingExecution.form_urls(execution))
+ end
+
+ Response.new(status: response.status, body: body)
+ end
+
+ def guardian_user
+ guardian = @service_params[:guardian] || @service_params["guardian"]
+ guardian&.user
+ end
+
+ def not_found
+ Response.new(status: :not_found, body: { error: "not_found" })
+ end
+ end
+end
diff --git a/plugins/discourse-workflows/lib/discourse_workflows/webhook_context.rb b/plugins/discourse-workflows/lib/discourse_workflows/webhook_context.rb
new file mode 100644
index 00000000000..6c21d035fda
--- /dev/null
+++ b/plugins/discourse-workflows/lib/discourse_workflows/webhook_context.rb
@@ -0,0 +1,53 @@
+# frozen_string_literal: true
+
+module DiscourseWorkflows
+ class WebhookContext
+ attr_reader :request, :response, :resume_items, :path_params
+
+ def initialize(request:, path_params: {})
+ @request = request
+ @response = nil
+ @resume_items = nil
+ @path_params = path_params
+ end
+
+ def apply_path_params(path_params)
+ @path_params = path_params || {}
+ @request =
+ WebhookRequest.new(
+ method: request.method,
+ path: request.path,
+ headers: request.headers,
+ params: @path_params,
+ query: request.query,
+ body: request.body,
+ raw_body: request.raw_body,
+ ip: request.ip,
+ ips: request.ips,
+ webhook_url: request.webhook_url,
+ )
+ end
+
+ def respond(response)
+ return false if responded?
+
+ @response = WebhookResponse.coerce(response)
+ true
+ end
+
+ def responded?
+ response.present?
+ end
+
+ def resume(items)
+ return false if resumed?
+
+ @resume_items = items
+ true
+ end
+
+ def resumed?
+ !resume_items.nil?
+ end
+ end
+end
diff --git a/plugins/discourse-workflows/lib/discourse_workflows/webhook_request.rb b/plugins/discourse-workflows/lib/discourse_workflows/webhook_request.rb
new file mode 100644
index 00000000000..d0a67c9f13b
--- /dev/null
+++ b/plugins/discourse-workflows/lib/discourse_workflows/webhook_request.rb
@@ -0,0 +1,44 @@
+# frozen_string_literal: true
+
+module DiscourseWorkflows
+ class WebhookRequest
+ attr_reader :method, :path, :headers, :params, :query, :body, :raw_body, :ip, :ips, :webhook_url
+
+ def initialize(
+ method:,
+ path:,
+ headers: {},
+ params: {},
+ query: {},
+ body: {},
+ raw_body: nil,
+ ip: nil,
+ ips: [],
+ webhook_url:
+ )
+ @method = method.to_s
+ @path = path.to_s
+ @headers = headers.to_h.deep_stringify_keys
+ @params = params.to_h.deep_stringify_keys
+ @query = query.to_h.deep_stringify_keys
+ @body = body
+ @raw_body = raw_body
+ @ip = ip
+ @ips = Array.wrap(ips).map(&:to_s)
+ @webhook_url = webhook_url.to_s
+ end
+
+ def item_json
+ data = {
+ "body" => body,
+ "headers" => headers,
+ "params" => params,
+ "query" => query,
+ "method" => method,
+ "webhook_url" => webhook_url,
+ }
+ data["raw_body"] = raw_body if raw_body.present?
+ data
+ end
+ end
+end
diff --git a/plugins/discourse-workflows/lib/discourse_workflows/webhook_request_parser.rb b/plugins/discourse-workflows/lib/discourse_workflows/webhook_request_parser.rb
new file mode 100644
index 00000000000..522e077d7a9
--- /dev/null
+++ b/plugins/discourse-workflows/lib/discourse_workflows/webhook_request_parser.rb
@@ -0,0 +1,71 @@
+# frozen_string_literal: true
+
+module DiscourseWorkflows
+ class WebhookRequestParser
+ MAX_BODY_SIZE = 1.megabyte
+ BODY_TOO_LARGE_ERROR = "Request body too large"
+
+ FILTERED_HEADERS = %w[authorization cookie proxy-authorization].to_set.freeze
+
+ RACK_UNPREFIXED_HEADERS = {
+ "CONTENT_TYPE" => "content-type",
+ "CONTENT_LENGTH" => "content-length",
+ }.freeze
+
+ def initialize(request, params)
+ @request = request
+ @params = params
+ end
+
+ def parse_body
+ validate_body_size!
+
+ if @request.content_type&.include?("application/json")
+ parse_json_body
+ else
+ if @request.raw_post.bytesize > MAX_BODY_SIZE
+ raise Discourse::InvalidParameters, BODY_TOO_LARGE_ERROR
+ end
+ @params.except(:path, :listener_id, :controller, :action, :format).to_unsafe_h
+ end
+ end
+
+ def extract_headers
+ @request
+ .headers
+ .env
+ .each_with_object({}) do |(key, value), headers|
+ header_name = normalize_header_name(key)
+ next unless header_name
+
+ headers[header_name] = FILTERED_HEADERS.include?(header_name) ? "[FILTERED]" : value.to_s
+ end
+ end
+
+ private
+
+ def validate_body_size!
+ if (@request.content_length || 0) > MAX_BODY_SIZE
+ raise Discourse::InvalidParameters, BODY_TOO_LARGE_ERROR
+ end
+ end
+
+ def parse_json_body
+ body = @request.raw_post
+ raise Discourse::InvalidParameters, BODY_TOO_LARGE_ERROR if body.bytesize > MAX_BODY_SIZE
+ parsed = JSON.parse(body)
+ raise Discourse::InvalidParameters, "JSON body must be an object" unless parsed.is_a?(Hash)
+ parsed
+ rescue JSON::ParserError
+ raise Discourse::InvalidParameters, "Invalid JSON in request body"
+ end
+
+ def normalize_header_name(key)
+ if key.start_with?("HTTP_")
+ key.delete_prefix("HTTP_").downcase.tr("_", "-")
+ else
+ RACK_UNPREFIXED_HEADERS[key]
+ end
+ end
+ end
+end
diff --git a/plugins/discourse-workflows/lib/discourse_workflows/webhook_response.rb b/plugins/discourse-workflows/lib/discourse_workflows/webhook_response.rb
new file mode 100644
index 00000000000..24eb8d37f9a
--- /dev/null
+++ b/plugins/discourse-workflows/lib/discourse_workflows/webhook_response.rb
@@ -0,0 +1,82 @@
+# frozen_string_literal: true
+
+module DiscourseWorkflows
+ class WebhookResponse
+ attr_reader :body, :headers, :status, :status_code, :workflow_data
+
+ def self.coerce(response)
+ return response if response.is_a?(self)
+
+ response = response.to_h.with_indifferent_access
+ new(
+ body: response[:body],
+ headers: response[:headers] || {},
+ no_body: response[:no_body] || false,
+ status: response[:status],
+ status_code: response[:status_code] || response[:status],
+ )
+ end
+
+ def self.respond(status:, body: {}, headers: {})
+ new(body: body, headers: headers, status: status, status_code: status)
+ end
+
+ def self.resume(workflow_data:, status: :ok, body: {}, headers: {})
+ new(
+ body: body,
+ headers: headers,
+ status: status,
+ status_code: status,
+ workflow_data: workflow_data,
+ )
+ end
+
+ def self.success
+ new(body: { success: true }, status_code: 200)
+ end
+
+ def initialize(
+ body: nil,
+ headers: {},
+ no_body: false,
+ status: nil,
+ status_code: 200,
+ workflow_data: nil
+ )
+ @body = body
+ @headers = headers.to_h.stringify_keys
+ @no_body = no_body
+ @status_code = sanitize_status_code(status_code || status)
+ @status = status || @status_code
+ @workflow_data = workflow_data
+ end
+
+ def location
+ headers["Location"] || headers["location"]
+ end
+
+ def redirect?
+ location.present? && (300..399).cover?(status_code)
+ end
+
+ def no_body?
+ @no_body
+ end
+
+ def resume?
+ workflow_data.present?
+ end
+
+ def text?
+ headers["Content-Type"].to_s.start_with?("text/plain") ||
+ headers["content-type"].to_s.start_with?("text/plain")
+ end
+
+ private
+
+ def sanitize_status_code(code)
+ status = Rack::Utils.status_code(code.presence || 200)
+ (200..599).cover?(status) ? status : 200
+ end
+ end
+end
diff --git a/plugins/discourse-workflows/lib/discourse_workflows/webhook_response_builder.rb b/plugins/discourse-workflows/lib/discourse_workflows/webhook_response_builder.rb
new file mode 100644
index 00000000000..f0e0ee9a0a4
--- /dev/null
+++ b/plugins/discourse-workflows/lib/discourse_workflows/webhook_response_builder.rb
@@ -0,0 +1,90 @@
+# frozen_string_literal: true
+
+module DiscourseWorkflows
+ class WebhookResponseBuilder
+ def self.immediate(parameters)
+ new(parameters).immediate
+ end
+
+ def self.last_node(execution, parameters)
+ new(parameters).last_node(execution)
+ end
+
+ def initialize(parameters)
+ @parameters = (parameters || {}).deep_stringify_keys
+ end
+
+ def immediate
+ WebhookResponse.new(
+ body: immediate_body,
+ headers: response_headers,
+ no_body: immediate_no_body?,
+ status_code: response_code,
+ )
+ end
+
+ def last_node(execution)
+ WebhookResponse.new(
+ body: last_node_body(execution),
+ headers: response_headers,
+ no_body: last_node_no_body?,
+ status_code: response_code,
+ )
+ end
+
+ private
+
+ def immediate_body
+ return nil if immediate_no_body?
+
+ body = @parameters["response_body"]
+ return { success: true } if body.blank?
+
+ parse_json_body(body)
+ end
+
+ def last_node_body(execution)
+ case @parameters["response_data"].presence || Schemas::Webhook::RESPONSE_DATA_FIRST_ENTRY_JSON
+ when Schemas::Webhook::RESPONSE_DATA_ALL_ENTRIES
+ last_node_items(execution).map { |item| item["json"] || {} }
+ when Schemas::Webhook::RESPONSE_DATA_NO_DATA
+ nil
+ else
+ last_node_items(execution).dig(0, "json")
+ end
+ end
+
+ def last_node_items(execution)
+ last_step = execution.execution_data&.last_step_with_status("success")
+ Array.wrap(last_step&.dig("output"))
+ end
+
+ def immediate_no_body?
+ @parameters["no_response_body"] == true
+ end
+
+ def last_node_no_body?
+ @parameters["response_data"] == Schemas::Webhook::RESPONSE_DATA_NO_DATA
+ end
+
+ def response_code
+ (@parameters["response_code"].presence || 200).to_i
+ end
+
+ def response_headers
+ rows = @parameters.dig("response_headers", "values") || []
+ rows.each_with_object({}) do |header, result|
+ key = header["key"].to_s
+ result[key] = header["value"].to_s if key.present?
+ end
+ end
+
+ def parse_json_body(body)
+ return body unless body.is_a?(String)
+
+ JSON.parse(body)
+ rescue JSON::ParserError
+ body
+ end
+ end
+end
diff --git a/plugins/discourse-workflows/lib/discourse_workflows/webhook_response_renderer.rb b/plugins/discourse-workflows/lib/discourse_workflows/webhook_response_renderer.rb
new file mode 100644
index 00000000000..05be6625d4d
--- /dev/null
+++ b/plugins/discourse-workflows/lib/discourse_workflows/webhook_response_renderer.rb
@@ -0,0 +1,36 @@
+# frozen_string_literal: true
+
+module DiscourseWorkflows
+ class WebhookResponseRenderer
+ def self.render(controller, response)
+ new(controller, WebhookResponse.coerce(response)).render
+ end
+
+ def initialize(controller, response)
+ @controller = controller
+ @response = response
+ end
+
+ def render
+ apply_headers
+
+ if @response.redirect?
+ @controller.redirect_to @response.location,
+ status: @response.status_code,
+ allow_other_host: true
+ elsif @response.no_body?
+ @controller.head @response.status_code
+ elsif @response.text?
+ @controller.render plain: @response.body.to_s, status: @response.status_code
+ else
+ @controller.render json: @response.body, status: @response.status_code
+ end
+ end
+
+ private
+
+ def apply_headers
+ @response.headers.each { |key, value| @controller.response.headers[key] = value }
+ end
+ end
+end
diff --git a/plugins/discourse-workflows/lib/discourse_workflows/webhook_test_listener.rb b/plugins/discourse-workflows/lib/discourse_workflows/webhook_test_listener.rb
new file mode 100644
index 00000000000..16e55406d9d
--- /dev/null
+++ b/plugins/discourse-workflows/lib/discourse_workflows/webhook_test_listener.rb
@@ -0,0 +1,139 @@
+# frozen_string_literal: true
+
+module DiscourseWorkflows
+ class WebhookTestListener
+ class ActiveRouteExists < StandardError
+ end
+
+ TTL = 120.seconds
+
+ def self.create!(workflow:, user:, trigger_node:)
+ parameters = NodeData.parameters(trigger_node)
+ http_method = Webhook.normalize_method(parameters["http_method"].to_s)
+ webhook_path = Webhook.normalize_path(parameters["path"].to_s)
+ listener_id = SecureRandom.uuid
+ snapshot = WorkflowSnapshot.from_workflow(workflow).to_h
+ node_name = trigger_node["name"].to_s
+
+ record =
+ Webhook.transaction do
+ Webhook
+ .test_listeners
+ .where(http_method: http_method, webhook_path: webhook_path)
+ .find_each do |existing|
+ if existing_can_be_replaced?(existing, workflow:, user:, node_name:)
+ existing.destroy!
+ else
+ raise ActiveRouteExists
+ end
+ end
+
+ Webhook.create!(
+ workflow_id: workflow.id,
+ node_name: node_name,
+ webhook_path: webhook_path,
+ http_method: http_method,
+ webhook_id: listener_id,
+ test_webhook: true,
+ user_id: user.id,
+ workflow_snapshot: snapshot,
+ expires_at: Time.current + TTL,
+ )
+ end
+
+ ActiveWebhooks.invalidate!
+ new(record)
+ rescue ActiveRecord::RecordNotUnique
+ raise ActiveRouteExists
+ end
+
+ def self.find(listener_id)
+ record = Webhook.test_listeners.live.find_by(webhook_id: listener_id.to_s)
+ record ? new(record) : nil
+ end
+
+ def self.find_by_route(method:, path:)
+ record =
+ Webhook.test_listeners.live.find_by(
+ http_method: Webhook.normalize_method(method),
+ webhook_path: Webhook.normalize_path(path),
+ )
+ record ? new(record) : nil
+ end
+
+ def self.find_for_request(listener_id:, method:, path:)
+ record =
+ Webhook.test_listeners.live.find_by(
+ webhook_id: listener_id.to_s,
+ http_method: Webhook.normalize_method(method),
+ webhook_path: Webhook.normalize_path(path),
+ )
+ record ? new(record) : nil
+ end
+
+ def self.claim(listener)
+ deleted = Webhook.test_listeners.where(id: listener.id).delete_all
+ return nil if deleted.zero?
+
+ ActiveWebhooks.invalidate!
+ listener
+ end
+
+ def self.cancel!(listener)
+ Webhook.test_listeners.where(id: listener.id).delete_all
+ ActiveWebhooks.invalidate!
+ end
+
+ def self.purge_expired!
+ deleted = Webhook.test_listeners.expired.delete_all
+ ActiveWebhooks.invalidate! if deleted.positive?
+ deleted
+ end
+
+ attr_reader :id,
+ :listener_id,
+ :workflow_id,
+ :user_id,
+ :trigger_node_name,
+ :http_method,
+ :path,
+ :workflow_snapshot,
+ :expires_at
+
+ def initialize(record)
+ @id = record.id
+ @listener_id = record.webhook_id.to_s
+ @workflow_id = record.workflow_id
+ @user_id = record.user_id
+ @trigger_node_name = record.node_name.to_s
+ @http_method = record.http_method
+ @path = record.webhook_path
+ @workflow_snapshot = WorkflowSnapshot.new(record.workflow_snapshot || {})
+ @expires_at = record.expires_at || (Time.current + TTL)
+ end
+
+ def trigger_node
+ workflow_snapshot.find_node_by_name(trigger_node_name)
+ end
+
+ def trigger_node_id
+ trigger_node&.id
+ end
+
+ def owned_by?(user)
+ user.present? && user.id == user_id
+ end
+
+ def test_url
+ "/workflows/webhook-test/#{listener_id}/#{path}"
+ end
+
+ def self.existing_can_be_replaced?(existing, workflow:, user:, node_name:)
+ return true if existing.expires_at.present? && existing.expires_at <= Time.current
+
+ existing.workflow_id == workflow.id && existing.user_id == user.id &&
+ existing.node_name.to_s == node_name
+ end
+ private_class_method :existing_can_be_replaced?
+ end
+end
diff --git a/plugins/discourse-workflows/lib/discourse_workflows/workflow_dependency_indexer.rb b/plugins/discourse-workflows/lib/discourse_workflows/workflow_dependency_indexer.rb
new file mode 100644
index 00000000000..08d3ce99a50
--- /dev/null
+++ b/plugins/discourse-workflows/lib/discourse_workflows/workflow_dependency_indexer.rb
@@ -0,0 +1,71 @@
+# frozen_string_literal: true
+
+module DiscourseWorkflows
+ class WorkflowDependencyIndexer
+ def self.call(
+ workflow,
+ version: workflow.workflow_versions.find_by(version_id: workflow.version_id)
+ )
+ new(workflow, version:).call
+ end
+
+ def initialize(workflow, version:)
+ @workflow = workflow
+ @version = version
+ end
+
+ def call
+ return unless @version
+
+ rows = []
+
+ @version.nodes.each do |node|
+ node_id = node["id"]
+ node_type = node["type"]
+ parameters = NodeData.parameters(node)
+ split =
+ NodeData.split(
+ parameters: parameters,
+ credentials: NodeData.credentials(node),
+ node_type: node_type,
+ )
+ credentials = split["credentials"]
+
+ rows << build_row("node_type", node_type, node_id) if node_type.present?
+
+ credentials.each_value do |credential|
+ rows << build_row("credential_id", credential["id"], node_id) if credential["id"].present?
+ end
+
+ if (dt_id = parameters["data_table_id"]).present?
+ rows << build_row("data_table_id", dt_id, node_id)
+ end
+ end
+
+ if @workflow.error_workflow_id.present?
+ rows << build_row("error_workflow", @workflow.error_workflow_id, nil)
+ end
+
+ @workflow.with_lock do
+ WorkflowDependency.where(workflow_version_id: @version.version_id).delete_all
+
+ WorkflowDependency.insert_all(rows) if rows.present?
+ end
+
+ WorkflowDependency.clear_cache!
+ end
+
+ private
+
+ def build_row(type, key, node_id)
+ {
+ workflow_id: @workflow.id,
+ dependency_type: type,
+ dependency_key: key.to_s,
+ node_id: node_id,
+ workflow_version_id: @version.version_id,
+ created_at: Time.current,
+ }
+ end
+ end
+end
diff --git a/plugins/discourse-workflows/lib/discourse_workflows/workflow_document.rb b/plugins/discourse-workflows/lib/discourse_workflows/workflow_document.rb
new file mode 100644
index 00000000000..1ab5d2d010c
--- /dev/null
+++ b/plugins/discourse-workflows/lib/discourse_workflows/workflow_document.rb
@@ -0,0 +1,159 @@
+# frozen_string_literal: true
+
+module DiscourseWorkflows
+ module WorkflowDocument
+ DEFAULT_CONNECTION_TYPE = "main"
+
+ module_function
+
+ def normalize_connections(nodes, connections)
+ return {} unless connections.is_a?(Hash)
+
+ node_names = Set.new(nodes.map { |node| node["name"].to_s })
+
+ connections.each_with_object({}) do |(source_name, outputs_by_type), normalized|
+ source_name = source_name.to_s
+ next if source_name.blank? || !node_names.include?(source_name)
+ next unless outputs_by_type.is_a?(Hash)
+
+ outputs_by_type.each do |connection_type, output_connections|
+ connection_type = connection_type.presence || DEFAULT_CONNECTION_TYPE
+ normalized_outputs = normalize_output_connections(output_connections, node_names)
+ next if normalized_outputs.all?(&:blank?)
+
+ normalized[source_name] ||= {}
+ normalized[source_name][connection_type] = normalized_outputs
+ end
+ end
+ end
+
+ def connection_records(nodes, connections)
+ nodes_by_name = nodes.index_by { |node| node["name"].to_s }
+
+ normalize_connections(nodes, connections).flat_map do |source_name, outputs_by_type|
+ source_node = nodes_by_name[source_name]
+ next [] unless source_node
+
+ outputs_by_type.flat_map do |connection_type, output_connections|
+ Array(output_connections).flat_map.with_index do |target_connections, source_output_index|
+ Array(target_connections).filter_map do |target_connection|
+ target_node = nodes_by_name[target_connection["node"].to_s]
+ next unless target_node
+
+ {
+ "source_node_id" => source_node["id"].to_s,
+ "source_output_index" => source_output_index,
+ "target_node_id" => target_node["id"].to_s,
+ "target_input_index" => target_connection["index"].to_i,
+ "connection_type" => target_connection["type"].presence || connection_type,
+ }
+ end
+ end
+ end
+ end
+ end
+
+ def connections_from_records(nodes, connection_records)
+ nodes_by_id = nodes.index_by { |node| node["id"].to_s }
+
+ Array(connection_records).each_with_object({}) do |connection, result|
+ source_node = nodes_by_id[read_connection(connection, "source_node_id").to_s]
+ target_node = nodes_by_id[read_connection(connection, "target_node_id").to_s]
+ next if source_node.blank? || target_node.blank?
+
+ source_name = source_node["name"].to_s
+ target_name = target_node["name"].to_s
+ connection_type =
+ read_connection(connection, "connection_type").presence || DEFAULT_CONNECTION_TYPE
+ source_output_index = read_connection(connection, "source_output_index").to_i
+ target_input_index = read_connection(connection, "target_input_index").to_i
+
+ result[source_name] ||= {}
+ result[source_name][connection_type] ||= []
+ while result[source_name][connection_type].length <= source_output_index
+ result[source_name][connection_type] << []
+ end
+ result[source_name][connection_type][source_output_index] << {
+ "node" => target_name,
+ "type" => connection_type,
+ "index" => target_input_index,
+ }
+ end
+ end
+
+ def workflow_payload(workflow, published: false)
+ version = published ? workflow.active_version : nil
+ nodes = published ? workflow.published_nodes : workflow.nodes
+ connections = published ? workflow.published_connections : workflow.connections
+ name = version&.name || workflow.name
+
+ {
+ "id" => workflow.id.to_s,
+ "name" => name,
+ "nodes" => nodes || [],
+ "connections" => connections || {},
+ "settings" => (published ? version&.settings : workflow.settings) || {},
+ "staticData" => workflow.normalized_static_data,
+ "pinData" => workflow.pin_data || {},
+ "versionId" => (published ? version&.version_id : workflow.version_id),
+ "activeVersionId" => workflow.active_version_id,
+ "versionCounter" => workflow.version_counter,
+ }
+ end
+
+ def node_type_version(node)
+ if node.respond_to?(:type_version)
+ node.type_version
+ else
+ node["typeVersion"]
+ end
+ end
+
+ def node_webhook_id(node)
+ if node.respond_to?(:webhook_id)
+ node.webhook_id
+ else
+ node[node_webhook_id_key]
+ end
+ end
+
+ def node_type_version_key
+ "typeVersion"
+ end
+
+ def node_webhook_id_key
+ NodeDataShape::FORM_TRIGGER_WEBHOOK_ID_KEY
+ end
+
+ def normalize_output_connections(output_connections, node_names)
+ Array(output_connections).map do |target_connections|
+ next [] if target_connections.nil?
+
+ normalized_targets =
+ Array(target_connections).filter_map do |target_connection|
+ next unless target_connection.is_a?(Hash)
+
+ target_connection = target_connection.deep_stringify_keys
+ target_name = target_connection["node"].to_s
+ next if target_name.blank? || !node_names.include?(target_name)
+
+ {
+ "node" => target_name,
+ "type" => target_connection["type"].presence || DEFAULT_CONNECTION_TYPE,
+ "index" => target_connection["index"].to_i,
+ }
+ end
+
+ normalized_targets.presence || []
+ end
+ end
+ private_class_method :normalize_output_connections
+
+ def read_connection(connection, key)
+ return connection.public_send(key) if connection.respond_to?(key)
+
+ connection[key] || connection[key.to_sym]
+ end
+ private_class_method :read_connection
+ end
+end
diff --git a/plugins/discourse-workflows/lib/discourse_workflows/workflow_graph_validator.rb b/plugins/discourse-workflows/lib/discourse_workflows/workflow_graph_validator.rb
new file mode 100644
index 00000000000..006dbfa2ed8
--- /dev/null
+++ b/plugins/discourse-workflows/lib/discourse_workflows/workflow_graph_validator.rb
@@ -0,0 +1,281 @@
+# frozen_string_literal: true
+
+module DiscourseWorkflows
+ class WorkflowGraphValidator
+ MAX_NODES = 50
+ UNSUPPORTED_NODE_KEYS = %i[type_version webhook_id position_index settings].freeze
+ STICKY_NOTE_TYPE = "flow:sticky_note"
+
+ attr_reader :workflow
+
+ def initialize(workflow:, nodes_data:, connections_data:)
+ @workflow = workflow
+ @nodes_data = nodes_data || []
+ @connections_data = connections_data || {}
+ end
+
+ def valid?
+ validate_payload_shape
+ return false if workflow.errors.any?
+
+ validate_node_fields
+ return false if workflow.errors.any?
+
+ validate_node_count
+ validate_node_json_keys
+ validate_unique_node_names
+ validate_node_type_limits
+ return false if workflow.errors.any?
+
+ existing_nodes_index = workflow.nodes.index_by { |n| n["id"] }
+
+ normalized_nodes_data.each do |node_data|
+ existing = existing_nodes_index[node_data[:id].to_s]
+ type_version = resolve_type_version(node_data, existing)
+ validate_node_type(node_data, type_version)
+ validate_node_version(node_data, type_version)
+ end
+
+ return false if workflow.errors.any?
+
+ validate_connections
+ workflow.errors.empty?
+ end
+
+ def nodes
+ node_map.values
+ end
+
+ def connections
+ DiscourseWorkflows::WorkflowDocument.normalize_connections(nodes, connections_data)
+ end
+
+ private
+
+ attr_reader :nodes_data, :connections_data
+
+ def validate_payload_shape
+ unless nodes_data.is_a?(Array)
+ workflow.errors.add(:base, I18n.t("discourse_workflows.errors.invalid_nodes"))
+ end
+
+ if nodes_data.is_a?(Array) && nodes_data.any? { |node| !node.is_a?(Hash) }
+ workflow.errors.add(:base, I18n.t("discourse_workflows.errors.invalid_nodes"))
+ end
+
+ unless connections_data.is_a?(Hash)
+ workflow.errors.add(:base, I18n.t("discourse_workflows.errors.invalid_connections"))
+ end
+ end
+
+ def validate_node_fields
+ normalized_nodes_data.each do |node_data|
+ validate_node_type_presence(node_data)
+ validate_node_name_presence(node_data)
+ validate_node_hash_field(node_data, :parameters)
+ validate_node_hash_field(node_data, :credentials)
+ end
+ end
+
+ def validate_node_type_presence(node_data)
+ return if node_data[:type].present?
+
+ workflow.errors.add(:base, I18n.t("discourse_workflows.errors.node_types_required"))
+ end
+
+ def validate_node_name_presence(node_data)
+ return if node_data[:name].present?
+
+ workflow.errors.add(:base, I18n.t("discourse_workflows.errors.node_names_required"))
+ end
+
+ def validate_node_hash_field(node_data, field)
+ return if node_data[field].nil? || node_data[field].is_a?(Hash)
+
+ workflow.errors.add(:base, I18n.t("discourse_workflows.errors.invalid_node_fields"))
+ end
+
+ def validate_node_count
+ if normalized_nodes_data.size > MAX_NODES
+ workflow.errors.add(
+ :base,
+ I18n.t("discourse_workflows.errors.max_nodes_exceeded", max: MAX_NODES),
+ )
+ end
+ end
+
+ def validate_node_json_keys
+ return if normalized_nodes_data.none? { |node_data| unsupported_node_key?(node_data) }
+
+ workflow.errors.add(:base, I18n.t("discourse_workflows.errors.invalid_node_json_keys"))
+ end
+
+ def unsupported_node_key?(node_data)
+ (node_data.keys & UNSUPPORTED_NODE_KEYS).present?
+ end
+
+ def validate_unique_node_names
+ executable_names =
+ normalized_nodes_data
+ .reject { |node_data| sticky_note?(node_data) }
+ .map { |node_data| node_data[:name].to_s }
+ sticky_note_names =
+ normalized_nodes_data
+ .select { |node_data| sticky_note?(node_data) }
+ .map { |node_data| node_data[:name].to_s }
+
+ duplicate_names = executable_names.tally.select { |_name, count| count > 1 }.keys
+ duplicate_names += sticky_note_names & executable_names
+ duplicate_names = duplicate_names.uniq
+
+ return if duplicate_names.empty?
+
+ workflow.errors.add(
+ :base,
+ I18n.t(
+ "discourse_workflows.errors.duplicate_node_names",
+ names: duplicate_names.join(", "),
+ ),
+ )
+ end
+
+ def sticky_note?(node_data)
+ node_data[:type] == STICKY_NOTE_TYPE
+ end
+
+ def validate_node_type_limits
+ normalized_nodes_data
+ .group_by { |node_data| node_data[:type] }
+ .each do |type, nodes|
+ node_type_class = DiscourseWorkflows::Registry.find_node_type(type)
+ max_nodes = node_type_class&.max_nodes
+ next if max_nodes.blank? || nodes.size <= max_nodes
+
+ workflow.errors.add(
+ :base,
+ I18n.t("discourse_workflows.errors.max_nodes_of_type_exceeded", max: max_nodes, type:),
+ )
+ end
+ end
+
+ def validate_node_type(node_data, type_version)
+ node_type_class =
+ DiscourseWorkflows::Registry.find_node_type(
+ node_data[:type],
+ version: type_version,
+ include_disabled_plugins: true,
+ )
+ parameters = split_node_data(node_data, existing: nil)[:parameters]
+
+ if node_type_class.respond_to?(:validate_configuration)
+ node_type_class.validate_configuration(parameters, workflow.errors)
+ end
+ end
+
+ def validate_node_version(node_data, type_version)
+ if DiscourseWorkflows::Registry.available_versions(
+ node_data[:type],
+ include_disabled_plugins: true,
+ ).exclude?(type_version)
+ workflow.errors.add(
+ :base,
+ I18n.t(
+ "discourse_workflows.errors.unsupported_node_version",
+ version: type_version,
+ type: node_data[:type],
+ ),
+ )
+ end
+ end
+
+ def validate_connections
+ connection_records.each do |connection_data|
+ target =
+ node_map.values.find { |node| node["id"].to_s == connection_data["target_node_id"].to_s }
+ next if target.blank?
+
+ target_type =
+ DiscourseWorkflows::Registry.find_node_type(
+ target["type"],
+ version: target["typeVersion"],
+ include_disabled_plugins: true,
+ )
+ next if target_type&.inputs(target["parameters"]).present?
+
+ workflow.errors.add(
+ :base,
+ I18n.t("discourse_workflows.errors.node_does_not_accept_inputs", node: target["name"]),
+ )
+ end
+ end
+
+ def connection_records
+ DiscourseWorkflows::WorkflowDocument.connection_records(nodes, connections_data)
+ end
+
+ def node_map
+ @node_map ||= build_node_map
+ end
+
+ def build_node_map
+ existing_nodes = workflow.nodes.index_by { |n| n["id"] }
+ node_map = {}
+
+ normalized_nodes_data.each do |node_data|
+ node_id = (node_data[:id].presence || SecureRandom.uuid).to_s
+ existing = existing_nodes[node_id]
+ node_map[node_id] = build_node_hash(node_data, node_id:, existing:)
+ end
+
+ node_map
+ end
+
+ def build_node_hash(node_data, node_id:, existing:)
+ node_data = split_node_data(node_data, existing:)
+
+ {
+ "id" => existing ? existing["id"] : (node_id.presence || SecureRandom.uuid),
+ "type" => node_data[:type],
+ "typeVersion" => resolve_type_version(node_data, existing),
+ "name" => node_data[:name],
+ "position" => node_data[:position],
+ "parameters" => node_data[:parameters],
+ "credentials" => node_data[:credentials],
+ "webhookId" => node_data[:webhookId],
+ }.merge(node_data[:directSettings])
+ end
+
+ def resolve_type_version(node_data, existing)
+ existing&.dig("typeVersion") || node_data[:typeVersion] ||
+ DiscourseWorkflows::Registry.latest_version(node_data[:type]) ||
+ DiscourseWorkflows::Registry::DEFAULT_VERSION
+ end
+
+ def normalized_nodes_data
+ @normalized_nodes_data ||= nodes_data.map(&:symbolize_keys)
+ end
+
+ def split_node_data(node_data, existing:)
+ split =
+ NodeData.split(
+ parameters: node_data[:parameters],
+ credentials: node_data[:credentials],
+ webhook_id: resolved_webhook_id(node_data, existing: existing),
+ node_type: node_data[:type],
+ )
+
+ node_data.merge(
+ parameters: split["parameters"],
+ credentials: split["credentials"],
+ webhookId: split[DiscourseWorkflows::WorkflowDocument.node_webhook_id_key],
+ directSettings: NodeData.direct_settings(node_data),
+ )
+ end
+
+ def resolved_webhook_id(node_data, existing:)
+ return node_data[:webhookId].presence if node_data[:webhookId].present?
+ return existing["webhookId"] if existing&.dig("webhookId").present?
+ SecureRandom.uuid if node_data[:type] == NodeDataShape::FORM_TRIGGER_TYPE
+ end
+ end
+end
diff --git a/plugins/discourse-workflows/lib/discourse_workflows/workflow_snapshot.rb b/plugins/discourse-workflows/lib/discourse_workflows/workflow_snapshot.rb
new file mode 100644
index 00000000000..b3d519ea870
--- /dev/null
+++ b/plugins/discourse-workflows/lib/discourse_workflows/workflow_snapshot.rb
@@ -0,0 +1,260 @@
+# frozen_string_literal: true
+
+module DiscourseWorkflows
+ class WorkflowSnapshot
+ SnapshotNode =
+ Struct.new(
+ :id,
+ :type,
+ :type_version,
+ :name,
+ :position,
+ :parameters,
+ :credentials,
+ :webhook_id,
+ :notes,
+ :notes_in_flow,
+ :always_output_data,
+ :on_error,
+ :continue_on_fail,
+ keyword_init: true,
+ ) do
+ def resolved_parameters
+ NodeData.resolved_parameters(self)
+ end
+
+ def to_workflow_node
+ {
+ "id" => id,
+ "type" => type,
+ "typeVersion" => type_version,
+ "name" => name,
+ "position" => position,
+ "parameters" => parameters,
+ "credentials" => credentials,
+ "webhookId" => webhook_id,
+ }.merge(NodeData.direct_settings(self)).compact
+ end
+ end
+
+ SnapshotConnection =
+ Struct.new(
+ :source_node_id,
+ :source_output_index,
+ :target_node_id,
+ :target_input_index,
+ :connection_type,
+ keyword_init: true,
+ )
+
+ attr_reader :nodes, :connections, :workflow_name
+
+ def initialize(workflow_data)
+ data = workflow_data.deep_stringify_keys
+ @workflow_name = data["name"]
+ @nodes =
+ data
+ .fetch("nodes") { [] }
+ .map do |n|
+ SnapshotNode.new(
+ id: n["id"].to_s,
+ type: n["type"],
+ type_version: n["typeVersion"] || Registry::DEFAULT_VERSION,
+ name: n["name"],
+ position: n["position"],
+ parameters: n["parameters"] || {},
+ credentials: n["credentials"] || {},
+ webhook_id: n["webhookId"],
+ notes: n["notes"],
+ notes_in_flow: n["notesInFlow"],
+ always_output_data: n["alwaysOutputData"],
+ on_error: n["onError"],
+ continue_on_fail: n["continueOnFail"],
+ ).freeze
+ end
+ @nodes_by_id = @nodes.index_by(&:id)
+ @nodes_by_name = @nodes.index_by(&:name)
+
+ @connections =
+ DiscourseWorkflows::WorkflowDocument
+ .connection_records(@nodes.map(&:to_workflow_node), data.fetch("connections") { {} })
+ .map do |c|
+ SnapshotConnection.new(
+ source_node_id: c["source_node_id"].to_s,
+ source_output_index: c["source_output_index"].to_i,
+ target_node_id: c["target_node_id"].to_s,
+ target_input_index: c["target_input_index"].to_i,
+ connection_type: c["connection_type"] || "main",
+ ).freeze
+ end
+
+ @connections_by_source = @connections.group_by(&:source_node_id)
+ @connections_by_source_output_index =
+ @connections.group_by do |connection|
+ [connection.source_node_id, connection.source_output_index]
+ end
+ @connections_by_target = @connections.group_by(&:target_node_id)
+ end
+
+ def find_node(node_id)
+ @nodes_by_id[node_id.to_s]
+ end
+
+ def find_node_by_name(node_name)
+ @nodes_by_name[node_name.to_s]
+ end
+
+ def child_nodes(node_name, connection_type: "main", depth: -1)
+ connected_nodes(
+ node_name,
+ direction: :downstream,
+ connection_type: connection_type,
+ depth: depth,
+ )
+ end
+
+ def parent_nodes(node_name, connection_type: "main", depth: -1)
+ connected_nodes(
+ node_name,
+ direction: :upstream,
+ connection_type: connection_type,
+ depth: depth,
+ )
+ end
+
+ def connections_from_output_index(node, output_index)
+ @connections_by_source_output_index.fetch([node.id, output_index.to_i]) { [] }
+ end
+
+ def connections_to(node)
+ @connections_by_target.fetch(node.id) { [] }
+ end
+
+ def target_node(connection)
+ @nodes_by_id[connection.target_node_id]
+ end
+
+ def source_node(connection)
+ @nodes_by_id[connection.source_node_id]
+ end
+
+ def node_has_reachable_downstream_of_type?(node_id, type)
+ visited = Set.new
+ queue = [node_id.to_s]
+
+ while (current = queue.shift)
+ next if visited.include?(current)
+ visited << current
+
+ @connections_by_source
+ .fetch(current) { [] }
+ .each do |connection|
+ target_node = target_node(connection)
+ next unless target_node
+ return true if target_node.type == type
+
+ queue << target_node.id
+ end
+ end
+
+ false
+ end
+
+ def connected_nodes(node_name, direction:, connection_type: "main", depth: -1)
+ start_node = find_node_by_name(node_name) || find_node(node_name)
+ return [] if start_node.blank?
+
+ collect_connected_nodes(
+ start_node.id,
+ direction: direction,
+ connection_type: connection_type.to_s,
+ depth: depth.to_i,
+ checked_nodes: Set.new,
+ )
+ end
+
+ def to_h
+ workflow_nodes = nodes.map(&:to_workflow_node)
+ {
+ "name" => workflow_name.presence,
+ "nodes" => workflow_nodes,
+ "connections" =>
+ DiscourseWorkflows::WorkflowDocument.connections_from_records(
+ workflow_nodes,
+ connections,
+ ),
+ }.compact
+ end
+
+ def self.from_workflow(workflow, published: false)
+ nodes = published ? workflow.published_nodes : workflow.nodes
+ connections = published ? workflow.published_connections : workflow.connections
+ workflow_name = published ? workflow.active_version&.name : workflow.name
+ new("name" => workflow_name || workflow.name, "nodes" => nodes, "connections" => connections)
+ end
+
+ def self.from_version(workflow, version)
+ new(
+ "name" => version.name || workflow.name,
+ "nodes" => version.nodes,
+ "connections" => version.connections,
+ )
+ end
+
+ private
+
+ def collect_connected_nodes(node_id, direction:, connection_type:, depth:, checked_nodes:)
+ return [] if depth.zero?
+ return [] if checked_nodes.include?(node_id)
+
+ next_depth = depth.negative? ? depth : depth - 1
+ next_checked_nodes = checked_nodes.dup
+ next_checked_nodes << node_id
+ connected = []
+
+ connections_for(node_id, direction).each do |connection|
+ next unless connection_type_matches?(connection, connection_type)
+
+ node = direction == :downstream ? target_node(connection) : source_node(connection)
+ next if node.blank? || next_checked_nodes.include?(node.id)
+
+ connected.unshift(node)
+ collect_connected_nodes(
+ node.id,
+ direction: direction,
+ connection_type: connection_type,
+ depth: next_depth,
+ checked_nodes: next_checked_nodes,
+ ).reverse_each do |connected_node|
+ index = connected.index { |existing_node| existing_node.id == connected_node.id }
+ connected.delete_at(index) if index
+ connected.unshift(connected_node)
+ end
+ end
+
+ connected
+ end
+
+ def connections_for(node_id, direction)
+ case direction
+ when :downstream
+ @connections_by_source.fetch(node_id) { [] }
+ when :upstream
+ @connections_by_target.fetch(node_id) { [] }
+ else
+ raise ArgumentError, "Unknown connection direction: #{direction}"
+ end
+ end
+
+ def connection_type_matches?(connection, connection_type)
+ case connection_type
+ when "ALL"
+ true
+ when "ALL_NON_MAIN"
+ connection.connection_type != "main"
+ else
+ connection.connection_type == connection_type
+ end
+ end
+ end
+end
diff --git a/plugins/discourse-workflows/lib/discourse_workflows/workflow_timezone.rb b/plugins/discourse-workflows/lib/discourse_workflows/workflow_timezone.rb
new file mode 100644
index 00000000000..110211cc844
--- /dev/null
+++ b/plugins/discourse-workflows/lib/discourse_workflows/workflow_timezone.rb
@@ -0,0 +1,31 @@
+# frozen_string_literal: true
+
+module DiscourseWorkflows
+ module WorkflowTimezone
+ module_function
+
+ DEFAULT = "UTC"
+
+ def default
+ timezone = Time.zone&.tzinfo&.name.presence
+ timezone == "Etc/UTC" ? DEFAULT : (timezone || DEFAULT)
+ end
+
+ def for(workflow:, workflow_version: nil)
+ timezone =
+ workflow_version&.settings&.dig("timezone").presence ||
+ workflow&.settings&.dig("timezone").presence || default
+
+ valid?(timezone) ? timezone : default
+ end
+
+ def valid?(timezone)
+ return false if timezone.blank?
+
+ TZInfo::Timezone.get(timezone)
+ true
+ rescue TZInfo::InvalidTimezoneIdentifier
+ false
+ end
+ end
+end
diff --git a/plugins/discourse-workflows/lib/discourse_workflows/workflow_view.rb b/plugins/discourse-workflows/lib/discourse_workflows/workflow_view.rb
new file mode 100644
index 00000000000..af22a7daf07
--- /dev/null
+++ b/plugins/discourse-workflows/lib/discourse_workflows/workflow_view.rb
@@ -0,0 +1,24 @@
+# frozen_string_literal: true
+
+module DiscourseWorkflows
+ class WorkflowView
+ attr_reader :id, :name, :active
+
+ def self.from_workflow(workflow, name: nil)
+ return new(id: nil, name: name, active: false) if workflow.blank?
+
+ new(id: workflow.id, name: name.presence || workflow.name, active: workflow.published?)
+ end
+
+ def initialize(id:, name:, active:)
+ @id = id&.to_s
+ @name = name.to_s
+ @active = !!active
+ freeze
+ end
+
+ def to_h
+ { "id" => id, "name" => name, "active" => active }.compact
+ end
+ end
+end
diff --git a/plugins/discourse-workflows/plugin.rb b/plugins/discourse-workflows/plugin.rb
new file mode 100644
index 00000000000..c94f875a4b6
--- /dev/null
+++ b/plugins/discourse-workflows/plugin.rb
@@ -0,0 +1,100 @@
+# frozen_string_literal: true
+
+# name: discourse-workflows
+# about: Workflow automation system for Discourse
+# meta_topic_id: 402418
+# version: 0.1
+# authors: Discourse
+# url: https://github.com/discourse/discourse-workflows
+
+enabled_site_setting :discourse_workflows_enabled
+
+module ::DiscourseWorkflows
+ PLUGIN_NAME = "discourse-workflows"
+ TEMPLATES_PATH = File.expand_path("config/templates", __dir__)
+end
+
+require_relative "lib/discourse_workflows/engine"
+require_relative "lib/discourse_workflows/plugin_node_registration"
+
+register_asset "stylesheets/common/index.scss"
+register_svg_icon "bolt"
+register_svg_icon "arrows-split-up-and-left"
+register_svg_icon "list"
+register_svg_icon "arrow-rotate-right"
+register_svg_icon "arrows-turn-to-dots"
+register_svg_icon "globe"
+register_svg_icon "table"
+register_svg_icon "table-cells"
+register_svg_icon "expand"
+register_svg_icon "magnifying-glass-minus"
+register_svg_icon "magnifying-glass-plus"
+register_svg_icon "user-check"
+register_svg_icon "calendar-days"
+register_svg_icon "rectangle-list"
+register_svg_icon "trash-can"
+register_svg_icon "broom"
+register_svg_icon "arrow-pointer"
+register_svg_icon "note-sticky"
+register_svg_icon "palette"
+register_svg_icon "reply"
+register_svg_icon "triangle-exclamation"
+register_svg_icon "clock"
+register_svg_icon "comments"
+register_svg_icon "pause"
+register_svg_icon "user-plus"
+register_svg_icon "grip-vertical"
+register_svg_icon "arrow-down-a-z"
+
+add_admin_route "discourse_workflows.admin.title", "discourse-workflows", use_new_show_route: true
+
+DiscoursePluginRegistry.define_filtered_register(:discourse_workflows_nodes)
+DiscoursePluginRegistry.define_filtered_register(:discourse_workflows_credential_types)
+
+after_initialize do
+ Rails.application.config.filter_parameters += %i[signature]
+
+ add_to_class(:guardian, :can_manage_workflows?) { is_admin? }
+
+ nodes_dir = File.join(File.dirname(__FILE__), "lib/discourse_workflows/nodes")
+ Dir.glob(File.join(nodes_dir, "**/*.rb")).each { |f| Rails.autoloaders.main.load_file(f) }
+
+ DiscourseWorkflows::NodeType.registered_nodes.each do |node_class|
+ DiscoursePluginRegistry.register_discourse_workflows_node(node_class, self)
+
+ next unless node_class.respond_to?(:event_name) && node_class.event_name
+ on(node_class.event_name) do |*args|
+ DiscourseWorkflows::EventListener.handle(node_class, *args)
+ end
+ end
+
+ DiscourseWorkflows.node_registration_ready = true
+ DiscourseWorkflows.flush_plugin_node_registrations!
+ DiscourseWorkflows::Registry.reset_indexes!
+
+ DiscoursePluginRegistry.register_discourse_workflows_credential_type(
+ DiscourseWorkflows::CredentialTypes::BasicAuth,
+ self,
+ )
+ DiscoursePluginRegistry.register_discourse_workflows_credential_type(
+ DiscourseWorkflows::CredentialTypes::BearerToken,
+ self,
+ )
+ DiscoursePluginRegistry.register_discourse_workflows_credential_type(
+ DiscourseWorkflows::CredentialTypes::HeaderAuth,
+ self,
+ )
+
+ add_to_serializer :site,
+ :topic_admin_button_workflows,
+ include_condition: -> { scope.is_admin? } do
+ DiscourseWorkflows::WorkflowDependency.cached_topic_admin_buttons
+ end
+
+ on(:site_setting_changed) do |name, old_value, new_value|
+ next if name != :discourse_workflows_enabled
+ next unless new_value && !old_value
+
+ DiscourseWorkflows::PluginEnableHandler.handle!
+ end
+end
diff --git a/plugins/discourse-workflows/spec/fabricators/discourse_workflows_data_table_fabricator.rb b/plugins/discourse-workflows/spec/fabricators/discourse_workflows_data_table_fabricator.rb
new file mode 100644
index 00000000000..39a9777e8f9
--- /dev/null
+++ b/plugins/discourse-workflows/spec/fabricators/discourse_workflows_data_table_fabricator.rb
@@ -0,0 +1,25 @@
+# frozen_string_literal: true
+
+Fabricator(:discourse_workflows_data_table, class_name: "DiscourseWorkflows::DataTable") do
+ transient :columns
+
+ name { sequence(:name) { |n| "data_table_#{n}" } }
+
+ after_create do |data_table, transients|
+ columns =
+ Array(
+ (
+ if transients[:columns].nil?
+ [{ "name" => "value", "type" => "string" }]
+ else
+ transients[:columns]
+ end
+ ),
+ ).map do |c|
+ c = c.respond_to?(:to_h) ? c.to_h.deep_stringify_keys : c
+ { "name" => c["name"].to_s, "type" => c["type"].to_s }
+ end
+
+ DiscourseWorkflows::DataTables::Facade.create_table!(data_table, columns: columns)
+ end
+end
diff --git a/plugins/discourse-workflows/spec/fabricators/discourse_workflows_fabricator.rb b/plugins/discourse-workflows/spec/fabricators/discourse_workflows_fabricator.rb
new file mode 100644
index 00000000000..dec5cee115e
--- /dev/null
+++ b/plugins/discourse-workflows/spec/fabricators/discourse_workflows_fabricator.rb
@@ -0,0 +1,105 @@
+# frozen_string_literal: true
+
+Fabricator(:discourse_workflows_workflow, class_name: "DiscourseWorkflows::Workflow") do
+ transient :published
+
+ name { sequence(:name) { |n| "Workflow #{n}" } }
+ created_by { Fabricate(:user) }
+ after_create do |workflow, attrs|
+ version = workflow.initial_snapshot!(user: workflow.created_by)
+ workflow.update_columns(active_version_id: workflow.version_id) if attrs[:published]
+ DiscourseWorkflows::WorkflowDependencyIndexer.call(workflow.reload, version:)
+ end
+end
+
+Fabricator(:discourse_workflows_execution, class_name: "DiscourseWorkflows::Execution") do
+ workflow { Fabricate(:discourse_workflows_workflow) }
+ workflow_version_id { |attrs| attrs[:workflow].version_id }
+ status :pending
+ trigger_data { {} }
+end
+
+Fabricator(
+ :discourse_workflows_completed_execution,
+ from: :discourse_workflows_execution,
+ class_name: "DiscourseWorkflows::Execution",
+) do
+ status :success
+ started_at { 1.hour.ago }
+ finished_at { Time.current }
+end
+
+Fabricator(
+ :discourse_workflows_error_execution,
+ from: :discourse_workflows_execution,
+ class_name: "DiscourseWorkflows::Execution",
+) do
+ status :error
+ started_at { 1.hour.ago }
+ finished_at { Time.current }
+end
+
+Fabricator(
+ :discourse_workflows_waiting_execution,
+ from: :discourse_workflows_execution,
+ class_name: "DiscourseWorkflows::Execution",
+) do
+ status :waiting
+ waiting_until { 1.hour.from_now }
+ resume_token { SecureRandom.hex(16) }
+end
+
+Fabricator(:discourse_workflows_execution_data, class_name: "DiscourseWorkflows::ExecutionData") do
+ execution { Fabricate(:discourse_workflows_execution) }
+ data { { "entries" => {}, "context" => {}, "node_contexts" => {}, "run_data" => {} } }
+ workflow_data { {} }
+end
+
+Fabricator(
+ :discourse_workflows_execution_data_with_steps,
+ from: :discourse_workflows_execution_data,
+ class_name: "DiscourseWorkflows::ExecutionData",
+) do
+ transient :node_id, :node_name, :node_type, :step_status
+ data do |attrs|
+ node_id = attrs[:node_id] || "trigger-1"
+ node_name = attrs[:node_name] || "Manual Trigger"
+ node_type = attrs[:node_type] || "trigger:manual"
+ step_status = attrs[:step_status] || "success"
+ {
+ "entries" => {
+ node_name => [
+ {
+ "node_id" => node_id,
+ "node_name" => node_name,
+ "node_type" => node_type,
+ "position" => 0,
+ "status" => step_status,
+ "input" => [],
+ "output" => [],
+ "started_at" => 1.hour.ago.iso8601,
+ "finished_at" => Time.current.iso8601,
+ },
+ ],
+ },
+ "context" => {
+ },
+ "node_contexts" => {
+ },
+ "run_data" => {
+ },
+ }
+ end
+end
+
+Fabricator(:discourse_workflows_variable, class_name: "DiscourseWorkflows::Variable") do
+ key { sequence(:key) { |n| "variable_#{n}" } }
+ value "test_value"
+ created_by { Fabricate(:user) }
+end
+
+Fabricator(:discourse_workflows_credential, class_name: "DiscourseWorkflows::Credential") do
+ name { sequence(:name) { |n| "Credential #{n}" } }
+ credential_type "basic_auth"
+ data { { "user" => "admin", "password" => "secret" } }
+end
diff --git a/plugins/discourse-workflows/spec/integration/data_table_workflow_spec.rb b/plugins/discourse-workflows/spec/integration/data_table_workflow_spec.rb
new file mode 100644
index 00000000000..1f2f6ac6d4a
--- /dev/null
+++ b/plugins/discourse-workflows/spec/integration/data_table_workflow_spec.rb
@@ -0,0 +1,191 @@
+# frozen_string_literal: true
+
+RSpec.describe "Data Table workflow integration" do
+ fab!(:admin)
+ fab!(:category)
+
+ fab!(:data_table) do
+ Fabricate(
+ :discourse_workflows_data_table,
+ name: "post_log",
+ columns: [
+ { "name" => "topic_id", "type" => "number" },
+ { "name" => "author", "type" => "string" },
+ { "name" => "logged", "type" => "boolean" },
+ ],
+ )
+ end
+
+ fab!(:workflow) { Fabricate(:discourse_workflows_workflow, published: true, created_by: admin) }
+
+ before do
+ graph =
+ build_workflow_graph do |g|
+ g.node "trigger-1",
+ "trigger:post_created",
+ name: "trigger",
+ configuration: {
+ "category_ids" => [category.id],
+ }
+ g.node "action-1",
+ "action:data_table",
+ name: "insert_row",
+ configuration: {
+ "operation" => "insert",
+ "data_table_id" => data_table.id.to_s,
+ "columns" => {
+ "topic_id" => "={{ $json.topic_id }}",
+ "author" => "={{ $json.username }}",
+ "logged" => "true",
+ },
+ }
+ g.chain "trigger-1", "action-1"
+ end
+
+ workflow.update!(**graph)
+ publish_workflow!(workflow)
+ end
+
+ it "inserts a data table row when a post is created" do
+ topic = Fabricate(:topic, category: category, user: admin)
+ trigger_data = {
+ "post_id" => 1,
+ "topic_id" => topic.id,
+ "username" => admin.username,
+ "category_id" => category.id,
+ "raw" => "test post",
+ }
+
+ execution = DiscourseWorkflows::Executor.new(workflow, "trigger-1", trigger_data).run
+
+ expect(execution.status).to eq("success")
+ expect(count_data_table_rows(data_table)).to eq(1)
+
+ row = list_data_table_rows(data_table)[:rows].first
+ expect(row).to include("topic_id" => topic.id, "author" => admin.username, "logged" => true)
+ end
+
+ context "with row_exists operation" do
+ fab!(:exists_workflow) do
+ Fabricate(:discourse_workflows_workflow, published: true, created_by: admin)
+ end
+
+ fab!(:logger_table) do
+ Fabricate(
+ :discourse_workflows_data_table,
+ name: "logged_topics",
+ columns: [{ "name" => "topic_id", "type" => "number" }],
+ )
+ end
+
+ before do
+ graph =
+ build_workflow_graph do |g|
+ g.node "trigger-1",
+ "trigger:post_created",
+ name: "trigger",
+ configuration: {
+ "category_ids" => [category.id],
+ }
+ g.node "action-1",
+ "action:data_table",
+ name: "row_exists",
+ configuration: {
+ "operation" => "row_exists",
+ "data_table_id" => logger_table.id.to_s,
+ "filter" => [
+ {
+ "columnName" => "topic_id",
+ "operator" => {
+ "type" => "number",
+ "operation" => "equals",
+ "singleValue" => false,
+ },
+ "value" => "={{ $json.topic_id }}",
+ },
+ ],
+ }
+ g.chain "trigger-1", "action-1"
+ end
+
+ exists_workflow.update!(**graph)
+ publish_workflow!(exists_workflow)
+ end
+
+ it "passes the trigger payload through when a matching row exists" do
+ topic = Fabricate(:topic, category: category, user: admin)
+ insert_data_table_row(logger_table, "topic_id" => topic.id)
+
+ trigger_data = {
+ "post_id" => 1,
+ "topic_id" => topic.id,
+ "username" => admin.username,
+ "category_id" => category.id,
+ "raw" => "test post",
+ }
+
+ execution = DiscourseWorkflows::Executor.new(exists_workflow, "trigger-1", trigger_data).run
+
+ expect(execution.status).to eq("success")
+
+ action_step = execution.execution_data.find_step(node_id: "action-1")
+ output_items = action_step["output"]
+ expect(output_items.length).to eq(1)
+ expect(output_items.first["json"]).to include("topic_id" => topic.id, "post_id" => 1)
+ expect(output_items.first["json"]).not_to have_key("id")
+ end
+
+ it "filters out the payload when no row matches" do
+ topic = Fabricate(:topic, category: category, user: admin)
+
+ trigger_data = {
+ "post_id" => 2,
+ "topic_id" => topic.id,
+ "username" => admin.username,
+ "category_id" => category.id,
+ "raw" => "test post",
+ }
+
+ execution = DiscourseWorkflows::Executor.new(exists_workflow, "trigger-1", trigger_data).run
+
+ expect(execution.status).to eq("success")
+
+ action_step = execution.execution_data.find_step(node_id: "action-1")
+ expect(action_step["output"]).to eq([])
+ end
+ end
+
+ it "writes to the renamed column once the workflow config is updated to match" do
+ DiscourseWorkflows::DataTableColumn::Rename.call(
+ params: {
+ data_table_id: data_table.id,
+ column_name: "author",
+ name: "post_author",
+ },
+ guardian: admin.guardian,
+ )
+
+ nodes = workflow.nodes.deep_dup
+ action_node = nodes.find { |n| n["id"] == "action-1" }
+ columns = action_node["parameters"]["columns"]
+ columns["post_author"] = columns.delete("author")
+ workflow.update!(nodes: nodes)
+ publish_workflow!(workflow)
+
+ topic = Fabricate(:topic, category: category, user: admin)
+ trigger_data = {
+ "post_id" => 1,
+ "topic_id" => topic.id,
+ "username" => admin.username,
+ "category_id" => category.id,
+ "raw" => "test post",
+ }
+
+ execution = DiscourseWorkflows::Executor.new(workflow, "trigger-1", trigger_data).run
+
+ expect(execution.status).to eq("success")
+
+ row = list_data_table_rows(data_table)[:rows].first
+ expect(row["post_author"]).to eq(admin.username)
+ end
+end
diff --git a/plugins/discourse-workflows/spec/integration/plugin_enable_hook_spec.rb b/plugins/discourse-workflows/spec/integration/plugin_enable_hook_spec.rb
new file mode 100644
index 00000000000..9f9ea7364e5
--- /dev/null
+++ b/plugins/discourse-workflows/spec/integration/plugin_enable_hook_spec.rb
@@ -0,0 +1,46 @@
+# frozen_string_literal: true
+
+describe "discourse_workflows_enabled site setting hook" do
+ fab!(:workflow) { Fabricate(:discourse_workflows_workflow, published: true) }
+ fab!(:execution) do
+ Fabricate(
+ :discourse_workflows_execution,
+ workflow: workflow,
+ status: :waiting,
+ waiting_until: 1.minute.ago,
+ )
+ end
+
+ it "reschedules waiting executions when the setting flips false to true" do
+ SiteSetting.discourse_workflows_enabled = false
+
+ expect_enqueued_with(
+ job: Jobs::DiscourseWorkflows::ResumeWaitingExecution,
+ args: {
+ execution_id: execution.id,
+ },
+ ) { SiteSetting.discourse_workflows_enabled = true }
+ end
+
+ it "does not reschedule when the setting flips true to false" do
+ SiteSetting.discourse_workflows_enabled = true
+
+ expect_not_enqueued_with(
+ job: Jobs::DiscourseWorkflows::ResumeWaitingExecution,
+ args: {
+ execution_id: execution.id,
+ },
+ ) { SiteSetting.discourse_workflows_enabled = false }
+ end
+
+ it "does not reschedule for unrelated setting changes" do
+ SiteSetting.discourse_workflows_enabled = true
+
+ expect_not_enqueued_with(
+ job: Jobs::DiscourseWorkflows::ResumeWaitingExecution,
+ args: {
+ execution_id: execution.id,
+ },
+ ) { SiteSetting.title = "Different title" }
+ end
+end
diff --git a/plugins/discourse-workflows/spec/integration/post_created_create_post_spec.rb b/plugins/discourse-workflows/spec/integration/post_created_create_post_spec.rb
new file mode 100644
index 00000000000..921440919da
--- /dev/null
+++ b/plugins/discourse-workflows/spec/integration/post_created_create_post_spec.rb
@@ -0,0 +1,52 @@
+# frozen_string_literal: true
+
+RSpec.describe "Workflow: post created -> create post" do
+ fab!(:admin)
+ fab!(:user) { Fabricate(:user, refresh_auto_groups: true) }
+ fab!(:topic_owner) { Fabricate(:user, refresh_auto_groups: true) }
+ fab!(:first_post) { create_post(user: topic_owner, raw: "First post") }
+ fab!(:topic) { first_post.topic }
+
+ before do
+ Jobs::DiscourseWorkflows::ExecuteWorkflow.jobs.clear
+
+ graph =
+ build_workflow_graph do |g|
+ g.node "trigger-1", "trigger:post_created"
+ g.node "action-1",
+ "action:create_post",
+ configuration: {
+ "topic_id" => "={{ $trigger.topic.id }}",
+ "raw" => "Automated reply",
+ }
+ g.chain "trigger-1", "action-1"
+ end
+
+ Fabricate(
+ :discourse_workflows_workflow,
+ created_by: admin,
+ published: true,
+ name: "Reply to new posts",
+ **graph,
+ )
+ end
+
+ it "creates one automated reply without enqueueing another workflow run" do
+ PostCreator.create!(
+ user,
+ topic_id: topic.id,
+ raw: "User reply",
+ reply_to_post_number: first_post.post_number,
+ )
+
+ expect(Jobs::DiscourseWorkflows::ExecuteWorkflow.jobs.size).to eq(1)
+
+ job_args = Jobs::DiscourseWorkflows::ExecuteWorkflow.jobs.last["args"].first.symbolize_keys
+
+ expect do Jobs::DiscourseWorkflows::ExecuteWorkflow.new.execute(job_args) end.to change {
+ Post.where(topic: topic, raw: "Automated reply").count
+ }.by(1)
+
+ expect(Jobs::DiscourseWorkflows::ExecuteWorkflow.jobs.size).to eq(1)
+ end
+end
diff --git a/plugins/discourse-workflows/spec/integration/post_created_tags_spec.rb b/plugins/discourse-workflows/spec/integration/post_created_tags_spec.rb
new file mode 100644
index 00000000000..e5787c12168
--- /dev/null
+++ b/plugins/discourse-workflows/spec/integration/post_created_tags_spec.rb
@@ -0,0 +1,61 @@
+# frozen_string_literal: true
+
+RSpec.describe "Workflow: post created -> topic tags" do
+ fab!(:admin)
+ fab!(:user) { Fabricate(:user, refresh_auto_groups: true) }
+ fab!(:topic_owner) { Fabricate(:user, refresh_auto_groups: true) }
+ fab!(:first_post) { create_post(user: topic_owner, raw: "First post") }
+ fab!(:topic) { first_post.topic }
+ fab!(:tag) { Fabricate(:tag, name: "responded") }
+
+ before do
+ SiteSetting.tagging_enabled = true
+
+ Jobs::DiscourseWorkflows::ExecuteWorkflow.jobs.clear
+
+ graph =
+ build_workflow_graph do |g|
+ g.node "trigger-1", "trigger:post_created"
+ g.node "action-1",
+ "action:topic_tags",
+ configuration: {
+ "operation" => "add",
+ "topic_id" => "={{ $trigger.topic.id }}",
+ "tag_names" => tag.name,
+ }
+ g.chain "trigger-1", "action-1"
+ end
+
+ Fabricate(
+ :discourse_workflows_workflow,
+ created_by: admin,
+ published: true,
+ name: "Tag topics with new replies",
+ **graph,
+ )
+ end
+
+ it "tags a topic when a reply is created" do
+ reply =
+ PostCreator.create!(
+ user,
+ topic_id: topic.id,
+ raw: "This is a reply",
+ reply_to_post_number: topic.first_post.post_number,
+ )
+
+ job_data = Jobs::DiscourseWorkflows::ExecuteWorkflow.jobs.last
+ expect(job_data).to be_present
+
+ trigger_data = job_data["args"].first["trigger_data"]
+ expect(trigger_data["post"]).to include("id" => reply.id, "raw" => reply.raw)
+ expect(trigger_data["topic"]).to include("id" => topic.id)
+
+ Jobs::DiscourseWorkflows::ExecuteWorkflow.new.execute(job_data["args"].first.symbolize_keys)
+
+ expect(topic.reload.tags.map(&:name)).to include("responded")
+
+ execution = DiscourseWorkflows::Execution.last
+ expect(execution.status).to eq("success")
+ end
+end
diff --git a/plugins/discourse-workflows/spec/integration/topic_category_changed_create_post_spec.rb b/plugins/discourse-workflows/spec/integration/topic_category_changed_create_post_spec.rb
new file mode 100644
index 00000000000..8e8784ad88a
--- /dev/null
+++ b/plugins/discourse-workflows/spec/integration/topic_category_changed_create_post_spec.rb
@@ -0,0 +1,72 @@
+# frozen_string_literal: true
+
+RSpec.describe "Workflow: topic category changed -> create post" do
+ fab!(:admin)
+ fab!(:category)
+ fab!(:target_category, :category)
+ fab!(:topic) { Fabricate(:topic, category: category) }
+
+ before do
+ Jobs::DiscourseWorkflows::ExecuteWorkflow.jobs.clear
+
+ graph =
+ build_workflow_graph do |g|
+ g.node "trigger-1", "trigger:topic_category_changed"
+ g.node "action-1",
+ "action:create_post",
+ configuration: {
+ "topic_id" => "={{ $trigger.topic.id }}",
+ "raw" =>
+ "=Category changed from {{ $trigger.old_category_id }} to {{ $trigger.topic.category_id }}",
+ }
+ g.chain "trigger-1", "action-1"
+ end
+
+ Fabricate(
+ :discourse_workflows_workflow,
+ created_by: admin,
+ published: true,
+ name: "Notify on category change",
+ **graph,
+ )
+ end
+
+ it "creates a post when topic category changes" do
+ topic.change_category_to_id(target_category.id)
+
+ job_data = Jobs::DiscourseWorkflows::ExecuteWorkflow.jobs.last
+ expect(job_data).to be_present
+
+ trigger_data = job_data["args"].first["trigger_data"]
+ expect(trigger_data["topic"]).to include("id" => topic.id, "category_id" => target_category.id)
+ expect(trigger_data).to include("old_category_id" => category.id)
+
+ Jobs::DiscourseWorkflows::ExecuteWorkflow.new.execute(job_data["args"].first.symbolize_keys)
+
+ post = topic.reload.posts.where.not(post_type: Post.types[:small_action]).last
+ expect(post.raw).to include(category.id.to_s)
+ expect(post.raw).to include(target_category.id.to_s)
+
+ execution = DiscourseWorkflows::Execution.last
+ expect(execution.status).to eq("success")
+ end
+
+ def expect_no_workflow_jobs_for(topic)
+ jobs =
+ Jobs::DiscourseWorkflows::ExecuteWorkflow.jobs.select do |j|
+ j["args"].first["trigger_data"]&.dig("topic", "id") == topic.id
+ end
+ expect(jobs).to be_empty
+ end
+
+ it "does not trigger when category stays the same" do
+ topic.change_category_to_id(category.id)
+ expect_no_workflow_jobs_for(topic)
+ end
+
+ it "does not trigger when the workflow is unpublished" do
+ DiscourseWorkflows::Workflow.find_each { |workflow| unpublish_workflow!(workflow) }
+ topic.change_category_to_id(target_category.id)
+ expect_no_workflow_jobs_for(topic)
+ end
+end
diff --git a/plugins/discourse-workflows/spec/integration/topic_closed_tags_spec.rb b/plugins/discourse-workflows/spec/integration/topic_closed_tags_spec.rb
new file mode 100644
index 00000000000..81a215e11c9
--- /dev/null
+++ b/plugins/discourse-workflows/spec/integration/topic_closed_tags_spec.rb
@@ -0,0 +1,70 @@
+# frozen_string_literal: true
+
+RSpec.describe "Workflow: topic closed -> topic tags" do
+ fab!(:admin)
+ fab!(:topic)
+ fab!(:tag) { Fabricate(:tag, name: "resolved") }
+
+ before do
+ SiteSetting.tagging_enabled = true
+
+ graph =
+ build_workflow_graph do |g|
+ g.node "trigger-1", "trigger:topic_closed"
+ g.node "action-1",
+ "action:topic_tags",
+ configuration: {
+ "operation" => "add",
+ "topic_id" => "={{ $trigger.topic.id }}",
+ "tag_names" => "resolved",
+ }
+ g.chain "trigger-1", "action-1"
+ end
+
+ Fabricate(
+ :discourse_workflows_workflow,
+ created_by: admin,
+ published: true,
+ name: "Tag closed topics",
+ **graph,
+ )
+ end
+
+ it "tags a topic when it is closed" do
+ topic.update_status("closed", true, admin)
+
+ job_data = Jobs::DiscourseWorkflows::ExecuteWorkflow.jobs.last
+ expect(job_data).to be_present
+
+ Jobs::DiscourseWorkflows::ExecuteWorkflow.new.execute(job_data["args"].first.symbolize_keys)
+
+ expect(topic.reload.tags.map(&:name)).to include("resolved")
+
+ execution = DiscourseWorkflows::Execution.last
+ expect(execution.status).to eq("success")
+ end
+
+ def expect_no_workflow_jobs_for(topic)
+ jobs =
+ Jobs::DiscourseWorkflows::ExecuteWorkflow.jobs.select do |j|
+ j["args"].first["trigger_data"].dig("topic", "id") == topic.id
+ end
+ expect(jobs).to be_empty
+ end
+
+ it "does not trigger when the topic is not closed" do
+ topic.update_status("visible", true, admin)
+ expect_no_workflow_jobs_for(topic)
+ end
+
+ it "does not trigger when the topic is reopened" do
+ topic.update_status("closed", false, admin)
+ expect_no_workflow_jobs_for(topic)
+ end
+
+ it "does not tag when the workflow is unpublished" do
+ DiscourseWorkflows::Workflow.find_each { |workflow| unpublish_workflow!(workflow) }
+ topic.update_status("closed", true, admin)
+ expect_no_workflow_jobs_for(topic)
+ end
+end
diff --git a/plugins/discourse-workflows/spec/integration/topic_created_topic_node_spec.rb b/plugins/discourse-workflows/spec/integration/topic_created_topic_node_spec.rb
new file mode 100644
index 00000000000..f0c9a64d5ba
--- /dev/null
+++ b/plugins/discourse-workflows/spec/integration/topic_created_topic_node_spec.rb
@@ -0,0 +1,52 @@
+# frozen_string_literal: true
+
+RSpec.describe "Workflow: topic created -> topic create" do
+ fab!(:admin)
+ fab!(:user) { Fabricate(:user, refresh_auto_groups: true) }
+ fab!(:category)
+
+ before do
+ Jobs::DiscourseWorkflows::ExecuteWorkflow.jobs.clear
+
+ graph =
+ build_workflow_graph do |g|
+ g.node "trigger-1", "trigger:topic_created"
+ g.node "action-1",
+ "action:topic",
+ configuration: {
+ "operation" => "create",
+ "title" => "Mirror: {{ $trigger.topic_title }}",
+ "raw" => "=Mirrored from topic {{ $trigger.topic_id }}",
+ "category_id" => category.id.to_s,
+ "actor_username" => "system",
+ }
+ g.chain "trigger-1", "action-1"
+ end
+
+ Fabricate(
+ :discourse_workflows_workflow,
+ created_by: admin,
+ published: true,
+ name: "Mirror new topics",
+ **graph,
+ )
+ end
+
+ it "creates a mirrored topic without triggering another workflow run" do
+ PostCreator.create!(user, title: "Original topic title here", raw: "This is the original body")
+
+ expect(Jobs::DiscourseWorkflows::ExecuteWorkflow.jobs.size).to eq(1)
+
+ job_args = Jobs::DiscourseWorkflows::ExecuteWorkflow.jobs.last["args"].first.symbolize_keys
+
+ expect { Jobs::DiscourseWorkflows::ExecuteWorkflow.new.execute(job_args) }.to change(
+ Topic,
+ :count,
+ ).by(1)
+
+ mirrored = Topic.last
+ expect(mirrored.category_id).to eq(category.id)
+
+ expect(Jobs::DiscourseWorkflows::ExecuteWorkflow.jobs.size).to eq(1)
+ end
+end
diff --git a/plugins/discourse-workflows/spec/jobs/regular/discourse_workflows/resume_waiting_execution_spec.rb b/plugins/discourse-workflows/spec/jobs/regular/discourse_workflows/resume_waiting_execution_spec.rb
new file mode 100644
index 00000000000..a8a0421f258
--- /dev/null
+++ b/plugins/discourse-workflows/spec/jobs/regular/discourse_workflows/resume_waiting_execution_spec.rb
@@ -0,0 +1,46 @@
+# frozen_string_literal: true
+
+RSpec.describe Jobs::DiscourseWorkflows::ResumeWaitingExecution do
+ fab!(:workflow) { Fabricate(:discourse_workflows_workflow, published: true) }
+ fab!(:execution) do
+ Fabricate(
+ :discourse_workflows_execution,
+ workflow: workflow,
+ status: :waiting,
+ waiting_until: 1.minute.ago,
+ )
+ end
+
+ it "leaves the execution waiting when the plugin is disabled" do
+ SiteSetting.discourse_workflows_enabled = false
+ before_updated_at = execution.updated_at
+
+ described_class.new.execute(execution_id: execution.id)
+
+ execution.reload
+ expect(execution.status).to eq("waiting")
+ expect(execution.updated_at).to eq_time(before_updated_at)
+ end
+
+ it "leaves the execution untouched when another worker already claimed it" do
+ allow(::DiscourseWorkflows::Execution).to receive(:claim_for_resume).and_return(nil)
+ before_updated_at = execution.updated_at
+
+ described_class.new.execute(execution_id: execution.id)
+
+ execution.reload
+ expect(execution.status).to eq("waiting")
+ expect(execution.updated_at).to eq_time(before_updated_at)
+ end
+
+ it "no-ops when the execution is no longer waiting" do
+ execution.update!(status: :running)
+ before_updated_at = execution.updated_at
+
+ described_class.new.execute(execution_id: execution.id)
+
+ execution.reload
+ expect(execution.status).to eq("running")
+ expect(execution.updated_at).to eq_time(before_updated_at)
+ end
+end
diff --git a/plugins/discourse-workflows/spec/jobs/regular/discourse_workflows/resume_webhook_waiting_spec.rb b/plugins/discourse-workflows/spec/jobs/regular/discourse_workflows/resume_webhook_waiting_spec.rb
new file mode 100644
index 00000000000..d046169e997
--- /dev/null
+++ b/plugins/discourse-workflows/spec/jobs/regular/discourse_workflows/resume_webhook_waiting_spec.rb
@@ -0,0 +1,30 @@
+# frozen_string_literal: true
+
+RSpec.describe Jobs::DiscourseWorkflows::ResumeWebhookWaiting do
+ fab!(:workflow) { Fabricate(:discourse_workflows_workflow, published: true) }
+ fab!(:execution) do
+ Fabricate(:discourse_workflows_execution, workflow: workflow, status: :waiting)
+ end
+
+ it "leaves the execution waiting when the plugin is disabled" do
+ SiteSetting.discourse_workflows_enabled = false
+ before_updated_at = execution.updated_at
+
+ described_class.new.execute(execution_id: execution.id)
+
+ execution.reload
+ expect(execution.status).to eq("waiting")
+ expect(execution.updated_at).to eq_time(before_updated_at)
+ end
+
+ it "leaves the execution untouched when another worker already claimed it" do
+ allow(::DiscourseWorkflows::Execution).to receive(:claim_for_resume).and_return(nil)
+ before_updated_at = execution.updated_at
+
+ described_class.new.execute(execution_id: execution.id)
+
+ execution.reload
+ expect(execution.status).to eq("waiting")
+ expect(execution.updated_at).to eq_time(before_updated_at)
+ end
+end
diff --git a/plugins/discourse-workflows/spec/lib/discourse_workflows/active_webhooks_spec.rb b/plugins/discourse-workflows/spec/lib/discourse_workflows/active_webhooks_spec.rb
new file mode 100644
index 00000000000..55f2d6dee1b
--- /dev/null
+++ b/plugins/discourse-workflows/spec/lib/discourse_workflows/active_webhooks_spec.rb
@@ -0,0 +1,104 @@
+# frozen_string_literal: true
+
+RSpec.describe DiscourseWorkflows::ActiveWebhooks do
+ fab!(:admin)
+
+ before { described_class.reset_for_tests! }
+ after { described_class.reset_for_tests! }
+
+ def make_workflow(path:, http_method:, webhook_id: nil)
+ graph =
+ build_workflow_graph do |g|
+ g.node "webhook-1",
+ "trigger:webhook",
+ webhook_id: webhook_id,
+ configuration: {
+ "path" => path,
+ "http_method" => http_method,
+ }
+ end
+ workflow = Fabricate(:discourse_workflows_workflow, created_by: admin, published: true, **graph)
+ version = workflow.workflow_versions.find_by(version_id: workflow.version_id)
+ DiscourseWorkflows::Webhook::Action::ActivateWebhooks.call(
+ workflow: workflow,
+ workflow_version: version,
+ )
+ workflow
+ end
+
+ describe ".find" do
+ it "matches static paths exactly with empty path_params" do
+ make_workflow(path: "hooks/inbound", http_method: "POST")
+
+ result = described_class.find(method: "POST", path: "hooks/inbound", test_webhook: false)
+
+ expect(result[:webhook].webhook_path).to eq("hooks/inbound")
+ expect(result[:path_params]).to eq({})
+ end
+
+ it "returns nil when the method does not match" do
+ make_workflow(path: "hooks/inbound", http_method: "POST")
+
+ expect(
+ described_class.find(method: "GET", path: "hooks/inbound", test_webhook: false),
+ ).to be_nil
+ end
+
+ it "matches dynamic paths by webhook_id prefix and captures path params" do
+ make_workflow(path: "users/:id/posts", http_method: "GET", webhook_id: "abcd-1234")
+
+ result =
+ described_class.find(method: "GET", path: "abcd-1234/users/42/posts", test_webhook: false)
+
+ expect(result[:webhook].webhook_id).to eq("abcd-1234")
+ expect(result[:path_params]).to eq("id" => "42")
+ end
+
+ it "prefers the longest template when several share the same webhook_id" do
+ graph =
+ build_workflow_graph do |g|
+ g.node "webhook-1",
+ "trigger:webhook",
+ webhook_id: "abcd-1234",
+ configuration: {
+ "path" => "users/:id/posts/:post_id",
+ "http_method" => "GET",
+ }
+ g.node "webhook-2",
+ "trigger:webhook",
+ webhook_id: "abcd-1234",
+ configuration: {
+ "path" => "users/:id",
+ "http_method" => "GET",
+ }
+ end
+ workflow =
+ Fabricate(:discourse_workflows_workflow, created_by: admin, published: true, **graph)
+ version = workflow.workflow_versions.find_by(version_id: workflow.version_id)
+ DiscourseWorkflows::Webhook::Action::ActivateWebhooks.call(
+ workflow: workflow,
+ workflow_version: version,
+ )
+
+ result =
+ described_class.find(method: "GET", path: "abcd-1234/users/9/posts/12", test_webhook: false)
+
+ expect(result[:webhook].webhook_path).to eq("users/:id/posts/:post_id")
+ expect(result[:path_params]).to eq("id" => "9", "post_id" => "12")
+ end
+
+ it "is invalidated when webhook rows change" do
+ make_workflow(path: "hooks/before", http_method: "POST")
+ expect(
+ described_class.find(method: "POST", path: "hooks/before", test_webhook: false),
+ ).to be_present
+
+ DiscourseWorkflows::Webhook.production.delete_all
+ described_class.invalidate!
+
+ expect(
+ described_class.find(method: "POST", path: "hooks/before", test_webhook: false),
+ ).to be_nil
+ end
+ end
+end
diff --git a/plugins/discourse-workflows/spec/lib/discourse_workflows/credential_data_validator_spec.rb b/plugins/discourse-workflows/spec/lib/discourse_workflows/credential_data_validator_spec.rb
new file mode 100644
index 00000000000..0f76d8552ab
--- /dev/null
+++ b/plugins/discourse-workflows/spec/lib/discourse_workflows/credential_data_validator_spec.rb
@@ -0,0 +1,113 @@
+# frozen_string_literal: true
+
+RSpec.describe DiscourseWorkflows::CredentialDataValidator do
+ describe ".call" do
+ let(:credential_type) { DiscourseWorkflows::CredentialTypes::BasicAuth }
+
+ it "returns no missing fields when all required fields are present" do
+ result =
+ described_class.call(
+ credential_type: credential_type,
+ data: {
+ "user" => "admin",
+ "password" => "secret",
+ },
+ )
+
+ expect(result).to be_empty
+ end
+
+ it "accepts symbol-keyed data" do
+ result =
+ described_class.call(
+ credential_type: credential_type,
+ data: {
+ user: "admin",
+ password: "secret",
+ },
+ )
+
+ expect(result).to be_empty
+ end
+
+ it "returns missing required fields when data is empty" do
+ result = described_class.call(credential_type: credential_type, data: {})
+
+ expect(result).to contain_exactly("user", "password")
+ end
+
+ it "returns missing required fields when data is nil" do
+ result = described_class.call(credential_type: credential_type, data: nil)
+
+ expect(result).to contain_exactly("user", "password")
+ end
+
+ it "treats nil values as missing" do
+ result =
+ described_class.call(
+ credential_type: credential_type,
+ data: {
+ "user" => "admin",
+ "password" => nil,
+ },
+ )
+
+ expect(result).to contain_exactly("password")
+ end
+
+ it "treats empty strings as missing" do
+ result =
+ described_class.call(
+ credential_type: credential_type,
+ data: {
+ "user" => "admin",
+ "password" => "",
+ },
+ )
+
+ expect(result).to contain_exactly("password")
+ end
+
+ it "treats whitespace-only strings as missing" do
+ result =
+ described_class.call(
+ credential_type: credential_type,
+ data: {
+ "user" => " ",
+ "password" => "secret",
+ },
+ )
+
+ expect(result).to contain_exactly("user")
+ end
+
+ it "ignores non-required fields" do
+ type_class =
+ Class.new do
+ def self.property_schema
+ { foo: { type: :string, required: true }, bar: { type: :string } }
+ end
+ end
+
+ result = described_class.call(credential_type: type_class, data: { "foo" => "x" })
+
+ expect(result).to be_empty
+ end
+
+ it "returns empty array when schema is empty" do
+ type_class = Class.new { def self.property_schema = {} }
+
+ result = described_class.call(credential_type: type_class, data: { "anything" => "x" })
+
+ expect(result).to be_empty
+ end
+
+ it "returns empty array when schema is nil" do
+ type_class = Class.new { def self.property_schema = nil }
+
+ result = described_class.call(credential_type: type_class, data: {})
+
+ expect(result).to be_empty
+ end
+ end
+end
diff --git a/plugins/discourse-workflows/spec/lib/discourse_workflows/cron_parser_spec.rb b/plugins/discourse-workflows/spec/lib/discourse_workflows/cron_parser_spec.rb
new file mode 100644
index 00000000000..45d6720e2e7
--- /dev/null
+++ b/plugins/discourse-workflows/spec/lib/discourse_workflows/cron_parser_spec.rb
@@ -0,0 +1,117 @@
+# frozen_string_literal: true
+
+RSpec.describe DiscourseWorkflows::CronParser do
+ describe ".matches?" do
+ it "matches a wildcard expression" do
+ time = Time.utc(2026, 3, 18, 14, 30)
+ expect(described_class.matches?("* * * * *", time)).to be(true)
+ end
+
+ it "matches a specific minute and hour" do
+ time = Time.utc(2026, 3, 18, 9, 0)
+ expect(described_class.matches?("0 9 * * *", time)).to be(true)
+ end
+
+ it "rejects a non-matching minute" do
+ time = Time.utc(2026, 3, 18, 9, 15)
+ expect(described_class.matches?("0 9 * * *", time)).to be(false)
+ end
+
+ it "handles step values" do
+ time = Time.utc(2026, 3, 18, 14, 15)
+ expect(described_class.matches?("*/15 * * * *", time)).to be(true)
+
+ time = Time.utc(2026, 3, 18, 14, 10)
+ expect(described_class.matches?("*/15 * * * *", time)).to be(false)
+ end
+
+ it "handles ranges" do
+ time = Time.utc(2026, 3, 18, 10, 0) # Wednesday
+ expect(described_class.matches?("0 * * * 1-5", time)).to be(true)
+
+ time = Time.utc(2026, 3, 22, 10, 0) # Sunday
+ expect(described_class.matches?("0 * * * 1-5", time)).to be(false)
+ end
+
+ it "handles lists" do
+ time = Time.utc(2026, 3, 18, 9, 0)
+ expect(described_class.matches?("0 9,17 * * *", time)).to be(true)
+
+ time = Time.utc(2026, 3, 18, 12, 0)
+ expect(described_class.matches?("0 9,17 * * *", time)).to be(false)
+ end
+
+ it "handles ranges with steps" do
+ time = Time.utc(2026, 3, 18, 10, 0)
+ expect(described_class.matches?("0 8-18/2 * * *", time)).to be(true)
+
+ time = Time.utc(2026, 3, 18, 11, 0)
+ expect(described_class.matches?("0 8-18/2 * * *", time)).to be(false)
+ end
+
+ it "handles day-of-week 0 and 7 both as Sunday" do
+ sunday = Time.utc(2026, 3, 22, 10, 0) # Sunday
+ expect(described_class.matches?("0 10 * * 0", sunday)).to be(true)
+ expect(described_class.matches?("0 10 * * 7", sunday)).to be(true)
+ end
+
+ it "handles optional seconds" do
+ time = Time.utc(2026, 3, 18, 9, 0, 30)
+ expect(described_class.matches?("30 0 9 * * *", time)).to be(true)
+ expect(described_class.matches?("0 9 * * *", time)).to be(false)
+ end
+
+ it "handles month and weekday names" do
+ time = Time.utc(2026, 3, 18, 9, 0) # Wednesday
+ expect(described_class.matches?("0 9 * mar MON-FRI", time)).to be(true)
+ end
+
+ it "uses standard cron semantics when day-of-month and day-of-week are both restricted" do
+ monday = Time.utc(2026, 6, 8, 9, 0) # Monday
+ first_of_month = Time.utc(2026, 4, 1, 9, 0) # Wednesday, first of month
+ neither = Time.utc(2026, 6, 9, 9, 0) # Tuesday
+
+ expect(described_class.matches?("0 9 1 * 1", monday)).to be(true)
+ expect(described_class.matches?("0 9 1 * 1", first_of_month)).to be(true)
+ expect(described_class.matches?("0 9 1 * 1", neither)).to be(false)
+ end
+
+ it "returns false for invalid expressions" do
+ time = Time.utc(2026, 3, 18, 14, 30)
+ expect(described_class.matches?("invalid", time)).to be(false)
+ expect(described_class.matches?("", time)).to be(false)
+ expect(described_class.matches?(nil, time)).to be(false)
+ expect(described_class.matches?("10-5 * * * *", time)).to be(false)
+ expect(described_class.matches?("*/0 * * * *", time)).to be(false)
+ expect(described_class.matches?("1,,2 * * * *", time)).to be(false)
+ expect(described_class.matches?("* * * * ?", time)).to be(false)
+ end
+ end
+
+ describe ".valid?" do
+ it "checks expression syntax without needing a time argument" do
+ expect(described_class.valid?("* * * * *")).to be(true)
+ expect(described_class.valid?("0 9 * * MON-FRI")).to be(true)
+ expect(described_class.valid?("invalid")).to be(false)
+ expect(described_class.valid?(nil)).to be(false)
+ end
+
+ it "rejects field-count mismatches that .matches? cannot surface" do
+ expect(described_class.valid?("* * *")).to be(false)
+ expect(described_class.valid?("60 * * * *")).to be(false)
+ expect(described_class.valid?("* 25 * * *")).to be(false)
+ end
+ end
+
+ describe ".minute_granularity?" do
+ it "accepts 5-field cron and 6-field cron fixed to second zero" do
+ expect(described_class.minute_granularity?("0 9 * * *")).to be(true)
+ expect(described_class.minute_granularity?("0 0 9 * * *")).to be(true)
+ end
+
+ it "rejects sub-minute cron expressions" do
+ expect(described_class.minute_granularity?("*/10 * * * * *")).to be(false)
+ expect(described_class.minute_granularity?("0,30 * * * * *")).to be(false)
+ end
+ end
+end
diff --git a/plugins/discourse-workflows/spec/lib/discourse_workflows/data_tables/columns_resolver_spec.rb b/plugins/discourse-workflows/spec/lib/discourse_workflows/data_tables/columns_resolver_spec.rb
new file mode 100644
index 00000000000..8dcc046b213
--- /dev/null
+++ b/plugins/discourse-workflows/spec/lib/discourse_workflows/data_tables/columns_resolver_spec.rb
@@ -0,0 +1,63 @@
+# frozen_string_literal: true
+
+RSpec.describe DiscourseWorkflows::DataTables::ColumnsResolver do
+ fab!(:data_table) do
+ Fabricate(
+ :discourse_workflows_data_table,
+ columns: [
+ { "name" => "email", "type" => "string" },
+ { "name" => "score", "type" => "number" },
+ ],
+ )
+ end
+
+ let(:resolver) { described_class.new(data_table) }
+
+ describe "#resolve" do
+ it "resolves hash input keyed by column name" do
+ result = resolver.resolve("email" => "[email protected]", "score" => "42")
+
+ expect(result).to eq("email" => "[email protected]", "score" => "42")
+ end
+
+ it "resolves array input from the workflow editor" do
+ result =
+ resolver.resolve(
+ [
+ { "columnName" => "email", "value" => "[email protected]" },
+ { "columnName" => "score", "value" => "42" },
+ ],
+ )
+
+ expect(result).to eq("email" => "[email protected]", "score" => "42")
+ end
+
+ it "returns an empty hash for blank input" do
+ expect(resolver.resolve(nil)).to eq({})
+ end
+
+ it "raises for unknown column names" do
+ expect { resolver.resolve("unknown" => "x") }.to raise_error(
+ ArgumentError,
+ /Unknown column name/,
+ )
+ end
+
+ it "does not resolve system columns" do
+ expect { resolver.resolve("id" => 1) }.to raise_error(ArgumentError, /Unknown column name/)
+ end
+ end
+
+ describe "#validate_column!" do
+ it "returns nil for known columns" do
+ expect(resolver.validate_column!("email")).to be_nil
+ end
+
+ it "raises for unknown column names" do
+ expect { resolver.validate_column!("unknown") }.to raise_error(
+ ArgumentError,
+ /Unknown column name/,
+ )
+ end
+ end
+end
diff --git a/plugins/discourse-workflows/spec/lib/discourse_workflows/data_tables/facade_spec.rb b/plugins/discourse-workflows/spec/lib/discourse_workflows/data_tables/facade_spec.rb
new file mode 100644
index 00000000000..199c5134c59
--- /dev/null
+++ b/plugins/discourse-workflows/spec/lib/discourse_workflows/data_tables/facade_spec.rb
@@ -0,0 +1,680 @@
+# frozen_string_literal: true
+
+RSpec.describe DiscourseWorkflows::DataTables::Facade do
+ fab!(:data_table) do
+ Fabricate(
+ :discourse_workflows_data_table,
+ columns: [
+ { "name" => "email", "type" => "string" },
+ { "name" => "score", "type" => "number" },
+ { "name" => "active", "type" => "boolean" },
+ { "name" => "joined_at", "type" => "date" },
+ ],
+ )
+ end
+
+ let(:facade) { described_class.new(data_table) }
+
+ let!(:row_1) do
+ insert_data_table_row(
+ data_table,
+ {
+ "email" => "[email protected]",
+ "score" => 90,
+ "active" => true,
+ "joined_at" => "2024-01-10",
+ },
+ )
+ end
+
+ let!(:row_2) do
+ insert_data_table_row(
+ data_table,
+ {
+ "email" => "[email protected]",
+ "score" => 60,
+ "active" => false,
+ "joined_at" => "2024-01-11",
+ },
+ )
+ end
+
+ let!(:row_3) do
+ insert_data_table_row(
+ data_table,
+ { "email" => "[email protected]", "score" => nil, "active" => nil },
+ )
+ end
+
+ let!(:row_4) do
+ insert_data_table_row(
+ data_table,
+ { "email" => "50%[email protected]", "score" => 50, "active" => true },
+ )
+ end
+
+ def build_query(
+ filter: nil,
+ limit: nil,
+ offset: nil,
+ sort_by: nil,
+ sort_direction: nil,
+ optional_filter: true
+ )
+ facade.build_query(
+ filter: filter,
+ limit: limit,
+ offset: offset,
+ sort_by: sort_by,
+ sort_direction: sort_direction,
+ optional_filter: optional_filter,
+ )
+ end
+
+ def build_row_input(data, fill_missing: false)
+ facade.build_row_input(data: data, fill_missing: fill_missing)
+ end
+
+ describe "#build_query" do
+ it "returns an invalid query when the filter is invalid" do
+ query =
+ build_query(
+ filter: {
+ "type" => "and",
+ "filters" => [{ "columnName" => "missing", "condition" => "eq", "value" => "x" }],
+ },
+ )
+
+ expect(query).to be_invalid
+ expect(query.errors.full_messages).to include("Unknown column name 'missing'")
+ end
+ end
+
+ describe "#query" do
+ it "returns all rows without a filter" do
+ result = facade.query(build_query)
+
+ expect(result[:count]).to eq(4)
+ expect(result[:rows].map { |row| row["id"] }).to eq(
+ [row_1["id"], row_2["id"], row_3["id"], row_4["id"]],
+ )
+ end
+
+ it "supports filtering" do
+ result =
+ facade.query(
+ build_query(
+ filter: {
+ "type" => "and",
+ "filters" => [
+ { "columnName" => "email", "condition" => "ilike", "value" => "ALICE" },
+ ],
+ },
+ ),
+ )
+
+ expect(result[:rows].map { |row| row["id"] }).to eq([row_1["id"]])
+ end
+
+ it "sorts and limits deterministically" do
+ result = facade.query(build_query(sort_by: "score", sort_direction: "desc", limit: 2))
+
+ expect(result[:rows].map { |row| row["id"] }).to eq([row_1["id"], row_2["id"]])
+ end
+
+ it "supports pagination with offset" do
+ result = facade.query(build_query(limit: 1, offset: 1))
+
+ expect(result[:count]).to eq(4)
+ expect(result[:rows].size).to eq(1)
+ expect(result[:rows].first["id"]).to eq(row_2["id"])
+ end
+ end
+
+ describe "filtering" do
+ describe "eq condition" do
+ it "matches exact values" do
+ result =
+ facade.query(
+ build_query(
+ filter: {
+ "type" => "and",
+ "filters" => [{ "columnName" => "score", "condition" => "eq", "value" => 90 }],
+ },
+ ),
+ )
+
+ expect(result[:rows].map { |r| r["id"] }).to eq([row_1["id"]])
+ end
+
+ it "matches nil values" do
+ result =
+ facade.query(
+ build_query(
+ filter: {
+ "type" => "and",
+ "filters" => [{ "columnName" => "score", "condition" => "eq", "value" => nil }],
+ },
+ ),
+ )
+
+ expect(result[:rows].map { |r| r["id"] }).to eq([row_3["id"]])
+ end
+ end
+
+ describe "neq condition" do
+ it "excludes matching values and includes nulls" do
+ result =
+ facade.query(
+ build_query(
+ filter: {
+ "type" => "and",
+ "filters" => [{ "columnName" => "score", "condition" => "neq", "value" => 90 }],
+ },
+ ),
+ )
+
+ expect(result[:rows].map { |r| r["id"] }).to contain_exactly(
+ row_2["id"],
+ row_3["id"],
+ row_4["id"],
+ )
+ end
+
+ it "excludes nil values" do
+ result =
+ facade.query(
+ build_query(
+ filter: {
+ "type" => "and",
+ "filters" => [{ "columnName" => "score", "condition" => "neq", "value" => nil }],
+ },
+ ),
+ )
+
+ expect(result[:rows].map { |r| r["id"] }).to contain_exactly(
+ row_1["id"],
+ row_2["id"],
+ row_4["id"],
+ )
+ end
+ end
+
+ describe "comparison conditions" do
+ it "gt filters strictly greater" do
+ result =
+ facade.query(
+ build_query(
+ filter: {
+ "type" => "and",
+ "filters" => [{ "columnName" => "score", "condition" => "gt", "value" => 60 }],
+ },
+ ),
+ )
+
+ expect(result[:rows].map { |r| r["id"] }).to eq([row_1["id"]])
+ end
+
+ it "gte includes equal values" do
+ result =
+ facade.query(
+ build_query(
+ filter: {
+ "type" => "and",
+ "filters" => [{ "columnName" => "score", "condition" => "gte", "value" => 60 }],
+ },
+ ),
+ )
+
+ expect(result[:rows].map { |r| r["id"] }).to contain_exactly(row_1["id"], row_2["id"])
+ end
+
+ it "lt filters strictly less" do
+ result =
+ facade.query(
+ build_query(
+ filter: {
+ "type" => "and",
+ "filters" => [{ "columnName" => "score", "condition" => "lt", "value" => 90 }],
+ },
+ ),
+ )
+
+ expect(result[:rows].map { |r| r["id"] }).to contain_exactly(row_2["id"], row_4["id"])
+ end
+
+ it "lte includes equal values" do
+ result =
+ facade.query(
+ build_query(
+ filter: {
+ "type" => "and",
+ "filters" => [{ "columnName" => "score", "condition" => "lte", "value" => 60 }],
+ },
+ ),
+ )
+
+ expect(result[:rows].map { |r| r["id"] }).to contain_exactly(row_2["id"], row_4["id"])
+ end
+ end
+
+ describe "like conditions" do
+ it "case-sensitive like match" do
+ result =
+ facade.query(
+ build_query(
+ filter: {
+ "type" => "and",
+ "filters" => [
+ { "columnName" => "email", "condition" => "like", "value" => "alice" },
+ ],
+ },
+ ),
+ )
+
+ expect(result[:rows].map { |r| r["id"] }).to eq([row_1["id"]])
+ end
+
+ it "case-insensitive ilike match" do
+ result =
+ facade.query(
+ build_query(
+ filter: {
+ "type" => "and",
+ "filters" => [
+ { "columnName" => "email", "condition" => "ilike", "value" => "ALICE" },
+ ],
+ },
+ ),
+ )
+
+ expect(result[:rows].map { |r| r["id"] }).to eq([row_1["id"]])
+ end
+
+ it "not_ilike excludes matches" do
+ result =
+ facade.query(
+ build_query(
+ filter: {
+ "type" => "and",
+ "filters" => [
+ { "columnName" => "email", "condition" => "not_ilike", "value" => "alice" },
+ ],
+ },
+ ),
+ )
+
+ expect(result[:rows].map { |r| r["id"] }).not_to include(row_1["id"])
+ end
+
+ it "escapes underscore in like patterns" do
+ result =
+ facade.query(
+ build_query(
+ filter: {
+ "type" => "and",
+ "filters" => [
+ { "columnName" => "email", "condition" => "ilike", "value" => "a_ice" },
+ ],
+ },
+ ),
+ )
+
+ expect(result[:rows]).to be_empty
+ end
+
+ it "escapes percent in like patterns" do
+ result =
+ facade.query(
+ build_query(
+ filter: {
+ "type" => "and",
+ "filters" => [
+ { "columnName" => "email", "condition" => "ilike", "value" => "50%off" },
+ ],
+ },
+ ),
+ )
+
+ expect(result[:rows].map { |r| r["id"] }).to eq([row_4["id"]])
+ end
+ end
+
+ describe "AND/OR combination" do
+ it "AND requires all conditions to match" do
+ result =
+ facade.query(
+ build_query(
+ filter: {
+ "type" => "and",
+ "filters" => [
+ { "columnName" => "score", "condition" => "eq", "value" => 60 },
+ { "columnName" => "active", "condition" => "eq", "value" => false },
+ ],
+ },
+ ),
+ )
+
+ expect(result[:rows].map { |r| r["id"] }).to eq([row_2["id"]])
+ end
+
+ it "OR requires any condition to match" do
+ result =
+ facade.query(
+ build_query(
+ filter: {
+ "type" => "or",
+ "filters" => [
+ { "columnName" => "score", "condition" => "eq", "value" => 90 },
+ { "columnName" => "active", "condition" => "eq", "value" => false },
+ ],
+ },
+ ),
+ )
+
+ expect(result[:rows].map { |r| r["id"] }).to contain_exactly(row_1["id"], row_2["id"])
+ end
+ end
+ end
+
+ describe "ordering" do
+ it "defaults to id ascending when sort_by is blank" do
+ result = facade.query(build_query)
+
+ expect(result[:rows].map { |r| r["id"] }).to eq(
+ [row_1["id"], row_2["id"], row_3["id"], row_4["id"]],
+ )
+ end
+
+ it "sorts ascending with nulls last" do
+ result = facade.query(build_query(sort_by: "score", sort_direction: "asc"))
+ ids = result[:rows].map { |r| r["id"] }
+
+ expect(ids).to eq([row_4["id"], row_2["id"], row_1["id"], row_3["id"]])
+ end
+
+ it "sorts descending with nulls last" do
+ result = facade.query(build_query(sort_by: "score", sort_direction: "desc"))
+ ids = result[:rows].map { |r| r["id"] }
+
+ expect(ids.first).to eq(row_1["id"])
+ expect(ids.last).to eq(row_3["id"])
+ end
+
+ it "defaults to ASC for invalid direction" do
+ result = facade.query(build_query(sort_by: "score", sort_direction: "invalid"))
+ ids = result[:rows].map { |r| r["id"] }
+
+ expect(ids).to eq([row_4["id"], row_2["id"], row_1["id"], row_3["id"]])
+ end
+
+ it "uses id as secondary sort for stability" do
+ row_4 =
+ insert_data_table_row(
+ data_table,
+ { "email" => "[email protected]", "score" => 60, "active" => true },
+ )
+
+ result = facade.query(build_query(sort_by: "score", sort_direction: "asc"))
+ ids = result[:rows].map { |r| r["id"] }
+ bob_idx = ids.index(row_2["id"])
+ dave_idx = ids.index(row_4["id"])
+
+ expect(bob_idx).to be < dave_idx
+ end
+
+ it "raises ArgumentError for unknown sort column" do
+ expect { facade.query(build_query(sort_by: "'; DROP TABLE users; --")) }.to raise_error(
+ ArgumentError,
+ /Invalid sort column/,
+ )
+ end
+ end
+
+ describe "pagination" do
+ it "limits results" do
+ result = facade.query(build_query(limit: 2))
+
+ expect(result[:rows].size).to eq(2)
+ end
+
+ it "offsets results" do
+ all_ids = facade.query(build_query)[:rows].map { |r| r["id"] }
+
+ result = facade.query(build_query(offset: 2))
+
+ expect(result[:rows].map { |r| r["id"] }).to eq(all_ids[2..])
+ end
+
+ it "combines limit and offset" do
+ all_ids = facade.query(build_query)[:rows].map { |r| r["id"] }
+
+ result = facade.query(build_query(limit: 1, offset: 1))
+
+ expect(result[:rows].map { |r| r["id"] }).to eq([all_ids[1]])
+ end
+
+ it "caps limit at MAX_LIMIT" do
+ result = facade.query(build_query(limit: 999))
+
+ expect(result[:rows].size).to be <= described_class::MAX_LIMIT
+ end
+
+ it "ignores zero limit" do
+ result = facade.query(build_query(limit: 0))
+
+ expect(result[:rows].size).to eq(4)
+ end
+
+ it "ignores zero offset" do
+ all_ids = facade.query(build_query)[:rows].map { |r| r["id"] }
+
+ result = facade.query(build_query(offset: 0))
+
+ expect(result[:rows].map { |r| r["id"] }).to eq(all_ids)
+ end
+ end
+
+ describe "#find_row" do
+ it "returns a row by id" do
+ row = facade.find_row(row_1["id"])
+
+ expect(row["email"]).to eq("[email protected]")
+ expect(row["score"]).to eq(90)
+ end
+
+ it "returns nil for a non-existent id" do
+ expect(facade.find_row(-1)).to be_nil
+ end
+ end
+
+ describe "#count" do
+ it "returns the total count without a filter" do
+ expect(facade.count).to eq(4)
+ end
+ end
+
+ describe "#insert" do
+ it "inserts a row with cast data" do
+ row = facade.insert(build_row_input({ "email" => "[email protected]" }, fill_missing: true))
+
+ expect(row["email"]).to eq("[email protected]")
+ expect(row["score"]).to be_nil
+ end
+
+ it "inserts a default row when data is empty" do
+ row = facade.insert(build_row_input({}))
+
+ expect(row["id"]).to be_present
+ end
+ end
+
+ describe "#update_row" do
+ it "updates a single row and returns it" do
+ updated =
+ facade.update_row(row_id: row_1["id"], row_input: build_row_input({ "score" => 99 }))
+
+ expect(updated["score"]).to eq(99)
+ expect(updated["email"]).to eq("[email protected]")
+ end
+
+ it "returns nil for a non-existent id" do
+ updated = facade.update_row(row_id: -1, row_input: build_row_input({ "score" => 99 }))
+
+ expect(updated).to be_nil
+ end
+
+ it "returns nil when the row input is empty" do
+ expect(facade.update_row(row_id: row_1["id"], row_input: build_row_input({}))).to be_nil
+ end
+ end
+
+ describe "#update" do
+ it "updates matching rows and returns the affected count" do
+ updated_count =
+ facade.update(
+ query:
+ build_query(
+ filter: {
+ "type" => "and",
+ "filters" => [
+ { "columnName" => "email", "condition" => "eq", "value" => "[email protected]" },
+ ],
+ },
+ ),
+ row_input: build_row_input({ "score" => 99 }),
+ )
+
+ expect(updated_count).to eq(1)
+ expect(find_data_table_row(data_table, row_1["id"])["score"]).to eq(99)
+ end
+ end
+
+ describe "#delete_rows" do
+ it "deletes rows by ids and returns the affected count" do
+ expect(facade.delete_rows([row_1["id"]])).to eq(1)
+ expect(find_data_table_row(data_table, row_1["id"])).to be_nil
+ end
+
+ it "returns 0 for non-existent ids" do
+ expect(facade.delete_rows([-1])).to eq(0)
+ end
+
+ it "returns 0 for an empty array" do
+ expect(facade.delete_rows([])).to eq(0)
+ end
+
+ it "deletes rows when storage is over the limit" do
+ allow(described_class).to receive(:within_storage_limit?).and_return(false)
+
+ expect(facade.delete_rows([row_1["id"]])).to eq(1)
+ expect(find_data_table_row(data_table, row_1["id"])).to be_nil
+ end
+ end
+
+ describe "#delete" do
+ it "deletes matching rows and returns the affected count" do
+ deleted_count =
+ facade.delete(
+ query:
+ build_query(
+ filter: {
+ "type" => "and",
+ "filters" => [
+ { "columnName" => "email", "condition" => "eq", "value" => "[email protected]" },
+ ],
+ },
+ ),
+ )
+
+ expect(deleted_count).to eq(1)
+ expect(find_data_table_row(data_table, row_2["id"])).to be_nil
+ end
+
+ it "deletes matching rows when storage is over the limit" do
+ allow(described_class).to receive(:within_storage_limit?).and_return(false)
+
+ deleted_count =
+ facade.delete(
+ query:
+ build_query(
+ filter: {
+ "type" => "and",
+ "filters" => [
+ { "columnName" => "email", "condition" => "eq", "value" => "[email protected]" },
+ ],
+ },
+ ),
+ )
+
+ expect(deleted_count).to eq(1)
+ expect(find_data_table_row(data_table, row_2["id"])).to be_nil
+ end
+ end
+
+ describe "statement timeout" do
+ it "raises StatementTimeout when a query exceeds the limit" do
+ stub_const(DiscourseWorkflows::DataTables::Facade, :STATEMENT_TIMEOUT_MS, 100) do
+ expect {
+ facade.send(:with_statement_timeout) do
+ ActiveRecord::Base.connection.execute("SELECT pg_sleep(1)")
+ end
+ }.to raise_error(described_class::StatementTimeout)
+ end
+ end
+ end
+
+ describe "lock timeout" do
+ it "wraps the block in a transaction so SET LOCAL lock_timeout takes effect" do
+ initial_open_transactions = ActiveRecord::Base.connection.open_transactions
+ observed_open_transactions = nil
+
+ facade.send(:with_lock_timeout) do
+ observed_open_transactions = ActiveRecord::Base.connection.open_transactions
+ end
+
+ expect(observed_open_transactions).to eq(initial_open_transactions + 1)
+ end
+ end
+
+ describe "#add_column!" do
+ it "adds a column to the storage table" do
+ facade.add_column!("notes", "string")
+
+ reloaded_facade = described_class.new(data_table)
+ row = reloaded_facade.insert(reloaded_facade.build_row_input(data: { "notes" => "hello" }))
+ expect(row["notes"]).to eq("hello")
+ end
+ end
+
+ describe "#rename_column!" do
+ it "renames a column in the storage table" do
+ facade.rename_column!(old_name: "email", new_name: "contact_email")
+
+ table_name = DiscourseWorkflows::DataTables::Storage.table_name(data_table.id)
+ columns =
+ DB.query_single(
+ "SELECT column_name FROM information_schema.columns WHERE table_name = :table_name",
+ table_name: table_name,
+ )
+
+ expect(columns).to include("contact_email")
+ expect(columns).not_to include("email")
+ end
+ end
+
+ describe "#drop_column!" do
+ it "drops a column from the storage table" do
+ facade.drop_column!("active")
+
+ table_name = DiscourseWorkflows::DataTables::Storage.table_name(data_table.id)
+ columns =
+ DB.query_single(
+ "SELECT column_name FROM information_schema.columns WHERE table_name = :table_name",
+ table_name: table_name,
+ )
+
+ expect(columns).not_to include("active")
+ end
+ end
+end
diff --git a/plugins/discourse-workflows/spec/lib/discourse_workflows/data_tables/node_proxy_spec.rb b/plugins/discourse-workflows/spec/lib/discourse_workflows/data_tables/node_proxy_spec.rb
new file mode 100644
index 00000000000..a6fed093100
--- /dev/null
+++ b/plugins/discourse-workflows/spec/lib/discourse_workflows/data_tables/node_proxy_spec.rb
@@ -0,0 +1,130 @@
+# frozen_string_literal: true
+
+RSpec.describe DiscourseWorkflows::DataTables::NodeProxy do
+ fab!(:data_table) do
+ Fabricate(
+ :discourse_workflows_data_table,
+ name: "contacts",
+ columns: [
+ { "name" => "email", "type" => "string" },
+ { "name" => "score", "type" => "number" },
+ ],
+ )
+ end
+
+ subject(:proxy) { described_class.new(data_table_facade(data_table)) }
+
+ def email_filter(email)
+ {
+ "type" => "and",
+ "filters" => [{ "columnName" => "email", "condition" => "eq", "value" => email }],
+ }
+ end
+
+ it "returns user columns without system columns" do
+ expect(proxy.get_columns).to eq(
+ [
+ { id: "email", name: "email", type: "string", index: 0, data_table_id: data_table.id },
+ { id: "score", name: "score", type: "number", index: 1, data_table_id: data_table.id },
+ ],
+ )
+ end
+
+ it "inserts rows with return mode 'all'" do
+ rows = [
+ { "email" => "[email protected]", "score" => "1" },
+ { "email" => "[email protected]", "score" => "2" },
+ ]
+
+ inserted_rows = proxy.insert_rows(rows, "all")
+ expect(inserted_rows.map { |row| row.slice("email", "score") }).to eq(
+ [{ "email" => "[email protected]", "score" => 1 }, { "email" => "[email protected]", "score" => 2 }],
+ )
+
+ ids = proxy.insert_rows([{ "email" => "[email protected]" }], "id")
+ expect(ids.first.keys).to contain_exactly("id")
+
+ expect(proxy.insert_rows([{ "email" => "[email protected]" }], "count")).to eq(
+ "success" => true,
+ "insertedRows" => 1,
+ )
+ end
+
+ it "gets many rows and count" do
+ insert_data_table_row(data_table, "email" => "[email protected]", "score" => 1)
+ insert_data_table_row(data_table, "email" => "[email protected]", "score" => 2)
+
+ result = proxy.get_many_rows_and_count(sort_by: %w[email DESC], take: 1)
+
+ expect(result[:count]).to eq(2)
+ expect(result[:data].map { |row| row["email"] }).to eq(["[email protected]"])
+ end
+
+ it "updates rows and returns updated rows" do
+ insert_data_table_row(data_table, "email" => "[email protected]", "score" => 1)
+ insert_data_table_row(data_table, "email" => "[email protected]", "score" => 2)
+
+ rows = proxy.update_rows(filter: email_filter("[email protected]"), data: { "score" => "10" })
+
+ expect(rows.map { |row| row.slice("email", "score") }).to eq(
+ [{ "email" => "[email protected]", "score" => 10 }],
+ )
+ end
+
+ it "upserts rows" do
+ insert_data_table_row(data_table, "email" => "[email protected]", "score" => 1)
+
+ updated_rows =
+ proxy.upsert_row(filter: email_filter("[email protected]"), data: { "score" => "10" })
+ inserted_rows =
+ proxy.upsert_row(
+ filter: email_filter("[email protected]"),
+ data: {
+ "email" => "[email protected]",
+ "score" => "2",
+ },
+ )
+
+ expect(updated_rows.map { |row| row.slice("email", "score") }).to eq(
+ [{ "email" => "[email protected]", "score" => 10 }],
+ )
+ expect(inserted_rows.map { |row| row.slice("email", "score") }).to eq(
+ [{ "email" => "[email protected]", "score" => 2 }],
+ )
+ end
+
+ it "deletes rows and returns deleted rows" do
+ insert_data_table_row(data_table, "email" => "[email protected]", "score" => 1)
+ insert_data_table_row(data_table, "email" => "[email protected]", "score" => 2)
+
+ rows = proxy.delete_rows(filter: email_filter("[email protected]"))
+
+ expect(rows.map { |row| row.slice("email", "score") }).to eq(
+ [{ "email" => "[email protected]", "score" => 1 }],
+ )
+ expect(count_data_table_rows(data_table)).to eq(1)
+ end
+
+ it "requires filters for mutating row operations" do
+ expect { proxy.update_rows(data: { "score" => "10" }) }.to raise_error(
+ ArgumentError,
+ /Filter must not be empty/,
+ )
+ expect { proxy.upsert_row(data: { "score" => "10" }) }.to raise_error(
+ ArgumentError,
+ /Filter must not be empty/,
+ )
+ expect { proxy.delete_rows({}) }.to raise_error(ArgumentError, /Filter must not be empty/)
+ end
+
+ it "manages table and column operations exposed by the proxy contract" do
+ expect(proxy.update_data_table(name: "renamed_contacts")).to eq(true)
+ expect(data_table.reload.name).to eq("renamed_contacts")
+
+ column = proxy.add_column(name: "active", type: "boolean")
+ expect(column).to include(name: "active", type: "boolean")
+
+ expect(proxy.delete_column("active")).to eq(true)
+ expect(proxy.get_columns.map { |c| c[:name] }).not_to include("active")
+ end
+end
diff --git a/plugins/discourse-workflows/spec/lib/discourse_workflows/data_tables/row_input_spec.rb b/plugins/discourse-workflows/spec/lib/discourse_workflows/data_tables/row_input_spec.rb
new file mode 100644
index 00000000000..6b2b6257235
--- /dev/null
+++ b/plugins/discourse-workflows/spec/lib/discourse_workflows/data_tables/row_input_spec.rb
@@ -0,0 +1,51 @@
+# frozen_string_literal: true
+
+RSpec.describe DiscourseWorkflows::DataTables::Facade::RowInput do
+ fab!(:data_table) do
+ Fabricate(
+ :discourse_workflows_data_table,
+ columns: [
+ { "name" => "email", "type" => "string" },
+ { "name" => "score", "type" => "number" },
+ ],
+ )
+ end
+
+ describe "with valid data" do
+ subject(:model) do
+ described_class.new(data_table:, data: { "email" => "[email protected]", "score" => "5" })
+ end
+
+ it "casts the column values" do
+ expect(model.columns).to eq("email" => "[email protected]", "score" => 5)
+ end
+ end
+
+ describe "with fill_missing" do
+ subject(:model) do
+ described_class.new(data_table:, data: { "email" => "[email protected]" }, fill_missing: true)
+ end
+
+ it "fills omitted columns with nil" do
+ expect(model.columns).to eq("email" => "[email protected]", "score" => nil)
+ end
+ end
+
+ describe "with unknown columns" do
+ subject(:model) { described_class.new(data_table:, data: { "unknown" => "val" }) }
+
+ it "is invalid" do
+ expect(model).not_to be_valid
+ expect(model.errors[:base]).to include(match(/Unknown column name/))
+ end
+ end
+
+ describe "with invalid type" do
+ subject(:model) { described_class.new(data_table:, data: { "score" => "not_a_number" }) }
+
+ it "is invalid" do
+ expect(model).not_to be_valid
+ expect(model.errors[:base]).to include(match(/does not match column type/))
+ end
+ end
+end
diff --git a/plugins/discourse-workflows/spec/lib/discourse_workflows/data_tables/storage_spec.rb b/plugins/discourse-workflows/spec/lib/discourse_workflows/data_tables/storage_spec.rb
new file mode 100644
index 00000000000..a69dd5dd32f
--- /dev/null
+++ b/plugins/discourse-workflows/spec/lib/discourse_workflows/data_tables/storage_spec.rb
@@ -0,0 +1,41 @@
+# frozen_string_literal: true
+
+RSpec.describe DiscourseWorkflows::DataTables::Storage do
+ fab!(:data_table) do
+ Fabricate(
+ :discourse_workflows_data_table,
+ columns: [
+ { "name" => "email", "type" => "string" },
+ { "name" => "score", "type" => "number" },
+ { "name" => "active", "type" => "boolean" },
+ { "name" => "happened_at", "type" => "date" },
+ ],
+ )
+ end
+
+ describe ".columns" do
+ it "returns all columns with mapped types ordered by attnum" do
+ columns = described_class.columns(data_table.id)
+
+ expect(columns).to eq(
+ [
+ { "name" => "id", "type" => "number" },
+ { "name" => "email", "type" => "string" },
+ { "name" => "score", "type" => "number" },
+ { "name" => "active", "type" => "boolean" },
+ { "name" => "happened_at", "type" => "date" },
+ { "name" => "created_at", "type" => "date" },
+ { "name" => "updated_at", "type" => "date" },
+ ],
+ )
+ end
+
+ it "returns only system columns for a table with no user columns" do
+ empty_table = Fabricate(:discourse_workflows_data_table, columns: [])
+
+ columns = described_class.columns(empty_table.id)
+
+ expect(columns.map { |c| c["name"] }).to eq(%w[id created_at updated_at])
+ end
+ end
+end
diff --git a/plugins/discourse-workflows/spec/lib/discourse_workflows/event_listener_spec.rb b/plugins/discourse-workflows/spec/lib/discourse_workflows/event_listener_spec.rb
new file mode 100644
index 00000000000..dede81be2ce
--- /dev/null
+++ b/plugins/discourse-workflows/spec/lib/discourse_workflows/event_listener_spec.rb
@@ -0,0 +1,152 @@
+# frozen_string_literal: true
+
+RSpec.describe DiscourseWorkflows::EventListener do
+ fab!(:user)
+ fab!(:admin)
+ fab!(:category)
+ fab!(:other_category, :category)
+ fab!(:topic) { Fabricate(:topic, category: category) }
+ fab!(:tag) { Fabricate(:tag, name: "matched") }
+
+ before { SiteSetting.tagging_enabled = true }
+
+ it "enqueues a job when a matching event fires" do
+ graph = build_workflow_graph { |g| g.node "trigger-1", "trigger:topic_closed" }
+ workflow = Fabricate(:discourse_workflows_workflow, created_by: user, published: true, **graph)
+ DiscourseWorkflows::WorkflowDependencyIndexer.call(workflow)
+
+ topic.update_status("closed", true, admin)
+
+ job = Jobs::DiscourseWorkflows::ExecuteWorkflow.jobs.last
+ expect(job).to be_present
+ expect(job["args"].first["trigger_node_id"]).to eq("trigger-1")
+ expect(job["args"].first["workflow_id"]).to eq(workflow.id)
+ end
+
+ it "does not enqueue when plugin is disabled" do
+ SiteSetting.discourse_workflows_enabled = false
+
+ graph = build_workflow_graph { |g| g.node "trigger-1", "trigger:topic_closed" }
+ workflow = Fabricate(:discourse_workflows_workflow, created_by: user, published: true, **graph)
+ DiscourseWorkflows::WorkflowDependencyIndexer.call(workflow)
+
+ topic.update_status("closed", true, admin)
+
+ jobs =
+ Jobs::DiscourseWorkflows::ExecuteWorkflow.jobs.select do |j|
+ j["args"].first["trigger_node_id"] == "trigger-1"
+ end
+ expect(jobs).to be_empty
+ end
+
+ it "only enqueues topic closed workflows matching the category and tags" do
+ topic.tags << tag
+ create_published_workflow(
+ "matching-trigger",
+ "trigger:topic_closed",
+ configuration: {
+ "category_id" => category.id.to_s,
+ "tag_names" => [tag.name],
+ },
+ )
+ create_published_workflow(
+ "category-mismatch",
+ "trigger:topic_closed",
+ configuration: {
+ "category_id" => other_category.id.to_s,
+ },
+ )
+ create_published_workflow(
+ "tag-mismatch",
+ "trigger:topic_closed",
+ configuration: {
+ "tag_names" => ["missing"],
+ },
+ )
+
+ topic.update_status("closed", true, admin)
+
+ expect(enqueued_trigger_node_ids).to include("matching-trigger")
+ expect(enqueued_trigger_node_ids).not_to include("category-mismatch", "tag-mismatch")
+ end
+
+ it "only enqueues topic created workflows matching the category and tags" do
+ create_post(topic: topic)
+ topic.tags << tag
+ create_published_workflow(
+ "matching-trigger",
+ "trigger:topic_created",
+ configuration: {
+ "category_id" => category.id.to_s,
+ "tag_names" => [tag.name],
+ },
+ )
+ create_published_workflow(
+ "category-mismatch",
+ "trigger:topic_created",
+ configuration: {
+ "category_id" => other_category.id.to_s,
+ },
+ )
+ create_published_workflow(
+ "tag-mismatch",
+ "trigger:topic_created",
+ configuration: {
+ "tag_names" => ["missing"],
+ },
+ )
+
+ described_class.handle(DiscourseWorkflows::Nodes::TopicCreated::V1, topic)
+
+ expect(enqueued_trigger_node_ids).to include("matching-trigger")
+ expect(enqueued_trigger_node_ids).not_to include("category-mismatch", "tag-mismatch")
+ end
+
+ it "only enqueues post created workflows matching the topic category and tags" do
+ topic.tags << tag
+ create_published_workflow(
+ "matching-trigger",
+ "trigger:post_created",
+ configuration: {
+ "category_id" => category.id.to_s,
+ "tag_names" => [tag.name],
+ },
+ )
+ create_published_workflow(
+ "category-mismatch",
+ "trigger:post_created",
+ configuration: {
+ "category_id" => other_category.id.to_s,
+ },
+ )
+ create_published_workflow(
+ "tag-mismatch",
+ "trigger:post_created",
+ configuration: {
+ "tag_names" => ["missing"],
+ },
+ )
+
+ post = create_post(topic: topic)
+ described_class.handle(DiscourseWorkflows::Nodes::PostCreated::V1, post)
+
+ expect(enqueued_trigger_node_ids).to include("matching-trigger")
+ expect(enqueued_trigger_node_ids).not_to include("category-mismatch", "tag-mismatch")
+ end
+
+ def create_published_workflow(trigger_node_id, trigger_type, configuration: {})
+ graph =
+ build_workflow_graph do |g|
+ g.node trigger_node_id, trigger_type, configuration: configuration
+ end
+ workflow = Fabricate(:discourse_workflows_workflow, created_by: user, published: true, **graph)
+ DiscourseWorkflows::WorkflowDependencyIndexer.call(workflow)
+ workflow
+ end
+
+ def enqueued_trigger_node_ids
+ Jobs::DiscourseWorkflows::ExecuteWorkflow.jobs.map do |job|
+ job["args"].first["trigger_node_id"]
+ end
+ end
+end
diff --git a/plugins/discourse-workflows/spec/lib/discourse_workflows/executor/code_runner_spec.rb b/plugins/discourse-workflows/spec/lib/discourse_workflows/executor/code_runner_spec.rb
new file mode 100644
index 00000000000..cfeb9dc8968
--- /dev/null
+++ b/plugins/discourse-workflows/spec/lib/discourse_workflows/executor/code_runner_spec.rb
@@ -0,0 +1,95 @@
+# frozen_string_literal: true
+
+RSpec.describe DiscourseWorkflows::Executor::CodeRunner do
+ let(:runtime_state) { DiscourseWorkflows::Executor::NodeExecutionContext::RuntimeState.new }
+
+ def build_runner(items: [{ "json" => {} }], parameters: {}, resolver_context: {})
+ described_class.new(
+ input_items: items,
+ parameters: parameters,
+ input_context: {
+ },
+ resolver_context: resolver_context,
+ user: nil,
+ vars: nil,
+ flow_context: {
+ },
+ runtime_state: runtime_state,
+ )
+ end
+
+ it "runs JavaScript in runCode mode" do
+ result =
+ build_runner.run({ "nodeMode" => "runCode", "code" => "return { json: { value: 2 } };" }, 0)
+
+ expect(result).to eq("json" => { "value" => 2 })
+ end
+
+ it "runs JavaScript once for all items with $input helpers" do
+ items = [{ "json" => { "value" => 1 } }, { "json" => { "value" => 2 } }]
+ result =
+ build_runner(items: items).run(
+ {
+ "nodeMode" => "runOnceForAllItems",
+ "code" => "return $input.all().map(function(item) { return item.json.value; });",
+ },
+ 0,
+ )
+
+ expect(result).to eq([1, 2])
+ end
+
+ it "runs JavaScript once for each item in the requested chunk" do
+ items = [{ "json" => { "value" => 1 } }, { "json" => { "value" => 2 } }]
+ result =
+ build_runner(items: items).run(
+ {
+ "nodeMode" => "runOnceForEachItem",
+ "code" => "return { json: { value: $json.value, index: $itemIndex } };",
+ "chunk" => {
+ "startIndex" => 1,
+ "count" => 1,
+ },
+ },
+ 0,
+ )
+
+ expect(result).to eq([{ "json" => { "value" => 2, "index" => 1 } }])
+ end
+
+ it "merges sandbox logs into the runtime state" do
+ build_runner.run(
+ { "nodeMode" => "runCode", "code" => 'console.log("from code"); return null;' },
+ 0,
+ )
+
+ expect(runtime_state.log.entries).to contain_exactly(
+ include("level" => "info", "message" => "from code"),
+ )
+ end
+
+ it "rejects invalid JavaScript additional property names" do
+ expect {
+ build_runner.run(
+ {
+ "nodeMode" => "runCode",
+ "code" => "return null;",
+ "additionalProperties" => {
+ "not valid" => true,
+ },
+ },
+ 0,
+ )
+ }.to raise_error(ArgumentError, "Invalid JavaScript property name: not valid")
+ end
+
+ it "preserves JavaScript null and undefined as distinct Ruby values" do
+ runner = build_runner
+
+ null_result = runner.run({ "nodeMode" => "runCode", "code" => "return null;" }, 0)
+ undefined_result = runner.run({ "nodeMode" => "runCode", "code" => "return;" }, 0)
+
+ expect(null_result).to be_nil
+ expect(undefined_result).to eq(described_class::JAVASCRIPT_UNDEFINED)
+ end
+end
diff --git a/plugins/discourse-workflows/spec/lib/discourse_workflows/executor/error_workflow_trigger_spec.rb b/plugins/discourse-workflows/spec/lib/discourse_workflows/executor/error_workflow_trigger_spec.rb
new file mode 100644
index 00000000000..5864506a12d
--- /dev/null
+++ b/plugins/discourse-workflows/spec/lib/discourse_workflows/executor/error_workflow_trigger_spec.rb
@@ -0,0 +1,188 @@
+# frozen_string_literal: true
+
+RSpec.describe DiscourseWorkflows::Executor::ErrorWorkflowTrigger do
+ fab!(:user)
+
+ def build_handler(workflow, steps, execution: nil, execution_mode: :normal)
+ execution ||=
+ Fabricate(
+ :discourse_workflows_error_execution,
+ workflow: workflow,
+ execution_mode: execution_mode,
+ )
+
+ described_class.new(workflow, steps, execution: execution, execution_mode: execution_mode)
+ end
+
+ def build_steps(last_failed_step: nil)
+ return [] if last_failed_step.nil?
+
+ [DiscourseWorkflows::Executor::Step.from_h(last_failed_step.merge("status" => "error"))]
+ end
+
+ def build_error_workflow
+ graph = build_workflow_graph { |g| g.node "error-trigger-1", "trigger:error" }
+ Fabricate(:discourse_workflows_workflow, created_by: user, published: true, **graph)
+ end
+
+ def build_workflow_with_error_handler(error_wf: nil, error_wf_published: true, handler_opts: {})
+ if error_wf.nil? && error_wf_published
+ error_wf = build_error_workflow
+ elsif error_wf.nil?
+ error_wf = build_error_workflow
+ unpublish_workflow!(error_wf)
+ end
+
+ workflow = Fabricate(:discourse_workflows_workflow, created_by: user, published: true)
+ workflow.update!(error_workflow_id: error_wf.id)
+ steps = build_steps(**handler_opts.slice(:last_failed_step))
+ handler = build_handler(workflow, steps, **handler_opts.except(:last_failed_step))
+
+ [error_wf, handler]
+ end
+
+ def trigger_and_expect_no_jobs(handler)
+ handler.trigger_error_workflow(StandardError.new("boom"))
+ expect(Jobs::DiscourseWorkflows::ExecuteWorkflow.jobs).to be_empty
+ end
+
+ describe "#trigger_error_workflow" do
+ it "enqueues an error workflow execution" do
+ error_wf, handler = build_workflow_with_error_handler
+
+ handler.trigger_error_workflow(StandardError.new("boom"))
+
+ job = Jobs::DiscourseWorkflows::ExecuteWorkflow.jobs.last
+ expect(job).to be_present
+ expect(job["args"].first["workflow_id"]).to eq(error_wf.id)
+ expect(job["args"].first["workflow_version_id"]).to eq(error_wf.active_version_id)
+ expect(job["args"].first["execution_mode"]).to eq("error_mode")
+ end
+
+ it "allows an error workflow to use itself when the failed execution is normal" do
+ graph = build_workflow_graph { |g| g.node "error-trigger-1", "trigger:error" }
+ workflow =
+ Fabricate(:discourse_workflows_workflow, created_by: user, published: true, **graph)
+ workflow.update_columns(error_workflow_id: workflow.id)
+ handler = build_handler(workflow, build_steps)
+
+ handler.trigger_error_workflow(StandardError.new("boom"))
+
+ job = Jobs::DiscourseWorkflows::ExecuteWorkflow.jobs.last
+ expect(job["args"].first["workflow_id"]).to eq(workflow.id)
+ expect(job["args"].first["trigger_node_id"]).to eq("error-trigger-1")
+ end
+
+ it "does not retrigger the same workflow when already running in error mode" do
+ graph = build_workflow_graph { |g| g.node "error-trigger-1", "trigger:error" }
+ workflow =
+ Fabricate(:discourse_workflows_workflow, created_by: user, published: true, **graph)
+ workflow.update_columns(error_workflow_id: workflow.id)
+ handler = build_handler(workflow, build_steps, execution_mode: :error_mode)
+
+ trigger_and_expect_no_jobs(handler)
+ end
+
+ it "runs a different configured error workflow when already running in error mode" do
+ error_wf, handler =
+ build_workflow_with_error_handler(handler_opts: { execution_mode: :error_mode })
+
+ handler.trigger_error_workflow(StandardError.new("boom"))
+
+ job = Jobs::DiscourseWorkflows::ExecuteWorkflow.jobs.last
+ expect(job["args"].first["workflow_id"]).to eq(error_wf.id)
+ end
+
+ it "enqueues an error workflow execution for manual executions" do
+ error_wf, handler =
+ build_workflow_with_error_handler(handler_opts: { execution_mode: :manual })
+
+ handler.trigger_error_workflow(StandardError.new("boom"))
+
+ job = Jobs::DiscourseWorkflows::ExecuteWorkflow.jobs.last
+ expect(job["args"].first["workflow_id"]).to eq(error_wf.id)
+ end
+
+ it "uses the failing workflow as its error workflow when it has an Error trigger and no configured error workflow" do
+ graph = build_workflow_graph { |g| g.node "error-trigger-1", "trigger:error" }
+ workflow =
+ Fabricate(:discourse_workflows_workflow, created_by: user, published: true, **graph)
+ handler = build_handler(workflow, build_steps)
+
+ handler.trigger_error_workflow(StandardError.new("boom"))
+
+ job = Jobs::DiscourseWorkflows::ExecuteWorkflow.jobs.last
+ expect(job["args"].first["workflow_id"]).to eq(workflow.id)
+ expect(job["args"].first["trigger_node_id"]).to eq("error-trigger-1")
+ end
+
+ it "does not trigger when no error workflow is configured" do
+ workflow = Fabricate(:discourse_workflows_workflow, created_by: user, published: true)
+ handler = build_handler(workflow, build_steps)
+ trigger_and_expect_no_jobs(handler)
+ end
+
+ it "does not trigger when error workflow is unpublished" do
+ _, handler = build_workflow_with_error_handler(error_wf_published: false)
+ trigger_and_expect_no_jobs(handler)
+ end
+
+ it "does not trigger when error workflow has no error trigger node" do
+ error_wf = Fabricate(:discourse_workflows_workflow, created_by: user, published: true)
+ workflow = Fabricate(:discourse_workflows_workflow, created_by: user, published: true)
+ workflow.update!(error_workflow_id: error_wf.id)
+ handler = build_handler(workflow, build_steps)
+ trigger_and_expect_no_jobs(handler)
+ end
+
+ it "includes compatible execution error data" do
+ failed_step = { "node_id" => "1", "node_name" => "My Node", "status" => "error" }
+ _, handler =
+ build_workflow_with_error_handler(handler_opts: { last_failed_step: failed_step })
+
+ handler.trigger_error_workflow(StandardError.new("something broke"))
+
+ trigger_data =
+ Jobs::DiscourseWorkflows::ExecuteWorkflow.jobs.last["args"].first["trigger_data"]
+ expect(trigger_data["workflow"]).to include("id" => be_present, "name" => be_present)
+ expect(trigger_data["execution"]).to include(
+ "id" => be_present,
+ "url" => include("/admin/plugins/discourse-workflows/workflows/"),
+ "retryOf" => nil,
+ "error" => include("message" => "something broke", "name" => "StandardError"),
+ "lastNodeExecuted" => "My Node",
+ "mode" => "trigger",
+ )
+ end
+
+ it "exposes execution.error with null id/url when no execution record is available" do
+ error_wf = build_error_workflow
+ workflow = Fabricate(:discourse_workflows_workflow, created_by: user, published: true)
+ workflow.update!(error_workflow_id: error_wf.id)
+ handler = described_class.new(workflow, build_steps, execution: nil, execution_mode: :normal)
+
+ handler.trigger_error_workflow(StandardError.new("trigger broke"))
+
+ trigger_data =
+ Jobs::DiscourseWorkflows::ExecuteWorkflow.jobs.last["args"].first["trigger_data"]
+ expect(trigger_data["execution"]).to include(
+ "id" => nil,
+ "url" => nil,
+ "error" => include("message" => "trigger broke", "name" => "StandardError"),
+ "lastNodeExecuted" => nil,
+ "mode" => "trigger",
+ )
+ expect(trigger_data["workflow"]).to include("id" => workflow.id.to_s, "name" => workflow.name)
+ end
+
+ it "truncates long error messages" do
+ _, handler = build_workflow_with_error_handler
+
+ handler.trigger_error_workflow(StandardError.new("x" * 2000))
+
+ trigger_data =
+ Jobs::DiscourseWorkflows::ExecuteWorkflow.jobs.last["args"].first["trigger_data"]
+ expect(trigger_data.dig("execution", "error", "message").length).to be <= 1003
+ end
+ end
+end
diff --git a/plugins/discourse-workflows/spec/lib/discourse_workflows/executor/execution_context_spec.rb b/plugins/discourse-workflows/spec/lib/discourse_workflows/executor/execution_context_spec.rb
new file mode 100644
index 00000000000..0901b005b2c
--- /dev/null
+++ b/plugins/discourse-workflows/spec/lib/discourse_workflows/executor/execution_context_spec.rb
@@ -0,0 +1,151 @@
+# frozen_string_literal: true
+
+RSpec.describe DiscourseWorkflows::Executor::ExecutionContext do
+ fab!(:workflow, :discourse_workflows_workflow)
+
+ let(:trigger_data) { { "topic_id" => 1 } }
+ let(:execution_context) do
+ described_class.new(workflow: workflow, trigger_data: trigger_data, user: nil)
+ end
+
+ describe ".generate_resume_token" do
+ it "returns a 256-bit url-safe token" do
+ expect(described_class.generate_resume_token).to match(/\A[A-Za-z0-9_-]{43}\z/)
+ end
+
+ it "returns a different value on each call" do
+ expect(described_class.generate_resume_token).not_to eq(described_class.generate_resume_token)
+ end
+ end
+
+ describe "#reset!" do
+ it "assigns a fresh url-safe resume_token by default" do
+ execution_context.reset!
+
+ expect(execution_context.resume_token).to match(/\A[A-Za-z0-9_-]{43}\z/)
+ end
+ end
+
+ describe "#store_context" do
+ it "stores values by key" do
+ execution_context.store_context("my_node", [{ "json" => { "x" => 1 } }])
+
+ expect(execution_context.context["my_node"]).to eq([{ "json" => { "x" => 1 } }])
+ end
+
+ it "still overwrites and warns when storing a reserved top-level key" do
+ allow(Rails.logger).to receive(:warn)
+ overridden = [{ "json" => { "overridden" => true } }]
+
+ execution_context.store_context("$trigger", overridden)
+
+ expect(execution_context.context["$trigger"]).to eq(overridden)
+ expect(Rails.logger).to have_received(:warn).with(/collides with reserved context key/)
+ end
+
+ it "still stores and warns when storing an internal resolver key" do
+ allow(Rails.logger).to receive(:warn)
+ payload = [{ "json" => { "x" => 1 } }]
+
+ execution_context.store_context("__input_item", payload)
+
+ expect(execution_context.context["__input_item"]).to eq(payload)
+ expect(Rails.logger).to have_received(:warn).with(/collides with reserved context key/)
+ end
+ end
+
+ describe "#resolver_context" do
+ before do
+ execution = Fabricate(:discourse_workflows_execution, workflow: workflow)
+ execution_context.execution = execution
+ execution_context.reset!(resume_token: SecureRandom.uuid)
+ execution_context.store_context("node_a", "data_a")
+ end
+
+ it "includes stored context and merged extra context" do
+ context = execution_context.resolver_context("$json" => { "extra" => true })
+
+ expect(context["node_a"]).to eq("data_a")
+ expect(context["$json"]).to eq({ "extra" => true })
+ end
+
+ it "includes execution variables from the schema" do
+ context = execution_context.resolver_context
+
+ expect(context["__execution"]).to include(
+ "id",
+ "workflow_id",
+ "workflow_name",
+ "resume_url",
+ "resumeFormUrl",
+ )
+ expect(context["__execution"]["workflow_id"]).to eq(workflow.id)
+ expect(context["__execution"]["resume_url"]).to match(
+ %r{/workflows/waiting/\d+/webhook\?signature=[a-f0-9-]+},
+ )
+ expect(context["__execution"]["resumeFormUrl"]).to match(
+ %r{/workflows/forms/waiting/\d+\.json\?signature=[a-f0-9-]+},
+ )
+ end
+
+ it "uses the configured workflow name" do
+ execution_context.use_workflow_nodes([], workflow_name: "Snapshot workflow")
+
+ expect(execution_context.resolver_context["__execution"]["workflow_name"]).to eq(
+ "Snapshot workflow",
+ )
+ end
+
+ it "appends webhook suffix to resume_url when present" do
+ context = execution_context.resolver_context("__webhook_suffix" => "my-hook/path")
+ expect(context["__execution"]["resume_url"]).to match(
+ %r{/workflows/waiting/\d+/webhook/my-hook/path\?signature=},
+ )
+ end
+ end
+
+ describe "#restore!" do
+ it "restores node contexts and preserves trigger data" do
+ execution_context.restore!(
+ context: {
+ "node_a" => "data_a",
+ },
+ node_contexts: {
+ "node_a" => {
+ "counter" => 1,
+ },
+ },
+ )
+
+ expect(execution_context.context).to include("$trigger" => trigger_data, "node_a" => "data_a")
+ expect(
+ execution_context.node_context_for(Struct.new(:id, :name).new("node_a", "node_a")),
+ ).to eq("counter" => 1)
+ end
+
+ it "exposes node contexts to expressions by node name" do
+ workflow.update!(nodes: [{ "id" => "1", "name" => "Node A" }])
+
+ execution_context.restore!(context: {}, node_contexts: { "1" => { "counter" => 1 } })
+
+ expect(execution_context.resolver_context["__node_contexts"]).to eq(
+ "Node A" => {
+ "counter" => 1,
+ },
+ )
+ end
+
+ it "uses restored workflow nodes for node context names" do
+ workflow.update!(nodes: [{ "id" => "1", "name" => "Renamed draft node" }])
+ execution_context.use_workflow_nodes([{ "id" => "1", "name" => "Snapshot node" }])
+
+ execution_context.restore!(context: {}, node_contexts: { "1" => { "counter" => 1 } })
+
+ expect(execution_context.resolver_context["__node_contexts"]).to eq(
+ "Snapshot node" => {
+ "counter" => 1,
+ },
+ )
+ end
+ end
+end
diff --git a/plugins/discourse-workflows/spec/lib/discourse_workflows/executor/execution_rate_limiter_spec.rb b/plugins/discourse-workflows/spec/lib/discourse_workflows/executor/execution_rate_limiter_spec.rb
new file mode 100644
index 00000000000..5f1e4f1a007
--- /dev/null
+++ b/plugins/discourse-workflows/spec/lib/discourse_workflows/executor/execution_rate_limiter_spec.rb
@@ -0,0 +1,52 @@
+# frozen_string_literal: true
+
+RSpec.describe DiscourseWorkflows::Executor::ExecutionRateLimiter do
+ fab!(:user)
+
+ before { RateLimiter.enable }
+
+ after { RateLimiter.disable }
+
+ fab!(:workflow) { Fabricate(:discourse_workflows_workflow, created_by: user, published: true) }
+ fab!(:other_workflow) do
+ Fabricate(:discourse_workflows_workflow, created_by: user, published: true)
+ end
+
+ let(:limiter) { described_class.new(workflow) }
+
+ describe "#within_limits?" do
+ it "returns true when under limits" do
+ SiteSetting.discourse_workflows_max_executions_per_minute = 10
+ SiteSetting.discourse_workflows_max_executions_per_minute_per_workflow = 5
+
+ expect(limiter.within_limits?).to be(true)
+ end
+
+ it "returns false when per-workflow limit is exceeded" do
+ SiteSetting.discourse_workflows_max_executions_per_minute = 100
+ SiteSetting.discourse_workflows_max_executions_per_minute_per_workflow = 1
+
+ expect(limiter.within_limits?).to be(true)
+ expect(limiter.within_limits?).to be(false)
+ end
+
+ it "returns false when global limit is exceeded" do
+ SiteSetting.discourse_workflows_max_executions_per_minute = 1
+ SiteSetting.discourse_workflows_max_executions_per_minute_per_workflow = 100
+
+ expect(limiter.within_limits?).to be(true)
+ expect(limiter.within_limits?).to be(false)
+ end
+
+ it "tracks limits independently per workflow" do
+ SiteSetting.discourse_workflows_max_executions_per_minute = 100
+ SiteSetting.discourse_workflows_max_executions_per_minute_per_workflow = 1
+
+ other_limiter = described_class.new(other_workflow)
+
+ expect(limiter.within_limits?).to be(true)
+ expect(limiter.within_limits?).to be(false)
+ expect(other_limiter.within_limits?).to be(true)
+ end
+ end
+end
diff --git a/plugins/discourse-workflows/spec/lib/discourse_workflows/executor/execution_store_spec.rb b/plugins/discourse-workflows/spec/lib/discourse_workflows/executor/execution_store_spec.rb
new file mode 100644
index 00000000000..15dc22ecac2
--- /dev/null
+++ b/plugins/discourse-workflows/spec/lib/discourse_workflows/executor/execution_store_spec.rb
@@ -0,0 +1,326 @@
+# frozen_string_literal: true
+
+RSpec.describe DiscourseWorkflows::Executor::ExecutionStore do
+ fab!(:workflow, :discourse_workflows_workflow)
+
+ let(:trigger_data) { { "topic_id" => 1 } }
+ let(:execution_context) do
+ DiscourseWorkflows::Executor::ExecutionContext.new(
+ workflow: workflow,
+ trigger_data: trigger_data,
+ user: nil,
+ )
+ end
+ let(:options) { DiscourseWorkflows::Executor::ExecutionOptions.new }
+ let(:store) do
+ described_class.new(
+ trigger_node_id: "node_1",
+ execution_context: execution_context,
+ execution_mode: :normal,
+ options: options,
+ )
+ end
+
+ describe "#start!" do
+ it "creates the execution and seeds the resume token" do
+ execution = store.start!
+
+ expect(execution).to be_present
+ expect(execution_context.execution).to eq(execution)
+ expect(execution_context.resume_token).to be_present
+ expect(execution_context.context["$trigger"]).to eq(trigger_data)
+ end
+ end
+
+ describe "#save! via finish!" do
+ before { store.start! }
+
+ it "persists entries and context to execution_data" do
+ execution_context.store_context("node_a", [{ "json" => { "x" => 1 } }])
+ steps = [
+ DiscourseWorkflows::Executor::Step.build(
+ node: OpenStruct.new(id: "1", name: "Node A", type: "action:code", typeVersion: "1.0"),
+ position: 0,
+ input: [],
+ status: DiscourseWorkflows::Executor::Step::SUCCESS,
+ ),
+ ]
+
+ store.finish!(steps: steps)
+
+ parsed = store.execution.execution_data.data
+ expect(parsed["context"]["node_a"]).to eq([{ "json" => { "x" => 1 } }])
+ expect(parsed["entries"]["1"]).to be_present
+ end
+
+ it "persists canonical run data grouped by node and output index" do
+ node = OpenStruct.new(id: "1", name: "Node A", type: "action:code", typeVersion: "1.0")
+ output_groups = [[{ "json" => { "value" => 1 } }], [{ "json" => { "alternate" => true } }]]
+ input_groups = [[{ "json" => { "input" => true } }]]
+ execution_context.store_node_run(
+ node,
+ inputs: input_groups,
+ outputs: output_groups,
+ input_sources: [{ "node_name" => "Trigger", "output_index" => 0 }],
+ )
+ steps = [
+ DiscourseWorkflows::Executor::Step.build(
+ node: node,
+ position: 0,
+ input: input_groups.first,
+ status: DiscourseWorkflows::Executor::Step::SUCCESS,
+ output: output_groups.flatten(1),
+ ),
+ ]
+
+ allow(MessageBus).to receive(:publish)
+
+ store.finish!(steps: steps)
+
+ expect(MessageBus).to have_received(:publish) do |channel, payload, opts|
+ expect(channel).to eq("/discourse-workflows/workflow/#{workflow.id}")
+ expect(opts).to eq(group_ids: [Group::AUTO_GROUPS[:admins]])
+ expect(payload[:type]).to eq("execution_completed")
+ published_run = payload.dig(:lastExecutionRunData, "Node A", 0)
+ expect(published_run).to include("node_name" => "Node A")
+ expect(published_run["outputs"]).to include(
+ hash_including("index" => 0, "item_count" => 1),
+ hash_including("index" => 1, "item_count" => 1),
+ )
+ end
+
+ run = store.execution.execution_data.run_data.dig("Node A", 0)
+ expect(run).to include(
+ "node_id" => "1",
+ "node_name" => "Node A",
+ "node_type" => "action:code",
+ "status" => "success",
+ "run_index" => 0,
+ )
+ expect(run.dig("inputs", 0, "source")).to eq("node_name" => "Trigger", "output_index" => 0)
+ expect(run.dig("outputs", 0, "items", 0, "json")).to eq("value" => 1)
+ expect(run.dig("outputs", 1, "items", 0, "json")).to eq("alternate" => true)
+ end
+
+ it "truncates oversized step strings before persistence" do
+ stub_const(described_class, :MAX_STEP_STRING_BYTES, 10) do
+ steps = [
+ DiscourseWorkflows::Executor::Step.build(
+ node: OpenStruct.new(id: "1", name: "Node A", type: "action:code", typeVersion: "1.0"),
+ position: 0,
+ input: [{ "json" => { "body" => "x" * 100 } }],
+ status: DiscourseWorkflows::Executor::Step::SUCCESS,
+ output: [{ "json" => { "body" => "y" * 100 } }],
+ ),
+ ]
+
+ store.finish!(steps: steps)
+
+ entry = store.execution.execution_data.data.dig("entries", "1", 0)
+ expect(entry.dig("input", 0, "json", "body")).to include(
+ "__truncated" => true,
+ "__reason" => "step_string_size_limit",
+ "__original_bytes" => 100,
+ "preview" => "x" * 10,
+ )
+ expect(entry.dig("output", 0, "json", "body")).to include(
+ "__truncated" => true,
+ "__reason" => "step_string_size_limit",
+ "__original_bytes" => 100,
+ "preview" => "y" * 10,
+ )
+ end
+ end
+
+ it "summarizes step input and output that still exceed the per-field size limit" do
+ stub_const(described_class, :MAX_STEP_IO_SIZE, 250) do
+ stub_const(described_class, :MAX_STEP_STRING_BYTES, 1.kilobyte) do
+ steps = [
+ DiscourseWorkflows::Executor::Step.build(
+ node:
+ OpenStruct.new(id: "1", name: "Node A", type: "action:code", typeVersion: "1.0"),
+ position: 0,
+ input: [{ "json" => { "body" => "x" * 500 } }],
+ status: DiscourseWorkflows::Executor::Step::SUCCESS,
+ output: [{ "json" => { "body" => "y" * 500 } }],
+ ),
+ ]
+
+ store.finish!(steps: steps)
+
+ entry = store.execution.execution_data.data.dig("entries", "1", 0)
+ expect(entry["input"]).to include(
+ "__truncated" => true,
+ "__reason" => "step_io_size_limit",
+ "__class" => "Array",
+ "__max_bytes" => 250,
+ )
+ expect(entry["output"]).to include(
+ "__truncated" => true,
+ "__reason" => "step_io_size_limit",
+ "__class" => "Array",
+ "__max_bytes" => 250,
+ )
+ end
+ end
+ end
+
+ it "compacts entries when bounded step data still exceeds the execution size limit" do
+ stub_const(described_class, :MAX_EXECUTION_DATA_SIZE, 5.kilobytes) do
+ steps =
+ 8.times.map do |index|
+ DiscourseWorkflows::Executor::Step.build(
+ node:
+ OpenStruct.new(
+ id: "node-#{index}",
+ name: "Node #{index}",
+ type: "action:code",
+ typeVersion: "1.0",
+ ),
+ position: index,
+ input: [{ "json" => { "body" => "x" * 1000 } }],
+ status: DiscourseWorkflows::Executor::Step::SUCCESS,
+ output: [{ "json" => { "body" => "y" * 1000 } }],
+ )
+ end
+
+ store.finish!(steps: steps)
+
+ data = store.execution.execution_data.data
+ entry = data.dig("entries", "node-0", 0)
+ expect(data.to_json.bytesize).to be <= described_class::MAX_EXECUTION_DATA_SIZE
+ expect(entry["input"]).to include(
+ "__truncated" => true,
+ "__reason" => "execution_data_size_limit",
+ )
+ expect(entry["output"]).to include(
+ "__truncated" => true,
+ "__reason" => "execution_data_size_limit",
+ )
+ end
+ end
+ end
+
+ describe "wait-state cleanup" do
+ let(:waiting_step) do
+ DiscourseWorkflows::Executor::Step.build(
+ node: OpenStruct.new(id: "1", name: "Node A", type: "action:code", typeVersion: "1.0"),
+ position: 0,
+ input: [],
+ status: DiscourseWorkflows::Executor::Step::SUCCESS,
+ )
+ end
+
+ before do
+ store.start!
+ store.execution.update!(
+ status: :waiting,
+ waiting_node_id: "1",
+ waiting_until: 1.hour.from_now,
+ resume_token: "stale-token",
+ timeout_action: "fail",
+ )
+ end
+
+ it "#finish! nils all wait-state columns" do
+ store.finish!(steps: [waiting_step])
+
+ expect(store.execution.reload).to have_attributes(
+ status: "success",
+ resume_token: nil,
+ waiting_node_id: nil,
+ waiting_until: nil,
+ timeout_action: nil,
+ )
+ end
+
+ it "#fail! nils all wait-state columns" do
+ store.fail!(error: StandardError.new("boom"), steps: [waiting_step])
+
+ expect(store.execution.reload).to have_attributes(
+ status: "error",
+ resume_token: nil,
+ waiting_node_id: nil,
+ waiting_until: nil,
+ timeout_action: nil,
+ )
+ end
+
+ context "with a draft execution" do
+ let(:options) { DiscourseWorkflows::Executor::ExecutionOptions.new(draft_execution: true) }
+
+ it "publishes completion data when the execution fails before node output exists" do
+ allow(MessageBus).to receive(:publish)
+
+ store.fail!(error: StandardError.new("boom"), steps: [])
+
+ expect(MessageBus).to have_received(:publish) do |channel, payload, opts|
+ expect(channel).to eq("/discourse-workflows/workflow/#{workflow.id}")
+ expect(opts).to eq(group_ids: [Group::AUTO_GROUPS[:admins]])
+ expect(payload[:type]).to eq("execution_completed")
+ expect(payload[:execution]).to include(
+ id: store.execution.id,
+ workflow_id: workflow.id,
+ trigger_node_id: "node_1",
+ status: "error",
+ )
+ expect(payload[:lastExecutionRunData]).to eq({})
+ end
+ end
+ end
+ end
+
+ describe "#resume!" do
+ it "restores context and workflow snapshot data" do
+ store.start!
+ execution_context.store_context("node_a", "data_a")
+ node = OpenStruct.new(id: "1", name: "Node A", type: "action:code", typeVersion: "1.0")
+ output_groups = [[{ "json" => { "saved" => true } }]]
+ execution_context.store_node_run(
+ node,
+ inputs: [[{ "json" => { "input" => true } }]],
+ outputs: output_groups,
+ input_sources: [{ "node_name" => "Trigger", "output_index" => 0 }],
+ )
+ steps = [
+ DiscourseWorkflows::Executor::Step.build(
+ node: node,
+ position: 0,
+ input: [],
+ status: DiscourseWorkflows::Executor::Step::WAITING,
+ output: output_groups.first,
+ ),
+ ]
+ store.finish!(steps: steps)
+ existing_data = store.execution.execution_data.data.deep_dup
+ existing_data["node_contexts"] = { "node_a" => { "counter" => 1 } }
+ store.execution.execution_data.update!(data: existing_data)
+ store.execution.update!(status: :waiting, waiting_node_id: "1")
+
+ restored_context =
+ DiscourseWorkflows::Executor::ExecutionContext.new(
+ workflow: workflow,
+ trigger_data: trigger_data,
+ user: nil,
+ )
+ restored =
+ described_class.new(
+ trigger_node_id: "node_1",
+ execution_context: restored_context,
+ execution_mode: :normal,
+ options: options,
+ )
+
+ restored.resume!(store.execution)
+
+ expect(restored_context.context).to include("node_a" => "data_a")
+ expect(
+ restored_context.context.dig("__node_runs", "Node A", 0, "outputs", 0, 0, "json"),
+ ).to eq("saved" => true)
+ expect(restored_context.node_context_for(OpenStruct.new(id: "node_a", name: "node_a"))).to eq(
+ "counter" => 1,
+ )
+ expect(restored.workflow_snapshot).to be_present
+ end
+ end
+end
diff --git a/plugins/discourse-workflows/spec/lib/discourse_workflows/executor/filter_parameter_spec.rb b/plugins/discourse-workflows/spec/lib/discourse_workflows/executor/filter_parameter_spec.rb
new file mode 100644
index 00000000000..f8ca4d1ca2a
--- /dev/null
+++ b/plugins/discourse-workflows/spec/lib/discourse_workflows/executor/filter_parameter_spec.rb
@@ -0,0 +1,242 @@
+# frozen_string_literal: true
+
+RSpec.describe DiscourseWorkflows::Executor::FilterParameter do
+ describe ".execute_filter" do
+ let(:resolver) do
+ Class
+ .new do
+ def resolve(value)
+ value
+ end
+ end
+ .new
+ end
+
+ it "resolves condition details" do
+ result =
+ described_class.execute_filter(
+ [
+ {
+ "leftValue" => "closed",
+ "rightValue" => "closed",
+ "operator" => {
+ "type" => "string",
+ "operation" => "equals",
+ "singleValue" => false,
+ },
+ },
+ ],
+ "and",
+ {},
+ resolver,
+ )
+
+ expect(result).to eq(
+ "passed" => true,
+ "details" => [
+ {
+ "left" => "closed",
+ "leftExpression" => "closed",
+ "operator" => "equals",
+ "right" => "closed",
+ "type" => "string",
+ "passed" => true,
+ },
+ ],
+ )
+ end
+ end
+
+ describe ".evaluate_type" do
+ context "with string type" do
+ it "equals" do
+ expect(described_class.evaluate_type("string", "closed", "closed", "equals", {})).to be(
+ true,
+ )
+ expect(described_class.evaluate_type("string", "closed", "open", "equals", {})).to be(false)
+ end
+
+ it "notEquals" do
+ expect(described_class.evaluate_type("string", "open", "closed", "notEquals", {})).to be(
+ true,
+ )
+ expect(described_class.evaluate_type("string", "closed", "closed", "notEquals", {})).to be(
+ false,
+ )
+ end
+
+ it "contains" do
+ expect(described_class.evaluate_type("string", "closed", "los", "contains", {})).to be(true)
+ expect(described_class.evaluate_type("string", "closed", "xyz", "contains", {})).to be(
+ false,
+ )
+ end
+
+ it "notContains" do
+ expect(described_class.evaluate_type("string", "closed", "xyz", "notContains", {})).to be(
+ true,
+ )
+ expect(described_class.evaluate_type("string", "closed", "los", "notContains", {})).to be(
+ false,
+ )
+ end
+
+ it "empty" do
+ expect(described_class.evaluate_type("string", "", nil, "empty", {})).to be(true)
+ expect(described_class.evaluate_type("string", "closed", nil, "empty", {})).to be(false)
+ end
+
+ it "notEmpty" do
+ expect(described_class.evaluate_type("string", "closed", nil, "notEmpty", {})).to be(true)
+ expect(described_class.evaluate_type("string", "", nil, "notEmpty", {})).to be(false)
+ end
+
+ it "is case insensitive when configured" do
+ options = { "caseSensitive" => false }
+ expect(
+ described_class.evaluate_type("string", "closed", "CLOSED", "equals", options),
+ ).to eq(true)
+ expect(
+ described_class.evaluate_type("string", "CLOSED", "closed", "equals", options),
+ ).to eq(true)
+ end
+
+ it "is case sensitive by default" do
+ expect(described_class.evaluate_type("string", "closed", "CLOSED", "equals", {})).to be(
+ false,
+ )
+ end
+
+ it "returns false for unknown operations" do
+ expect(described_class.evaluate_type("string", "a", "b", "unknown", {})).to be(false)
+ end
+ end
+
+ context "with number type" do
+ it "equals" do
+ expect(described_class.evaluate_type("number", 42, 42, "equals", {})).to be(true)
+ expect(described_class.evaluate_type("number", 42, 43, "equals", {})).to be(false)
+ end
+
+ it "notEquals" do
+ expect(described_class.evaluate_type("number", 42, 43, "notEquals", {})).to be(true)
+ expect(described_class.evaluate_type("number", 42, 42, "notEquals", {})).to be(false)
+ end
+
+ it "gt" do
+ expect(described_class.evaluate_type("number", 42, 10, "gt", {})).to be(true)
+ expect(described_class.evaluate_type("number", 5, 10, "gt", {})).to be(false)
+ end
+
+ it "lt" do
+ expect(described_class.evaluate_type("number", 10, 20, "lt", {})).to be(true)
+ expect(described_class.evaluate_type("number", 20, 10, "lt", {})).to be(false)
+ end
+
+ it "gte" do
+ expect(described_class.evaluate_type("number", 10, 10, "gte", {})).to be(true)
+ expect(described_class.evaluate_type("number", 11, 10, "gte", {})).to be(true)
+ expect(described_class.evaluate_type("number", 9, 10, "gte", {})).to be(false)
+ end
+
+ it "lte" do
+ expect(described_class.evaluate_type("number", 10, 10, "lte", {})).to be(true)
+ expect(described_class.evaluate_type("number", 9, 10, "lte", {})).to be(true)
+ expect(described_class.evaluate_type("number", 11, 10, "lte", {})).to be(false)
+ end
+
+ it "returns false for unknown operations" do
+ expect(described_class.evaluate_type("number", 1, 2, "unknown", {})).to be(false)
+ end
+
+ it "handles string numeric values" do
+ expect(described_class.evaluate_type("number", "42", "42", "equals", {})).to be(true)
+ expect(described_class.evaluate_type("number", "10.5", "5", "gt", {})).to be(true)
+ end
+
+ it "returns false when left value is not numeric" do
+ expect(described_class.evaluate_type("number", "hello", 42, "equals", {})).to be(false)
+ expect(described_class.evaluate_type("number", "hello", 42, "gt", {})).to be(false)
+ end
+
+ it "returns false when right value is not numeric" do
+ expect(described_class.evaluate_type("number", 42, "hello", "equals", {})).to be(false)
+ end
+
+ it "returns false when both values are not numeric" do
+ expect(described_class.evaluate_type("number", "foo", "bar", "equals", {})).to be(false)
+ end
+
+ it "returns false for nil values" do
+ expect(described_class.evaluate_type("number", nil, 42, "equals", {})).to be(false)
+ expect(described_class.evaluate_type("number", 42, nil, "equals", {})).to be(false)
+ end
+ end
+
+ context "with boolean type" do
+ it "true" do
+ expect(described_class.evaluate_type("boolean", true, nil, "true", {})).to be(true)
+ expect(described_class.evaluate_type("boolean", false, nil, "true", {})).to be(false)
+ end
+
+ it "false" do
+ expect(described_class.evaluate_type("boolean", false, nil, "false", {})).to be(true)
+ expect(described_class.evaluate_type("boolean", true, nil, "false", {})).to be(false)
+ end
+
+ it "equals" do
+ expect(described_class.evaluate_type("boolean", true, true, "equals", {})).to be(true)
+ expect(described_class.evaluate_type("boolean", true, false, "equals", {})).to be(false)
+ end
+
+ it "notEquals" do
+ expect(described_class.evaluate_type("boolean", true, false, "notEquals", {})).to be(true)
+ expect(described_class.evaluate_type("boolean", true, true, "notEquals", {})).to be(false)
+ end
+
+ it "returns false for unknown operations" do
+ expect(described_class.evaluate_type("boolean", true, nil, "unknown", {})).to be(false)
+ end
+ end
+
+ context "with array type" do
+ it "contains" do
+ expect(described_class.evaluate_type("array", %w[a b c], "b", "contains", {})).to be(true)
+ expect(described_class.evaluate_type("array", %w[a b c], "d", "contains", {})).to be(false)
+ end
+
+ it "notContains" do
+ expect(described_class.evaluate_type("array", %w[a b c], "d", "notContains", {})).to be(
+ true,
+ )
+ expect(described_class.evaluate_type("array", %w[a b c], "b", "notContains", {})).to be(
+ false,
+ )
+ end
+
+ it "empty" do
+ expect(described_class.evaluate_type("array", [], nil, "empty", {})).to be(true)
+ expect(described_class.evaluate_type("array", %w[a], nil, "empty", {})).to be(false)
+ end
+
+ it "handles nil for empty" do
+ expect(described_class.evaluate_type("array", nil, nil, "empty", {})).to be(false)
+ end
+
+ it "notEmpty" do
+ expect(described_class.evaluate_type("array", %w[a], nil, "notEmpty", {})).to be(true)
+ expect(described_class.evaluate_type("array", [], nil, "notEmpty", {})).to be(false)
+ end
+
+ it "returns false for unknown operations" do
+ expect(described_class.evaluate_type("array", [], nil, "unknown", {})).to be(false)
+ end
+ end
+
+ context "with unknown type" do
+ it "returns false" do
+ expect(described_class.evaluate_type("unknown", "a", "b", "equals", {})).to be(false)
+ end
+ end
+ end
+end
diff --git a/plugins/discourse-workflows/spec/lib/discourse_workflows/executor/node_execution_context_spec.rb b/plugins/discourse-workflows/spec/lib/discourse_workflows/executor/node_execution_context_spec.rb
new file mode 100644
index 00000000000..1f0d284c1ef
--- /dev/null
+++ b/plugins/discourse-workflows/spec/lib/discourse_workflows/executor/node_execution_context_spec.rb
@@ -0,0 +1,832 @@
+# frozen_string_literal: true
+
+RSpec.describe DiscourseWorkflows::Executor::NodeExecutionContext do
+ describe "#get_context" do
+ it "exposes mutable execution contexts to node implementations" do
+ ctx =
+ described_class.new(
+ input_items: [],
+ resolver: nil,
+ node_context: {
+ "index" => 1,
+ },
+ flow_context: {
+ "shared" => true,
+ },
+ )
+
+ expect(ctx.get_context).to eq("index" => 1)
+ expect(ctx.get_context(:flow)).to eq("shared" => true)
+ expect { ctx.get_context(:global) }.to raise_error(
+ ArgumentError,
+ "Unknown context scope: global. Use :node or :flow",
+ )
+ end
+ end
+
+ describe "#input_context" do
+ it "returns the public input context for node execution" do
+ ctx =
+ described_class.new(
+ input_items: [{ "json" => { "username" => "item-user" } }],
+ resolver: nil,
+ node_context: {
+ "no_items_left" => true,
+ },
+ )
+
+ expect(ctx.input_context).to eq("noItemsLeft" => true)
+ end
+ end
+
+ describe "#continue_on_fail" do
+ it "reads continueOnFail from direct node settings" do
+ ctx =
+ described_class.new(
+ input_items: [],
+ resolver: nil,
+ node_settings: {
+ "continueOnFail" => true,
+ },
+ )
+
+ expect(ctx.continue_on_fail).to eq(true)
+ end
+
+ it "treats onError continue modes as continueOnFail" do
+ ctx =
+ described_class.new(
+ input_items: [],
+ resolver: nil,
+ node_settings: {
+ "onError" => "continueErrorOutput",
+ },
+ )
+
+ expect(ctx.continue_on_fail).to eq(true)
+ end
+ end
+
+ describe "node and graph views" do
+ let(:snapshot) do
+ graph =
+ build_workflow_graph do |g|
+ g.node "trigger-1", "trigger:manual", name: "Manual"
+ g.node "set-1", "action:set_fields", name: "Prepare"
+ g.node "form-1",
+ "action:form",
+ name: "Review",
+ configuration: {
+ "form_fields" => [{ "field_label" => "Reason", "field_type" => "text" }],
+ }
+ g.chain "trigger-1", "set-1", "form-1"
+ end
+
+ DiscourseWorkflows::WorkflowSnapshot.new(graph.merge(workflow_name: "Runtime workflow"))
+ end
+
+ it "exposes the current node as a public view" do
+ ctx =
+ described_class.new(
+ input_items: [],
+ resolver: nil,
+ node_id: "form-1",
+ node_identifier: "action:form",
+ workflow_snapshot: snapshot,
+ )
+
+ expect(ctx.get_node).to have_attributes(
+ id: "form-1",
+ name: "Review",
+ type: "action:form",
+ type_version: 1.0,
+ )
+ expect(ctx.get_node.parameters).to include(
+ "form_fields" => [{ "field_label" => "Reason", "field_type" => "text" }],
+ )
+ expect(ctx.get_node.to_h).to include("typeVersion" => 1.0)
+ end
+
+ it "returns recursive parent and child node views from the workflow snapshot" do
+ ctx =
+ described_class.new(
+ input_items: [],
+ resolver: nil,
+ node_id: "set-1",
+ node_identifier: "action:set_fields",
+ workflow_snapshot: snapshot,
+ )
+
+ expect(ctx.get_parent_nodes(ctx.get_node.name).map(&:name)).to eq(["Manual"])
+ expect(ctx.get_child_nodes(ctx.get_node.name).map(&:name)).to eq(["Review"])
+ expect(ctx.get_parent_nodes("Review").map(&:name)).to eq(%w[Manual Prepare])
+ end
+
+ it "only includes node parameters when requested" do
+ ctx =
+ described_class.new(
+ input_items: [],
+ resolver: nil,
+ node_id: "set-1",
+ node_identifier: "action:set_fields",
+ workflow_snapshot: snapshot,
+ )
+
+ child = ctx.get_child_nodes(ctx.get_node.name, include_node_parameters: true).first
+
+ expect(child.parameters).to include(
+ "form_fields" => [{ "field_label" => "Reason", "field_type" => "text" }],
+ )
+ end
+ end
+
+ describe "#helpers" do
+ it "normalizes runtime-compatible items through execution helpers" do
+ ctx = described_class.new(input_items: [], resolver: nil)
+
+ expect(ctx.helpers.normalize_items([{ json: { name: "Ada" }, pairedItem: 0 }])).to eq(
+ [{ "json" => { "name" => "Ada" }, "pairedItem" => { "item" => 0 } }],
+ )
+ end
+
+ it "raises node errors for incompatible item formats" do
+ ctx = described_class.new(input_items: [], resolver: nil)
+
+ expect { ctx.helpers.normalize_items([{ json: { id: 1 } }, { binary: {} }]) }.to raise_error(
+ DiscourseWorkflows::NodeError,
+ "Inconsistent item format: Every returned item must use the same format.",
+ )
+ end
+ end
+
+ describe "#get_workflow_static_data" do
+ let(:state) do
+ DiscourseWorkflows::Executor::StaticDataState.new(
+ global: {
+ "tenant" => "acme",
+ },
+ node: {
+ "Existing" => {
+ "cursor" => "abc",
+ },
+ },
+ )
+ end
+
+ it "returns the node-scoped hash for the current node, creating the slot lazily" do
+ ctx =
+ described_class.new(
+ input_items: [],
+ resolver: nil,
+ node_name: "Fresh",
+ static_data_state: state,
+ )
+
+ slot = ctx.get_workflow_static_data(:node)
+ expect(slot).to eq({})
+
+ slot["seen"] = 1
+ expect(state.node["Fresh"]).to eq("seen" => 1)
+ expect(state).to be_dirty
+ end
+
+ it "returns the existing node slot when one is already present" do
+ ctx =
+ described_class.new(
+ input_items: [],
+ resolver: nil,
+ node_name: "Existing",
+ static_data_state: state,
+ )
+
+ expect(ctx.get_workflow_static_data(:node)).to eq("cursor" => "abc")
+ end
+
+ it "returns the global hash for :global" do
+ ctx =
+ described_class.new(
+ input_items: [],
+ resolver: nil,
+ node_name: "Fresh",
+ static_data_state: state,
+ )
+
+ expect(ctx.get_workflow_static_data(:global)).to eq("tenant" => "acme")
+ end
+
+ it "raises when no static_data_state was provided" do
+ ctx = described_class.new(input_items: [], resolver: nil, node_name: "Fresh")
+
+ expect { ctx.get_workflow_static_data(:node) }.to raise_error(/not available/)
+ end
+
+ it "raises on node scope without a node_name" do
+ ctx = described_class.new(input_items: [], resolver: nil, static_data_state: state)
+
+ expect { ctx.get_workflow_static_data(:node) }.to raise_error(/requires a node name/)
+ end
+
+ it "raises on unknown scopes" do
+ ctx =
+ described_class.new(
+ input_items: [],
+ resolver: nil,
+ node_name: "Fresh",
+ static_data_state: state,
+ )
+
+ expect { ctx.get_workflow_static_data(:bogus) }.to raise_error(ArgumentError)
+ end
+ end
+
+ describe "#resume_action_id" do
+ it "returns a signed action id for interactive resume nodes" do
+ ctx =
+ described_class.new(
+ input_items: [{ "json" => { "username" => "item-user" } }],
+ resolver: nil,
+ execution_id: 123,
+ resume_token: "resume-token",
+ )
+
+ payload =
+ DiscourseWorkflows::InteractiveResume.action_payload(ctx.resume_action_id("approve"))
+
+ expect(payload).to include("execution_id" => 123, "action" => "approve")
+ end
+ end
+
+ describe "#set_metadata" do
+ it "merges execution metadata with string keys" do
+ ctx = described_class.new(input_items: [], resolver: nil)
+
+ ctx.set_metadata(resumeFormUrl: "/resume")
+
+ expect(ctx.metadata).to eq("resumeFormUrl" => "/resume")
+ end
+ end
+
+ describe "#get_node_parameter" do
+ it "resolves a nested parameter path against the current item" do
+ ctx, resolver, sandbox =
+ build_parameter_context(
+ { "outer" => { "inner" => "={{ $json.value }}" } },
+ input_items: [{ "json" => { "value" => "resolved" } }],
+ )
+
+ value = ctx.get_node_parameter("outer.inner", 0)
+
+ expect(value).to eq("resolved")
+ ensure
+ resolver&.dispose
+ sandbox&.dispose
+ end
+
+ it "returns the default for a missing parameter path" do
+ ctx, resolver, sandbox = build_parameter_context({ "outer" => {} })
+
+ value = ctx.get_node_parameter("outer.inner", 0, default: "default-value")
+
+ expect(value).to eq("default-value")
+ ensure
+ resolver&.dispose
+ sandbox&.dispose
+ end
+
+ it "evaluates condition-builder parameters even when the root key is absent" do
+ ctx, resolver, sandbox =
+ build_parameter_context({}, schema: { conditions: { ui: { control: :condition_builder } } })
+
+ value = ctx.get_node_parameter(:conditions, 0)
+
+ expect(value).to eq(true)
+ ensure
+ resolver&.dispose
+ sandbox&.dispose
+ end
+
+ it "returns literal values for no_data_expression fields" do
+ ctx, resolver, sandbox =
+ build_parameter_context(
+ { "code" => "={{ $json.value }}" },
+ schema: {
+ code: {
+ type: :string,
+ no_data_expression: true,
+ },
+ },
+ input_items: [{ "json" => { "value" => "resolved" } }],
+ )
+
+ value = ctx.get_node_parameter("code", 0)
+
+ expect(value).to eq("={{ $json.value }}")
+ ensure
+ resolver&.dispose
+ sandbox&.dispose
+ end
+
+ it "returns raw stored values when raw_expressions is requested" do
+ ctx, resolver, sandbox =
+ build_parameter_context(
+ { "message" => "={{ $json.value }}" },
+ input_items: [{ "json" => { "value" => "resolved" } }],
+ )
+
+ resolved = ctx.get_node_parameter("message", 0)
+ raw = ctx.get_node_parameter("message", 0, options: { raw_expressions: true })
+
+ expect(resolved).to eq("resolved")
+ expect(raw).to eq("={{ $json.value }}")
+ ensure
+ resolver&.dispose
+ sandbox&.dispose
+ end
+ end
+
+ describe "#get_credentials" do
+ fab!(:admin)
+ fab!(:credential) do
+ Fabricate(
+ :discourse_workflows_credential,
+ credential_type: "basic_auth",
+ data: {
+ "user" => "={{ $json.username }}",
+ "password" => "static-password",
+ },
+ )
+ end
+
+ it "resolves credential expressions against the current item" do
+ resolver_context = { "$json" => {} }
+ sandbox = DiscourseWorkflows::JsSandbox.new(resolver_context)
+ resolver = DiscourseWorkflows::ExpressionResolver.new(resolver_context, sandbox: sandbox)
+ ctx =
+ described_class.new(
+ input_items: [{ "json" => { "username" => "item-user" } }],
+ parameters: {
+ "authentication" => "basic_auth",
+ },
+ credentials: {
+ "auth" => {
+ "id" => credential.id,
+ "credential_type" => "basic_auth",
+ },
+ },
+ credential_schema: DiscourseWorkflows::Nodes::HttpRequest::V1.credentials,
+ resolver: resolver,
+ )
+
+ resolved = ctx.get_credentials("auth", 0)
+
+ expect(resolved).to eq("user" => "item-user", "password" => "static-password")
+ ensure
+ resolver&.dispose
+ sandbox&.dispose
+ end
+
+ it "allows access when the current workflow node references the credential" do
+ workflow = workflow_with_credential_dependency(credential)
+ ctx, resolver, sandbox =
+ build_credential_context(
+ workflow: workflow,
+ input_items: [{ "json" => { "username" => "dependency-user" } }],
+ )
+
+ resolved = ctx.get_credentials("auth", 0)
+
+ expect(resolved).to eq("user" => "dependency-user", "password" => "static-password")
+ ensure
+ resolver&.dispose
+ sandbox&.dispose
+ end
+
+ it "denies access when the current workflow node does not reference the credential" do
+ workflow = workflow_with_credential_dependency(credential)
+ DiscourseWorkflows::WorkflowDependency.where(workflow_id: workflow.id).delete_all
+ ctx, resolver, sandbox = build_credential_context(workflow: workflow)
+
+ expect { ctx.get_credentials("auth") }.to raise_error(Discourse::InvalidAccess)
+ ensure
+ resolver&.dispose
+ sandbox&.dispose
+ end
+
+ it "rejects undeclared credential slots" do
+ ctx, resolver, sandbox =
+ build_credential_context(
+ credentials: {
+ "other" => {
+ "id" => credential.id,
+ "credential_type" => "basic_auth",
+ },
+ },
+ )
+
+ expect { ctx.get_credentials("other") }.to raise_error(Discourse::InvalidAccess)
+ ensure
+ resolver&.dispose
+ sandbox&.dispose
+ end
+
+ it "raises when the node is not configured to use the requested credential" do
+ resolver_context = { "$json" => {} }
+ sandbox = DiscourseWorkflows::JsSandbox.new(resolver_context)
+ resolver = DiscourseWorkflows::ExpressionResolver.new(resolver_context, sandbox: sandbox)
+ ctx =
+ described_class.new(
+ input_items: [],
+ parameters: {
+ "authentication" => "basic_auth",
+ },
+ credentials: {
+ "auth" => {
+ "id" => credential.id + 1,
+ "credential_type" => "basic_auth",
+ },
+ },
+ credential_schema: DiscourseWorkflows::Nodes::HttpRequest::V1.credentials,
+ resolver: resolver,
+ )
+
+ expect { ctx.get_credentials("auth") }.to raise_error(Discourse::InvalidAccess)
+ ensure
+ resolver&.dispose
+ sandbox&.dispose
+ end
+ end
+
+ describe "#helpers" do
+ fab!(:admin)
+ fab!(:data_table, :discourse_workflows_data_table)
+
+ it "returns a Data Table node proxy for the requested data table when config references it" do
+ ctx =
+ described_class.new(
+ input_items: [],
+ parameters: {
+ "data_table_id" => data_table.id,
+ },
+ node_identifier: "action:data_table",
+ resolver: nil,
+ )
+
+ expect(ctx.helpers.get_data_table_proxy(data_table.id)).to be_a(
+ DiscourseWorkflows::DataTables::NodeProxy,
+ )
+ end
+
+ it "allows access when the current workflow node references the data table" do
+ workflow = workflow_with_data_table_dependency(data_table)
+ ctx = build_data_table_context(workflow: workflow)
+
+ expect(ctx.helpers.get_data_table_proxy(data_table.id)).to be_a(
+ DiscourseWorkflows::DataTables::NodeProxy,
+ )
+ end
+
+ it "returns a Data Table aggregate proxy for allowed nodes" do
+ ctx = build_data_table_context
+
+ expect(ctx.helpers.get_data_table_aggregate_proxy).to be_a(
+ DiscourseWorkflows::DataTables::AggregateNodeProxy,
+ )
+ end
+
+ it "denies access when the current workflow node does not reference the data table" do
+ workflow = workflow_with_data_table_dependency(data_table)
+ DiscourseWorkflows::WorkflowDependency.where(workflow_id: workflow.id).delete_all
+ ctx = build_data_table_context(workflow: workflow)
+
+ expect { ctx.helpers.get_data_table_proxy(data_table.id) }.to raise_error(
+ Discourse::InvalidAccess,
+ )
+ end
+
+ it "does not reveal whether an unauthorized data table id exists" do
+ ctx = build_data_table_context(configuration: { "data_table_id" => data_table.id + 1 })
+
+ expect { ctx.helpers.get_data_table_proxy(data_table.id) }.to raise_error(
+ Discourse::InvalidAccess,
+ )
+ end
+
+ it "raises when the node is not configured to use the requested data table" do
+ ctx =
+ described_class.new(
+ input_items: [],
+ parameters: {
+ "data_table_id" => data_table.id + 1,
+ },
+ node_identifier: "action:data_table",
+ resolver: nil,
+ )
+
+ expect { ctx.helpers.get_data_table_proxy(data_table.id) }.to raise_error(
+ Discourse::InvalidAccess,
+ )
+ end
+
+ it "does not expose Data Table helpers to other node types" do
+ ctx =
+ described_class.new(
+ input_items: [],
+ parameters: {
+ "data_table_id" => data_table.id,
+ },
+ node_identifier: "action:badge",
+ resolver: nil,
+ )
+
+ expect { ctx.helpers.get_data_table_proxy(data_table.id) }.to raise_error(
+ Discourse::InvalidAccess,
+ )
+ end
+ end
+
+ describe "#find_user" do
+ fab!(:user)
+
+ it "finds a user by username" do
+ ctx = described_class.new(input_items: [], resolver: nil)
+
+ expect(ctx.find_user(username: user.username)).to eq(user)
+ end
+
+ it "finds a user by id" do
+ ctx = described_class.new(input_items: [], resolver: nil)
+
+ expect(ctx.find_user(id: user.id)).to eq(user)
+ end
+
+ it "raises a node error when the username cannot be found" do
+ ctx = described_class.new(input_items: [], resolver: nil)
+
+ expect { ctx.find_user(username: "nonexistent_user") }.to raise_error(
+ DiscourseWorkflows::NodeError,
+ "User 'nonexistent_user' not found",
+ )
+ end
+
+ it "raises a node error when the id cannot be found" do
+ ctx = described_class.new(input_items: [], resolver: nil)
+
+ expect { ctx.find_user(id: -999) }.to raise_error(
+ DiscourseWorkflows::NodeError,
+ "User with id -999 not found",
+ )
+ end
+
+ it "requires exactly one lookup key" do
+ ctx = described_class.new(input_items: [], resolver: nil)
+
+ expect { ctx.find_user }.to raise_error(
+ ArgumentError,
+ "Provide exactly one of username or id",
+ )
+ expect { ctx.find_user(username: user.username, id: user.id) }.to raise_error(
+ ArgumentError,
+ "Provide exactly one of username or id",
+ )
+ end
+ end
+
+ describe "#actor_from_parameter" do
+ fab!(:user)
+
+ it "resolves actor fields through the central actor policy" do
+ resolver_context = { "$json" => { "actor" => user.username } }
+ sandbox = DiscourseWorkflows::JsSandbox.new(resolver_context)
+ resolver = DiscourseWorkflows::ExpressionResolver.new(resolver_context, sandbox: sandbox)
+ policy = instance_spy(DiscourseWorkflows::Executor::ActorPolicy)
+ allow(DiscourseWorkflows::Executor::ActorPolicy).to receive(:new).and_return(policy)
+ ctx =
+ described_class.new(
+ input_items: [{ "json" => { "actor" => user.username } }],
+ parameters: {
+ "actor_username" => "={{ $json.actor }}",
+ },
+ resolver: resolver,
+ node_identifier: "action:create_post",
+ )
+
+ expect(ctx.actor_from_parameter("actor_username")).to eq(user)
+ expect(policy).to have_received(:ensure_allowed!).with(
+ user,
+ field: "actor_username",
+ item_index: 0,
+ source: :expression,
+ purpose: "action:create_post",
+ )
+ ensure
+ resolver&.dispose
+ sandbox&.dispose
+ end
+
+ it "rejects actors with restricted account states" do
+ staged_user = Fabricate(:user, staged: true)
+ silenced_user = Fabricate(:user, silenced_till: 1.year.from_now)
+ suspended_user = Fabricate(:user, suspended_till: 1.year.from_now)
+ inactive_user = Fabricate(:user, active: false)
+ ctx = described_class.new(input_items: [], resolver: nil)
+
+ aggregate_failures do
+ expect { ctx.actor_from(username: staged_user.username) }.to raise_error(
+ Discourse::InvalidAccess,
+ )
+ expect { ctx.actor_from(username: silenced_user.username) }.to raise_error(
+ Discourse::InvalidAccess,
+ )
+ expect { ctx.actor_from(username: suspended_user.username) }.to raise_error(
+ Discourse::InvalidAccess,
+ )
+ expect { ctx.actor_from(username: inactive_user.username) }.to raise_error(
+ Discourse::InvalidAccess,
+ )
+ end
+ end
+
+ it "falls back to the default actor for blank actor fields" do
+ resolver_context = { "$json" => {} }
+ sandbox = DiscourseWorkflows::JsSandbox.new(resolver_context)
+ resolver = DiscourseWorkflows::ExpressionResolver.new(resolver_context, sandbox: sandbox)
+ ctx =
+ described_class.new(
+ input_items: [],
+ parameters: {
+ "actor_username" => "",
+ },
+ resolver: resolver,
+ )
+
+ expect(ctx.actor_from_parameter("actor_username")).to eq(Discourse.system_user)
+ ensure
+ resolver&.dispose
+ sandbox&.dispose
+ end
+ end
+
+ describe "#http_request" do
+ it "returns a parsed response object" do
+ stub_request(:get, "https://api.example.com/data").to_return(
+ status: 200,
+ body: { ok: true }.to_json,
+ headers: {
+ "content-type" => "application/json",
+ },
+ )
+
+ ctx = described_class.new(input_items: [], resolver: nil)
+ response = ctx.http_request(method: "GET", url: "https://api.example.com/data")
+
+ expect(response.status).to eq(200)
+ expect(response.headers).to include("content-type" => "application/json")
+ expect(response.body).to eq("ok" => true)
+ end
+
+ it "does not retry transient GET response statuses by default" do
+ stub_request(:get, "https://api.example.com/retry").to_return(
+ { status: 503, body: "unavailable" },
+ {
+ status: 200,
+ body: { ok: true }.to_json,
+ headers: {
+ "content-type" => "application/json",
+ },
+ },
+ )
+
+ ctx = described_class.new(input_items: [], resolver: nil)
+
+ expect {
+ ctx.http_request(method: "GET", url: "https://api.example.com/retry")
+ }.to raise_error(
+ DiscourseWorkflows::NodeError,
+ "HTTP GET https://api.example.com/retry failed with status 503",
+ )
+ expect(WebMock).to have_requested(:get, "https://api.example.com/retry").once
+ end
+
+ it "does not retry non-GET transient response statuses by default" do
+ stub_request(:post, "https://api.example.com/retry").to_return(
+ status: 503,
+ body: "unavailable",
+ )
+
+ ctx = described_class.new(input_items: [], resolver: nil)
+
+ expect {
+ ctx.http_request(method: "POST", url: "https://api.example.com/retry")
+ }.to raise_error(
+ DiscourseWorkflows::NodeError,
+ "HTTP POST https://api.example.com/retry failed with status 503",
+ )
+ expect(WebMock).to have_requested(:post, "https://api.example.com/retry").once
+ end
+
+ it "allows callers to opt non-GET requests into retries" do
+ stub_request(:post, "https://api.example.com/retry").to_return(
+ { status: 503, body: "unavailable" },
+ {
+ status: 200,
+ body: { ok: true }.to_json,
+ headers: {
+ "content-type" => "application/json",
+ },
+ },
+ )
+
+ ctx = described_class.new(input_items: [], resolver: nil)
+ response =
+ ctx.http_request(
+ method: "POST",
+ url: "https://api.example.com/retry",
+ options: {
+ max_retries: 1,
+ },
+ )
+
+ expect(response.status).to eq(200)
+ expect(WebMock).to have_requested(:post, "https://api.example.com/retry").twice
+ end
+ end
+
+ def workflow_with_data_table_dependency(data_table)
+ graph =
+ build_workflow_graph do |g|
+ g.node "dt-1", "action:data_table", configuration: { "data_table_id" => data_table.id }
+ end
+ Fabricate(:discourse_workflows_workflow, created_by: admin, **graph)
+ end
+
+ def build_data_table_context(workflow: nil, configuration: { "data_table_id" => data_table.id })
+ described_class.new(
+ input_items: [],
+ parameters: configuration,
+ resolver: nil,
+ workflow: workflow,
+ node_id: workflow ? "dt-1" : nil,
+ node_identifier: "action:data_table",
+ )
+ end
+
+ def workflow_with_credential_dependency(credential)
+ graph =
+ build_workflow_graph do |g|
+ g.node "http-1",
+ "action:http_request",
+ parameters: {
+ "authentication" => "basic_auth",
+ },
+ credentials: {
+ "auth" => {
+ "id" => credential.id,
+ "credential_type" => "basic_auth",
+ },
+ }
+ end
+ Fabricate(:discourse_workflows_workflow, created_by: admin, **graph)
+ end
+
+ def build_credential_context(
+ workflow: nil,
+ configuration: { "authentication" => "basic_auth" },
+ credentials: { "auth" => { "id" => credential.id, "credential_type" => "basic_auth" } },
+ input_items: []
+ )
+ resolver_context = { "$json" => {} }
+ sandbox = DiscourseWorkflows::JsSandbox.new(resolver_context)
+ resolver = DiscourseWorkflows::ExpressionResolver.new(resolver_context, sandbox: sandbox)
+ ctx =
+ described_class.new(
+ input_items: input_items,
+ parameters: configuration,
+ credentials: credentials,
+ credential_schema: DiscourseWorkflows::Nodes::HttpRequest::V1.credentials,
+ resolver: resolver,
+ workflow: workflow,
+ node_id: workflow ? "http-1" : nil,
+ )
+ [ctx, resolver, sandbox]
+ end
+
+ def build_parameter_context(
+ parameters = nil,
+ schema: {},
+ input_items: [{ "json" => {} }],
+ **keyword_parameters
+ )
+ parameters ||= keyword_parameters
+ resolver_context = { "$json" => {} }
+ sandbox = DiscourseWorkflows::JsSandbox.new(resolver_context)
+ resolver = DiscourseWorkflows::ExpressionResolver.new(resolver_context, sandbox: sandbox)
+ ctx =
+ described_class.new(
+ input_items: input_items,
+ parameters: parameters,
+ property_schema: schema,
+ resolver: resolver,
+ )
+ [ctx, resolver, sandbox]
+ end
+end
diff --git a/plugins/discourse-workflows/spec/lib/discourse_workflows/executor/parameter_resolver_spec.rb b/plugins/discourse-workflows/spec/lib/discourse_workflows/executor/parameter_resolver_spec.rb
new file mode 100644
index 00000000000..b8a266b6012
--- /dev/null
+++ b/plugins/discourse-workflows/spec/lib/discourse_workflows/executor/parameter_resolver_spec.rb
@@ -0,0 +1,130 @@
+# frozen_string_literal: true
+
+RSpec.describe DiscourseWorkflows::Executor::ParameterResolver do
+ let(:runtime_state) { DiscourseWorkflows::Executor::NodeExecutionContext::RuntimeState.new }
+
+ def build_resolver(parameters, schema: {}, items: [{ "json" => {} }])
+ resolver_context = { "$json" => items.first.fetch("json") { {} } }
+ sandbox = DiscourseWorkflows::JsSandbox.new(resolver_context)
+ expression_resolver =
+ DiscourseWorkflows::ExpressionResolver.new(resolver_context, sandbox: sandbox)
+ parameter_resolver =
+ described_class.new(
+ parameters: parameters,
+ property_schema: schema,
+ resolver: expression_resolver,
+ input_items: items,
+ runtime_state: runtime_state,
+ )
+
+ [parameter_resolver, expression_resolver, sandbox]
+ end
+
+ it "resolves nested paths, defaults, and raw expressions" do
+ resolver, expression_resolver, sandbox =
+ build_resolver(
+ { "outer" => { "inner" => "={{ $json.value }}" }, "count" => "={{ $json.count }}" },
+ items: [{ "json" => { "value" => "resolved", "count" => "4" } }],
+ )
+
+ expect(resolver.resolve("outer.inner", 0)).to eq("resolved")
+ expect(resolver.resolve("outer.missing", 0, default: "fallback")).to eq("fallback")
+ expect(resolver.resolve("outer.inner", 0, options: { raw_expressions: true })).to eq(
+ "={{ $json.value }}",
+ )
+ ensure
+ expression_resolver&.dispose
+ sandbox&.dispose
+ end
+
+ it "keeps no_data_expression values literal" do
+ resolver, expression_resolver, sandbox =
+ build_resolver(
+ { "code" => "={{ $json.value }}" },
+ schema: {
+ code: {
+ type: :string,
+ no_data_expression: true,
+ },
+ },
+ items: [{ "json" => { "value" => "resolved" } }],
+ )
+
+ expect(resolver.resolve("code", 0)).to eq("={{ $json.value }}")
+ ensure
+ expression_resolver&.dispose
+ sandbox&.dispose
+ end
+
+ it "resolves condition-builder parameters and records condition metadata" do
+ resolver, expression_resolver, sandbox =
+ build_resolver(
+ {
+ "conditions" => [
+ {
+ "leftValue" => "={{ $json.status }}",
+ "operator" => {
+ "type" => "string",
+ "operation" => "equals",
+ },
+ "rightValue" => "open",
+ },
+ ],
+ },
+ schema: {
+ conditions: {
+ ui: {
+ control: :condition_builder,
+ },
+ },
+ },
+ items: [{ "json" => { "status" => "open" } }],
+ )
+
+ expect(resolver.resolve(:conditions, 0)).to eq(true)
+ expect(runtime_state.step_metadata["conditions"]).to contain_exactly(
+ include("left" => "open", "right" => "open", "passed" => true),
+ )
+ ensure
+ expression_resolver&.dispose
+ sandbox&.dispose
+ end
+
+ it "resolves fixed collection rows with their nested schemas" do
+ resolver, expression_resolver, sandbox =
+ build_resolver(
+ {
+ "fields" => {
+ "values" => [{ "name" => "={{ $json.name }}", "literal" => "={{ $json.name }}" }],
+ },
+ },
+ schema: {
+ fields: {
+ type: :fixed_collection,
+ options: [
+ {
+ name: "values",
+ values: {
+ name: {
+ type: :string,
+ },
+ literal: {
+ type: :string,
+ no_data_expression: true,
+ },
+ },
+ },
+ ],
+ },
+ },
+ items: [{ "json" => { "name" => "Ada" } }],
+ )
+
+ expect(resolver.resolve("fields.values", 0)).to eq(
+ [{ "name" => "Ada", "literal" => "={{ $json.name }}" }],
+ )
+ ensure
+ expression_resolver&.dispose
+ sandbox&.dispose
+ end
+end
diff --git a/plugins/discourse-workflows/spec/lib/discourse_workflows/executor/step_log_spec.rb b/plugins/discourse-workflows/spec/lib/discourse_workflows/executor/step_log_spec.rb
new file mode 100644
index 00000000000..d736f00fcdc
--- /dev/null
+++ b/plugins/discourse-workflows/spec/lib/discourse_workflows/executor/step_log_spec.rb
@@ -0,0 +1,113 @@
+# frozen_string_literal: true
+
+RSpec.describe DiscourseWorkflows::Executor::StepLog do
+ subject(:log) { described_class.new }
+
+ describe "#info" do
+ it "adds an info-level entry" do
+ log.info("hello")
+ expect(log.entries.size).to eq(1)
+ entry = log.entries.first
+ expect(entry["level"]).to eq("info")
+ expect(entry["message"]).to eq("hello")
+ expect(entry["at"]).to be_present
+ end
+ end
+
+ describe "#warn" do
+ it "adds a warn-level entry" do
+ log.warn("careful")
+ expect(log.entries.first["level"]).to eq("warn")
+ expect(log.entries.first["message"]).to eq("careful")
+ end
+ end
+
+ describe "#error" do
+ it "adds an error-level entry" do
+ log.error("broken")
+ expect(log.entries.first["level"]).to eq("error")
+ expect(log.entries.first["message"]).to eq("broken")
+ end
+ end
+
+ describe "#kv" do
+ it "adds a key/value entry at info level" do
+ log.kv("user_id", "42")
+ entry = log.entries.first
+ expect(entry["level"]).to eq("info")
+ expect(entry["key"]).to eq("user_id")
+ expect(entry["value"]).to eq("42")
+ expect(entry["at"]).to be_present
+ end
+ end
+
+ describe "#errors?" do
+ it "returns false when no errors" do
+ log.info("fine")
+ expect(log.errors?).to be(false)
+ end
+
+ it "returns true when error entries exist" do
+ log.error("boom")
+ expect(log.errors?).to be(true)
+ end
+ end
+
+ describe "#empty?" do
+ it "returns true when no entries" do
+ expect(log).to be_empty
+ end
+
+ it "returns false when entries exist" do
+ log.info("hi")
+ expect(log).not_to be_empty
+ end
+ end
+
+ describe "#merge" do
+ it "copies entries from another StepLog" do
+ other = described_class.new
+ other.info("from other")
+ other.error("other error")
+
+ log.info("local")
+ log.merge(other)
+
+ expect(log.entries.size).to eq(3)
+ expect(log.errors?).to be(true)
+ end
+ end
+
+ describe "#as_json" do
+ it "returns a serializable array" do
+ log.info("hello")
+ log.kv("key", "val")
+ result = log.as_json
+ expect(result).to be_an(Array)
+ expect(result.size).to eq(2)
+ expect(result.first).to include("level" => "info", "message" => "hello")
+ expect(result.second).to include("level" => "info", "key" => "key", "value" => "val")
+ end
+ end
+
+ describe "entry cap" do
+ it "stops adding entries after MAX_ENTRIES and warns about truncation" do
+ stub_const(DiscourseWorkflows::Executor::StepLog, :MAX_ENTRIES, 5) do
+ 7.times { |i| log.info("msg #{i}") }
+ expect(log.entries.size).to eq(5)
+ expect(log.entries.last).to include(
+ "level" => "warn",
+ "message" => "Log truncated at 5 entries",
+ )
+ end
+ end
+ end
+
+ describe "#error_summary" do
+ it "returns a summary of error entries" do
+ log.error("first problem")
+ log.error("second problem")
+ expect(log.error_summary).to include("first problem")
+ end
+ end
+end
diff --git a/plugins/discourse-workflows/spec/lib/discourse_workflows/executor/step_spec.rb b/plugins/discourse-workflows/spec/lib/discourse_workflows/executor/step_spec.rb
new file mode 100644
index 00000000000..ddd15c555a2
--- /dev/null
+++ b/plugins/discourse-workflows/spec/lib/discourse_workflows/executor/step_spec.rb
@@ -0,0 +1,216 @@
+# frozen_string_literal: true
+
+RSpec.describe DiscourseWorkflows::Executor::Step do
+ let(:node) { Struct.new(:id, :name, :type).new("abc-123", "My Node", "action:code") }
+
+ describe ".build" do
+ it "creates a running step with required fields" do
+ step = described_class.build(node: node, position: 0, input: [])
+
+ expect(step.node_id).to eq("abc-123")
+ expect(step.node_name).to eq("My Node")
+ expect(step.node_type).to eq("action:code")
+ expect(step.position).to eq(0)
+ expect(step).to be_running
+ expect(step.input).to eq([])
+ expect(step.started_at).to be_present
+ expect(step.finished_at).to be_nil
+ expect(step.output).to be_nil
+ expect(step.error).to be_nil
+ end
+
+ it "includes finished_at for non-running statuses" do
+ step =
+ described_class.build(node: node, position: 1, input: [], status: "success", output: [])
+
+ expect(step).to be_success
+ expect(step.finished_at).to be_present
+ expect(step.output).to eq([])
+ end
+
+ it "includes error when provided" do
+ step =
+ described_class.build(
+ node: node,
+ position: 2,
+ input: [],
+ status: "error",
+ error: "something broke",
+ )
+
+ expect(step.error).to eq("something broke")
+ end
+
+ it "includes metadata when provided" do
+ step =
+ described_class.build(
+ node: node,
+ position: 0,
+ input: [],
+ metadata: {
+ "resolved_configuration" => {
+ "key" => "val",
+ },
+ },
+ )
+
+ expect(step.metadata).to eq("resolved_configuration" => { "key" => "val" })
+ end
+ end
+
+ describe "timestamp precision" do
+ it "stores timestamps with millisecond precision" do
+ step = described_class.build(node: node, position: 0, input: [])
+ expect(step.started_at).to match(/\.\d{3}/)
+
+ step.succeed!(output: [])
+ expect(step.finished_at).to match(/\.\d{3}/)
+ end
+ end
+
+ describe "status transitions" do
+ let(:step) { described_class.build(node: node, position: 0, input: []) }
+
+ it "#succeed! transitions to success with output" do
+ step.succeed!(output: [{ "json" => { "result" => true } }])
+
+ expect(step).to be_success
+ expect(step.output).to eq([{ "json" => { "result" => true } }])
+ expect(step.finished_at).to be_present
+ end
+
+ it "#filter! transitions to filtered with output" do
+ step.filter!(output: { "true" => [], "false" => [{ "json" => {} }] })
+
+ expect(step).to be_filtered
+ expect(step.output).to be_present
+ expect(step.finished_at).to be_present
+ end
+
+ it "#fail! transitions to error with message" do
+ step.fail!("something broke")
+
+ expect(step).to be_error
+ expect(step.error).to eq("something broke")
+ expect(step.finished_at).to be_present
+ end
+
+ it "#mark_waiting! transitions to waiting without finishing" do
+ step.mark_waiting!
+
+ expect(step).to be_waiting
+ expect(step.finished_at).to be_nil
+ end
+ end
+
+ describe "#add_metadata" do
+ it "initializes metadata hash and sets the key" do
+ step = described_class.build(node: node, position: 0, input: [])
+ step.add_metadata("logs", [{ "level" => "info" }])
+
+ expect(step.metadata).to eq("logs" => [{ "level" => "info" }])
+ end
+
+ it "merges into existing metadata" do
+ step = described_class.build(node: node, position: 0, input: [], metadata: { "a" => 1 })
+ step.add_metadata("b", 2)
+
+ expect(step.metadata).to eq("a" => 1, "b" => 2)
+ end
+ end
+
+ describe "#apply_updates!" do
+ it "applies hash updates to matching fields" do
+ step = described_class.build(node: node, position: 0, input: [])
+ step.mark_waiting!
+
+ step.apply_updates!(
+ "status" => "success",
+ "output" => [{ "json" => {} }],
+ "finished_at" => "2025-01-01T00:00:00Z",
+ )
+
+ expect(step).to be_success
+ expect(step.output).to eq([{ "json" => {} }])
+ expect(step.finished_at).to be_present
+ end
+ end
+
+ describe "#to_h" do
+ it "serializes to the expected hash format" do
+ step = described_class.build(node: node, position: 0, input: [{ "json" => {} }])
+ step.succeed!(output: [{ "json" => { "done" => true } }])
+ step.add_metadata("logs", [])
+
+ h = step.to_h
+
+ expect(h["node_id"]).to eq("abc-123")
+ expect(h["node_name"]).to eq("My Node")
+ expect(h["node_type"]).to eq("action:code")
+ expect(h["position"]).to eq(0)
+ expect(h["status"]).to eq("success")
+ expect(h["input"]).to eq([{ "json" => {} }])
+ expect(h["output"]).to eq([{ "json" => { "done" => true } }])
+ expect(h["started_at"]).to be_present
+ expect(h["finished_at"]).to be_present
+ expect(h["metadata"]).to eq("logs" => [])
+ expect(h).not_to have_key("error")
+ end
+
+ it "omits nil optional fields" do
+ step = described_class.build(node: node, position: 0, input: [])
+ h = step.to_h
+
+ expect(h).not_to have_key("output")
+ expect(h).not_to have_key("finished_at")
+ expect(h).not_to have_key("error")
+ expect(h).not_to have_key("metadata")
+ end
+ end
+
+ describe ".from_h" do
+ it "round-trips through to_h" do
+ original = described_class.build(node: node, position: 3, input: [{ "json" => {} }])
+ original.succeed!(output: [{ "json" => { "x" => 1 } }])
+ original.add_metadata("resolved_configuration", { "key" => "val" })
+
+ restored = described_class.from_h(original.to_h)
+
+ expect(restored.to_h).to eq(original.to_h)
+ end
+ end
+
+ describe "SKIPPED status" do
+ it "supports skip! transition" do
+ step =
+ described_class.new(
+ node_id: "1",
+ node_name: "Test",
+ node_type: "action:test",
+ position: 0,
+ input: [],
+ )
+
+ step.skip!(output: [{ "json" => { "a" => 1 } }], reason: "Node unavailable")
+
+ expect(step.status).to eq("skipped")
+ expect(step.output).to eq([{ "json" => { "a" => 1 } }])
+ expect(step.error).to eq("Node unavailable")
+ expect(step.finished_at).to be_present
+ end
+
+ it "responds to skipped?" do
+ step =
+ described_class.new(
+ node_id: "1",
+ node_name: "Test",
+ node_type: "action:test",
+ position: 0,
+ input: [],
+ status: described_class::SKIPPED,
+ )
+
+ expect(step).to be_skipped
+ end
+ end
+end
diff --git a/plugins/discourse-workflows/spec/lib/discourse_workflows/executor/trigger_execution_context_spec.rb b/plugins/discourse-workflows/spec/lib/discourse_workflows/executor/trigger_execution_context_spec.rb
new file mode 100644
index 00000000000..54c7bcf0b01
--- /dev/null
+++ b/plugins/discourse-workflows/spec/lib/discourse_workflows/executor/trigger_execution_context_spec.rb
@@ -0,0 +1,61 @@
+# frozen_string_literal: true
+
+RSpec.describe DiscourseWorkflows::Executor::TriggerExecutionContext do
+ fab!(:workflow) do
+ graph =
+ build_workflow_graph do |g|
+ g.node "trigger-1",
+ "trigger:schedule",
+ configuration: {
+ rule: {
+ interval: [{ field: "days" }],
+ },
+ }
+ end
+ Fabricate(
+ :discourse_workflows_workflow,
+ published: true,
+ settings: {
+ "timezone" => "Europe/Paris",
+ },
+ **graph,
+ )
+ end
+
+ let(:trigger_node) { workflow.active_version.nodes.first }
+ let(:published_trigger) do
+ DiscourseWorkflows::PublishedTrigger.new(
+ workflow:,
+ workflow_version: workflow.active_version,
+ trigger_node:,
+ )
+ end
+ let(:runtime_state) do
+ described_class::RuntimeState.new(
+ trigger_state: workflow.node_trigger_state(trigger_node["id"]).deep_dup,
+ static_data_global: workflow.global_static_data.deep_dup,
+ static_data_node: workflow.node_static_data(trigger_node["name"]).deep_dup,
+ )
+ end
+ let(:ctx) { described_class.new(published_trigger:, runtime_state:) }
+
+ describe "#get_timezone" do
+ it "returns the resolved workflow timezone" do
+ expect(ctx.get_timezone).to eq("Europe/Paris")
+ end
+ end
+
+ describe "#get_workflow_static_data" do
+ it "returns the node-scoped hash for :node" do
+ expect(ctx.get_workflow_static_data(:node)).to equal(runtime_state.static_data_node)
+ end
+
+ it "returns the global hash for :global" do
+ expect(ctx.get_workflow_static_data(:global)).to equal(runtime_state.static_data_global)
+ end
+
+ it "raises on unknown scopes" do
+ expect { ctx.get_workflow_static_data(:bogus) }.to raise_error(ArgumentError)
+ end
+ end
+end
diff --git a/plugins/discourse-workflows/spec/lib/discourse_workflows/executor_create_post_spec.rb b/plugins/discourse-workflows/spec/lib/discourse_workflows/executor_create_post_spec.rb
new file mode 100644
index 00000000000..c11cb20339a
--- /dev/null
+++ b/plugins/discourse-workflows/spec/lib/discourse_workflows/executor_create_post_spec.rb
@@ -0,0 +1,50 @@
+# frozen_string_literal: true
+
+RSpec.describe DiscourseWorkflows::Executor do
+ fab!(:admin)
+ fab!(:topic_owner) { Fabricate(:user, refresh_auto_groups: true) }
+ fab!(:first_post) { create_post(user: topic_owner, raw: "First post") }
+ fab!(:topic) { first_post.topic }
+
+ describe "#run" do
+ it "creates a post from trigger data" do
+ graph =
+ build_workflow_graph do |g|
+ g.node "trigger-1", "trigger:manual"
+ g.node "action-1",
+ "action:create_post",
+ name: "Create Post",
+ configuration: {
+ "topic_id" => "={{ $trigger.topic_id }}",
+ "raw" => "={{ $trigger.raw }}",
+ "reply_to_post_number" => "={{ $trigger.reply_to_post_number }}",
+ "author_username" => "={{ $trigger.author_username }}",
+ }
+ g.chain "trigger-1", "action-1"
+ end
+ workflow =
+ Fabricate(:discourse_workflows_workflow, created_by: admin, published: true, **graph)
+
+ trigger_data = {
+ topic_id: topic.id,
+ raw: "Generated reply",
+ reply_to_post_number: first_post.post_number,
+ author_username: admin.username,
+ }
+
+ execution = described_class.new(workflow, "trigger-1", trigger_data).run
+ reply = topic.posts.order(:id).last
+
+ expect(execution.status).to eq("success")
+ expect(reply.raw).to eq("Generated reply")
+ expect(reply.reply_to_post_number).to eq(first_post.post_number)
+ expect(reply.user_id).to eq(admin.id)
+ expect(execution.execution_data.context_data["Create Post"].first["json"]["post"]).to include(
+ "id" => reply.id,
+ "raw" => "Generated reply",
+ "user_id" => admin.id,
+ "post_number" => reply.post_number,
+ )
+ end
+ end
+end
diff --git a/plugins/discourse-workflows/spec/lib/discourse_workflows/executor_item_linking_spec.rb b/plugins/discourse-workflows/spec/lib/discourse_workflows/executor_item_linking_spec.rb
new file mode 100644
index 00000000000..813dc303258
--- /dev/null
+++ b/plugins/discourse-workflows/spec/lib/discourse_workflows/executor_item_linking_spec.rb
@@ -0,0 +1,223 @@
+# frozen_string_literal: true
+
+RSpec.describe DiscourseWorkflows::Executor do
+ fab!(:user)
+
+ def run_workflow(&block)
+ graph = build_workflow_graph(&block)
+ workflow = Fabricate(:discourse_workflows_workflow, created_by: user, published: true, **graph)
+
+ described_class.new(workflow, "trigger-1", {}).run
+ end
+
+ def context_output(execution, name)
+ execution.execution_data.context_data[name]
+ end
+
+ it "adds pairedItem to one-to-one action outputs" do
+ execution =
+ run_workflow do |g|
+ g.node "trigger-1", "trigger:manual"
+ g.node "source",
+ "action:set_fields",
+ name: "Source",
+ configuration: {
+ "mode" => "raw",
+ "include_other_fields" => false,
+ "json_output" => '{"rows": [{"id": 1}, {"id": 2}]}',
+ }
+ g.node "split", "action:split_out", name: "Split", configuration: { "field" => "rows" }
+ g.node "set",
+ "action:set_fields",
+ name: "Set",
+ configuration: {
+ "mode" => "manual",
+ "include_other_fields" => true,
+ "assignments" => {
+ "assignments" => [{ "name" => "seen", "value" => "true", "type" => "boolean" }],
+ },
+ }
+ g.chain "trigger-1", "source", "split", "set"
+ end
+
+ expect(execution.status).to eq("success")
+ expect(context_output(execution, "Set").map { |item| item["pairedItem"] }).to eq(
+ [{ "item" => 0 }, { "item" => 1 }],
+ )
+ end
+
+ it "keeps original input indexes after filtering items" do
+ execution =
+ run_workflow do |g|
+ g.node "trigger-1", "trigger:manual"
+ g.node "source",
+ "action:set_fields",
+ name: "Source",
+ configuration: {
+ "mode" => "raw",
+ "include_other_fields" => false,
+ "json_output" => '{"rows": [{"id": 1}, {"id": 2}]}',
+ }
+ g.node "split", "action:split_out", name: "Split", configuration: { "field" => "rows" }
+ g.node "filter",
+ "condition:filter",
+ name: "Filter",
+ configuration: {
+ "conditions" => [
+ {
+ "id" => "1",
+ "leftValue" => "={{ $json.id }}",
+ "rightValue" => 2,
+ "operator" => {
+ "type" => "number",
+ "operation" => "equals",
+ },
+ },
+ ],
+ "combinator" => "and",
+ }
+ g.chain "trigger-1", "source", "split", "filter"
+ end
+
+ expect(execution.status).to eq("success")
+ expect(context_output(execution, "Filter").map { |item| item["json"]["id"] }).to eq([2, 1])
+ expect(context_output(execution, "Filter").first["pairedItem"]).to eq("item" => 1)
+ end
+
+ it "resolves previous-node .item through linked lineage" do
+ execution =
+ run_workflow do |g|
+ g.node "trigger-1", "trigger:manual"
+ g.node "source",
+ "action:set_fields",
+ name: "Source",
+ configuration: {
+ "mode" => "raw",
+ "include_other_fields" => false,
+ "json_output" =>
+ '{"rows": [{"id": 1, "label": "first"}, {"id": 2, "label": "second"}]}',
+ }
+ g.node "split", "action:split_out", name: "Split", configuration: { "field" => "rows" }
+ g.node "filter",
+ "condition:filter",
+ name: "Filter",
+ configuration: {
+ "conditions" => [
+ {
+ "id" => "1",
+ "leftValue" => "={{ $json.id }}",
+ "rightValue" => 2,
+ "operator" => {
+ "type" => "number",
+ "operation" => "equals",
+ },
+ },
+ ],
+ "combinator" => "and",
+ }
+ g.node "set",
+ "action:set_fields",
+ name: "Set",
+ configuration: {
+ "mode" => "manual",
+ "include_other_fields" => false,
+ "assignments" => {
+ "assignments" => [
+ {
+ "name" => "linked_label",
+ "value" => "={{ $('Split').item.json.label }}",
+ "type" => "string",
+ },
+ ],
+ },
+ }
+ g.chain "trigger-1", "source", "split", "filter", "set"
+ end
+
+ expect(execution.status).to eq("success")
+ expect(context_output(execution, "Set").first.dig("json", "linked_label")).to eq("second")
+ end
+
+ it "does not resolve ambiguous previous-node .item after a merge" do
+ execution =
+ run_workflow do |g|
+ g.node "trigger-1", "trigger:manual"
+ g.node "source",
+ "action:set_fields",
+ name: "Source",
+ configuration: {
+ "mode" => "raw",
+ "include_other_fields" => false,
+ "json_output" =>
+ '{"rows": [{"id": 1, "label": "first"}, {"id": 2, "label": "second"}]}',
+ }
+ g.node "split", "action:split_out", name: "Split", configuration: { "field" => "rows" }
+ g.node "filter-1",
+ "condition:filter",
+ configuration: {
+ "conditions" => [
+ {
+ "id" => "1",
+ "leftValue" => "={{ $json.id }}",
+ "rightValue" => 1,
+ "operator" => {
+ "type" => "number",
+ "operation" => "equals",
+ },
+ },
+ ],
+ "combinator" => "and",
+ }
+ g.node "filter-2",
+ "condition:filter",
+ configuration: {
+ "conditions" => [
+ {
+ "id" => "1",
+ "leftValue" => "={{ $json.id }}",
+ "rightValue" => 2,
+ "operator" => {
+ "type" => "number",
+ "operation" => "equals",
+ },
+ },
+ ],
+ "combinator" => "and",
+ }
+ g.node "merge",
+ "flow:merge",
+ name: "Merge",
+ configuration: {
+ "mode" => "combine",
+ "combine_by" => "all",
+ }
+ g.node "set",
+ "action:set_fields",
+ configuration: {
+ "mode" => "manual",
+ "include_other_fields" => false,
+ "assignments" => {
+ "assignments" => [
+ {
+ "name" => "linked_label",
+ "value" => "={{ $('Split').item.json.label }}",
+ "type" => "string",
+ },
+ ],
+ },
+ }
+ g.chain "trigger-1", "source", "split"
+ g.connect "split", "filter-1"
+ g.connect "split", "filter-2"
+ g.connect "filter-1", "merge", output: "true", input: "input_1"
+ g.connect "filter-2", "merge", output: "true", input: "input_2"
+ g.chain "merge", "set"
+ end
+
+ expect(execution.status).to eq("error")
+ expect(execution.error).to include("Multiple matching items for expression")
+ expect(context_output(execution, "Merge").first["pairedItem"]).to eq(
+ [{ "input" => 0, "item" => 0 }, { "input" => 1, "item" => 0 }],
+ )
+ end
+end
diff --git a/plugins/discourse-workflows/spec/lib/discourse_workflows/executor_loop_spec.rb b/plugins/discourse-workflows/spec/lib/discourse_workflows/executor_loop_spec.rb
new file mode 100644
index 00000000000..83bc2bffbd4
--- /dev/null
+++ b/plugins/discourse-workflows/spec/lib/discourse_workflows/executor_loop_spec.rb
@@ -0,0 +1,432 @@
+# frozen_string_literal: true
+
+RSpec.describe DiscourseWorkflows::Executor do
+ fab!(:user)
+
+ before { SiteSetting.tagging_enabled = true }
+
+ describe "#run" do
+ it "executes a loop workflow: trigger -> loop -> action -> loop-back -> done" do
+ graph =
+ build_workflow_graph do |g|
+ g.node "trigger-1", "trigger:manual"
+ g.node "set-fields-1",
+ "action:set_fields",
+ configuration: {
+ "mode" => "raw",
+ "include_other_fields" => false,
+ "json_output" => '{"item_id": "1"}',
+ }
+ g.node "loop-1", "flow:loop_over_items", configuration: { "batch_size" => 1 }
+ g.node "process-1",
+ "action:set_fields",
+ configuration: {
+ "mode" => "raw",
+ "include_other_fields" => true,
+ "json_output" => '{"processed": "true"}',
+ }
+ g.node "done-1",
+ "action:set_fields",
+ name: "Final Step",
+ configuration: {
+ "mode" => "raw",
+ "include_other_fields" => true,
+ "json_output" => '{"completed": "true"}',
+ }
+ g.chain "trigger-1", "set-fields-1", "loop-1"
+ g.connect "loop-1", "process-1", output: "loop"
+ g.chain "process-1", "loop-1"
+ g.connect "loop-1", "done-1", output: "done"
+ end
+ workflow =
+ Fabricate(:discourse_workflows_workflow, created_by: user, published: true, **graph)
+
+ trigger_data = {}
+ execution = described_class.new(workflow, "trigger-1", trigger_data).run
+
+ expect(execution.status).to eq("success")
+
+ final_output = execution.execution_data.context_data["Final Step"]
+ expect(final_output).to be_an(Array)
+ expect(final_output.first["json"]).to include("processed" => "true", "completed" => "true")
+ end
+
+ it "processes multiple items through the loop in batches" do
+ graph =
+ build_workflow_graph do |g|
+ g.node "trigger-1", "trigger:manual"
+ g.node "loop-1", "flow:loop_over_items", configuration: { "batch_size" => 1 }
+ g.node "process-1",
+ "action:set_fields",
+ configuration: {
+ "mode" => "raw",
+ "include_other_fields" => true,
+ "json_output" => '{"tagged": "yes"}',
+ }
+ g.node "done-1",
+ "action:set_fields",
+ name: "Done",
+ configuration: {
+ "include_other_fields" => true,
+ "assignments" => {
+ "assignments" => [
+ { "name" => "final", "value" => "true", "type" => "string" },
+ ],
+ },
+ }
+ g.chain "trigger-1", "loop-1"
+ g.connect "loop-1", "process-1", output: "loop"
+ g.chain "process-1", "loop-1"
+ g.connect "loop-1", "done-1", output: "done"
+ end
+ workflow =
+ Fabricate(:discourse_workflows_workflow, created_by: user, published: true, **graph)
+
+ trigger_data = { items: [{ name: "a" }, { name: "b" }, { name: "c" }] }
+ execution = described_class.new(workflow, "trigger-1", trigger_data).run
+
+ expect(execution.status).to eq("success")
+
+ done_output = execution.execution_data.context_data["Done"]
+ expect(done_output).to be_an(Array)
+ expect(done_output.length).to eq(1)
+ end
+
+ it "waits for required target inputs before executing a merge node" do
+ graph =
+ build_workflow_graph do |g|
+ g.node "trigger-1", "trigger:manual"
+ g.node "left-1",
+ "action:set_fields",
+ configuration: {
+ "mode" => "raw",
+ "include_other_fields" => false,
+ "json_output" => '{"id": 1, "left": "yes"}',
+ }
+ g.node "right-1",
+ "action:set_fields",
+ configuration: {
+ "mode" => "raw",
+ "include_other_fields" => false,
+ "json_output" => '{"topic_id": 1, "right": "yes"}',
+ }
+ g.node "merge-1",
+ "flow:merge",
+ name: "Merge branches",
+ configuration: {
+ "mode" => "combine",
+ "combine_by" => "matching_fields",
+ "fields_to_match" => {
+ "values" => [{ "field_1" => "id", "field_2" => "topic_id" }],
+ },
+ }
+ g.connect "trigger-1", "left-1"
+ g.connect "trigger-1", "right-1"
+ g.connect "left-1", "merge-1", input: "input_1"
+ g.connect "right-1", "merge-1", input: "input_2"
+ end
+ workflow =
+ Fabricate(:discourse_workflows_workflow, created_by: user, published: true, **graph)
+
+ execution = described_class.new(workflow, "trigger-1", {}).run
+
+ expect(execution.status).to eq("success")
+ merge_steps =
+ execution.execution_data.steps_array.select { |step| step["node_id"] == "merge-1" }
+ expect(merge_steps.length).to eq(1)
+ expect(merge_steps.first["output"].first["json"]).to include(
+ "id" => 1,
+ "left" => "yes",
+ "topic_id" => 1,
+ "right" => "yes",
+ )
+ end
+
+ it "waits for all incoming branches before executing append merge" do
+ graph =
+ build_workflow_graph do |g|
+ g.node "trigger-1", "trigger:manual"
+ g.node "first-1",
+ "action:set_fields",
+ configuration: {
+ "mode" => "raw",
+ "include_other_fields" => false,
+ "json_output" => '{"source": "first"}',
+ }
+ g.node "second-1",
+ "action:set_fields",
+ configuration: {
+ "mode" => "raw",
+ "include_other_fields" => false,
+ "json_output" => '{"source": "second"}',
+ }
+ g.node "third-1",
+ "action:set_fields",
+ configuration: {
+ "mode" => "raw",
+ "include_other_fields" => false,
+ "json_output" => '{"source": "third"}',
+ }
+ g.node "merge-1",
+ "flow:merge",
+ name: "Append branches",
+ configuration: {
+ "mode" => "append",
+ }
+ g.connect "trigger-1", "first-1"
+ g.connect "trigger-1", "second-1"
+ g.connect "trigger-1", "third-1"
+ g.connect "first-1", "merge-1", input: "input_1"
+ g.connect "second-1", "merge-1", input: "input_2"
+ g.connect "third-1", "merge-1", input: "input_3"
+ end
+ workflow =
+ Fabricate(:discourse_workflows_workflow, created_by: user, published: true, **graph)
+
+ execution = described_class.new(workflow, "trigger-1", {}).run
+
+ expect(execution.status).to eq("success")
+ merge_steps =
+ execution.execution_data.steps_array.select { |step| step["node_id"] == "merge-1" }
+ expect(merge_steps.length).to eq(1)
+ expect(merge_steps.first["output"].map { |item| item["json"]["source"] }).to contain_exactly(
+ "first",
+ "second",
+ "third",
+ )
+ end
+
+ it "does not wait for unwired append merge inputs" do
+ graph =
+ build_workflow_graph do |g|
+ g.node "trigger-1", "trigger:manual"
+ g.node "first-1",
+ "action:set_fields",
+ configuration: {
+ "mode" => "raw",
+ "include_other_fields" => false,
+ "json_output" => '{"source": "first"}',
+ }
+ g.node "second-1",
+ "action:set_fields",
+ configuration: {
+ "mode" => "raw",
+ "include_other_fields" => false,
+ "json_output" => '{"source": "second"}',
+ }
+ g.node "merge-1",
+ "flow:merge",
+ name: "Append branches",
+ configuration: {
+ "mode" => "append",
+ "number_inputs" => 3,
+ }
+ g.connect "trigger-1", "first-1"
+ g.connect "trigger-1", "second-1"
+ g.connect "first-1", "merge-1", input: "input_1"
+ g.connect "second-1", "merge-1", input: "input_2"
+ end
+ workflow =
+ Fabricate(:discourse_workflows_workflow, created_by: user, published: true, **graph)
+
+ execution = described_class.new(workflow, "trigger-1", {}).run
+
+ expect(execution.status).to eq("success")
+ merge_steps =
+ execution.execution_data.steps_array.select { |step| step["node_id"] == "merge-1" }
+ expect(merge_steps.length).to eq(1)
+ expect(merge_steps.first["output"].map { |item| item["json"]["source"] }).to contain_exactly(
+ "first",
+ "second",
+ )
+ end
+
+ it "runs append merge with available data when a connected branch does not execute" do
+ graph =
+ build_workflow_graph do |g|
+ g.node "trigger-1", "trigger:manual"
+ g.node "source-1",
+ "action:set_fields",
+ configuration: {
+ "mode" => "raw",
+ "include_other_fields" => false,
+ "json_output" => '{"route": "left"}',
+ }
+ g.node "branch-1",
+ "condition:if",
+ configuration: {
+ "conditions" => [
+ {
+ "id" => "1",
+ "leftValue" => "={{ $json.route }}",
+ "rightValue" => "left",
+ "operator" => {
+ "type" => "string",
+ "operation" => "equals",
+ },
+ },
+ ],
+ "combinator" => "and",
+ }
+ g.node "left-1",
+ "action:set_fields",
+ configuration: {
+ "mode" => "raw",
+ "include_other_fields" => true,
+ "json_output" => '{"source": "left"}',
+ }
+ g.node "right-1",
+ "action:set_fields",
+ configuration: {
+ "mode" => "raw",
+ "include_other_fields" => true,
+ "json_output" => '{"source": "right"}',
+ }
+ g.node "merge-1",
+ "flow:merge",
+ name: "Append branches",
+ configuration: {
+ "mode" => "append",
+ }
+ g.chain "trigger-1", "source-1", "branch-1"
+ g.connect "branch-1", "left-1", output: "true"
+ g.connect "branch-1", "right-1", output: "false"
+ g.connect "left-1", "merge-1", input: "input_1"
+ g.connect "right-1", "merge-1", input: "input_2"
+ end
+ workflow =
+ Fabricate(:discourse_workflows_workflow, created_by: user, published: true, **graph)
+
+ execution = described_class.new(workflow, "trigger-1", {}).run
+
+ expect(execution.status).to eq("success")
+ merge_steps =
+ execution.execution_data.steps_array.select { |step| step["node_id"] == "merge-1" }
+ expect(merge_steps.length).to eq(1)
+ expect(merge_steps.first["output"].map { |item| item["json"]["source"] }).to eq(["left"])
+ end
+
+ it "waits for a partial parent merge before flushing a downstream merge" do
+ graph =
+ build_workflow_graph do |g|
+ g.node "trigger-1", "trigger:manual"
+ g.node "direct-1",
+ "action:set_fields",
+ configuration: {
+ "mode" => "raw",
+ "include_other_fields" => false,
+ "json_output" => '{"source": "direct"}',
+ }
+ g.node "upstream-1",
+ "action:set_fields",
+ configuration: {
+ "mode" => "raw",
+ "include_other_fields" => false,
+ "json_output" => '{"source": "upstream"}',
+ }
+ g.node "never-1",
+ "action:set_fields",
+ configuration: {
+ "mode" => "raw",
+ "include_other_fields" => false,
+ "json_output" => '{"source": "never"}',
+ }
+ g.node "merge-a",
+ "flow:merge",
+ name: "Parent merge",
+ configuration: {
+ "mode" => "append",
+ }
+ g.node "merge-b",
+ "flow:merge",
+ name: "Downstream merge",
+ configuration: {
+ "mode" => "append",
+ }
+ g.connect "trigger-1", "upstream-1"
+ g.connect "trigger-1", "direct-1"
+ g.connect "direct-1", "merge-b", input: "input_1"
+ g.connect "upstream-1", "merge-a", input: "input_1"
+ g.connect "never-1", "merge-a", input: "input_2"
+ g.connect "merge-a", "merge-b", input: "input_2"
+ end
+ workflow =
+ Fabricate(:discourse_workflows_workflow, created_by: user, published: true, **graph)
+
+ execution = described_class.new(workflow, "trigger-1", {}).run
+
+ expect(execution.status).to eq("success")
+ merge_steps =
+ execution.execution_data.steps_array.select { |step| step["node_id"] == "merge-b" }
+ expect(merge_steps.length).to eq(1)
+ expect(merge_steps.first["output"].map { |item| item["json"]["source"] }).to eq(
+ %w[direct upstream],
+ )
+ end
+
+ it "does not run choose branch merge with a missing connected branch" do
+ graph =
+ build_workflow_graph do |g|
+ g.node "trigger-1", "trigger:manual"
+ g.node "source-1",
+ "action:set_fields",
+ configuration: {
+ "mode" => "raw",
+ "include_other_fields" => false,
+ "json_output" => '{"route": "left"}',
+ }
+ g.node "branch-1",
+ "condition:if",
+ configuration: {
+ "conditions" => [
+ {
+ "id" => "1",
+ "leftValue" => "={{ $json.route }}",
+ "rightValue" => "left",
+ "operator" => {
+ "type" => "string",
+ "operation" => "equals",
+ },
+ },
+ ],
+ "combinator" => "and",
+ }
+ g.node "left-1",
+ "action:set_fields",
+ configuration: {
+ "mode" => "raw",
+ "include_other_fields" => true,
+ "json_output" => '{"source": "left"}',
+ }
+ g.node "right-1",
+ "action:set_fields",
+ configuration: {
+ "mode" => "raw",
+ "include_other_fields" => true,
+ "json_output" => '{"source": "right"}',
+ }
+ g.node "merge-1",
+ "flow:merge",
+ name: "Choose branch",
+ configuration: {
+ "mode" => "choose_branch",
+ "use_data_of_input" => "input_1",
+ }
+ g.chain "trigger-1", "source-1", "branch-1"
+ g.connect "branch-1", "left-1", output: "true"
+ g.connect "branch-1", "right-1", output: "false"
+ g.connect "left-1", "merge-1", input: "input_1"
+ g.connect "right-1", "merge-1", input: "input_2"
+ end
+ workflow =
+ Fabricate(:discourse_workflows_workflow, created_by: user, published: true, **graph)
+
+ execution = described_class.new(workflow, "trigger-1", {}).run
+
+ expect(execution.status).to eq("success")
+ merge_steps =
+ execution.execution_data.steps_array.select { |step| step["node_id"] == "merge-1" }
+ expect(merge_steps).to be_empty
+ end
+ end
+end
diff --git a/plugins/discourse-workflows/spec/lib/discourse_workflows/executor_pin_data_spec.rb b/plugins/discourse-workflows/spec/lib/discourse_workflows/executor_pin_data_spec.rb
new file mode 100644
index 00000000000..15efd843f53
--- /dev/null
+++ b/plugins/discourse-workflows/spec/lib/discourse_workflows/executor_pin_data_spec.rb
@@ -0,0 +1,99 @@
+# frozen_string_literal: true
+
+RSpec.describe DiscourseWorkflows::Executor do
+ fab!(:user)
+
+ def build_workflow
+ graph =
+ build_workflow_graph do |g|
+ g.node "trigger-1", "trigger:post_created", name: "Post Created"
+ g.node "set-1",
+ "action:set_fields",
+ name: "Set Fields",
+ configuration: {
+ "mode" => "raw",
+ "include_other_fields" => true,
+ "json_output" => '{"echoed": true}',
+ }
+ g.chain "trigger-1", "set-1"
+ end
+ Fabricate(:discourse_workflows_workflow, created_by: user, published: true, **graph)
+ end
+
+ let(:workflow) { build_workflow }
+
+ let(:manual_options) do
+ DiscourseWorkflows::Executor::ExecutionOptions.new(
+ user: user,
+ execution_mode: :manual,
+ draft_execution: true,
+ )
+ end
+
+ def trigger_output(execution)
+ execution.execution_data.run_data["Post Created"].first["outputs"].first["items"]
+ end
+
+ def node_output(execution, node_name)
+ runs = execution.execution_data.run_data[node_name]
+ runs.first["outputs"].first["items"]
+ end
+
+ describe "manual execution with pinned trigger data" do
+ before do
+ workflow.update_node_pin_data!(
+ "Post Created",
+ [{ "json" => { "post_id" => 1234, "raw" => "pinned" } }],
+ )
+ end
+
+ it "emits pinned items as the trigger output" do
+ execution = described_class.new(workflow, "trigger-1", {}, manual_options).run
+
+ expect(trigger_output(execution).first["json"]).to include("post_id" => 1234)
+ end
+
+ it "marks the trigger run as successful" do
+ execution = described_class.new(workflow, "trigger-1", {}, manual_options).run
+
+ expect(execution.status).to eq("success")
+ end
+
+ it "still runs downstream nodes against the pinned data" do
+ execution = described_class.new(workflow, "trigger-1", {}, manual_options).run
+
+ expect(node_output(execution, "Set Fields").first["json"]).to include(
+ "echoed" => true,
+ "post_id" => 1234,
+ )
+ end
+ end
+
+ describe "normal execution ignores pin data" do
+ before do
+ workflow.update_node_pin_data!(
+ "Post Created",
+ [{ "json" => { "post_id" => 9999, "raw" => "should not be used" } }],
+ )
+ end
+
+ it "uses the real trigger data, not the pin" do
+ execution = described_class.new(workflow, "trigger-1", { "post_id" => 1 }).run
+
+ expect(trigger_output(execution).first["json"]).to include("post_id" => 1)
+ expect(trigger_output(execution).first["json"]).not_to include("post_id" => 9999)
+ end
+ end
+
+ describe "pin data on a downstream node" do
+ before do
+ workflow.update_node_pin_data!("Set Fields", [{ "json" => { "frozen_output" => true } }])
+ end
+
+ it "short-circuits the node's execute and emits the pinned items" do
+ execution = described_class.new(workflow, "trigger-1", { "post_id" => 1 }, manual_options).run
+
+ expect(node_output(execution, "Set Fields").first["json"]).to eq("frozen_output" => true)
+ end
+ end
+end
diff --git a/plugins/discourse-workflows/spec/lib/discourse_workflows/executor_spec.rb b/plugins/discourse-workflows/spec/lib/discourse_workflows/executor_spec.rb
new file mode 100644
index 00000000000..8021416f773
--- /dev/null
+++ b/plugins/discourse-workflows/spec/lib/discourse_workflows/executor_spec.rb
@@ -0,0 +1,807 @@
+# frozen_string_literal: true
+
+RSpec.describe DiscourseWorkflows::Executor do
+ fab!(:user)
+ fab!(:topic)
+ fab!(:tag)
+ fab!(:false_tag) { Fabricate(:tag, name: "needs-review") }
+
+ before { SiteSetting.tagging_enabled = true }
+
+ def build_workflow
+ graph =
+ build_workflow_graph do |g|
+ g.node "trigger-1", "trigger:topic_closed", name: "Topic Closed"
+ g.node "action-1",
+ "action:topic_tags",
+ name: "Topic Tags",
+ configuration: {
+ "topic_id" => "={{ $trigger.topic_id }}",
+ "tag_names" => tag.name,
+ }
+ g.chain "trigger-1", "action-1"
+ end
+ Fabricate(:discourse_workflows_workflow, created_by: user, published: true, **graph)
+ end
+
+ describe "#run" do
+ context "with a simple trigger -> action workflow" do
+ fab!(:workflow) { build_workflow }
+ let(:trigger_data) { { topic_id: topic.id, tags: topic.tags.pluck(:name) } }
+
+ it "executes successfully and tags the topic" do
+ execution = described_class.new(workflow, "trigger-1", trigger_data).run
+
+ expect(execution.status).to eq("success")
+ expect(topic.reload.tags).to include(tag)
+ end
+
+ it "creates an execution record" do
+ expect { described_class.new(workflow, "trigger-1", trigger_data).run }.to change {
+ DiscourseWorkflows::Execution.count
+ }.by(1)
+ end
+
+ it "stores context with item arrays in the execution" do
+ execution = described_class.new(workflow, "trigger-1", trigger_data).run
+
+ ed = execution.execution_data.context_data
+ expect(ed["Topic Closed"]).to be_an(Array)
+
+ topic_tags_output = ed["Topic Tags"]
+ expect(topic_tags_output).to be_an(Array)
+ expect(topic_tags_output.first["json"]["tag_names"]).to eq([tag.name])
+ end
+
+ it "handles errors gracefully" do
+ execution = described_class.new(workflow, "trigger-1", { topic_id: -999, tags: [] }).run
+
+ expect(execution).to have_attributes(status: "error", error: be_present)
+ end
+
+ it "skips unpublished workflows" do
+ unpublish_workflow!(workflow)
+
+ execution = described_class.new(workflow, "trigger-1", trigger_data).run
+
+ expect(execution.status).to eq("skipped")
+ end
+
+ it "preloads dependencies from the active workflow snapshot" do
+ executor = described_class.new(workflow, "trigger-1", trigger_data)
+ snapshot =
+ DiscourseWorkflows::WorkflowSnapshot.new(
+ "nodes" => [
+ {
+ "id" => "http-1",
+ "type" => "action:http_request",
+ "parameters" => {
+ "authentication" => "basic_auth",
+ },
+ "credentials" => {
+ "auth" => {
+ "id" => "123",
+ "credential_type" => "basic_auth",
+ },
+ },
+ },
+ ],
+ "connections" => [],
+ )
+ executor.instance_variable_set(:@snapshot, snapshot)
+
+ expect(executor.send(:preloaded_workflow_dependencies)["http-1"]).to include(
+ "credential_id:123",
+ )
+ end
+ end
+
+ it "fails when trigger node is not in the snapshot" do
+ graph = build_workflow_graph { |g| g.node "trigger-1", "trigger:topic_closed" }
+ workflow =
+ Fabricate(:discourse_workflows_workflow, created_by: user, published: true, **graph)
+
+ executor = described_class.new(workflow, "trigger-1", {})
+ workflow.active_version.update!(nodes: [])
+
+ execution = executor.run
+
+ expect(execution).to have_attributes(
+ status: "error",
+ error: include("not found in workflow snapshot"),
+ )
+ end
+
+ it "follows the correct branch of a condition node" do
+ graph =
+ build_workflow_graph do |g|
+ g.node "trigger-1", "trigger:topic_closed"
+ g.node "condition-1",
+ "condition:if",
+ configuration: {
+ "conditions" => [
+ {
+ "id" => "1",
+ "leftValue" => "={{ $json.tags }}",
+ "rightValue" => "bug",
+ "operator" => {
+ "type" => "array",
+ "operation" => "contains",
+ },
+ },
+ ],
+ "combinator" => "and",
+ }
+ g.node "action-true",
+ "action:topic_tags",
+ configuration: {
+ "topic_id" => "={{ $trigger.topic_id }}",
+ "tag_names" => tag.name,
+ }
+ g.node "action-false",
+ "action:topic_tags",
+ configuration: {
+ "topic_id" => "={{ $trigger.topic_id }}",
+ "tag_names" => false_tag.name,
+ }
+ g.chain "trigger-1", "condition-1"
+ g.connect "condition-1", "action-true", output: "true"
+ g.connect "condition-1", "action-false", output: "false"
+ end
+ workflow =
+ Fabricate(:discourse_workflows_workflow, created_by: user, published: true, **graph)
+
+ trigger_data = { topic_id: topic.id, tags: %w[bug help] }
+ execution = described_class.new(workflow, "trigger-1", trigger_data).run
+
+ expect(execution.status).to eq("success")
+ expect(topic.reload.tags.map(&:name)).to include(tag.name)
+ expect(topic.reload.tags.map(&:name)).not_to include("needs-review")
+
+ condition_step = execution.execution_data.find_step(node_id: "condition-1")
+ expect(condition_step["metadata"]["conditions"]).to be_present
+ expect(condition_step["metadata"]["conditions"].first).to include(
+ "left" => include("bug"),
+ "operator" => "contains",
+ "passed" => true,
+ )
+ end
+
+ context "with a filter workflow" do
+ let(:filter_workflow) do
+ graph =
+ build_workflow_graph do |g|
+ g.node "trigger-1", "trigger:topic_closed"
+ g.node "filter-1",
+ "condition:filter",
+ configuration: {
+ "conditions" => [
+ {
+ "id" => "1",
+ "leftValue" => "={{ $json.tags }}",
+ "rightValue" => "bug",
+ "operator" => {
+ "type" => "array",
+ "operation" => "contains",
+ },
+ },
+ ],
+ "combinator" => "and",
+ }
+ g.node "action-1",
+ "action:topic_tags",
+ configuration: {
+ "topic_id" => "={{ $trigger.topic_id }}",
+ "tag_names" => tag.name,
+ }
+ g.chain "trigger-1", "filter-1"
+ g.connect "filter-1", "action-1", output: "true"
+ end
+ Fabricate(:discourse_workflows_workflow, created_by: user, published: true, **graph)
+ end
+
+ it "continues execution when filter passes" do
+ trigger_data = { topic_id: topic.id, tags: %w[bug help] }
+ execution = described_class.new(filter_workflow, "trigger-1", trigger_data).run
+
+ expect(execution.status).to eq("success")
+ expect(topic.reload.tags.map(&:name)).to include(tag.name)
+ end
+
+ it "stops execution when filter does not pass" do
+ trigger_data = { topic_id: topic.id, tags: %w[feature help] }
+ execution = described_class.new(filter_workflow, "trigger-1", trigger_data).run
+
+ expect(execution.status).to eq("success")
+ expect(topic.reload.tags.map(&:name)).not_to include(tag.name)
+ end
+ end
+
+ it "marks condition step as filtered when all items fail" do
+ graph =
+ build_workflow_graph do |g|
+ g.node "trigger-1", "trigger:topic_closed"
+ g.node "filter-1",
+ "condition:filter",
+ configuration: {
+ "conditions" => [
+ {
+ "id" => "1",
+ "leftValue" => "={{ $json.tags }}",
+ "rightValue" => "bug",
+ "operator" => {
+ "type" => "array",
+ "operation" => "contains",
+ },
+ },
+ ],
+ "combinator" => "and",
+ }
+ g.chain "trigger-1", "filter-1"
+ end
+ workflow =
+ Fabricate(:discourse_workflows_workflow, created_by: user, published: true, **graph)
+
+ trigger_data = { topic_id: topic.id, tags: %w[feature help] }
+ execution = described_class.new(workflow, "trigger-1", trigger_data).run
+
+ filter_step = execution.execution_data.find_step(node_id: "filter-1")
+ expect(filter_step["status"]).to eq("filtered")
+ end
+
+ it "routes rejected filter items to the false branch" do
+ graph =
+ build_workflow_graph do |g|
+ g.node "trigger-1", "trigger:topic_closed"
+ g.node "filter-1",
+ "condition:filter",
+ configuration: {
+ "conditions" => [
+ {
+ "id" => "1",
+ "leftValue" => "={{ $json.tags }}",
+ "rightValue" => "bug",
+ "operator" => {
+ "type" => "array",
+ "operation" => "contains",
+ },
+ },
+ ],
+ "combinator" => "and",
+ }
+ g.node "action-false",
+ "action:set_fields",
+ name: "Rejected",
+ configuration: {
+ "include_other_fields" => true,
+ "mode" => "manual",
+ "assignments" => {
+ "assignments" => [
+ { "name" => "rejected", "value" => "yes", "type" => "string" },
+ ],
+ },
+ }
+ g.chain "trigger-1", "filter-1"
+ g.connect "filter-1", "action-false", output: "false"
+ end
+ workflow =
+ Fabricate(:discourse_workflows_workflow, created_by: user, published: true, **graph)
+
+ trigger_data = { topic_id: topic.id, tags: %w[feature help] }
+ execution = described_class.new(workflow, "trigger-1", trigger_data).run
+
+ expect(execution.status).to eq("success")
+ expect(execution.execution_data.find_step(node_id: "action-false")).to be_present
+ expect(execution.execution_data.context_data["Rejected"].first.dig("json", "rejected")).to eq(
+ "yes",
+ )
+ end
+
+ it "records an error step for unknown node types" do
+ graph =
+ build_workflow_graph do |g|
+ g.node "trigger-1", "trigger:topic_closed"
+ g.node "unknown-1", "action:nonexistent_type"
+ g.chain "trigger-1", "unknown-1"
+ end
+ workflow =
+ Fabricate(:discourse_workflows_workflow, created_by: user, published: true, **graph)
+
+ trigger_data = { topic_id: topic.id, tags: [] }
+ execution = described_class.new(workflow, "trigger-1", trigger_data).run
+
+ expect(execution.status).to eq("success")
+
+ step = execution.execution_data.find_step(node_id: "unknown-1")
+ expect(step["status"]).to eq("error")
+ expect(step["error"]).to include("Unknown node type 'action:nonexistent_type'")
+ end
+
+ it "persists node logs to step metadata" do
+ graph =
+ build_workflow_graph do |g|
+ g.node "trigger-1", "trigger:topic_closed"
+ g.node "log-1",
+ "action:log",
+ configuration: {
+ "alwaysOutputData" => true,
+ "entries" => {
+ "values" => [{ "key" => "topic", "value" => "={{ $json.topic_id }}" }],
+ },
+ }
+ g.chain "trigger-1", "log-1"
+ end
+ workflow =
+ Fabricate(:discourse_workflows_workflow, created_by: user, published: true, **graph)
+
+ trigger_data = { topic_id: topic.id, tags: [] }
+ execution = described_class.new(workflow, "trigger-1", trigger_data).run
+
+ expect(execution.status).to eq("success")
+ log_step = execution.execution_data.find_step(node_id: "log-1")
+ logs = log_step.dig("metadata", "logs")
+ expect(logs).to be_present
+ expect(logs.first).to include("key" => "topic", "value" => topic.id.to_s)
+ end
+
+ it "does not route downstream when log returns no output" do
+ graph =
+ build_workflow_graph do |g|
+ g.node "trigger-1", "trigger:topic_closed"
+ g.node "log-1",
+ "action:log",
+ configuration: {
+ "entries" => {
+ "values" => [{ "key" => "topic", "value" => "={{ $json.topic_id }}" }],
+ },
+ }
+ g.node "code-1", "action:code", configuration: { "code" => "return $input.all();" }
+ g.chain "trigger-1", "log-1", "code-1"
+ end
+ workflow =
+ Fabricate(:discourse_workflows_workflow, created_by: user, published: true, **graph)
+
+ trigger_data = { topic_id: topic.id, tags: [] }
+ execution = described_class.new(workflow, "trigger-1", trigger_data).run
+
+ expect(execution.status).to eq("success")
+
+ log_step = execution.execution_data.find_step(node_id: "log-1")
+ expect(log_step["output"]).to eq([])
+ expect(log_step.dig("metadata", "logs").first).to include(
+ "key" => "topic",
+ "value" => topic.id.to_s,
+ )
+
+ expect(execution.execution_data.find_step(node_id: "code-1")).to be_nil
+
+ run_data = execution.execution_data.run_data
+ expect(run_data.dig("Log-1", 0, "outputs", 0, "item_count")).to eq(0)
+ expect(run_data.dig("Log-1", 0, "outputs", 0, "items")).to eq([])
+ expect(run_data["Code-1"]).to be_nil
+ end
+
+ it "fails the step when expression errors are logged" do
+ graph =
+ build_workflow_graph do |g|
+ g.node "trigger-1", "trigger:topic_closed"
+ g.node "code-1",
+ "action:code",
+ configuration: {
+ "code" => "throw new Error('deliberate failure');",
+ }
+ g.chain "trigger-1", "code-1"
+ end
+ workflow =
+ Fabricate(:discourse_workflows_workflow, created_by: user, published: true, **graph)
+
+ trigger_data = { topic_id: topic.id, tags: [] }
+ execution = described_class.new(workflow, "trigger-1", trigger_data).run
+
+ expect(execution.status).to eq("error")
+ code_step = execution.execution_data.find_step(node_id: "code-1")
+ expect(code_step["status"]).to eq("error")
+ end
+
+ it "continues through the regular output when onError asks to continue" do
+ graph =
+ build_workflow_graph do |g|
+ g.node "trigger-1", "trigger:topic_closed"
+ g.node "code-1",
+ "action:code",
+ configuration: {
+ "code" => "throw new Error('deliberate failure');",
+ "onError" => "continueRegularOutput",
+ }
+ g.node "code-2", "action:code", configuration: { "code" => "return $input.all();" }
+ g.chain "trigger-1", "code-1", "code-2"
+ end
+ workflow =
+ Fabricate(:discourse_workflows_workflow, created_by: user, published: true, **graph)
+
+ trigger_data = { topic_id: topic.id, tags: [] }
+ execution = described_class.new(workflow, "trigger-1", trigger_data).run
+
+ expect(execution.status).to eq("success")
+ code_1_step = execution.execution_data.find_step(node_id: "code-1")
+ expect(code_1_step["status"]).to eq("success")
+ expect(code_1_step.dig("metadata", "handled_error", "message")).to include(
+ "deliberate failure",
+ )
+
+ code_2_step = execution.execution_data.find_step(node_id: "code-2")
+ expect(code_2_step["input"].first["json"]).to include("topic_id" => topic.id)
+ end
+
+ it "routes error items through the error output when onError asks for an error branch" do
+ graph =
+ build_workflow_graph do |g|
+ g.node "trigger-1", "trigger:topic_closed"
+ g.node "code-1",
+ "action:code",
+ configuration: {
+ "code" => "throw new Error('deliberate failure');",
+ "onError" => "continueErrorOutput",
+ }
+ g.node "code-2", "action:code", configuration: { "code" => "return $input.all();" }
+ g.connect "trigger-1", "code-1"
+ g.connect "code-1", "code-2", output: 1
+ end
+ workflow =
+ Fabricate(:discourse_workflows_workflow, created_by: user, published: true, **graph)
+
+ trigger_data = { topic_id: topic.id, tags: [] }
+ execution = described_class.new(workflow, "trigger-1", trigger_data).run
+
+ expect(execution.status).to eq("success")
+ code_2_step = execution.execution_data.find_step(node_id: "code-2")
+ expect(code_2_step["input"].first["json"]).to include("topic_id" => topic.id)
+ expect(code_2_step["input"].first.dig("error", "message")).to include("deliberate failure")
+ expect(code_2_step["input"].first["pairedItem"]).to eq("item" => 0)
+ end
+
+ it "truncates long error messages" do
+ graph =
+ build_workflow_graph do |g|
+ g.node "trigger-1", "trigger:topic_closed"
+ g.node "code-1",
+ "action:code",
+ configuration: {
+ "code" => "throw new Error('x'.repeat(2000));",
+ }
+ g.chain "trigger-1", "code-1"
+ end
+ workflow =
+ Fabricate(:discourse_workflows_workflow, created_by: user, published: true, **graph)
+
+ trigger_data = { topic_id: topic.id, tags: [] }
+ execution = described_class.new(workflow, "trigger-1", trigger_data).run
+
+ expect(execution.status).to eq("error")
+ expect(execution.error.length).to be <= 1000
+ end
+
+ context "with alwaysOutputData" do
+ def chained_code_graph(always_output_data:)
+ build_workflow_graph do |g|
+ g.node "trigger-1", "trigger:topic_closed"
+ g.node "code-1",
+ "action:code",
+ configuration: {
+ "code" => "return [];",
+ "alwaysOutputData" => always_output_data,
+ }
+ g.node "code-2", "action:code", configuration: { "code" => "return $input.all();" }
+ g.chain "trigger-1", "code-1", "code-2"
+ end
+ end
+
+ let(:trigger_data) { { topic_id: topic.id, tags: [] } }
+
+ it "skips downstream when the first code returns no items" do
+ workflow =
+ Fabricate(
+ :discourse_workflows_workflow,
+ created_by: user,
+ published: true,
+ **chained_code_graph(always_output_data: false),
+ )
+
+ execution = described_class.new(workflow, "trigger-1", trigger_data).run
+
+ expect(execution.status).to eq("success")
+ expect(execution.execution_data.find_step(node_id: "code-1")["status"]).to eq("success")
+ expect(execution.execution_data.find_step(node_id: "code-2")).to be_nil
+ end
+
+ it "feeds downstream an empty item when alwaysOutputData is set" do
+ workflow =
+ Fabricate(
+ :discourse_workflows_workflow,
+ created_by: user,
+ published: true,
+ **chained_code_graph(always_output_data: true),
+ )
+
+ execution = described_class.new(workflow, "trigger-1", trigger_data).run
+
+ expect(execution.status).to eq("success")
+ code_2_step = execution.execution_data.find_step(node_id: "code-2")
+ expect(code_2_step["status"]).to eq("success")
+ expect(code_2_step["input"]).to eq(
+ [{ "json" => {}, "pairedItem" => [{ "item" => 0, "input" => 0 }] }],
+ )
+ expect(code_2_step["output"]).to eq(
+ [{ "json" => {}, "pairedItem" => [{ "item" => 0, "input" => 0 }] }],
+ )
+ end
+ end
+
+ context "with rate limiting" do
+ before { RateLimiter.enable }
+ after { RateLimiter.disable }
+
+ it "creates a rate_limited execution when limits are exceeded" do
+ SiteSetting.discourse_workflows_max_executions_per_minute_per_workflow = 1
+
+ graph = build_workflow_graph { |g| g.node "trigger-1", "trigger:topic_closed" }
+ workflow =
+ Fabricate(:discourse_workflows_workflow, created_by: user, published: true, **graph)
+
+ trigger_data = { topic_id: topic.id, tags: [] }
+
+ first_execution = described_class.new(workflow, "trigger-1", trigger_data).run
+ expect(first_execution.status).to eq("success")
+
+ second_execution = described_class.new(workflow, "trigger-1", trigger_data).run
+ expect(second_execution.status).to eq("rate_limited")
+ expect(second_execution.trigger_data).to eq("rate_limited" => true)
+ end
+ end
+
+ context "with an unavailable node" do
+ let(:unavailable_reason_key) do
+ "discourse_workflows.unavailable_reasons.test_plugin_disabled"
+ end
+
+ let(:unavailable_node_class) do
+ reason_key = unavailable_reason_key
+
+ Class.new(DiscourseWorkflows::NodeType) do
+ description(
+ name: "action:unavailable_test",
+ available: false,
+ unavailable_reason_key: -> { reason_key },
+ )
+
+ def execute(_ctx)
+ raise "should never be called"
+ end
+ end
+ end
+
+ let(:plugin) do
+ p = Plugin::Instance.new
+ p.enabled_site_setting(:discourse_workflows_enabled)
+ p
+ end
+
+ before do
+ DiscoursePluginRegistry.register_discourse_workflows_node(unavailable_node_class, plugin)
+ DiscourseWorkflows::Registry.reset_indexes!
+ end
+
+ after do
+ DiscoursePluginRegistry._raw_discourse_workflows_nodes.reject! do |h|
+ h[:value] == unavailable_node_class
+ end
+ DiscourseWorkflows::Registry.reset_indexes!
+ end
+
+ it "passes data through and records a skipped step" do
+ graph =
+ build_workflow_graph do |g|
+ g.node "trigger-1", "trigger:topic_closed", name: "Topic Closed"
+ g.node "unavailable-1", "action:unavailable_test", name: "Unavailable Node"
+ g.node "action-1",
+ "action:topic_tags",
+ name: "Topic Tags",
+ configuration: {
+ "topic_id" => "={{ $trigger.topic_id }}",
+ "tag_names" => tag.name,
+ }
+ g.chain "trigger-1", "unavailable-1", "action-1"
+ end
+ workflow =
+ Fabricate(:discourse_workflows_workflow, created_by: user, published: true, **graph)
+
+ trigger_data = { topic_id: topic.id, tags: topic.tags.pluck(:name) }
+ execution = described_class.new(workflow, "trigger-1", trigger_data).run
+
+ expect(execution.status).to eq("success")
+ expect(topic.reload.tags).to include(tag)
+
+ step = execution.execution_data.find_step(node_id: "unavailable-1")
+ expect(step["status"]).to eq("skipped")
+ expect(step["error"]).to eq(unavailable_reason_key)
+ end
+
+ it "does not execute the unavailable node" do
+ graph =
+ build_workflow_graph do |g|
+ g.node "trigger-1", "trigger:topic_closed", name: "Topic Closed"
+ g.node "unavailable-1", "action:unavailable_test", name: "Unavailable Node"
+ g.chain "trigger-1", "unavailable-1"
+ end
+ workflow =
+ Fabricate(:discourse_workflows_workflow, created_by: user, published: true, **graph)
+
+ trigger_data = { topic_id: topic.id, tags: [] }
+ execution = described_class.new(workflow, "trigger-1", trigger_data).run
+
+ expect(execution.status).to eq("success")
+ end
+ end
+
+ context "with versioned node implementations" do
+ let(:v1_node_class) do
+ Class.new(DiscourseWorkflows::NodeType) do
+ description(name: "action:executor_versioned_test", version: "1.0")
+
+ def execute(_ctx)
+ [[DiscourseWorkflows::Item.wrap("version" => "1.0")]]
+ end
+ end
+ end
+
+ let(:v2_node_class) do
+ Class.new(DiscourseWorkflows::NodeType) do
+ description(name: "action:executor_versioned_test", version: "2.0")
+
+ def execute(_ctx)
+ [[DiscourseWorkflows::Item.wrap("version" => "2.0")]]
+ end
+ end
+ end
+
+ before do
+ plugin = Plugin::Instance.new
+ DiscoursePluginRegistry.register_discourse_workflows_node(v1_node_class, plugin)
+ DiscoursePluginRegistry.register_discourse_workflows_node(v2_node_class, plugin)
+ DiscourseWorkflows::Registry.reset_indexes!
+ end
+
+ after do
+ DiscoursePluginRegistry._raw_discourse_workflows_nodes.reject! do |entry|
+ [v1_node_class, v2_node_class].include?(entry[:value])
+ end
+ DiscourseWorkflows::Registry.reset_indexes!
+ end
+
+ it "dispatches execution to the saved node type version" do
+ graph =
+ build_workflow_graph do |g|
+ g.node "trigger-1", "trigger:topic_closed", name: "Topic Closed"
+ g.node "action-1", "action:executor_versioned_test", name: "Versioned"
+ g.chain "trigger-1", "action-1"
+ end
+ graph[:nodes].find { |node| node["id"] == "action-1" }["typeVersion"] = "2.0"
+ workflow =
+ Fabricate(:discourse_workflows_workflow, created_by: user, published: true, **graph)
+
+ execution = described_class.new(workflow, "trigger-1", {}).run
+
+ expect(execution.status).to eq("success")
+ expect(execution.execution_data.entries.dig("action-1", 0, "output", 0, "json")).to eq(
+ "version" => "2.0",
+ )
+ end
+ end
+
+ context "with node result contracts" do
+ let(:raw_array_node_class) do
+ Class.new(DiscourseWorkflows::NodeType) do
+ description(name: "action:raw_result_test", version: "1.0")
+
+ def execute(exec_ctx)
+ [exec_ctx.input_items]
+ end
+ end
+ end
+
+ let(:named_outputs_node_class) do
+ Class.new(DiscourseWorkflows::NodeType) do
+ description(
+ name: "action:named_outputs_test",
+ version: "1.0",
+ outputs: [{ key: "true", label_key: "true" }, { key: "false", label_key: "false" }],
+ )
+
+ def execute(exec_ctx)
+ { "true" => exec_ctx.input_items, "false" => [] }
+ end
+ end
+ end
+
+ let(:malformed_array_node_class) do
+ Class.new(DiscourseWorkflows::NodeType) do
+ description(name: "action:malformed_array_test", version: "1.0")
+
+ def execute(exec_ctx)
+ [exec_ctx.input_items.first]
+ end
+ end
+ end
+
+ before do
+ plugin = Plugin::Instance.new
+ DiscoursePluginRegistry.register_discourse_workflows_node(raw_array_node_class, plugin)
+ DiscoursePluginRegistry.register_discourse_workflows_node(named_outputs_node_class, plugin)
+ DiscoursePluginRegistry.register_discourse_workflows_node(
+ malformed_array_node_class,
+ plugin,
+ )
+ DiscourseWorkflows::Registry.reset_indexes!
+ end
+
+ after do
+ DiscoursePluginRegistry._raw_discourse_workflows_nodes.reject! do |entry|
+ [raw_array_node_class, named_outputs_node_class, malformed_array_node_class].include?(
+ entry[:value],
+ )
+ end
+ DiscourseWorkflows::Registry.reset_indexes!
+ end
+
+ it "accepts positional output arrays" do
+ graph =
+ build_workflow_graph do |g|
+ g.node "trigger-1", "trigger:topic_closed"
+ g.node "raw-1", "action:raw_result_test", name: "Raw Result"
+ g.chain "trigger-1", "raw-1"
+ end
+ workflow =
+ Fabricate(:discourse_workflows_workflow, created_by: user, published: true, **graph)
+
+ execution = described_class.new(workflow, "trigger-1", { topic_id: topic.id }).run
+
+ expect(execution.status).to eq("success")
+ expect(
+ execution.execution_data.context_data["Raw Result"].first.dig("json", "topic_id"),
+ ).to eq(topic.id)
+ end
+
+ it "rejects named output hashes" do
+ graph =
+ build_workflow_graph do |g|
+ g.node "trigger-1", "trigger:topic_closed"
+ g.node "named-1", "action:named_outputs_test"
+ g.chain "trigger-1", "named-1"
+ end
+ workflow =
+ Fabricate(:discourse_workflows_workflow, created_by: user, published: true, **graph)
+
+ execution = described_class.new(workflow, "trigger-1", { topic_id: topic.id }).run
+
+ expect(execution.status).to eq("error")
+ expect(execution.error).to include("execute must return Array<Array<Item>>, got Hash")
+ end
+
+ it "reports contract errors for malformed positional output arrays" do
+ graph =
+ build_workflow_graph do |g|
+ g.node "trigger-1", "trigger:topic_closed"
+ g.node "malformed-1", "action:malformed_array_test"
+ g.chain "trigger-1", "malformed-1"
+ end
+ workflow =
+ Fabricate(:discourse_workflows_workflow, created_by: user, published: true, **graph)
+
+ execution = described_class.new(workflow, "trigger-1", { topic_id: topic.id }).run
+
+ expect(execution.status).to eq("error")
+ expect(execution.error).to include("execute must return Array<Array<Item>>")
+ end
+ end
+ end
+end
diff --git a/plugins/discourse-workflows/spec/lib/discourse_workflows/executor_split_out_spec.rb b/plugins/discourse-workflows/spec/lib/discourse_workflows/executor_split_out_spec.rb
new file mode 100644
index 00000000000..60a50eb7770
--- /dev/null
+++ b/plugins/discourse-workflows/spec/lib/discourse_workflows/executor_split_out_spec.rb
@@ -0,0 +1,107 @@
+# frozen_string_literal: true
+
+RSpec.describe DiscourseWorkflows::Executor do
+ fab!(:user)
+
+ describe "#run" do
+ it "splits items then loops over them in batches" do
+ graph =
+ build_workflow_graph do |g|
+ g.node "trigger-1", "trigger:manual"
+ g.node "set-fields-1",
+ "action:set_fields",
+ configuration: {
+ "mode" => "raw",
+ "include_other_fields" => false,
+ "json_output" => '{"urls": ["a.png", "b.png", "c.png"]}',
+ }
+ g.node "split-1",
+ "action:split_out",
+ name: "Split Out",
+ configuration: {
+ "field" => "urls",
+ }
+ g.node "loop-1", "flow:loop_over_items", configuration: { "batch_size" => 2 }
+ g.node "code-1",
+ "action:code",
+ configuration: {
+ "code" => "return { processed: $json.urls };",
+ }
+ g.node "done-1",
+ "action:set_fields",
+ name: "Done",
+ configuration: {
+ "mode" => "raw",
+ "include_other_fields" => false,
+ "json_output" => '{"done": true}',
+ }
+ g.chain "trigger-1", "set-fields-1", "split-1", "loop-1"
+ g.connect "loop-1", "code-1", output: "loop"
+ g.chain "code-1", "loop-1"
+ g.connect "loop-1", "done-1", output: "done"
+ end
+ workflow =
+ Fabricate(:discourse_workflows_workflow, created_by: user, published: true, **graph)
+
+ execution = described_class.new(workflow, "trigger-1", {}).run
+
+ expect(execution.status).to eq("success")
+
+ split_out_output = execution.execution_data.context_data["Split Out"]
+ expect(split_out_output).to be_an(Array)
+ expect(split_out_output.length).to eq(3)
+ expect(split_out_output.map { |i| i["json"]["urls"] }).to eq(%w[a.png b.png c.png])
+
+ done_output = execution.execution_data.context_data["Done"]
+ expect(done_output).to be_an(Array)
+ end
+
+ it "records a hint and emits no items when the split field is missing" do
+ graph =
+ build_workflow_graph do |g|
+ g.node "trigger-1", "trigger:manual"
+ g.node "set-fields-1",
+ "action:set_fields",
+ configuration: {
+ "mode" => "raw",
+ "include_other_fields" => false,
+ "json_output" => '{"name": "test"}',
+ }
+ g.node "split-1",
+ "action:split_out",
+ name: "Split Out",
+ configuration: {
+ "field" => "urls",
+ }
+ g.node "done-1",
+ "action:set_fields",
+ name: "Done",
+ configuration: {
+ "mode" => "raw",
+ "include_other_fields" => false,
+ "json_output" => '{"done": true}',
+ }
+ g.chain "trigger-1", "set-fields-1", "split-1", "done-1"
+ end
+ workflow =
+ Fabricate(:discourse_workflows_workflow, created_by: user, published: true, **graph)
+
+ execution = described_class.new(workflow, "trigger-1", {}).run
+
+ expect(execution.status).to eq("success")
+ expect(execution.execution_data.context_data["Split Out"]).to eq([])
+ expect(execution.execution_data.context_data).not_to have_key("Done")
+
+ split_step = execution.execution_data.find_step(node_id: "split-1")
+ expect(split_step["output"]).to eq([])
+ expect(split_step.dig("metadata", "hints")).to eq(
+ [
+ {
+ "message" => "The field 'urls' wasn't found in any input item.",
+ "location" => "outputPane",
+ },
+ ],
+ )
+ end
+ end
+end
diff --git a/plugins/discourse-workflows/spec/lib/discourse_workflows/executor_topic_spec.rb b/plugins/discourse-workflows/spec/lib/discourse_workflows/executor_topic_spec.rb
new file mode 100644
index 00000000000..dca96878937
--- /dev/null
+++ b/plugins/discourse-workflows/spec/lib/discourse_workflows/executor_topic_spec.rb
@@ -0,0 +1,54 @@
+# frozen_string_literal: true
+
+RSpec.describe DiscourseWorkflows::Executor do
+ fab!(:admin)
+ fab!(:category)
+
+ before { SiteSetting.tagging_enabled = true }
+
+ describe "#run" do
+ it "creates a topic from trigger data" do
+ graph =
+ build_workflow_graph do |g|
+ g.node "trigger-1", "trigger:manual"
+ g.node "action-1",
+ "action:topic",
+ name: "Create Topic",
+ configuration: {
+ "operation" => "create",
+ "title" => "={{ $trigger.title }}",
+ "raw" => "={{ $trigger.raw }}",
+ "category_id" => "={{ $trigger.category_id }}",
+ "tag_names" => "={{ $trigger.tags }}",
+ "actor_username" => "={{ $trigger.username }}",
+ }
+ g.chain "trigger-1", "action-1"
+ end
+ workflow =
+ Fabricate(:discourse_workflows_workflow, created_by: admin, published: true, **graph)
+
+ trigger_data = {
+ title: "Created from workflow",
+ raw: "Generated body",
+ category_id: category.id,
+ tags: %w[alpha beta],
+ username: admin.username,
+ }
+
+ execution = described_class.new(workflow, "trigger-1", trigger_data).run
+ topic = Topic.last
+
+ expect(execution.status).to eq("success")
+ expect(topic.title).to eq("Created from workflow")
+ expect(topic.first_post.raw).to eq("Generated body")
+ expect(topic.category_id).to eq(category.id)
+ expect(topic.user_id).to eq(admin.id)
+ expect(topic.tags.pluck(:name)).to contain_exactly("alpha", "beta")
+ expect(execution.execution_data.context_data["Create Topic"].first["json"]).to include(
+ "topic" => include("id" => topic.id, "title" => topic.title, "category_id" => category.id),
+ "post_id" => topic.first_post.id,
+ "post_number" => topic.first_post.post_number,
+ )
+ end
+ end
+end
diff --git a/plugins/discourse-workflows/spec/lib/discourse_workflows/executor_wait_spec.rb b/plugins/discourse-workflows/spec/lib/discourse_workflows/executor_wait_spec.rb
new file mode 100644
index 00000000000..515600a5dd4
--- /dev/null
+++ b/plugins/discourse-workflows/spec/lib/discourse_workflows/executor_wait_spec.rb
@@ -0,0 +1,221 @@
+# frozen_string_literal: true
+
+RSpec.describe DiscourseWorkflows::Executor do
+ fab!(:user)
+
+ describe "pause on wait request" do
+ it "pauses execution and stores the waiting node id when a node signals wait" do
+ graph =
+ build_workflow_graph do |g|
+ g.node "trigger-1", "trigger:manual"
+ g.node "wait-1", "flow:wait", configuration: { "resume" => "webhook" }
+ g.node "after-1",
+ "action:set_fields",
+ name: "After",
+ configuration: {
+ "mode" => "raw",
+ "include_other_fields" => true,
+ "json_output" => '{"done": "true"}',
+ }
+ g.chain "trigger-1", "wait-1", "after-1"
+ end
+ workflow =
+ Fabricate(:discourse_workflows_workflow, created_by: user, published: true, **graph)
+
+ freeze_time do
+ execution = described_class.new(workflow, "trigger-1", {}).run
+
+ expect(execution).to have_attributes(
+ status: "waiting",
+ waiting_node_id: "wait-1",
+ finished_at: nil,
+ )
+ expect(execution.waiting_until).to eq_time(
+ described_class::MAX_WAIT_DURATION_SECONDS.seconds.from_now,
+ )
+
+ waiting_step = execution.execution_data.find_step(node_id: "wait-1")
+ expect(waiting_step["status"]).to eq("waiting")
+
+ expect(execution.execution_data.context_data).not_to have_key("After")
+ end
+ end
+
+ it "applies the default wait ceiling to form waits" do
+ graph =
+ build_workflow_graph do |g|
+ g.node "trigger-1", "trigger:manual"
+ g.node "form-1",
+ "action:form",
+ configuration: {
+ "form_title" => "Approval",
+ "form_fields" => [{ "field_label" => "Reason", "field_type" => "text" }],
+ }
+ g.chain "trigger-1", "form-1"
+ end
+ workflow =
+ Fabricate(:discourse_workflows_workflow, created_by: user, published: true, **graph)
+
+ allow(MessageBus).to receive(:publish)
+
+ freeze_time do
+ execution = described_class.new(workflow, "trigger-1", {}).run
+
+ expect(execution).to have_attributes(status: "waiting", waiting_node_id: "form-1")
+ expect(execution.waiting_until).to eq_time(
+ described_class::MAX_WAIT_DURATION_SECONDS.seconds.from_now,
+ )
+ end
+ end
+
+ it "caps explicit timer waits at the executor ceiling" do
+ graph =
+ build_workflow_graph do |g|
+ g.node "trigger-1", "trigger:manual"
+ g.node "wait-1",
+ "flow:wait",
+ configuration: {
+ "resume" => "time_interval",
+ "wait_amount" => 60,
+ "wait_unit" => "days",
+ }
+ g.chain "trigger-1", "wait-1"
+ end
+ workflow =
+ Fabricate(:discourse_workflows_workflow, created_by: user, published: true, **graph)
+
+ freeze_time do
+ execution = described_class.new(workflow, "trigger-1", {}).run
+
+ expect(execution).to have_attributes(status: "waiting", waiting_node_id: "wait-1")
+ expect(execution.waiting_until).to eq_time(
+ described_class::MAX_WAIT_DURATION_SECONDS.seconds.from_now,
+ )
+ end
+ end
+
+ it "persists explicit timer waits" do
+ graph =
+ build_workflow_graph do |g|
+ g.node "trigger-1", "trigger:manual"
+ g.node "wait-1",
+ "flow:wait",
+ configuration: {
+ "resume" => "time_interval",
+ "wait_amount" => 2,
+ "wait_unit" => "hours",
+ }
+ g.chain "trigger-1", "wait-1"
+ end
+ workflow =
+ Fabricate(:discourse_workflows_workflow, created_by: user, published: true, **graph)
+
+ freeze_time do
+ execution = described_class.new(workflow, "trigger-1", {}).run
+
+ expect(execution).to have_attributes(status: "waiting", waiting_node_id: "wait-1")
+ expect(execution.waiting_until).to eq_time(2.hours.from_now)
+ end
+ end
+
+ it "caps explicit webhook waits at the executor ceiling" do
+ graph =
+ build_workflow_graph do |g|
+ g.node "trigger-1", "trigger:manual"
+ g.node "wait-1",
+ "flow:wait",
+ configuration: {
+ "resume" => "webhook",
+ "limit_wait_time" => true,
+ "timeout_amount" => 60,
+ "timeout_unit" => "days",
+ }
+ g.chain "trigger-1", "wait-1"
+ end
+ workflow =
+ Fabricate(:discourse_workflows_workflow, created_by: user, published: true, **graph)
+
+ freeze_time do
+ execution = described_class.new(workflow, "trigger-1", {}).run
+
+ expect(execution).to have_attributes(status: "waiting", waiting_node_id: "wait-1")
+ expect(execution.waiting_until).to eq_time(
+ described_class::MAX_WAIT_DURATION_SECONDS.seconds.from_now,
+ )
+ end
+ end
+
+ it "persists bounded webhook waits" do
+ graph =
+ build_workflow_graph do |g|
+ g.node "trigger-1", "trigger:manual"
+ g.node "wait-1",
+ "flow:wait",
+ configuration: {
+ "resume" => "webhook",
+ "limit_wait_time" => true,
+ "timeout_amount" => 3,
+ "timeout_unit" => "hours",
+ }
+ g.chain "trigger-1", "wait-1"
+ end
+ workflow =
+ Fabricate(:discourse_workflows_workflow, created_by: user, published: true, **graph)
+
+ freeze_time do
+ execution = described_class.new(workflow, "trigger-1", {}).run
+
+ expect(execution).to have_attributes(status: "waiting", waiting_node_id: "wait-1")
+ expect(execution.waiting_until).to eq_time(3.hours.from_now)
+ end
+ end
+ end
+
+ describe ".resume" do
+ fab!(:completed_execution) { Fabricate(:discourse_workflows_execution, status: :success) }
+
+ it "resumes a waiting execution and continues to downstream nodes" do
+ graph =
+ build_workflow_graph do |g|
+ g.node "trigger-1", "trigger:manual"
+ g.node "wait-1", "flow:wait", configuration: { "resume" => "webhook" }
+ g.node "after-1",
+ "action:set_fields",
+ name: "After",
+ configuration: {
+ "mode" => "raw",
+ "include_other_fields" => true,
+ "json_output" => '{"done": "true"}',
+ }
+ g.chain "trigger-1", "wait-1", "after-1"
+ end
+ workflow =
+ Fabricate(:discourse_workflows_workflow, created_by: user, published: true, **graph)
+
+ execution = described_class.new(workflow, "trigger-1", {}).run
+ expect(execution.status).to eq("waiting")
+
+ response_items = [{ "json" => { "approved" => true } }]
+ claimed = DiscourseWorkflows::Execution.claim_for_resume(execution)
+ resumed = DiscourseWorkflows::Executor.resume(claimed, response_items)
+
+ expect(resumed).to have_attributes(
+ status: "success",
+ finished_at: be_present,
+ waiting_node_id: nil,
+ )
+
+ after_output = resumed.execution_data.context_data["After"]
+ expect(after_output).to be_an(Array)
+ expect(after_output.first["json"]).to include("approved" => true, "done" => "true")
+ end
+
+ it "raises when the execution has not been claimed for resume" do
+ response_items = [{ "json" => { "approved" => true } }]
+
+ expect {
+ DiscourseWorkflows::Executor.resume(completed_execution, response_items)
+ }.to raise_error(ArgumentError, /Cannot resume execution/)
+ end
+ end
+end
diff --git a/plugins/discourse-workflows/spec/lib/discourse_workflows/expression_context_schema_spec.rb b/plugins/discourse-workflows/spec/lib/discourse_workflows/expression_context_schema_spec.rb
new file mode 100644
index 00000000000..da1fa54cdbf
--- /dev/null
+++ b/plugins/discourse-workflows/spec/lib/discourse_workflows/expression_context_schema_spec.rb
@@ -0,0 +1,185 @@
+# frozen_string_literal: true
+
+RSpec.describe DiscourseWorkflows::ExpressionContextSchema do
+ describe ".to_hash" do
+ it "returns a hash with environment, node_reference_shape, and item_prefix" do
+ schema = described_class.to_hash
+ expect(schema).to have_key(:environment)
+ expect(schema).to have_key(:node_reference_shape)
+ expect(schema).to have_key(:item_prefix)
+ end
+
+ it "declares $site_settings, $vars, $current_user, $execution as environment symbols" do
+ symbols = described_class.environment_symbols.keys
+ expect(symbols).to contain_exactly("$site_settings", "$vars", "$current_user", "$execution")
+ end
+
+ it "declares $current_user fields matching JsSandbox#build_current_user" do
+ fields = described_class.environment_symbols["$current_user"][:fields]
+ expect(fields.keys).to contain_exactly("id", "username")
+ end
+
+ it "declares $execution fields matching ExecutionState#execution_variables" do
+ fields = described_class.environment_symbols["$execution"][:fields]
+ expect(fields.keys).to contain_exactly(
+ "id",
+ "workflow_id",
+ "workflow_name",
+ "resume_url",
+ "resumeFormUrl",
+ )
+ end
+
+ it "marks resume_url as conditionally visible" do
+ field = described_class.environment_symbols.dig("$execution", :fields, "resume_url")
+ expect(field[:display_options]).to eq(
+ show: {
+ node_present: [{ type: "flow:wait", parameters: { resume: "webhook" } }],
+ },
+ )
+ end
+
+ it "marks resumeFormUrl as conditionally visible" do
+ field = described_class.environment_symbols.dig("$execution", :fields, "resumeFormUrl")
+ expect(field[:display_options]).to eq(
+ show: {
+ node_present: [{ type: "action:form", parameters: { page_type: "page" } }],
+ },
+ )
+ end
+
+ it "marks $current_user as provided_by_trigger" do
+ current_user = described_class.environment_symbols["$current_user"]
+ expect(current_user[:provided_by_trigger]).to eq(true)
+ end
+
+ it "declares node_reference_shape with item.json and context" do
+ shape = described_class.node_reference_shape
+ expect(shape).to eq(item: { json: :object }, context: :object)
+ end
+
+ it "declares $json as the item prefix" do
+ expect(described_class.item_prefix).to eq("$json")
+ end
+ end
+
+ describe "backend alignment" do
+ fab!(:user)
+
+ it "JsSandbox exposes core environment symbols" do
+ context = { "$trigger" => {} }
+ sandbox = DiscourseWorkflows::JsSandbox.new(context, user: user)
+
+ # $execution is injected by ExpressionResolver, not JsSandbox directly
+ sandbox_symbols = %w[$site_settings $vars $current_user]
+ sandbox_symbols.each do |symbol|
+ result = sandbox.eval("typeof #{symbol}")
+ expect(result).not_to eq("undefined"),
+ "expected #{symbol} to be defined in JsSandbox, got undefined"
+ end
+ ensure
+ sandbox&.dispose
+ end
+
+ it "JsSandbox $current_user shape matches schema fields" do
+ context = { "$trigger" => {} }
+ sandbox = DiscourseWorkflows::JsSandbox.new(context, user: user)
+
+ schema_fields = described_class.environment_symbols["$current_user"][:fields]
+ schema_fields.each_key do |field_name|
+ result = sandbox.eval("$current_user.#{field_name}")
+ expect(result).not_to be_nil, "expected $current_user.#{field_name} to be defined, got nil"
+ end
+ ensure
+ sandbox&.dispose
+ end
+
+ it "ExpressionResolver $() returns node output and context accessors" do
+ context = {
+ "$trigger" => {
+ },
+ "$json" => {
+ },
+ "Test Node" => [{ "json" => { "data" => 1 } }],
+ "__node_contexts" => {
+ "Test Node" => {
+ "approved" => true,
+ },
+ },
+ }
+
+ sandbox = DiscourseWorkflows::JsSandbox.new(context, user: user)
+ resolver = DiscourseWorkflows::ExpressionResolver.new(context, user: user, sandbox: sandbox)
+
+ item_json = resolver.resolve("={{ $('Test Node').first().json.data }}")
+ expect(item_json).to eq(1)
+
+ node_context = resolver.resolve('={{ $("Test Node").context.approved }}')
+ expect(node_context).to eq(true)
+ ensure
+ resolver&.dispose
+ sandbox&.dispose
+ end
+
+ it "ExpressionResolver exposes $execution" do
+ execution =
+ Fabricate(:discourse_workflows_execution, status: :running, started_at: Time.current)
+
+ context =
+ DiscourseWorkflows::Executor::ExecutionContext.new(
+ workflow: execution.workflow,
+ trigger_data: {
+ },
+ user: user,
+ execution: execution,
+ )
+ context.reset!(resume_token: SecureRandom.uuid)
+
+ resolver_ctx = context.resolver_context.merge("$json" => {})
+ sandbox = DiscourseWorkflows::JsSandbox.new(resolver_ctx, user: user)
+ resolver =
+ DiscourseWorkflows::ExpressionResolver.new(resolver_ctx, user: user, sandbox: sandbox)
+
+ result = resolver.resolve("={{ $execution.workflow_id }}")
+ expect(result).to eq(execution.workflow.id)
+ ensure
+ resolver&.dispose
+ sandbox&.dispose
+ end
+
+ it "ExpressionResolver exposes current-input helpers" do
+ context = {
+ "$json" => {
+ "name" => "current",
+ },
+ "__input_item" => {
+ "json" => {
+ "name" => "current",
+ },
+ },
+ "__input_items" => [
+ { "json" => { "name" => "first" } },
+ { "json" => { "name" => "last" } },
+ ],
+ "__input_params" => {
+ "mode" => "test",
+ },
+ "__input_context" => {
+ "noItemsLeft" => true,
+ },
+ "$itemIndex" => 1,
+ }
+ sandbox = DiscourseWorkflows::JsSandbox.new(context, user: user)
+ resolver = DiscourseWorkflows::ExpressionResolver.new(context, user: user, sandbox: sandbox)
+
+ expect(resolver.resolve("={{ $input.first().json.name }}")).to eq("first")
+ expect(resolver.resolve("={{ $input.last().json.name }}")).to eq("last")
+ expect(resolver.resolve("={{ $input.params.mode }}")).to eq("test")
+ expect(resolver.resolve("={{ $input.context.noItemsLeft }}")).to eq(true)
+ expect(resolver.resolve("={{ $itemIndex }}")).to eq(1)
+ ensure
+ resolver&.dispose
+ sandbox&.dispose
+ end
+ end
+end
diff --git a/plugins/discourse-workflows/spec/lib/discourse_workflows/expression_resolver_spec.rb b/plugins/discourse-workflows/spec/lib/discourse_workflows/expression_resolver_spec.rb
new file mode 100644
index 00000000000..36e9fded45e
--- /dev/null
+++ b/plugins/discourse-workflows/spec/lib/discourse_workflows/expression_resolver_spec.rb
@@ -0,0 +1,680 @@
+# frozen_string_literal: true
+
+RSpec.describe DiscourseWorkflows::ExpressionResolver do
+ subject(:resolver) { build_resolver(context.merge("$json" => context["$trigger"])) }
+
+ fab!(:api_url_variable) do
+ Fabricate(:discourse_workflows_variable, key: "API_URL", value: "https://example.com")
+ end
+ fab!(:prefix_variable) { Fabricate(:discourse_workflows_variable, key: "PREFIX", value: "hello") }
+
+ let(:context) { { "$trigger" => { "topic_id" => 42, "tags" => %w[bug help] } } }
+
+ before do
+ @resolvers_under_test = []
+ @sandboxes_under_test = []
+ end
+
+ after do
+ @resolvers_under_test.each(&:dispose)
+ @sandboxes_under_test.each(&:dispose)
+ end
+
+ def build_resolver(ctx, **kwargs)
+ sandbox = DiscourseWorkflows::JsSandbox.new(ctx)
+ @sandboxes_under_test << sandbox
+ resolver = described_class.new(ctx, sandbox: sandbox, **kwargs)
+ @resolvers_under_test << resolver
+ resolver
+ end
+
+ describe "#resolve" do
+ it "returns non-string values as-is" do
+ expect(resolver.resolve(42)).to eq(42)
+ expect(resolver.resolve(true)).to be(true)
+ expect(resolver.resolve(nil)).to be_nil
+ end
+
+ it "returns fixed strings as-is" do
+ expect(resolver.resolve("hello")).to eq("hello")
+ end
+
+ it "resolves context dot-path expressions preserving type" do
+ expect(resolver.resolve("={{ $trigger.topic_id }}")).to eq(42)
+ end
+
+ it "resolves $json expressions preserving type" do
+ expect(resolver.resolve("={{ $json.topic_id }}")).to eq(42)
+ end
+
+ it "exposes $input.item as the current input item" do
+ expect(resolver.resolve("={{ $input.item.json.topic_id }}")).to eq(42)
+ end
+
+ it "allows resolving $input without cloning function properties" do
+ result = resolver.resolve("={{ $input }}")
+
+ expect(result["item"]["json"]["topic_id"]).to eq(42)
+ end
+
+ it "resolves $site_settings expressions" do
+ SiteSetting.title = "My Forum"
+ expect(resolver.resolve("={{ $site_settings.title }}")).to eq("My Forum")
+ end
+
+ it "handles mixed literal and expression" do
+ expect(resolver.resolve("=topic-{{ $trigger.topic_id }}-closed")).to eq("topic-42-closed")
+ end
+
+ it "handles multiple expressions" do
+ expect(resolver.resolve("={{ $trigger.topic_id }}-{{ $json.topic_id }}")).to eq("42-42")
+ end
+
+ it "resolves node output references preserving type" do
+ node_context = {
+ "Previous Step" => [{ "json" => { "topic_id" => 99, "tags" => %w[dev ops] } }],
+ }
+
+ node_resolver = build_resolver(node_context.merge("$json" => context["$trigger"]))
+
+ expect(node_resolver.resolve("={{ $('Previous Step').first().json.topic_id }}")).to eq(99)
+ end
+
+ it "resolves node output references through pairedItem lineage" do
+ node_context = {
+ "$json" => {
+ "id" => 2,
+ },
+ "$itemIndex" => 0,
+ "__current_node_id" => "set",
+ "__input_item" => {
+ "json" => {
+ "id" => 2,
+ },
+ "pairedItem" => {
+ "item" => 1,
+ },
+ },
+ "__input_items" => [{ "json" => { "id" => 2 }, "pairedItem" => { "item" => 1 } }],
+ "__input_sources" => [{ "node_name" => "Filter", "output_index" => 0 }],
+ "Split" => [
+ { "json" => { "id" => 1, "label" => "first" }, "pairedItem" => { "item" => 0 } },
+ { "json" => { "id" => 2, "label" => "second" }, "pairedItem" => { "item" => 0 } },
+ ],
+ "__node_runs" => {
+ "Split" => [
+ {
+ "outputs" => [
+ [
+ { "json" => { "id" => 1, "label" => "first" }, "pairedItem" => { "item" => 0 } },
+ { "json" => { "id" => 2, "label" => "second" }, "pairedItem" => { "item" => 0 } },
+ ],
+ ],
+ "input_sources" => [{ "node_name" => "Source", "output_index" => 0 }],
+ },
+ ],
+ "Filter" => [
+ {
+ "outputs" => [[{ "json" => { "id" => 2 }, "pairedItem" => { "item" => 1 } }]],
+ "input_sources" => [{ "node_name" => "Split", "output_index" => 0 }],
+ },
+ ],
+ },
+ }
+ node_resolver = build_resolver(node_context)
+
+ expect(node_resolver.resolve("={{ $('Split').item.json.label }}")).to eq("second")
+ end
+
+ it "does not guess an item when pairedItem lineage data is unavailable" do
+ node_context = {
+ "$json" => {
+ "id" => 2,
+ },
+ "$itemIndex" => 0,
+ "__current_node_id" => "set",
+ "__input_sources" => [{ "node_name" => "Code", "output_index" => 0 }],
+ "Split" => [{ "json" => { "label" => "first" } }, { "json" => { "label" => "second" } }],
+ "__node_runs" => {
+ "Split" => [
+ {
+ "outputs" => [
+ [{ "json" => { "label" => "first" } }, { "json" => { "label" => "second" } }],
+ ],
+ "input_sources" => [{ "node_name" => "Source", "output_index" => 0 }],
+ },
+ ],
+ "Code" => [
+ {
+ "outputs" => [[{ "json" => { "id" => 2 } }]],
+ "input_sources" => [{ "node_name" => "Split", "output_index" => 0 }],
+ },
+ ],
+ },
+ }
+ node_resolver = build_resolver(node_context)
+
+ expect(node_resolver.resolve("={{ $('Split').item.json.label }}")).to be_nil
+ expect(node_resolver.expression_errors.last[:error]).to include(
+ "Info for expression missing from previous node",
+ )
+ end
+
+ it "defaults $().all() to the connected output branch" do
+ node_context = {
+ "$json" => {
+ },
+ "__current_node_id" => "set",
+ "__input_sources" => [{ "node_name" => "If", "output_index" => 1 }],
+ "If" => [{ "json" => { "branch" => "true" } }, { "json" => { "branch" => "false" } }],
+ "__node_runs" => {
+ "If" => [
+ {
+ "outputs" => [
+ [{ "json" => { "branch" => "true" } }],
+ [{ "json" => { "branch" => "false" } }],
+ ],
+ },
+ ],
+ },
+ }
+ node_resolver = build_resolver(node_context)
+
+ expect(node_resolver.resolve("={{ $('If').all()[0].json.branch }}")).to eq("false")
+ expect(node_resolver.resolve("={{ $('If').all(0)[0].json.branch }}")).to eq("true")
+ expect(node_resolver.resolve("={{ $('If').all(2).length }}")).to eq(0)
+ end
+
+ it "uses the active resolver context when a shared sandbox is reused" do
+ sandbox = DiscourseWorkflows::JsSandbox.new({})
+ stale_resolver = described_class.new({ "$json" => { "id" => 1 } }, sandbox: sandbox)
+ stale_resolver.resolve("={{ $json.id }}")
+ stale_resolver.dispose
+
+ active_context = {
+ "$json" => {
+ "id" => 2,
+ },
+ "$itemIndex" => 0,
+ "__current_node_id" => "set",
+ "__input_item" => {
+ "json" => {
+ "id" => 2,
+ },
+ "pairedItem" => {
+ "item" => 1,
+ },
+ },
+ "__input_items" => [{ "json" => { "id" => 2 }, "pairedItem" => { "item" => 1 } }],
+ "__input_sources" => [{ "node_name" => "Filter", "output_index" => 0 }],
+ "Split" => [{ "json" => { "label" => "first" } }, { "json" => { "label" => "second" } }],
+ "__node_runs" => {
+ "Split" => [
+ {
+ "outputs" => [
+ [{ "json" => { "label" => "first" } }, { "json" => { "label" => "second" } }],
+ ],
+ "input_sources" => [{ "node_name" => "Source", "output_index" => 0 }],
+ },
+ ],
+ "Filter" => [
+ {
+ "outputs" => [[{ "json" => { "id" => 2 }, "pairedItem" => { "item" => 1 } }]],
+ "input_sources" => [{ "node_name" => "Split", "output_index" => 0 }],
+ },
+ ],
+ },
+ }
+ active_resolver = described_class.new(active_context, sandbox: sandbox)
+
+ expect(active_resolver.resolve("={{ $('Split').item.json.label }}")).to eq("second")
+ ensure
+ active_resolver&.dispose
+ sandbox&.dispose
+ end
+
+ it "does not guess when pairedItem lineage matches multiple previous items" do
+ node_context = {
+ "$json" => {
+ "merged" => true,
+ },
+ "$itemIndex" => 0,
+ "__current_node_id" => "set",
+ "__input_item" => {
+ "json" => {
+ "merged" => true,
+ },
+ "pairedItem" => {
+ "item" => 0,
+ },
+ },
+ "__input_items" => [{ "json" => { "merged" => true }, "pairedItem" => { "item" => 0 } }],
+ "__input_sources" => [{ "node_name" => "Merge", "output_index" => 0 }],
+ "Split" => [{ "json" => { "label" => "first" } }, { "json" => { "label" => "second" } }],
+ "__node_runs" => {
+ "Split" => [
+ {
+ "outputs" => [
+ [{ "json" => { "label" => "first" } }, { "json" => { "label" => "second" } }],
+ ],
+ "input_sources" => [{ "node_name" => "Source", "output_index" => 0 }],
+ },
+ ],
+ "Filter 1" => [
+ {
+ "outputs" => [
+ [{ "json" => { "label" => "first" }, "pairedItem" => { "item" => 0 } }],
+ ],
+ "input_sources" => [{ "node_name" => "Split", "output_index" => 0 }],
+ },
+ ],
+ "Filter 2" => [
+ {
+ "outputs" => [
+ [{ "json" => { "label" => "second" }, "pairedItem" => { "item" => 1 } }],
+ ],
+ "input_sources" => [{ "node_name" => "Split", "output_index" => 0 }],
+ },
+ ],
+ "Merge" => [
+ {
+ "outputs" => [
+ [
+ {
+ "json" => {
+ "merged" => true,
+ },
+ "pairedItem" => [{ "input" => 0, "item" => 0 }, { "input" => 1, "item" => 0 }],
+ },
+ ],
+ ],
+ "input_sources" => [
+ { "node_name" => "Filter 1", "output_index" => 0 },
+ { "node_name" => "Filter 2", "output_index" => 0 },
+ ],
+ },
+ ],
+ },
+ }
+ node_resolver = build_resolver(node_context)
+
+ expect { node_resolver.resolve("={{ $('Split').item.json.label }}") }.to raise_error(
+ RuntimeError,
+ "Multiple matching items for expression",
+ )
+ end
+
+ it "resolves node context references preserving type" do
+ node_context = { "__node_contexts" => { "Approval" => { "approved" => true } } }
+ node_resolver = build_resolver(context.merge(node_context, "$json" => context["$trigger"]))
+
+ expect(node_resolver.resolve('={{ $("Approval").context["approved"] }}')).to be(true)
+ end
+
+ it "preserves array type for single-expression values" do
+ expect(resolver.resolve("={{ $trigger.tags }}")).to eq(%w[bug help])
+ end
+
+ it "formats arrays when interpolating into a larger string" do
+ expect(resolver.resolve("=tags: {{ $trigger.tags }}")).to eq("tags: bug, help")
+ end
+
+ it "returns nil for missing paths" do
+ expect(resolver.resolve("={{ $trigger.nonexistent }}")).to be_nil
+ end
+
+ it "returns nil for missing node output paths" do
+ node_resolver = build_resolver(context.merge("$json" => context["$trigger"]))
+
+ expect(node_resolver.resolve("={{ $('Missing Step').item.json.topic_id }}")).to be_nil
+ end
+
+ it "returns nil for missing node context paths" do
+ node_resolver = build_resolver(context.merge("$json" => context["$trigger"]))
+
+ expect(node_resolver.resolve('={{ $("Missing Step").context["approved"] }}')).to be_nil
+ end
+
+ it "returns nil for invalid site settings" do
+ expect(resolver.resolve("={{ $site_settings.nonexistent_setting_xyz }}")).to be_nil
+ end
+
+ it "returns an empty string for invalid site settings in mixed templates" do
+ expect(resolver.resolve("=prefix-{{ $site_settings.nonexistent_setting_xyz }}")).to eq(
+ "prefix-",
+ )
+ end
+
+ it "resolves $vars expressions" do
+ expect(resolver.resolve("={{ $vars.API_URL }}")).to eq("https://example.com")
+ end
+
+ it "returns nil for missing $vars" do
+ expect(resolver.resolve("={{ $vars.nonexistent }}")).to be_nil
+ end
+
+ it "resolves $vars in mixed templates" do
+ expect(resolver.resolve("={{ $vars.PREFIX }}-world")).to eq("hello-world")
+ end
+ end
+
+ describe "JavaScript expressions" do
+ it "evaluates .join() on arrays" do
+ expect(resolver.resolve("={{ $json.tags.join(', ') }}")).to eq("bug, help")
+ end
+
+ it "evaluates JSON.stringify()" do
+ result = resolver.resolve("={{ JSON.stringify($json.tags) }}")
+ expect(result).to eq('["bug","help"]')
+ end
+
+ it "evaluates .length on arrays" do
+ expect(resolver.resolve("={{ $json.tags.length }}")).to eq(2)
+ end
+
+ it "evaluates .includes() on arrays" do
+ expect(resolver.resolve("={{ $json.tags.includes('bug') }}")).to be(true)
+ expect(resolver.resolve("={{ $json.tags.includes('nope') }}")).to be(false)
+ end
+
+ it "evaluates ternary expressions" do
+ expect(resolver.resolve("={{ $json.topic_id > 10 ? 'high' : 'low' }}")).to eq("high")
+ end
+
+ it "evaluates arithmetic" do
+ expect(resolver.resolve("={{ $json.topic_id + 8 }}")).to eq(50)
+ end
+
+ it "evaluates string concatenation" do
+ expect(resolver.resolve("={{ 'topic-' + $json.topic_id }}")).to eq("topic-42")
+ end
+
+ it "evaluates .toUpperCase() on strings" do
+ ctx = { "$trigger" => { "name" => "hello" }, "$json" => { "name" => "hello" } }
+ r = build_resolver(ctx)
+ expect(r.resolve("={{ $json.name.toUpperCase() }}")).to eq("HELLO")
+ end
+
+ it "evaluates parseInt and parseFloat" do
+ ctx = { "$json" => { "val" => "42.5" } }
+ r = build_resolver(ctx)
+ expect(r.resolve("={{ parseInt($json.val) }}")).to eq(42)
+ expect(r.resolve("={{ parseFloat($json.val) }}")).to eq(42.5)
+ end
+
+ it "returns nil for JS errors" do
+ expect(resolver.resolve("={{ $json.nonexistent.join(', ') }}")).to be_nil
+ end
+
+ it "works in template interpolation" do
+ expect(resolver.resolve("=tags: {{ $json.tags.join(' | ') }}")).to eq("tags: bug | help")
+ end
+
+ it "evaluates node output references with JS methods" do
+ node_context = { "Previous Step" => [{ "json" => { "items" => %w[a b c] } }] }
+ r = build_resolver(node_context.merge("$json" => context["$trigger"]))
+ expect(r.resolve("={{ $('Previous Step').first().json.items.join('-') }}")).to eq("a-b-c")
+ end
+ end
+
+ describe "#resolve_hash" do
+ it "resolves all string values in a hash" do
+ config = {
+ "topic_id" => "={{ $trigger.topic_id }}",
+ "tag_name" => "resolved",
+ "nested" => {
+ "value" => "={{ $json.topic_id }}",
+ },
+ }
+
+ result = resolver.resolve_hash(config)
+ expect(result).to include(
+ "topic_id" => 42,
+ "tag_name" => "resolved",
+ "nested" => include("value" => 42),
+ )
+ end
+
+ it "resolves expressions inside arrays of hashes" do
+ result = resolver.resolve_hash({ "items" => [{ "value" => "={{ $trigger.topic_id }}" }] })
+ expect(result["items"][0]["value"]).to eq(42)
+ end
+
+ it "resolves expressions inside nested arrays" do
+ result = resolver.resolve_hash({ "items" => [["={{ $trigger.topic_id }}"]] })
+ expect(result["items"][0][0]).to eq(42)
+ end
+ end
+
+ describe "#with_item" do
+ it "rebinds $json for the duration of the block" do
+ resolver = build_resolver(context.merge("$json" => context["$trigger"]))
+ result_inside = nil
+ result_outside_before = resolver.resolve("={{ $json.topic_id }}")
+
+ resolver.with_item({ "topic_id" => 999 }) do
+ result_inside = resolver.resolve("={{ $json.topic_id }}")
+ end
+
+ result_outside_after = resolver.resolve("={{ $json.topic_id }}")
+
+ expect(result_outside_before).to eq(42)
+ expect(result_inside).to eq(999)
+ expect(result_outside_after).to eq(42)
+ end
+
+ it "keeps $input.item and $itemIndex in sync for the duration of the block" do
+ resolver =
+ build_resolver(
+ context.merge(
+ "$json" => context["$trigger"],
+ "__input_item" => {
+ "json" => context["$trigger"],
+ },
+ "__input_items" => [
+ { "json" => context["$trigger"] },
+ { "json" => { "topic_id" => 999 } },
+ ],
+ "__input_params" => {
+ "operation" => "test",
+ },
+ ),
+ )
+ result_inside = nil
+
+ resolver.with_item({ "json" => { "topic_id" => 999 } }, item_index: 1) do
+ result_inside =
+ resolver.resolve(
+ "={{ [$json.topic_id, $input.item.json.topic_id, $input.first().json.topic_id, $input.last().json.topic_id, $input.params.operation, $itemIndex] }}",
+ )
+ end
+
+ expect(result_inside).to eq([999, 999, 42, 999, "test", 1])
+ end
+
+ it "accepts symbol-keyed input items that already include json" do
+ resolver = build_resolver(context.merge("$json" => context["$trigger"]))
+ result_inside = nil
+
+ resolver.with_item({ json: { topic_id: 999 } }) do
+ result_inside = resolver.resolve("={{ $json.topic_id }}")
+ end
+
+ expect(result_inside).to eq(999)
+ end
+
+ it "restores $json even if the block raises" do
+ resolver = build_resolver(context.merge("$json" => context["$trigger"]))
+ expect { resolver.with_item({ "topic_id" => 999 }) { raise "boom" } }.to raise_error("boom")
+
+ expect(resolver.resolve("={{ $json.topic_id }}")).to eq(42)
+ end
+ end
+
+ describe "#expression_errors" do
+ it "captures JS expression errors" do
+ resolver = build_resolver({ "$json" => {} })
+ resolver.resolve("={{ $json.nonexistent.toUpperCase() }}")
+ expect(resolver.expression_errors.size).to eq(1)
+ expect(resolver.expression_errors.first[:expression]).to eq("$json.nonexistent.toUpperCase()")
+ expect(resolver.expression_errors.first[:error]).to be_present
+ end
+
+ it "is empty when no errors occur" do
+ resolver = build_resolver({ "$json" => { "name" => "test" } })
+ resolver.resolve("={{ $json.name }}")
+ expect(resolver.expression_errors).to be_empty
+ end
+ end
+
+ describe "shared sandbox" do
+ it "reuses a shared sandbox across resolver instances" do
+ sandbox = DiscourseWorkflows::JsSandbox.new({})
+
+ resolver_a = described_class.new({ "$json" => { "a" => 1 } }, sandbox: sandbox)
+ expect(resolver_a.resolve("={{ $json.a }}")).to eq(1)
+ resolver_a.dispose
+
+ resolver_b = described_class.new({ "$json" => { "b" => 2 } }, sandbox: sandbox)
+ expect(resolver_b.resolve("={{ $json.b }}")).to eq(2)
+ resolver_b.dispose
+
+ expect(sandbox.js_context).not_to be_nil
+ ensure
+ sandbox&.dispose
+ end
+
+ it "propagates workflow budget errors from the shared sandbox" do
+ sandbox =
+ DiscourseWorkflows::JsSandbox.new(
+ {},
+ budget_tracker: DiscourseWorkflows::SandboxBudget.new({}, budget_ms: 10),
+ )
+ resolver = described_class.new({ "$json" => { "a" => 1 } }, sandbox: sandbox)
+
+ Process.stubs(:clock_gettime).with(Process::CLOCK_MONOTONIC).returns(0.0, 0.02)
+
+ expect { resolver.resolve("={{ $json.a }}") }.to raise_error(
+ DiscourseWorkflows::JsSandbox::BudgetExceededError,
+ )
+ ensure
+ resolver&.dispose
+ sandbox&.dispose
+ end
+ end
+
+ describe "#resolve_segments" do
+ it "returns plaintext for text without expressions" do
+ segments = resolver.resolve_segments("hello world")
+ expect(segments).to eq([{ kind: "plaintext", text: "hello world" }])
+ end
+
+ it "returns a resolved segment for a valid expression" do
+ segments = resolver.resolve_segments("{{ $json.topic_id }}")
+ expect(segments.size).to eq(1)
+ expect(segments[0][:kind]).to eq("resolved")
+ expect(segments[0][:state]).to eq("valid")
+ expect(segments[0][:text]).to eq("42")
+ expect(segments[0][:from]).to eq(0)
+ expect(segments[0][:to]).to eq("{{ $json.topic_id }}".length)
+ end
+
+ it "returns mixed segments for text with expressions" do
+ segments = resolver.resolve_segments("id: {{ $json.topic_id }}!")
+ expect(segments.size).to eq(3)
+ expect(segments[0]).to eq({ kind: "plaintext", text: "id: " })
+ expect(segments[1][:kind]).to eq("resolved")
+ expect(segments[1][:state]).to eq("valid")
+ expect(segments[2]).to eq({ kind: "plaintext", text: "!" })
+ end
+
+ it "marks undefined references" do
+ segments = resolver.resolve_segments("{{ undefined_var }}")
+ expect(segments[0][:state]).to eq("undefined")
+ end
+
+ it "marks syntax errors as invalid" do
+ segments = resolver.resolve_segments("{{ if( }}")
+ expect(segments[0][:state]).to eq("invalid")
+ end
+
+ it "marks uncalled functions as warning" do
+ segments = resolver.resolve_segments("{{ $json.tags.join }}")
+ expect(segments[0][:state]).to eq("warning")
+ end
+
+ it "marks empty expressions" do
+ segments = resolver.resolve_segments("{{ }}")
+ expect(segments[0][:state]).to eq("empty")
+ end
+
+ it "treats unclosed {{ as plaintext" do
+ segments = resolver.resolve_segments("hello {{ $json.title")
+ expect(segments.last[:kind]).to eq("plaintext")
+ expect(segments.last[:text]).to include("{{")
+ end
+ end
+
+ describe ".resolve" do
+ fab!(:user)
+
+ it "resolves a single expression without manual lifecycle" do
+ result =
+ described_class.resolve(
+ "={{ $json.topic_id }}",
+ context: {
+ "$json" => {
+ "topic_id" => 42,
+ },
+ },
+ )
+ expect(result).to eq(42)
+ end
+
+ it "returns non-expression values as-is" do
+ expect(described_class.resolve("hello", context: {})).to eq("hello")
+ end
+
+ it "passes user to the resolver" do
+ result = described_class.resolve("={{ $current_user.username }}", context: {}, user: user)
+ expect(result).to eq(user.username)
+ end
+ end
+
+ describe ".resolve_hash" do
+ it "resolves a hash without manual lifecycle" do
+ result =
+ described_class.resolve_hash(
+ { "id" => "={{ $json.topic_id }}", "fixed" => "hello" },
+ context: {
+ "$json" => {
+ "topic_id" => 42,
+ },
+ },
+ )
+ expect(result).to eq({ "id" => 42, "fixed" => "hello" })
+ end
+ end
+
+ describe ".resolve_segments" do
+ fab!(:user)
+
+ it "passes user through to the resolver" do
+ segments =
+ described_class.resolve_segments("{{ $current_user.username }}", context: {}, user: user)
+
+ expect(segments.first[:text]).to eq(user.username)
+ end
+
+ it "returns an empty array and logs a warning on MiniRacer::Error" do
+ fake_resolver = instance_double(described_class)
+ allow(fake_resolver).to receive(:resolve_segments).and_raise(MiniRacer::Error.new("boom"))
+ allow(fake_resolver).to receive(:dispose)
+ allow(described_class).to receive(:new).and_return(fake_resolver)
+ allow(Rails.logger).to receive(:warn)
+
+ expect(described_class.resolve_segments("{{ x }}", context: {})).to eq([])
+ expect(Rails.logger).to have_received(:warn).with(/Expression evaluation failed: boom/)
+ end
+ end
+end
diff --git a/plugins/discourse-workflows/spec/lib/discourse_workflows/form_trigger_token_spec.rb b/plugins/discourse-workflows/spec/lib/discourse_workflows/form_trigger_token_spec.rb
new file mode 100644
index 00000000000..6a5e20e412f
--- /dev/null
+++ b/plugins/discourse-workflows/spec/lib/discourse_workflows/form_trigger_token_spec.rb
@@ -0,0 +1,55 @@
+# frozen_string_literal: true
+
+RSpec.describe DiscourseWorkflows::FormTriggerToken do
+ let(:workflow_id) { 42 }
+ let(:trigger_node_id) { "trigger-1" }
+ let(:uuid) { "a1b2c3d4-e5f6-7890-abcd-ef0123456789" }
+
+ describe ".generate" do
+ it "encrypts query parameters embedded in public form tokens" do
+ token =
+ described_class.generate(
+ workflow_id: workflow_id,
+ trigger_node_id: trigger_node_id,
+ uuid: uuid,
+ form_query_parameters: {
+ tracking_id: "query-hidden-value",
+ },
+ )
+
+ expect(token).not_to include("query-hidden-value")
+ expect(
+ described_class.payload(
+ token,
+ workflow_id: workflow_id,
+ trigger_node_id: trigger_node_id,
+ uuid: uuid,
+ ),
+ ).to include("form_query_parameters" => { "tracking_id" => "query-hidden-value" })
+ end
+
+ it "treats expired tokens as invalid" do
+ token = nil
+
+ freeze_time do
+ token =
+ described_class.generate(
+ workflow_id: workflow_id,
+ trigger_node_id: trigger_node_id,
+ uuid: uuid,
+ )
+ end
+
+ freeze_time 2.hours.from_now
+
+ expect(
+ described_class.valid?(
+ token,
+ workflow_id: workflow_id,
+ trigger_node_id: trigger_node_id,
+ uuid: uuid,
+ ),
+ ).to be(false)
+ end
+ end
+end
diff --git a/plugins/discourse-workflows/spec/lib/discourse_workflows/forms/payload_spec.rb b/plugins/discourse-workflows/spec/lib/discourse_workflows/forms/payload_spec.rb
new file mode 100644
index 00000000000..e9fba129320
--- /dev/null
+++ b/plugins/discourse-workflows/spec/lib/discourse_workflows/forms/payload_spec.rb
@@ -0,0 +1,42 @@
+# frozen_string_literal: true
+
+RSpec.describe DiscourseWorkflows::Forms::Payload do
+ describe ".build" do
+ it "builds form submission data with metadata" do
+ freeze_time Time.utc(2026, 1, 1)
+
+ payload = described_class.build({ name: "Joffrey" }, query_parameters: { source: "email" })
+
+ expect(payload).to eq(
+ "name" => "Joffrey",
+ "submitted_at" => "2026-01-01T00:00:00.000Z",
+ "form_mode" => "production",
+ "form_query_parameters" => {
+ "source" => "email",
+ },
+ )
+ end
+
+ it "falls back to production mode when form mode is blank" do
+ payload = described_class.build({}, submitted_at: "now", form_mode: "")
+
+ expect(payload["form_mode"]).to eq("production")
+ end
+ end
+
+ describe ".form_mode_from" do
+ it "reads form mode from trigger data with a production fallback" do
+ expect(described_class.form_mode_from("form_mode" => "test")).to eq("test")
+ expect(described_class.form_mode_from({})).to eq("production")
+ end
+ end
+
+ describe ".query_parameters_from" do
+ it "reads query parameters from trigger data with an empty fallback" do
+ expect(
+ described_class.query_parameters_from("form_query_parameters" => { "source" => "email" }),
+ ).to eq("source" => "email")
+ expect(described_class.query_parameters_from({})).to eq({})
+ end
+ end
+end
diff --git a/plugins/discourse-workflows/spec/lib/discourse_workflows/forms/schema_spec.rb b/plugins/discourse-workflows/spec/lib/discourse_workflows/forms/schema_spec.rb
new file mode 100644
index 00000000000..a49cb662d47
--- /dev/null
+++ b/plugins/discourse-workflows/spec/lib/discourse_workflows/forms/schema_spec.rb
@@ -0,0 +1,104 @@
+# frozen_string_literal: true
+
+RSpec.describe DiscourseWorkflows::Forms::Schema do
+ describe ".build" do
+ it "maps workflow form fields to frontend field config and initial data" do
+ schema =
+ described_class.build(
+ [
+ {
+ "field_label" => "Name",
+ "field_type" => "text",
+ "required" => true,
+ "default_value" => "Ada",
+ "placeholder" => "Your name",
+ },
+ { "field_label" => "Age", "field_type" => "number" },
+ { "field_label" => "Email", "field_type" => "email" },
+ {
+ "field_label" => "Password",
+ "field_type" => "password",
+ "default_value" => "do-not-render",
+ },
+ { "field_label" => "Start Date", "field_type" => "date" },
+ { "field_label" => "Agree", "field_type" => "checkbox", "default_value" => "true" },
+ {
+ "field_label" => "Plan",
+ "field_name" => "plan_id",
+ "field_type" => "dropdown",
+ "options" => {
+ "values" => [{ "value" => "basic" }, { "value" => "pro" }],
+ },
+ },
+ {
+ "field_label" => "Contact method",
+ "field_name" => "contact_method",
+ "field_type" => "radio",
+ "options" => {
+ "values" => [{ "value" => "email" }, { "value" => "phone" }],
+ },
+ },
+ {
+ "field_label" => "Tracking ID",
+ "field_name" => "tracking_id",
+ "field_type" => "hiddenField",
+ "field_value" => "abc-123",
+ },
+ {
+ "field_label" => "Intro",
+ "field_type" => "html",
+ "html" =>
+ '<strong>Hello</strong><script>alert("x")</script><iframe src="https://example.com"></iframe><a href="javascript:alert(1)">Bad</a>',
+ },
+ ],
+ )
+
+ expect(schema[:data]).to eq(
+ "name" => "Ada",
+ "age" => "",
+ "email" => "",
+ "password" => "",
+ "start_date" => "",
+ "agree" => true,
+ "plan_id" => "",
+ "contact_method" => "",
+ )
+ html_field = schema[:fields].find { |field| field[:name] == "intro" }
+ expect(html_field[:html]).to include("<strong>Hello</strong>")
+ expect(html_field[:html]).not_to include("script")
+ expect(html_field[:html]).not_to include("iframe")
+ expect(html_field[:html]).not_to include("javascript")
+
+ expect(schema[:fields]).to contain_exactly(
+ {
+ name: "name",
+ title: "Name",
+ type: "input",
+ validation: "required",
+ placeholder: "Your name",
+ autofocus: false,
+ },
+ { name: "age", title: "Age", type: "input-number", autofocus: false },
+ { name: "email", title: "Email", type: "input-email", autofocus: false },
+ { name: "password", title: "Password", type: "password", autofocus: false },
+ { name: "start_date", title: "Start Date", type: "input-date", autofocus: false },
+ { name: "agree", title: "Agree", type: "checkbox", autofocus: false },
+ {
+ name: "plan_id",
+ title: "Plan",
+ type: "select",
+ options: [{ value: "basic", label: "basic" }, { value: "pro", label: "pro" }],
+ autofocus: false,
+ },
+ {
+ name: "contact_method",
+ title: "Contact method",
+ type: "radio-group",
+ options: [{ value: "email", label: "email" }, { value: "phone", label: "phone" }],
+ autofocus: false,
+ },
+ { name: "intro", title: "Intro", type: "html", html: html_field[:html], autofocus: false },
+ )
+ end
+ end
+end
diff --git a/plugins/discourse-workflows/spec/lib/discourse_workflows/interactive_resume_spec.rb b/plugins/discourse-workflows/spec/lib/discourse_workflows/interactive_resume_spec.rb
new file mode 100644
index 00000000000..3415a4b3be9
--- /dev/null
+++ b/plugins/discourse-workflows/spec/lib/discourse_workflows/interactive_resume_spec.rb
@@ -0,0 +1,112 @@
+# frozen_string_literal: true
+
+RSpec.describe DiscourseWorkflows::InteractiveResume do
+ fab!(:user)
+ fab!(:workflow) do
+ graph =
+ build_workflow_graph do |g|
+ g.node "trigger-1", "trigger:manual"
+ g.node "wait-1", "flow:wait", configuration: { "resume" => "webhook" }
+ g.chain "trigger-1", "wait-1"
+ end
+ Fabricate(:discourse_workflows_workflow, created_by: user, **graph).tap do |wf|
+ publish_workflow!(wf)
+ end
+ end
+
+ let(:execution) { DiscourseWorkflows::Executor.new(workflow, "trigger-1", {}).run }
+ let(:action_id) do
+ DiscourseWorkflows::InteractiveResume.action_id(
+ execution_id: execution.id,
+ resume_token: execution.resume_token,
+ action: "resume",
+ )
+ end
+
+ describe ".action_id" do
+ it "returns an opaque signed action id" do
+ payload = described_class.action_payload(action_id)
+
+ expect(payload).to include("execution_id" => execution.id, "action" => "resume")
+ expect(action_id).not_to include(execution.resume_token)
+ end
+ end
+
+ describe ".action_id?" do
+ it "returns true for a valid waiting execution action" do
+ expect(
+ described_class.action_id?(
+ action_id,
+ expected_node_type: "flow:wait",
+ allowed_actions: %w[resume],
+ ),
+ ).to eq(true)
+ end
+
+ it "returns false when the action is not allowed" do
+ expect(
+ described_class.action_id?(
+ action_id,
+ expected_node_type: "flow:wait",
+ allowed_actions: %w[approve deny],
+ ),
+ ).to eq(false)
+ end
+ end
+
+ describe ".from_action_id" do
+ it "returns a resumable request for a valid waiting execution action" do
+ request =
+ described_class.from_action_id(
+ action_id,
+ expected_node_type: "flow:wait",
+ allowed_actions: %w[resume],
+ )
+
+ expect(request.action).to eq("resume")
+ end
+
+ it "returns nil when the waiting node type does not match" do
+ expect(
+ described_class.from_action_id(
+ action_id,
+ expected_node_type: "action:chat_approval",
+ allowed_actions: %w[resume],
+ ),
+ ).to be_nil
+ end
+ end
+
+ describe DiscourseWorkflows::InteractiveResume::Request do
+ it "claims the execution atomically" do
+ request =
+ DiscourseWorkflows::InteractiveResume.from_action_id(
+ action_id,
+ expected_node_type: "flow:wait",
+ allowed_actions: %w[resume],
+ )
+
+ claimed_request = request.claim
+
+ expect(claimed_request.action).to eq("resume")
+ expect(execution.reload.status).to eq("running")
+ expect(request.claim).to be_nil
+ end
+ end
+
+ describe DiscourseWorkflows::InteractiveResume::ClaimedRequest do
+ it "resumes the claimed execution" do
+ request =
+ DiscourseWorkflows::InteractiveResume.from_action_id(
+ action_id,
+ expected_node_type: "flow:wait",
+ allowed_actions: %w[resume],
+ )
+ claimed_request = request.claim
+
+ claimed_request.resume!([{ "json" => { "approved" => true } }])
+
+ expect(execution.reload.status).to eq("success")
+ end
+ end
+end
diff --git a/plugins/discourse-workflows/spec/lib/discourse_workflows/item_contract_spec.rb b/plugins/discourse-workflows/spec/lib/discourse_workflows/item_contract_spec.rb
new file mode 100644
index 00000000000..ffa7a0e4ae1
--- /dev/null
+++ b/plugins/discourse-workflows/spec/lib/discourse_workflows/item_contract_spec.rb
@@ -0,0 +1,124 @@
+# frozen_string_literal: true
+
+RSpec.describe DiscourseWorkflows::ItemContract do
+ describe ".validate_items!" do
+ it "accepts a valid items array" do
+ items = [{ "json" => { "key" => "value" } }]
+ expect { described_class.validate_items!(items, source: "test") }.not_to raise_error
+ end
+
+ it "accepts an empty array" do
+ expect { described_class.validate_items!([], source: "test") }.not_to raise_error
+ end
+
+ it "accepts multi-item arrays" do
+ items = [{ "json" => { "a" => 1 } }, { "json" => { "b" => 2 } }]
+ expect { described_class.validate_items!(items, source: "test") }.not_to raise_error
+ end
+
+ it "accepts compatible pairedItem metadata" do
+ items = [
+ {
+ "json" => {
+ "a" => 1,
+ },
+ "pairedItem" => [{ "input" => 0, "item" => 0 }, { "input" => 1, "item" => 2 }],
+ },
+ ]
+
+ expect { described_class.validate_items!(items, source: "test") }.not_to raise_error
+ end
+
+ it "accepts shorthand pairedItem metadata" do
+ items = [{ "json" => {}, "pairedItem" => 0 }]
+
+ expect { described_class.validate_items!(items, source: "test") }.not_to raise_error
+ end
+
+ it "rejects nil" do
+ expect { described_class.validate_items!(nil, source: "test") }.to raise_error(
+ DiscourseWorkflows::ItemContract::Error,
+ /Invalid items from test/,
+ )
+ end
+
+ it "rejects a hash instead of array" do
+ expect { described_class.validate_items!({ "json" => {} }, source: "test") }.to raise_error(
+ DiscourseWorkflows::ItemContract::Error,
+ )
+ end
+
+ it "rejects items missing the json key" do
+ expect { described_class.validate_items!([{ "data" => {} }], source: "test") }.to raise_error(
+ DiscourseWorkflows::ItemContract::Error,
+ )
+ end
+
+ it "rejects unsupported top-level item keys" do
+ expect {
+ described_class.validate_items!([{ "json" => {}, "binary" => {} }], source: "test")
+ }.to raise_error(DiscourseWorkflows::ItemContract::Error, /Invalid item keys/)
+ end
+
+ it "rejects items with non-object json data" do
+ expect {
+ described_class.validate_items!([{ "json" => "not an object" }], source: "test")
+ }.to raise_error(DiscourseWorkflows::ItemContract::Error)
+ end
+
+ it "rejects items that are not hashes" do
+ expect { described_class.validate_items!(["string"], source: "test") }.to raise_error(
+ DiscourseWorkflows::ItemContract::Error,
+ )
+ end
+
+ it "rejects invalid pairedItem metadata" do
+ items = [{ "json" => {}, "pairedItem" => { "item" => "0" } }]
+
+ expect { described_class.validate_items!(items, source: "test") }.to raise_error(
+ DiscourseWorkflows::ItemContract::Error,
+ /Invalid pairedItem/,
+ )
+ end
+ end
+
+ describe ".validate_output_arrays!" do
+ it "accepts valid output arrays" do
+ result = [[{ "json" => { "a" => 1 } }], [{ "json" => { "b" => 2 } }]]
+ expect { described_class.validate_output_arrays!(result, source: "test") }.not_to raise_error
+ end
+
+ it "accepts empty inner arrays" do
+ result = [[], [{ "json" => { "a" => 1 } }]]
+ expect { described_class.validate_output_arrays!(result, source: "test") }.not_to raise_error
+ end
+
+ it "rejects non-array outer" do
+ expect {
+ described_class.validate_output_arrays!({ "true" => [] }, source: "test")
+ }.to raise_error(DiscourseWorkflows::ItemContract::Error)
+ end
+
+ it "rejects non-array inner" do
+ expect {
+ described_class.validate_output_arrays!([{ "json" => {} }], source: "test")
+ }.to raise_error(DiscourseWorkflows::ItemContract::Error)
+ end
+
+ it "validates items within inner arrays" do
+ expect {
+ described_class.validate_output_arrays!([["not an item"]], source: "test")
+ }.to raise_error(DiscourseWorkflows::ItemContract::Error)
+ end
+
+ it "rejects more outputs than the node declares" do
+ expect {
+ described_class.validate_output_arrays!(
+ [[{ "json" => { "a" => 1 } }], [{ "json" => { "b" => 2 } }]],
+ source: "test",
+ ports: [{ key: "main" }],
+ )
+ }.to raise_error(DiscourseWorkflows::ItemContract::Error, /returned 2 outputs/)
+ end
+ end
+end
diff --git a/plugins/discourse-workflows/spec/lib/discourse_workflows/item_spec.rb b/plugins/discourse-workflows/spec/lib/discourse_workflows/item_spec.rb
new file mode 100644
index 00000000000..c073c152187
--- /dev/null
+++ b/plugins/discourse-workflows/spec/lib/discourse_workflows/item_spec.rb
@@ -0,0 +1,89 @@
+# frozen_string_literal: true
+
+RSpec.describe DiscourseWorkflows::Item do
+ describe ".wrap" do
+ it "wraps a hash with stringified keys" do
+ expect(described_class.wrap(name: "Alice")).to eq("json" => { "name" => "Alice" })
+ end
+
+ it "deep-stringifies nested keys" do
+ expect(described_class.wrap(outer: { inner: "val" })).to eq(
+ "json" => {
+ "outer" => {
+ "inner" => "val",
+ },
+ },
+ )
+ end
+
+ it "freezes the inner json hash" do
+ expect(described_class.wrap("key" => "value")["json"]).to be_frozen
+ end
+
+ it "maps over an array of hashes" do
+ expect(described_class.wrap([{ "name" => "A" }, { "name" => "B" }])).to eq(
+ [{ "json" => { "name" => "A" } }, { "json" => { "name" => "B" } }],
+ )
+ end
+
+ it "adds compatible pairedItem metadata" do
+ expect(described_class.wrap({ "name" => "A" }, paired_item: { item: 1 })).to eq(
+ "json" => {
+ "name" => "A",
+ },
+ "pairedItem" => {
+ "item" => 1,
+ },
+ )
+ end
+
+ it "normalizes shorthand pairedItem metadata" do
+ expect(described_class.wrap({ "name" => "A" }, paired_item: 1)).to include(
+ "pairedItem" => {
+ "item" => 1,
+ },
+ )
+ end
+
+ it "raises when given something other than a Hash or Array" do
+ expect { described_class.wrap(nil) }.to raise_error(ArgumentError)
+ expect { described_class.wrap("string") }.to raise_error(ArgumentError)
+ end
+ end
+
+ describe ".normalize_items" do
+ it "wraps plain objects as json items" do
+ expect(described_class.normalize_items([{ name: "Ada" }])).to eq(
+ [{ "json" => { "name" => "Ada" } }],
+ )
+ end
+
+ it "preserves item-shaped objects and normalizes pairedItem" do
+ expect(described_class.normalize_items([{ json: { name: "Ada" }, pairedItem: 0 }])).to eq(
+ [{ "json" => { "name" => "Ada" }, "pairedItem" => { "item" => 0 } }],
+ )
+ end
+
+ it "raises when json item and plain object formats are mixed" do
+ expect { described_class.normalize_items([{ json: { id: 1 } }, { id: 2 }]) }.to raise_error(
+ described_class::InconsistentItemFormatError,
+ described_class::INCONSISTENT_ITEM_FORMAT_MESSAGE,
+ )
+ end
+
+ it "treats binary as a regular JSON field" do
+ expect(described_class.normalize_items([{ binary: {} }, { id: 2 }])).to eq(
+ [{ "json" => { "binary" => {} } }, { "json" => { "id" => 2 } }],
+ )
+ end
+
+ it "raises when item-shaped and plain binary field formats are mixed" do
+ expect {
+ described_class.normalize_items([{ json: { id: 1 } }, { binary: {} }])
+ }.to raise_error(
+ described_class::InconsistentItemFormatError,
+ described_class::INCONSISTENT_ITEM_FORMAT_MESSAGE,
+ )
+ end
+ end
+end
diff --git a/plugins/discourse-workflows/spec/lib/discourse_workflows/js_sandbox_spec.rb b/plugins/discourse-workflows/spec/lib/discourse_workflows/js_sandbox_spec.rb
new file mode 100644
index 00000000000..c9c5dd1111e
--- /dev/null
+++ b/plugins/discourse-workflows/spec/lib/discourse_workflows/js_sandbox_spec.rb
@@ -0,0 +1,175 @@
+# frozen_string_literal: true
+
+RSpec.describe DiscourseWorkflows::JsSandbox do
+ subject(:sandbox) do
+ described_class
+ .new(workflow_context, user: user, vars: vars)
+ .tap { |instance| owned_sandboxes << instance }
+ end
+
+ fab!(:user)
+
+ let(:workflow_context) { { "$trigger" => { "topic_id" => 42 } } }
+ let(:vars) { { "API_URL" => "https://example.com" } }
+ let(:owned_sandboxes) { [] }
+
+ after { owned_sandboxes.each(&:dispose) }
+
+ describe "timeout" do
+ it "raises when JS execution exceeds the time limit" do
+ expect { sandbox.eval("while(true) {}") }.to raise_error(
+ DiscourseWorkflows::JsSandbox::BudgetExceededError,
+ /exceeded #{DiscourseWorkflows::JsSandbox::EVAL_TIMEOUT_MS}ms time limit/,
+ )
+ end
+ end
+
+ describe "memory limit" do
+ it "raises when JS allocates too much memory" do
+ expect { sandbox.eval(<<~JS) }.to raise_error(DiscourseWorkflows::JsSandbox::SandboxError)
+ var a = [];
+ while(true) { a.push(new Array(10000).fill('x')); }
+ JS
+ end
+ end
+
+ describe "site setting filtering" do
+ it "returns [FILTERED] for secret settings" do
+ SiteSetting.secret_settings << :some_secret_key
+ result = sandbox.eval("$site_settings.some_secret_key")
+ expect(result).to eq("[FILTERED]")
+ ensure
+ SiteSetting.secret_settings.delete(:some_secret_key)
+ end
+
+ it "returns [FILTERED] for hidden settings" do
+ SiteSetting.stubs(:hidden_settings).returns(Set.new([:some_hidden_key]))
+ result = sandbox.eval("$site_settings.some_hidden_key")
+ expect(result).to eq("[FILTERED]")
+ end
+
+ it "returns the value for normal settings" do
+ SiteSetting.title = "Test Forum"
+ expect(sandbox.eval("$site_settings.title")).to eq("Test Forum")
+ end
+ end
+
+ describe "private node names" do
+ it "returns empty object for underscore-prefixed node names" do
+ context = { "_internal" => [{ "json" => { "secret" => "data" } }] }
+ private_sandbox = described_class.new(context, vars: {})
+
+ result = private_sandbox.eval("$('_internal').item")
+ expect(result).to eq({ "json" => {} })
+ ensure
+ private_sandbox&.dispose
+ end
+
+ it "returns node data for normal names" do
+ context = { "My Node" => [{ "json" => { "value" => 123 } }] }
+ named_sandbox = described_class.new(context, vars: {})
+
+ result = named_sandbox.eval("$('My Node').first()")
+ expect(result).to eq({ "json" => { "value" => 123 } })
+ ensure
+ named_sandbox&.dispose
+ end
+ end
+
+ describe "current user exposure" do
+ it "only exposes schema-declared fields" do
+ result = sandbox.eval("JSON.stringify(Object.keys($current_user).sort())")
+ keys = JSON.parse(result)
+ expect(keys).to contain_exactly("id", "username")
+ end
+
+ it "populates user fields correctly" do
+ expect(sandbox.eval("$current_user.id")).to eq(user.id)
+ expect(sandbox.eval("$current_user.username")).to eq(user.username)
+ end
+
+ it "returns empty object when no user is provided" do
+ no_user_sandbox = described_class.new(workflow_context, vars: vars)
+ expect(no_user_sandbox.eval("JSON.stringify($current_user)")).to eq("{}")
+ ensure
+ no_user_sandbox&.dispose
+ end
+ end
+
+ describe "$execution exposure" do
+ it "exposes execution variables from workflow context" do
+ context = { "__execution" => { "id" => 42, "workflow_name" => "My Workflow" } }
+ exec_sandbox = described_class.new(context, vars: {})
+
+ expect(exec_sandbox.eval("$execution.id")).to eq(42)
+ expect(exec_sandbox.eval("$execution.workflow_name")).to eq("My Workflow")
+ ensure
+ exec_sandbox&.dispose
+ end
+
+ it "defaults to empty object when no execution context" do
+ expect(sandbox.eval("JSON.stringify($execution)")).to eq("{}")
+ end
+ end
+
+ describe "console capture" do
+ it "captures log messages when enabled" do
+ capturing_sandbox =
+ described_class.new(workflow_context, user: user, vars: vars, capture_logs: true)
+
+ capturing_sandbox.eval('console.log("hello")')
+ capturing_sandbox.eval('console.warn("careful")')
+ capturing_sandbox.eval('console.error("boom")')
+
+ entries = capturing_sandbox.log.as_json
+ expect(entries.map { |e| e["message"] }).to eq(%w[hello careful boom])
+ expect(entries.map { |e| e["level"] }).to eq(%w[info warn error])
+ ensure
+ capturing_sandbox&.dispose
+ end
+ end
+
+ describe "workflow budget" do
+ it "shares elapsed sandbox time through workflow context" do
+ budget_state = {}
+ first_sandbox =
+ described_class.new(
+ workflow_context,
+ user: user,
+ vars: vars,
+ budget_tracker: DiscourseWorkflows::SandboxBudget.new(budget_state, budget_ms: 100),
+ )
+ second_sandbox =
+ described_class.new(
+ workflow_context,
+ user: user,
+ vars: vars,
+ budget_tracker: DiscourseWorkflows::SandboxBudget.new(budget_state, budget_ms: 100),
+ )
+
+ Process.stubs(:clock_gettime).with(Process::CLOCK_MONOTONIC).returns(0.0, 0.06, 0.06, 0.12)
+
+ first_sandbox.eval("1 + 1")
+
+ expect { second_sandbox.eval("2 + 2") }.to raise_error(
+ described_class::BudgetExceededError,
+ /100ms/,
+ )
+ expect(budget_state[DiscourseWorkflows::SandboxBudget::CONTEXT_KEY]).to be > 100
+ ensure
+ first_sandbox&.dispose
+ second_sandbox&.dispose
+ end
+ end
+
+ describe "embedded JSON payloads" do
+ it "rejects payloads larger than MAX_INJECTED_JSON_BYTES" do
+ oversized_payload = { "data" => "x" * described_class::MAX_INJECTED_JSON_BYTES }
+
+ expect { sandbox.declare_json("__huge", oversized_payload) }.to raise_error(
+ described_class::PayloadTooLargeError,
+ /__huge/,
+ )
+ end
+ end
+end
diff --git a/plugins/discourse-workflows/spec/lib/discourse_workflows/node_data_spec.rb b/plugins/discourse-workflows/spec/lib/discourse_workflows/node_data_spec.rb
new file mode 100644
index 00000000000..0386336b46f
--- /dev/null
+++ b/plugins/discourse-workflows/spec/lib/discourse_workflows/node_data_spec.rb
@@ -0,0 +1,135 @@
+# frozen_string_literal: true
+
+RSpec.describe DiscourseWorkflows::NodeData do
+ describe ".split" do
+ it "stores credential references by declared slot" do
+ split =
+ described_class.split(
+ node_type: "action:http_request",
+ parameters: {
+ "authentication" => "basic_auth",
+ },
+ credentials: {
+ "auth" => {
+ "id" => 12,
+ "credential_type" => "basic_auth",
+ },
+ },
+ )
+
+ expect(split["parameters"]).to eq("authentication" => "basic_auth")
+ expect(split["credentials"]).to eq(
+ "auth" => {
+ "id" => "12",
+ "credential_type" => "basic_auth",
+ },
+ )
+ end
+
+ it "keeps declared parameters unchanged" do
+ split =
+ described_class.split(
+ node_type: "action:http_request",
+ parameters: {
+ "authentication" => "basic_auth",
+ "credential_id" => 12,
+ },
+ )
+
+ expect(split["parameters"]).to eq("authentication" => "basic_auth", "credential_id" => 12)
+ expect(split["credentials"]).to eq({})
+ end
+
+ it "removes stored credentials hidden by credential display options" do
+ split =
+ described_class.split(
+ node_type: "action:http_request",
+ parameters: {
+ "authentication" => "none",
+ },
+ credentials: {
+ "auth" => {
+ "id" => 12,
+ "credential_type" => "basic_auth",
+ },
+ },
+ )
+
+ expect(split["credentials"]).to eq({})
+ end
+
+ it "removes credentials from node types without credential declarations" do
+ split =
+ described_class.split(
+ node_type: "action:log",
+ parameters: {
+ "message" => "hello",
+ },
+ credentials: {
+ "auth" => {
+ "id" => 12,
+ "credential_type" => "basic_auth",
+ },
+ },
+ )
+
+ expect(split["credentials"]).to eq({})
+ end
+
+ it "does not move direct node settings into parameters" do
+ split = described_class.split(node_type: "action:log", parameters: { "message" => "hello" })
+
+ expect(split).not_to have_key("settings")
+ expect(split["parameters"]).to eq("message" => "hello")
+ end
+
+ it "keeps form trigger parameters separate from webhook IDs" do
+ split =
+ described_class.split(
+ node_type: DiscourseWorkflows::NodeDataShape::FORM_TRIGGER_TYPE,
+ parameters: {
+ "form_title" => "Signup",
+ },
+ webhook_id: "form-uuid",
+ )
+
+ expect(split["parameters"]).to eq("form_title" => "Signup")
+ expect(split[DiscourseWorkflows::WorkflowDocument.node_webhook_id_key]).to eq("form-uuid")
+ end
+ end
+
+ describe ".direct_settings" do
+ it "reads direct node settings directly from the node" do
+ node = {
+ "notes" => "Shown on canvas",
+ "alwaysOutputData" => false,
+ "parameters" => {
+ "message" => "hello",
+ },
+ }
+
+ expect(described_class.direct_settings(node)).to eq(
+ "notes" => "Shown on canvas",
+ "alwaysOutputData" => false,
+ )
+ end
+ end
+
+ describe ".resolved_parameters" do
+ it "does not merge credential references into ordinary parameters" do
+ node = {
+ "parameters" => {
+ "authentication" => "basic_auth",
+ },
+ "credentials" => {
+ "auth" => {
+ "id" => "12",
+ "credential_type" => "basic_auth",
+ },
+ },
+ }
+
+ expect(described_class.resolved_parameters(node)).to eq("authentication" => "basic_auth")
+ end
+ end
+end
diff --git a/plugins/discourse-workflows/spec/lib/discourse_workflows/node_issues_spec.rb b/plugins/discourse-workflows/spec/lib/discourse_workflows/node_issues_spec.rb
new file mode 100644
index 00000000000..01e9a2213ff
--- /dev/null
+++ b/plugins/discourse-workflows/spec/lib/discourse_workflows/node_issues_spec.rb
@@ -0,0 +1,127 @@
+# frozen_string_literal: true
+
+RSpec.describe DiscourseWorkflows::NodeIssues do
+ def node_type_class(schema)
+ Class.new { define_singleton_method(:property_schema) { schema } }
+ end
+
+ def node(configuration)
+ DiscourseWorkflows::WorkflowSnapshot::SnapshotNode.new(
+ id: "n1",
+ type: "action:test",
+ type_version: "1.0",
+ name: "Test",
+ parameters: configuration,
+ )
+ end
+
+ it "returns no issues when all required fields are set" do
+ schema = { form_title: { type: :string, required: true } }
+ issues = described_class.for_node(node("form_title" => "My form"), node_type_class(schema))
+ expect(issues).to be_empty
+ end
+
+ it "reports a top-level required field as missing" do
+ schema = { form_title: { type: :string, required: true } }
+ issues = described_class.for_node(node({}), node_type_class(schema))
+ expect(issues).to eq([{ path: "form_title", name: "form_title", message: "required" }])
+ end
+
+ it "treats blank strings as missing" do
+ schema = { form_title: { type: :string, required: true } }
+ issues = described_class.for_node(node("form_title" => " "), node_type_class(schema))
+ expect(issues.size).to eq(1)
+ end
+
+ it "walks fixed collection items and reports missing nested required fields" do
+ schema = {
+ form_fields: {
+ type: :fixed_collection,
+ options: [
+ {
+ name: "values",
+ values: {
+ field_label: {
+ type: :string,
+ required: true,
+ },
+ field_type: {
+ type: :options,
+ required: true,
+ },
+ },
+ },
+ ],
+ },
+ }
+ config = {
+ "form_fields" => {
+ "values" => [
+ { "field_label" => "", "field_type" => "text" },
+ { "field_label" => "Name", "field_type" => "" },
+ ],
+ },
+ }
+
+ paths = described_class.for_node(node(config), node_type_class(schema)).map { |i| i[:path] }
+ expect(paths).to contain_exactly(
+ "form_fields.values.0.field_label",
+ "form_fields.values.1.field_type",
+ )
+ end
+
+ it "respects display_options show rules — hidden required fields are not reported" do
+ schema = {
+ page_type: {
+ type: :options,
+ },
+ completion_title: {
+ type: :string,
+ required: true,
+ display_options: {
+ show: {
+ page_type: %w[completion],
+ },
+ },
+ },
+ }
+
+ expect(
+ described_class.for_node(node("page_type" => "page"), node_type_class(schema)),
+ ).to be_empty
+
+ issues = described_class.for_node(node("page_type" => "completion"), node_type_class(schema))
+ expect(issues.size).to eq(1)
+ end
+
+ it "applies field defaults before checking required" do
+ schema = { operation: { type: :options, required: true, default: "add" } }
+ expect(described_class.for_node(node({}), node_type_class(schema))).to be_empty
+ end
+
+ it "walks optional fields inside fixed collections" do
+ schema = {
+ form_fields: {
+ type: :fixed_collection,
+ options: [
+ {
+ name: "values",
+ values: {
+ field_label: {
+ type: :string,
+ required: true,
+ },
+ custom_required: {
+ type: :string,
+ required: true,
+ },
+ },
+ },
+ ],
+ },
+ }
+ config = { "form_fields" => { "values" => [{ "field_label" => "Name" }] } }
+ paths = described_class.for_node(node(config), node_type_class(schema)).map { |i| i[:path] }
+ expect(paths).to eq(["form_fields.values.0.custom_required"])
+ end
+end
diff --git a/plugins/discourse-workflows/spec/lib/discourse_workflows/node_type_descriptor_spec.rb b/plugins/discourse-workflows/spec/lib/discourse_workflows/node_type_descriptor_spec.rb
new file mode 100644
index 00000000000..7c77c0124eb
--- /dev/null
+++ b/plugins/discourse-workflows/spec/lib/discourse_workflows/node_type_descriptor_spec.rb
@@ -0,0 +1,208 @@
+# frozen_string_literal: true
+
+RSpec.describe DiscourseWorkflows::NodeTypeDescriptor do
+ let(:trigger_class) do
+ Class.new(DiscourseWorkflows::NodeType) do
+ description(name: "trigger:test_event", defaults: { icon: "bolt", color: "blue" })
+ end
+ end
+
+ let(:action_class) do
+ Class.new(DiscourseWorkflows::NodeType) { description(name: "action:do_thing") }
+ end
+
+ let(:condition_class) do
+ Class.new(DiscourseWorkflows::NodeType) { description(name: "condition:check") }
+ end
+
+ let(:flow_class) { Class.new(DiscourseWorkflows::NodeType) { description(name: "flow:wait") } }
+
+ describe "#kind" do
+ it "extracts the prefix from the identifier" do
+ expect(trigger_class.kind).to eq("trigger")
+ expect(action_class.kind).to eq("action")
+ end
+ end
+
+ describe "#label_key" do
+ it "builds the i18n key from the identifier" do
+ expect(trigger_class.label_key).to eq("discourse_workflows.nodes.trigger:test_event")
+ end
+ end
+
+ describe "#description_key" do
+ it "builds the i18n key from the identifier" do
+ expect(trigger_class.description_key).to eq(
+ "discourse_workflows.node_descriptions.trigger:test_event",
+ )
+ end
+ end
+
+ describe "#i18n_prefix" do
+ it "returns the default prefix" do
+ expect(trigger_class.i18n_prefix).to eq("discourse_workflows")
+ end
+ end
+
+ describe "#i18n_scope" do
+ it "extracts the suffix from the identifier" do
+ expect(trigger_class.i18n_scope).to eq("test_event")
+ end
+ end
+
+ describe "#group" do
+ it "returns 'triggers' for trigger nodes" do
+ expect(trigger_class.group).to eq("triggers")
+ end
+
+ it "returns 'flow' for condition nodes" do
+ expect(condition_class.group).to eq("flow")
+ end
+
+ it "returns 'flow' for flow nodes" do
+ expect(flow_class.group).to eq("flow")
+ end
+
+ it "returns 'utilities' for action nodes" do
+ expect(action_class.group).to eq("utilities")
+ end
+ end
+
+ describe "#palette_group" do
+ it "returns the group definition with id" do
+ result = trigger_class.palette_group
+ expect(result[:id]).to eq("triggers")
+ expect(result[:icon]).to eq("bolt")
+ expect(result[:label_key]).to eq("discourse_workflows.add_node.categories.triggers")
+ expect(result[:order]).to eq(20)
+ end
+ end
+
+ describe "#operations" do
+ it "returns empty when no operation field" do
+ expect(trigger_class.operations).to eq([])
+ end
+
+ it "returns empty when operation has single option" do
+ klass =
+ Class.new(DiscourseWorkflows::NodeType) do
+ description(
+ name: "action:single_op",
+ properties: {
+ operation: {
+ type: :options,
+ options: %w[get],
+ },
+ },
+ )
+ end
+
+ expect(klass.operations).to eq([])
+ end
+
+ it "returns labeled operations when multiple options exist" do
+ klass =
+ Class.new(DiscourseWorkflows::NodeType) do
+ description(
+ name: "action:multi_op",
+ properties: {
+ operation: {
+ type: :options,
+ options: %w[get insert delete],
+ },
+ },
+ )
+ end
+
+ ops = klass.operations
+ expect(ops.length).to eq(3)
+ expect(ops.first).to eq(
+ { value: "get", label_key: "discourse_workflows.multi_op.operations.get" },
+ )
+ end
+ end
+
+ describe "#ports" do
+ it "normalizes outputs into port definitions" do
+ expect(trigger_class.ports).to eq([{ key: "main", type: "main", index: 0, primary: true }])
+ end
+
+ it "handles multiple outputs for branching nodes" do
+ klass =
+ Class.new(DiscourseWorkflows::NodeType) do
+ description(
+ name: "condition:branch",
+ outputs: [{ key: "true", label_key: "t" }, { key: "false", label_key: "f" }],
+ )
+ end
+
+ ports = klass.ports
+ expect(ports.length).to eq(2)
+ expect(ports[0]).to eq({ key: "true", type: "main", index: 0, label_key: "t", primary: true })
+ expect(ports[1]).to eq(
+ { key: "false", type: "main", index: 1, label_key: "f", primary: false },
+ )
+ end
+ end
+
+ describe "#capabilities" do
+ it "returns capability hash for a simple node" do
+ expect(trigger_class.capabilities).to eq(
+ {
+ branching: false,
+ manually_triggerable: false,
+ provides_current_user: false,
+ result_mode: "items",
+ },
+ )
+ end
+
+ it "reflects branching and manually_triggerable" do
+ klass =
+ Class.new(DiscourseWorkflows::NodeType) do
+ description(
+ name: "trigger:manual",
+ outputs: %w[true false],
+ capabilities: {
+ manually_triggerable: true,
+ },
+ )
+ end
+
+ caps = klass.capabilities
+ expect(caps[:branching]).to eq(true)
+ expect(caps[:manually_triggerable]).to eq(true)
+ expect(caps[:result_mode]).to eq("ports")
+ end
+
+ it "includes node-specific capabilities" do
+ klass =
+ Class.new(DiscourseWorkflows::NodeType) do
+ description(name: "action:sort", capabilities: { run_scope: "all_items" })
+ end
+
+ expect(klass.capabilities[:run_scope]).to eq("all_items")
+ end
+ end
+
+ describe "#ui_metadata" do
+ it "assembles all UI fields" do
+ result = trigger_class.ui_metadata
+ expect(result[:icon]).to eq("bolt")
+ expect(result[:color]).to eq("blue")
+ expect(result[:label_key]).to eq("discourse_workflows.nodes.trigger:test_event")
+ expect(result[:description_key]).to eq(
+ "discourse_workflows.node_descriptions.trigger:test_event",
+ )
+ expect(result[:palette_group][:id]).to eq("triggers")
+ expect(result[:i18n_prefix]).to eq("discourse_workflows")
+ expect(result[:i18n_scope]).to eq("test_event")
+ end
+
+ it "omits nil values" do
+ result = action_class.ui_metadata
+ expect(result).not_to have_key(:icon)
+ expect(result).not_to have_key(:color)
+ end
+ end
+end
diff --git a/plugins/discourse-workflows/spec/lib/discourse_workflows/node_type_spec.rb b/plugins/discourse-workflows/spec/lib/discourse_workflows/node_type_spec.rb
new file mode 100644
index 00000000000..be3b4fb7f98
--- /dev/null
+++ b/plugins/discourse-workflows/spec/lib/discourse_workflows/node_type_spec.rb
@@ -0,0 +1,114 @@
+# frozen_string_literal: true
+
+RSpec.describe DiscourseWorkflows::NodeType do
+ around do |example|
+ nodes_before = described_class.registered_nodes.dup
+ example.run
+ described_class.registered_nodes.replace(nodes_before)
+ end
+
+ describe ".webhooks" do
+ it "normalizes webhook descriptors to symbol keys" do
+ klass =
+ Class.new(described_class) do
+ description(
+ webhooks: [
+ {
+ "path" => "status",
+ "http_method" => "GET",
+ "restart_webhook" => true,
+ "node_type" => "form",
+ },
+ ],
+ )
+ end
+
+ expect(klass.webhooks).to contain_exactly(
+ path: "status",
+ http_method: "GET",
+ restart_webhook: true,
+ node_type: "form",
+ )
+ end
+ end
+
+ describe ".waiting_webhook_for" do
+ it "finds a matching restart webhook descriptor" do
+ klass =
+ Class.new(described_class) do
+ description(
+ webhooks: [{ path: "", http_method: "POST", restart_webhook: true, node_type: "form" }],
+ )
+ end
+
+ expect(klass.waiting_webhook_for(http_method: "post", path: "", node_type: "form")).to eq(
+ path: "",
+ http_method: "POST",
+ restart_webhook: true,
+ node_type: "form",
+ )
+ end
+
+ it "ignores non-restart webhook descriptors" do
+ klass =
+ Class.new(described_class) do
+ description(webhooks: [{ path: "", http_method: "POST", node_type: "form" }])
+ end
+
+ expect(klass.waiting_webhook_for(http_method: "POST", path: "", node_type: "form")).to be_nil
+ end
+ end
+
+ describe ".branching?" do
+ it "returns false when single output" do
+ expect(described_class.branching?).to eq(false)
+ end
+
+ it "returns true when multiple outputs" do
+ klass =
+ Class.new(described_class) do
+ description(outputs: [{ key: "true", label_key: "t" }, { key: "false", label_key: "f" }])
+ end
+ expect(klass.branching?).to eq(true)
+ end
+ end
+
+ describe ".available?" do
+ it "can be overridden by subclass" do
+ klass =
+ Class.new(described_class) { description(name: "action:unavailable", available: false) }
+ expect(klass.available?).to eq(false)
+ end
+ end
+
+ describe ".unavailable_reason_key" do
+ it "evaluates callable unavailable reason descriptors" do
+ reason = "discourse_workflows.node_unavailable.dynamic_reason"
+ klass =
+ Class.new(described_class) do
+ description(
+ name: "action:dynamic_unavailable_reason",
+ unavailable_reason_key: -> { reason },
+ )
+ end
+
+ expect(klass.unavailable_reason_key).to eq(reason)
+ end
+ end
+
+ describe "#with_paired_item" do
+ it "adds normalized paired item metadata to an item" do
+ node = described_class.new
+ item = { "json" => { "name" => "Ada" } }
+
+ expect(node.send(:with_paired_item, item, { item: 1 })).to eq(
+ "json" => {
+ "name" => "Ada",
+ },
+ "pairedItem" => {
+ "item" => 1,
+ },
+ )
+ end
+ end
+end
diff --git a/plugins/discourse-workflows/spec/lib/discourse_workflows/nodes/badge_spec.rb b/plugins/discourse-workflows/spec/lib/discourse_workflows/nodes/badge_spec.rb
new file mode 100644
index 00000000000..549552fd975
--- /dev/null
+++ b/plugins/discourse-workflows/spec/lib/discourse_workflows/nodes/badge_spec.rb
@@ -0,0 +1,172 @@
+# frozen_string_literal: true
+
+RSpec.describe DiscourseWorkflows::Nodes::Badge::V1 do
+ fab!(:user)
+ fab!(:badge)
+
+ describe ".load_options_context" do
+ fab!(:badge_2) { Fabricate(:badge, name: "A badge") }
+
+ def load_options(filter: nil)
+ context =
+ DiscourseWorkflows::LoadOptionsContext.new(
+ method_name: "badges",
+ filter: filter,
+ node_class: described_class,
+ )
+
+ described_class.load_options_context(context)
+ end
+
+ it "returns enabled badges for the chooser" do
+ expect(load_options).to include(
+ { id: badge_2.id, name: badge_2.name },
+ { id: badge.id, name: badge.name },
+ )
+ end
+
+ it "excludes disabled badges" do
+ disabled_badge = Fabricate(:badge, name: "Disabled Badge", enabled: false)
+ expect(load_options).not_to include({ id: disabled_badge.id, name: disabled_badge.name })
+ end
+
+ it "filters badges by the filter term" do
+ expect(load_options(filter: "A badge")).to contain_exactly(
+ { id: badge_2.id, name: badge_2.name },
+ )
+ end
+ end
+
+ describe "#execute" do
+ fab!(:admin)
+
+ let(:item) { { "json" => {} } }
+
+ context "with grant operation" do
+ it "grants the badge to the user" do
+ config = {
+ "operation" => "grant",
+ "username" => user.username,
+ "badge_id" => badge.id.to_s,
+ }
+
+ result = execute_node(configuration: config, item: item)
+
+ expect(result["user_id"]).to eq(user.id)
+ expect(result["username"]).to eq(user.username)
+ expect(result["badge_id"]).to eq(badge.id)
+ expect(result["badge_name"]).to eq(badge.name)
+ expect(UserBadge.exists?(user: user, badge: badge)).to be(true)
+ end
+
+ it "does not duplicate a non-multiple-grant badge" do
+ BadgeGranter.grant(badge, user, granted_by: Discourse.system_user)
+
+ config = {
+ "operation" => "grant",
+ "username" => user.username,
+ "badge_id" => badge.id.to_s,
+ }
+
+ expect { execute_node(configuration: config, item: item) }.not_to change {
+ UserBadge.where(user: user, badge: badge).count
+ }
+ end
+ end
+
+ context "with revoke operation" do
+ it "revokes the badge from the user" do
+ BadgeGranter.grant(badge, user, granted_by: Discourse.system_user)
+
+ config = {
+ "operation" => "revoke",
+ "username" => user.username,
+ "badge_id" => badge.id.to_s,
+ }
+
+ execute_node(configuration: config, item: item)
+
+ expect(UserBadge.exists?(user: user, badge: badge)).to be(false)
+ end
+
+ it "is idempotent when user does not have the badge" do
+ config = {
+ "operation" => "revoke",
+ "username" => user.username,
+ "badge_id" => badge.id.to_s,
+ }
+
+ result = nil
+ expect { result = execute_node(configuration: config, item: item) }.not_to change {
+ UserBadge.where(user: user, badge: badge).count
+ }
+
+ expect(result).to include(
+ "user_id" => user.id,
+ "username" => user.username,
+ "badge_id" => badge.id,
+ "badge_name" => badge.name,
+ )
+ end
+ end
+
+ it "raises when user does not exist" do
+ config = {
+ "operation" => "grant",
+ "username" => "nonexistent_user",
+ "badge_id" => badge.id.to_s,
+ }
+
+ expect { execute_node(configuration: config, item: item) }.to raise_error(
+ DiscourseWorkflows::NodeError,
+ "User 'nonexistent_user' not found",
+ )
+ end
+
+ it "raises when badge does not exist" do
+ config = { "operation" => "grant", "username" => user.username, "badge_id" => "-1" }
+
+ expect { execute_node(configuration: config, item: item) }.to raise_error(
+ ActiveRecord::RecordNotFound,
+ )
+ end
+
+ it "uses actor_username when granting" do
+ config = {
+ "operation" => "grant",
+ "username" => user.username,
+ "badge_id" => badge.id.to_s,
+ "actor_username" => admin.username,
+ }
+
+ execute_node(configuration: config, item: item)
+
+ expect(UserBadge.find_by(user: user, badge: badge).granted_by_id).to eq(admin.id)
+ end
+
+ it "uses actor_username when revoking" do
+ BadgeGranter.grant(badge, user, granted_by: Discourse.system_user)
+
+ config = {
+ "operation" => "revoke",
+ "username" => user.username,
+ "badge_id" => badge.id.to_s,
+ "actor_username" => admin.username,
+ }
+
+ execute_node(configuration: config, item: item)
+
+ expect(UserBadge.exists?(user: user, badge: badge)).to be(false)
+ end
+
+ it "defaults to system user when actor_username is not set" do
+ config = { "operation" => "grant", "username" => user.username, "badge_id" => badge.id.to_s }
+
+ execute_node(configuration: config, item: item)
+
+ expect(UserBadge.find_by(user: user, badge: badge).granted_by_id).to eq(
+ Discourse.system_user.id,
+ )
+ end
+ end
+end
diff --git a/plugins/discourse-workflows/spec/lib/discourse_workflows/nodes/code/js_task_runner_sandbox_spec.rb b/plugins/discourse-workflows/spec/lib/discourse_workflows/nodes/code/js_task_runner_sandbox_spec.rb
new file mode 100644
index 00000000000..8e0a0b9bd61
--- /dev/null
+++ b/plugins/discourse-workflows/spec/lib/discourse_workflows/nodes/code/js_task_runner_sandbox_spec.rb
@@ -0,0 +1,104 @@
+# frozen_string_literal: true
+
+RSpec.describe DiscourseWorkflows::Nodes::Code::JsTaskRunnerSandbox do
+ let(:input_items) { [{ "json" => { "name" => "Ada" } }] }
+ let(:runner) { described_class.new("manual", exec_ctx) }
+
+ def build_exec_ctx(items = input_items)
+ resolver_context = { "$json" => items.first&.dig("json") || {} }
+ sandbox = DiscourseWorkflows::JsSandbox.new(resolver_context)
+ resolver = DiscourseWorkflows::ExpressionResolver.new(resolver_context, sandbox: sandbox)
+ ctx =
+ DiscourseWorkflows::Executor::NodeExecutionContext.new(
+ input_items: items,
+ parameters: {
+ },
+ resolver: resolver,
+ resolver_context: resolver_context,
+ )
+ [ctx, resolver, sandbox]
+ end
+
+ before { @exec_ctx, @resolver, @sandbox = build_exec_ctx }
+ after do
+ @resolver&.dispose
+ @sandbox&.dispose
+ end
+
+ let(:exec_ctx) { @exec_ctx }
+
+ describe "#run_code_all_items" do
+ it "normalizes all-items JavaScript results" do
+ result = runner.run_code_all_items("return [{ name: $input.first().json.name }];")
+
+ expect(result).to eq([{ "json" => { "name" => "Ada" } }])
+ end
+
+ it "binds $json to the first input item" do
+ result = runner.run_code_all_items("return { name: $json.name };")
+
+ expect(result).to eq([{ "json" => { "name" => "Ada" } }])
+ end
+
+ it "raises node validation errors for mixed item formats" do
+ expect {
+ runner.run_code_all_items("return [{ json: { id: 1 } }, { id: 2 }];")
+ }.to raise_error(DiscourseWorkflows::NodeError, /Unknown top-level item key: id/)
+ end
+
+ it "raises node validation errors for unsupported top-level binary items" do
+ expect {
+ runner.run_code_all_items("return [{ json: { id: 1 } }, { binary: {} }];")
+ }.to raise_error(DiscourseWorkflows::NodeError, /Unknown top-level item key: binary/)
+ end
+ end
+
+ describe "#run_code_for_each_item" do
+ it "adds pairedItem metadata for per-item JavaScript results" do
+ result = runner.run_code_for_each_item("return { name: $json.name };", input_items.length)
+
+ expect(result).to eq([{ "json" => { "name" => "Ada" }, "pairedItem" => { "item" => 0 } }])
+ end
+
+ it "rejects all-items helpers in per-item mode" do
+ expect {
+ runner.run_code_for_each_item("return { count: $input.all().length };", input_items.length)
+ }.to raise_error(DiscourseWorkflows::NodeError, /Can't use \.all\(\) here/)
+ end
+ end
+
+ describe "#run_code" do
+ it "runs raw JavaScript with additional properties" do
+ runner = described_class.new("manual", exec_ctx, nil, { "items" => input_items.deep_dup })
+
+ result = runner.run_code("return items.map(function(item) { return item.json.name; });")
+
+ expect(result).to eq(["Ada"])
+ end
+
+ it "raises node errors for task runner failures without exception objects" do
+ execute_functions =
+ Class
+ .new do
+ def continue_on_fail
+ false
+ end
+
+ def start_job(*)
+ DiscourseWorkflows::Executor::NodeExecutionContext::JobResult.new(
+ ok: false,
+ result: nil,
+ error: "broken",
+ )
+ end
+ end
+ .new
+ runner = described_class.new("manual", execute_functions)
+
+ expect { runner.run_code("return 1;") }.to raise_error(
+ DiscourseWorkflows::NodeError,
+ "JavaScript execution failed: broken",
+ )
+ end
+ end
+end
diff --git a/plugins/discourse-workflows/spec/lib/discourse_workflows/nodes/code_spec.rb b/plugins/discourse-workflows/spec/lib/discourse_workflows/nodes/code_spec.rb
new file mode 100644
index 00000000000..0fc8eb28803
--- /dev/null
+++ b/plugins/discourse-workflows/spec/lib/discourse_workflows/nodes/code_spec.rb
@@ -0,0 +1,545 @@
+# frozen_string_literal: true
+
+RSpec.describe DiscourseWorkflows::Nodes::Code::V1 do
+ let(:sandbox) { DiscourseWorkflows::JsSandbox.new({}) }
+ after { sandbox.dispose }
+
+ def build_exec_ctx(items, resolver_context: nil, parameters: {}, **kwargs)
+ resolver_context ||= { "$json" => items.first&.dig("json") || {} }
+ resolver = DiscourseWorkflows::ExpressionResolver.new(resolver_context, sandbox: sandbox)
+ DiscourseWorkflows::Executor::NodeExecutionContext.new(
+ input_items: items,
+ parameters: parameters,
+ resolver: resolver,
+ resolver_context: resolver_context,
+ **kwargs,
+ )
+ end
+
+ def execute_code(code, items: [{ "json" => {} }], **kwargs)
+ parameters = { "code" => code, "mode" => "runOnceForEachItem" }
+ action = described_class.new(parameters: parameters)
+ action.execute(build_exec_ctx(items, parameters: parameters, **kwargs))[0]
+ end
+
+ def execute_all(code, items:, **kwargs)
+ parameters = { "code" => code, "mode" => "runOnceForAllItems" }
+ action = described_class.new(parameters: parameters)
+ action.execute(build_exec_ctx(items, parameters: parameters, **kwargs))[0]
+ end
+
+ def execute_code_with_log(code, items: [{ "json" => {} }], **kwargs)
+ parameters = kwargs.delete(:configuration) || { "code" => code, "mode" => "runOnceForEachItem" }
+ action = described_class.new(parameters: parameters)
+ exec_ctx = build_exec_ctx(items, parameters: parameters, **kwargs)
+ action.execute(exec_ctx)
+ exec_ctx.log
+ end
+
+ describe "#execute" do
+ it "defaults to runOnceForAllItems" do
+ parameters = { "code" => "return $input.all();" }
+ action = described_class.new(parameters: parameters)
+ result =
+ action.execute(
+ build_exec_ctx(
+ [{ "json" => { "n" => 1 } }, { "json" => { "n" => 2 } }],
+ parameters: parameters,
+ ),
+ )[
+ 0
+ ]
+
+ expect(result.map { |item| item["json"]["n"] }).to eq([1, 2])
+ end
+
+ it "rejects legacy snake_case modes" do
+ parameters = { "code" => "return { name: $json.name };", "mode" => "run_once_for_each_item" }
+ action = described_class.new(parameters: parameters)
+
+ expect {
+ action.execute(build_exec_ctx([{ "json" => {} }], parameters: parameters))
+ }.to raise_error(DiscourseWorkflows::NodeError, /Invalid Code mode/)
+ end
+
+ it "rejects unsupported modes" do
+ parameters = { "code" => "return $input.all();", "mode" => "run_sometimes" }
+ action = described_class.new(parameters: parameters)
+
+ expect {
+ action.execute(build_exec_ctx([{ "json" => {} }], parameters: parameters))
+ }.to raise_error(DiscourseWorkflows::NodeError, /Invalid Code mode/)
+ end
+
+ it "executes JavaScript and returns the result" do
+ result =
+ execute_code('return { greeting: "hello" };', items: [{ "json" => { "name" => "world" } }])
+
+ expect(result.first["json"]["greeting"]).to eq("hello")
+ end
+
+ it "exposes $json with the current item data" do
+ result =
+ execute_code("return { name: $json.name };", items: [{ "json" => { "name" => "Alice" } }])
+
+ expect(result.first["json"]["name"]).to eq("Alice")
+ end
+
+ it "caps console.log output at MAX_ENTRIES" do
+ log =
+ execute_code_with_log(
+ "for (var i = 0; i < 300; i++) { console.log('line ' + i); } return {};",
+ )
+
+ expect(log.entries.size).to eq(DiscourseWorkflows::Executor::StepLog::MAX_ENTRIES)
+ expect(log.entries.last["message"]).to include("truncated")
+ end
+
+ it "captures console.log output" do
+ log = execute_code_with_log('console.log("debug message"); return {};')
+
+ expect(log.entries.size).to eq(1)
+ expect(log.entries.first).to include("level" => "info", "message" => "debug message")
+ end
+
+ it "accumulates logs across all input items" do
+ items = [{ "json" => { "n" => 1 } }, { "json" => { "n" => 2 } }]
+ log = execute_code_with_log('console.log("item " + $json.n); return {};', items: items)
+
+ expect(log.entries.map { |e| e["message"] }).to eq(["item 1", "item 2"])
+ end
+
+ it "captures console.warn as warn level" do
+ log = execute_code_with_log('console.warn("careful"); return {};')
+
+ expect(log.entries.first).to include("level" => "warn", "message" => "careful")
+ end
+
+ it "captures console.error as error level" do
+ log = execute_code_with_log('console.error("broken"); return {};')
+
+ expect(log.entries.first).to include("level" => "error", "message" => "broken")
+ expect(log.errors?).to be(true)
+ end
+
+ it "processes each input item independently" do
+ items = [{ "json" => { "n" => 3 } }, { "json" => { "n" => 5 } }]
+ result = execute_code("return { doubled: $json.n * 2 };", items: items)
+
+ expect(result.map { |r| r["json"]["doubled"] }).to eq([6, 10])
+ end
+
+ it "raises when returning non-object values per item" do
+ expect { execute_code('return "just a string";') }.to raise_error(
+ DiscourseWorkflows::NodeError,
+ /Code doesn't return an object/,
+ )
+ end
+
+ it "raises when returning arrays per item" do
+ expect { execute_code("return [{ json: { n: 1 } }];") }.to raise_error(
+ DiscourseWorkflows::NodeError,
+ /Code doesn't return a single object/,
+ )
+ end
+
+ it "drops items when returning null per item" do
+ items = [{ "json" => { "n" => 1 } }, { "json" => { "n" => 2 } }]
+ result = execute_code("return $json.n === 1 ? { kept: $json.n } : null;", items: items)
+
+ expect(result.map { |item| item["json"]["kept"] }).to eq([1])
+ expect(result.first["pairedItem"]).to eq("item" => 0)
+ end
+
+ it "preserves item-shaped return values" do
+ result =
+ execute_code(
+ "return { json: { name: $json.name }, pairedItem: 0 };",
+ items: [{ "json" => { "name" => "Alice" } }],
+ )
+
+ expect(result.first).to eq("json" => { "name" => "Alice" }, "pairedItem" => { "item" => 0 })
+ end
+
+ it "allows returning the current input item" do
+ result = execute_code("return $input.item;", items: [{ "json" => { "name" => "Alice" } }])
+
+ expect(result.first["json"]["name"]).to eq("Alice")
+ end
+
+ it "rejects $input.all() in per-item mode" do
+ expect { execute_code("return { count: $input.all().length };") }.to raise_error(
+ DiscourseWorkflows::NodeError,
+ /Can't use \.all\(\) here/,
+ )
+ end
+
+ it "keeps $json aliased to $input.item.json" do
+ result = execute_code(<<~JS)
+ var sameRef = $json === $input.item.json;
+ $input.item.json.foo = 1;
+ $json.bar = 2;
+ return { sameRef: sameRef, foo: $json.foo, bar: $input.item.json.bar };
+ JS
+
+ expect(result.first["json"]).to include("sameRef" => true, "foo" => 1, "bar" => 2)
+ end
+
+ it "allows returning $input without cloning function properties" do
+ items = [{ "json" => { "name" => "Alice" } }]
+ result = execute_code("return $input;", items: items)
+
+ expect(result.first["json"]["item"]["json"]["name"]).to eq("Alice")
+ end
+
+ it "exposes the global item alias in per-item mode" do
+ result = execute_code("return item;", items: [{ "json" => { "name" => "Alice" } }])
+
+ expect(result.first["json"]["name"]).to eq("Alice")
+ end
+
+ it "exposes $input.params for the current code node" do
+ parameters = {
+ "code" => "return { mode: $input.params.mode };",
+ "mode" => "runOnceForEachItem",
+ }
+ action = described_class.new(parameters: parameters)
+ result = action.execute(build_exec_ctx([{ "json" => {} }], parameters: parameters))[0]
+
+ expect(result.first["json"]["mode"]).to eq("runOnceForEachItem")
+ end
+
+ it "exposes $itemIndex for each input item" do
+ items = [{ "json" => { "a" => 1 } }, { "json" => { "b" => 2 } }]
+ result = execute_code("return { itemIndex: $itemIndex };", items: items)
+
+ expect(result.map { |r| r["json"]["itemIndex"] }).to eq([0, 1])
+ end
+
+ it "raises when $input.all() exceeds the sandbox payload limit" do
+ items = [
+ { "json" => { "data" => "x" * DiscourseWorkflows::JsSandbox::MAX_INJECTED_JSON_BYTES } },
+ ]
+
+ expect { execute_all("return { count: $input.all().length };", items: items) }.to raise_error(
+ DiscourseWorkflows::JsSandbox::PayloadTooLargeError,
+ /__allInputItems/,
+ )
+ end
+
+ it "raises when $().item exceeds the sandbox payload limit" do
+ large_item = {
+ "json" => {
+ "data" => "x" * DiscourseWorkflows::JsSandbox::MAX_INJECTED_JSON_BYTES,
+ },
+ }
+
+ expect {
+ execute_code(
+ 'return $("Source").item;',
+ resolver_context: {
+ "$json" => {
+ },
+ "__current_node_id" => "code",
+ "__input_sources" => [{ "node_name" => "Source", "output_index" => 0 }],
+ "__node_runs" => {
+ "Source" => [{ "outputs" => [[large_item]] }],
+ },
+ },
+ )
+ }.to raise_error(DiscourseWorkflows::JsSandbox::PayloadTooLargeError, /\$\(\)\.item/)
+ end
+
+ context "with workflow variables" do
+ fab!(:api_key_variable) do
+ Fabricate(:discourse_workflows_variable, key: "api_key", value: "secret123")
+ end
+
+ it "accesses workflow variables via $vars" do
+ result = execute_code("return { key: $vars.api_key };")
+
+ expect(result.first["json"]["key"]).to eq("secret123")
+ end
+ end
+
+ it "filters secret site settings from $site_settings" do
+ result = execute_code("return { val: $site_settings.discourse_connect_secret };")
+
+ expect(result.first["json"]["val"]).to eq("[FILTERED]")
+ end
+
+ it "filters hidden site settings from $site_settings" do
+ result = execute_code("return { val: $site_settings.vapid_public_key };")
+
+ expect(result.first["json"]["val"]).to eq("[FILTERED]")
+ end
+
+ it "filters internal context keys from $() node output accessor" do
+ result = execute_code('return $("__resume_token").item;')
+
+ expect(result.first["json"]).to eq({})
+ end
+
+ it "exposes $execution variables" do
+ result =
+ execute_code(
+ "return { id: $execution.id, name: $execution.workflow_name };",
+ resolver_context: {
+ "$json" => {
+ },
+ "__execution" => {
+ "id" => 99,
+ "workflow_name" => "Test Flow",
+ },
+ },
+ )
+
+ expect(result.first["json"]["id"]).to eq(99)
+ expect(result.first["json"]["name"]).to eq("Test Flow")
+ end
+
+ it "allows accessing normal node outputs via $()" do
+ result =
+ execute_code(
+ 'return $("MyNode").first().json;',
+ resolver_context: {
+ "$json" => {
+ },
+ "MyNode" => [{ "json" => { "data" => "visible" } }],
+ },
+ )
+
+ expect(result.first["json"]["data"]).to eq("visible")
+ end
+
+ it "resolves $().item through pairedItem lineage" do
+ result =
+ execute_code(
+ 'return $("Split").item.json;',
+ items: [{ "json" => { "id" => 2 } }],
+ resolver_context: {
+ "$json" => {
+ "id" => 2,
+ },
+ "__current_node_id" => "code",
+ "__input_sources" => [{ "node_name" => "Filter", "output_index" => 0 }],
+ "Split" => [
+ { "json" => { "id" => 1, "label" => "first" } },
+ { "json" => { "id" => 2, "label" => "second" } },
+ ],
+ "__node_runs" => {
+ "Split" => [
+ {
+ "outputs" => [
+ [
+ { "json" => { "id" => 1, "label" => "first" } },
+ { "json" => { "id" => 2, "label" => "second" } },
+ ],
+ ],
+ "input_sources" => [{ "node_name" => "Source", "output_index" => 0 }],
+ },
+ ],
+ "Filter" => [
+ {
+ "outputs" => [[{ "json" => { "id" => 2 }, "pairedItem" => { "item" => 1 } }]],
+ "input_sources" => [{ "node_name" => "Split", "output_index" => 0 }],
+ },
+ ],
+ },
+ },
+ )
+
+ expect(result.first["json"]["label"]).to eq("second")
+ end
+
+ it "raises when $().item cannot determine pairedItem lineage" do
+ expect {
+ execute_code(
+ 'return $("Split").item.json;',
+ items: [{ "json" => { "id" => 2 } }],
+ resolver_context: {
+ "$json" => {
+ "id" => 2,
+ },
+ "__current_node_id" => "code",
+ "__input_sources" => [{ "node_name" => "Filter", "output_index" => 0 }],
+ "Split" => [
+ { "json" => { "label" => "first" } },
+ { "json" => { "label" => "second" } },
+ ],
+ "__node_runs" => {
+ "Split" => [
+ {
+ "outputs" => [
+ [{ "json" => { "label" => "first" } }, { "json" => { "label" => "second" } }],
+ ],
+ "input_sources" => [{ "node_name" => "Source", "output_index" => 0 }],
+ },
+ ],
+ "Filter" => [
+ {
+ "outputs" => [[{ "json" => { "id" => 2 } }]],
+ "input_sources" => [{ "node_name" => "Split", "output_index" => 0 }],
+ },
+ ],
+ },
+ },
+ )
+ }.to raise_error(
+ DiscourseWorkflows::JsSandbox::SandboxError,
+ /Info for expression missing from previous node/,
+ )
+ end
+
+ it "raises on invalid JavaScript" do
+ expect { execute_code("this is not valid js {{{") }.to raise_error(
+ DiscourseWorkflows::JsSandbox::SandboxError,
+ )
+ end
+
+ context "with mode runOnceForAllItems" do
+ it "runs the code once and returns array results as items" do
+ items = [{ "json" => { "n" => 1 } }, { "json" => { "n" => 2 } }, { "json" => { "n" => 3 } }]
+ result =
+ execute_all(
+ "return $input.all().map(function(i) { return { doubled: i.json.n * 2 }; });",
+ items: items,
+ )
+
+ expect(result.map { |r| r["json"]["doubled"] }).to eq([2, 4, 6])
+ end
+
+ it "exposes all-items input helpers" do
+ items = [{ "json" => { "a" => 1 } }, { "json" => { "b" => 2 } }]
+ result =
+ execute_all(
+ "return { all: $input.all().length, first: $input.first().json.a, last: $input.last().json.b };",
+ items: items,
+ )
+
+ expect(result.first["json"]).to include("all" => 2, "first" => 1, "last" => 2)
+ end
+
+ it "exposes the global items alias in all-items mode" do
+ result =
+ execute_all(
+ "return { count: items.length };",
+ items: [{ "json" => {} }, { "json" => {} }],
+ )
+
+ expect(result.first["json"]["count"]).to eq(2)
+ end
+
+ it "returns no items when code returns null" do
+ result = execute_all("return null;", items: [{ "json" => { "n" => 1 } }])
+
+ expect(result).to eq([])
+ end
+
+ it "raises when all-items code returns a primitive" do
+ expect { execute_all("return 1;", items: [{ "json" => {} }]) }.to raise_error(
+ DiscourseWorkflows::NodeError,
+ /Code doesn't return items properly/,
+ )
+ end
+
+ it "raises when an all-items array contains a primitive" do
+ expect { execute_all("return [1];", items: [{ "json" => {} }]) }.to raise_error(
+ DiscourseWorkflows::NodeError,
+ /Code doesn't return items properly/,
+ )
+ end
+
+ it "exposes node output data proxy helpers" do
+ result =
+ execute_all(
+ <<~JS,
+ return {
+ count: $("Source").all().length,
+ first: $("Source").first().json.id,
+ last: $("Source").last().json.id,
+ params: $("Source").params.mode,
+ context: $("Source").context.done,
+ executed: $("Source").isExecuted
+ };
+ JS
+ items: [{ "json" => {} }],
+ resolver_context: {
+ "$json" => {
+ },
+ "__node_parameters_by_name" => {
+ "Source" => {
+ "mode" => "manual",
+ },
+ },
+ "__node_contexts" => {
+ "Source" => {
+ "done" => true,
+ },
+ },
+ "__node_runs" => {
+ "Source" => [
+ { "outputs" => [[{ "json" => { "id" => 1 } }, { "json" => { "id" => 2 } }]] },
+ ],
+ },
+ },
+ )
+
+ expect(result.first["json"]).to include(
+ "count" => 2,
+ "first" => 1,
+ "last" => 2,
+ "params" => "manual",
+ "context" => true,
+ "executed" => true,
+ )
+ end
+
+ it "defaults node output helpers to the connected source branch" do
+ result =
+ execute_all(
+ 'return $("Source").first().json;',
+ items: [{ "json" => {} }],
+ resolver_context: {
+ "$json" => {
+ },
+ "__current_node_id" => "code",
+ "__input_sources" => [{ "node_name" => "Source", "output_index" => 1 }],
+ "__node_runs" => {
+ "Source" => [
+ {
+ "outputs" => [
+ [{ "json" => { "branch" => 0 } }],
+ [{ "json" => { "branch" => 1 } }],
+ ],
+ },
+ ],
+ },
+ },
+ )
+
+ expect(result.first["json"]["branch"]).to eq(1)
+ end
+
+ it "wraps a single object return into one item" do
+ items = [{ "json" => { "n" => 1 } }, { "json" => { "n" => 2 } }]
+ result =
+ execute_all(
+ "var sum = $input.all().reduce(function(s, i) { return s + i.json.n; }, 0); return { total: sum };",
+ items: items,
+ )
+
+ expect(result.length).to eq(1)
+ expect(result.first["json"]["total"]).to eq(3)
+ end
+
+ it "binds $json to the first item in all-items mode" do
+ items = [{ "json" => { "a" => 1 } }, { "json" => { "b" => 2 } }]
+ result = execute_all("return { keys: Object.keys($json) };", items: items)
+
+ expect(result.length).to eq(1)
+ expect(result.first["json"]["keys"]).to eq(["a"])
+ end
+ end
+ end
+end
diff --git a/plugins/discourse-workflows/spec/lib/discourse_workflows/nodes/create_post_spec.rb b/plugins/discourse-workflows/spec/lib/discourse_workflows/nodes/create_post_spec.rb
new file mode 100644
index 00000000000..d50f04f676f
--- /dev/null
+++ b/plugins/discourse-workflows/spec/lib/discourse_workflows/nodes/create_post_spec.rb
@@ -0,0 +1,185 @@
+# frozen_string_literal: true
+
+RSpec.describe DiscourseWorkflows::Nodes::CreatePost::V1 do
+ fab!(:admin)
+ fab!(:topic_owner) { Fabricate(:user, refresh_auto_groups: true) }
+ fab!(:first_post) { create_post(user: topic_owner, raw: "First post") }
+ fab!(:topic) { first_post.topic }
+
+ describe "#execute" do
+ let(:item) { { "json" => {} } }
+
+ it "creates a reply for the configured user" do
+ result = nil
+
+ expect do
+ result =
+ execute_node(
+ configuration: {
+ "topic_id" => topic.id.to_s,
+ "raw" => "Workflow reply",
+ "author_username" => admin.username,
+ },
+ item: item,
+ )
+ end.to change { topic.posts.count }.by(1)
+
+ reply = topic.posts.order(:id).last
+
+ expect(reply.raw).to eq("Workflow reply")
+ expect(reply.user_id).to eq(admin.id)
+ expect(result["post"]).to include(
+ "id" => reply.id,
+ "post_number" => reply.post_number,
+ "raw" => "Workflow reply",
+ "reply_to_post_number" => nil,
+ "user_id" => admin.id,
+ "username" => admin.username,
+ )
+ end
+
+ it "falls back to the system user when no user is configured" do
+ execute_node(
+ configuration: {
+ "topic_id" => topic.id.to_s,
+ "raw" => "Created by workflows",
+ },
+ item: item,
+ )
+
+ expect(topic.posts.order(:id).last.user_id).to eq(Discourse.system_user.id)
+ end
+
+ it "creates a reply to a specific post number" do
+ execute_node(
+ configuration: {
+ "topic_id" => topic.id.to_s,
+ "raw" => "Threaded reply",
+ "reply_to_post_number" => first_post.post_number.to_s,
+ },
+ item: item,
+ )
+
+ expect(topic.posts.order(:id).last.reply_to_post_number).to eq(first_post.post_number)
+ end
+
+ it "raises when the author_username cannot be found" do
+ expect do
+ execute_node(
+ configuration: {
+ "topic_id" => topic.id.to_s,
+ "raw" => "Workflow reply",
+ "author_username" => "nonexistent_user",
+ },
+ item: item,
+ )
+ end.to raise_error(DiscourseWorkflows::NodeError, "User 'nonexistent_user' not found")
+ end
+
+ it "raises when the author cannot see the topic" do
+ group = Fabricate(:group)
+ category = Fabricate(:private_category, group: group)
+ hidden_topic = create_post(user: admin, category: category).topic
+ author = Fabricate(:user)
+
+ expect do
+ execute_node(
+ configuration: {
+ "topic_id" => hidden_topic.id.to_s,
+ "raw" => "Workflow reply",
+ "author_username" => author.username,
+ },
+ item: item,
+ )
+ end.to raise_error(Discourse::InvalidAccess).and not_change { hidden_topic.posts.count }
+ end
+
+ it "raises when the topic is closed" do
+ topic.update!(closed: true)
+
+ expect do
+ execute_node(
+ configuration: {
+ "topic_id" => topic.id.to_s,
+ "raw" => "Workflow reply",
+ },
+ item: item,
+ )
+ end.to raise_error(
+ DiscourseWorkflows::NodeError,
+ /Cannot create a post in a closed or archived topic/,
+ )
+ end
+
+ it "raises when the topic is archived" do
+ topic.update!(archived: true)
+
+ expect do
+ execute_node(
+ configuration: {
+ "topic_id" => topic.id.to_s,
+ "raw" => "Workflow reply",
+ },
+ item: item,
+ )
+ end.to raise_error(
+ DiscourseWorkflows::NodeError,
+ /Cannot create a post in a closed or archived topic/,
+ )
+ end
+
+ it "raises when topic does not exist" do
+ expect do
+ execute_node(configuration: { "topic_id" => "-1", "raw" => "Workflow reply" }, item: item)
+ end.to raise_error(ActiveRecord::RecordNotFound)
+ end
+
+ it "resolves expressions for each input item" do
+ config = {
+ "topic_id" => "={{ $trigger.topic_id }}",
+ "raw" => "=Hello {{ $json.name }}",
+ "reply_to_post_number" => "={{ $trigger.reply_to_post_number }}",
+ "author_username" => "={{ $trigger.author_username }}",
+ }
+ resolver_context = {
+ "$json" => {
+ "name" => "Ada",
+ },
+ "$trigger" => {
+ "topic_id" => topic.id,
+ "reply_to_post_number" => first_post.post_number,
+ "author_username" => admin.username,
+ },
+ }
+ sandbox = DiscourseWorkflows::JsSandbox.new(resolver_context)
+ resolver = DiscourseWorkflows::ExpressionResolver.new(resolver_context, sandbox: sandbox)
+ result =
+ described_class.new(parameters: config).execute(
+ DiscourseWorkflows::Executor::NodeExecutionContext.new(
+ input_items: [{ "json" => { "name" => "Ada" } }],
+ node_context: {
+ },
+ resolver: resolver,
+ parameters: config,
+ property_schema: described_class.property_schema,
+ ),
+ )[
+ 0
+ ]
+
+ reply = topic.posts.order(:id).last
+
+ expect(reply.raw).to eq("Hello Ada")
+ expect(reply.reply_to_post_number).to eq(first_post.post_number)
+ expect(reply.user_id).to eq(admin.id)
+ expect(result.first["json"]["post"]).to include(
+ "id" => reply.id,
+ "post_number" => reply.post_number,
+ "raw" => "Hello Ada",
+ )
+ ensure
+ resolver&.dispose
+ sandbox&.dispose
+ end
+ end
+end
diff --git a/plugins/discourse-workflows/spec/lib/discourse_workflows/nodes/data_table_spec.rb b/plugins/discourse-workflows/spec/lib/discourse_workflows/nodes/data_table_spec.rb
new file mode 100644
index 00000000000..7e71e7e82b6
--- /dev/null
+++ b/plugins/discourse-workflows/spec/lib/discourse_workflows/nodes/data_table_spec.rb
@@ -0,0 +1,551 @@
+# frozen_string_literal: true
+
+RSpec.describe DiscourseWorkflows::Nodes::DataTable::V1 do
+ fab!(:data_table) do
+ Fabricate(
+ :discourse_workflows_data_table,
+ name: "contacts",
+ columns: [
+ { "name" => "email", "type" => "string" },
+ { "name" => "score", "type" => "number" },
+ ],
+ )
+ end
+
+ def execute_data_table(configuration)
+ execute_node_output(configuration: configuration).first
+ end
+
+ def execute_data_table_with_item(configuration, item)
+ execute_node_output(configuration: configuration, item: item).first
+ end
+
+ def filter_condition(column_name, operation, value: nil, type: "string")
+ single_value = %w[empty notEmpty true false].include?(operation)
+
+ {
+ "columnName" => column_name,
+ "operator" => {
+ "type" => type,
+ "operation" => operation,
+ "singleValue" => single_value,
+ },
+ "value" => value,
+ }
+ end
+
+ describe ".load_options_context" do
+ def load_options(filter: nil)
+ context =
+ DiscourseWorkflows::LoadOptionsContext.new(
+ method_name: "data_tables",
+ filter: filter,
+ node_class: described_class,
+ )
+
+ described_class.load_options_context(context)
+ end
+
+ it "marks reserved columns" do
+ tables = load_options
+ table_meta = tables.find { |dt| dt[:id] == data_table.id }
+ column_names_reserved = table_meta[:columns].select { |c| c[:reserved] }.map { |c| c[:name] }
+
+ expect(column_names_reserved).to contain_exactly("id", "created_at", "updated_at")
+ expect(table_meta[:columns].find { |c| c[:name] == "email" }).not_to have_key(:reserved)
+ end
+
+ it "filters data tables by the filter term" do
+ Fabricate(:discourse_workflows_data_table, name: "projects")
+
+ expect(load_options(filter: "cont").map { |table| table[:id] }).to contain_exactly(
+ data_table.id,
+ )
+ end
+ end
+
+ describe "error handling" do
+ it "raises when data table does not exist" do
+ expect {
+ execute_data_table(
+ "operation" => "insert",
+ "data_table_id" => "-1",
+ "columns" => {
+ "email" => "x",
+ },
+ )
+ }.to raise_error(ActiveRecord::RecordNotFound)
+ end
+
+ it "raises for unknown column names" do
+ expect {
+ execute_data_table(
+ "operation" => "insert",
+ "data_table_id" => data_table.id.to_s,
+ "columns" => {
+ "nonexistent" => "test",
+ },
+ )
+ }.to raise_error(DiscourseWorkflows::NodeError, /Unknown column name/)
+ end
+
+ it "raises invalid row errors with the node error prefix" do
+ expect {
+ execute_data_table(
+ "operation" => "insert",
+ "data_table_id" => data_table.id.to_s,
+ "columns" => {
+ "score" => "not-a-number",
+ },
+ )
+ }.to raise_error(DiscourseWorkflows::NodeError, /Invalid row: Value 'not-a-number'/)
+ end
+
+ it "raises invalid query errors with the node error prefix" do
+ expect {
+ execute_data_table(
+ "operation" => "get",
+ "data_table_id" => data_table.id.to_s,
+ "filter" => [filter_condition("nonexistent", "equals", value: "test")],
+ )
+ }.to raise_error(DiscourseWorkflows::NodeError, /Invalid query: Unknown column name/)
+ end
+
+ it "raises for unknown operations" do
+ expect {
+ execute_data_table("operation" => "truncate", "data_table_id" => data_table.id.to_s)
+ }.to raise_error(DiscourseWorkflows::NodeError, /Unknown operation/)
+ end
+ end
+
+ describe "insert operation" do
+ it "raises when the storage limit is exceeded" do
+ allow(DiscourseWorkflows::DataTables::Facade).to receive(:within_storage_limit?).and_return(
+ false,
+ )
+
+ expect {
+ execute_data_table(
+ "operation" => "insert",
+ "data_table_id" => data_table.id.to_s,
+ "columns" => {
+ "email" => "[email protected]",
+ "score" => "42",
+ },
+ )
+ }.to raise_error(DiscourseWorkflows::NodeError, "Data table storage limit exceeded")
+ end
+
+ context "when mapping_mode is auto" do
+ it "picks matching keys from the incoming item JSON" do
+ items =
+ execute_data_table_with_item(
+ {
+ "operation" => "insert",
+ "data_table_id" => data_table.id.to_s,
+ "mapping_mode" => "auto",
+ },
+ { "json" => { "email" => "[email protected]", "score" => 7, "ignored" => "value" } },
+ )
+
+ expect(items[0]["json"]).to include("email" => "[email protected]", "score" => 7)
+ expect(count_data_table_rows(data_table)).to eq(1)
+ end
+
+ it "ignores keys whose case does not match a column name" do
+ items =
+ execute_data_table_with_item(
+ {
+ "operation" => "insert",
+ "data_table_id" => data_table.id.to_s,
+ "mapping_mode" => "auto",
+ },
+ { "json" => { "Email" => "[email protected]", "email" => "[email protected]" } },
+ )
+
+ expect(items[0]["json"]).to include("email" => "[email protected]")
+ expect(items[0]["json"]).not_to have_key("Email")
+ end
+
+ it "inserts each input item and preserves item pairing" do
+ items =
+ execute_node_output(
+ configuration: {
+ "operation" => "insert",
+ "data_table_id" => data_table.id.to_s,
+ "mapping_mode" => "auto",
+ },
+ input_items: [
+ { "json" => { "email" => "[email protected]", "score" => 1 } },
+ { "json" => { "email" => "[email protected]", "score" => 2 } },
+ ],
+ ).first
+
+ expect(items.map { |item| item["json"].slice("email", "score") }).to eq(
+ [
+ { "email" => "[email protected]", "score" => 1 },
+ { "email" => "[email protected]", "score" => 2 },
+ ],
+ )
+ expect(items.map { |item| item["pairedItem"] }).to eq([{ "item" => 0 }, { "item" => 1 }])
+ expect(count_data_table_rows(data_table)).to eq(2)
+ end
+ end
+ end
+
+ describe "get operation" do
+ before do
+ insert_data_table_row(data_table, "email" => "[email protected]", "score" => 10)
+ insert_data_table_row(data_table, "email" => "[email protected]", "score" => 20)
+ end
+
+ it "resolves filters for each input item and preserves item pairing" do
+ items =
+ execute_node_output(
+ configuration: {
+ "operation" => "get",
+ "data_table_id" => data_table.id.to_s,
+ "filter" => [filter_condition("email", "contains", value: "={{ $json.domain }}")],
+ "sort_column" => "email",
+ "sort_direction" => "asc",
+ },
+ input_items: [
+ { "json" => { "domain" => "example.com" } },
+ { "json" => { "domain" => "test.com" } },
+ ],
+ ).first
+
+ expect(items.map { |item| item["json"]["email"] }).to eq(%w[[email protected] [email protected]])
+ expect(items.map { |item| item["pairedItem"] }).to eq([{ "item" => 0 }, { "item" => 1 }])
+ end
+
+ it "preserves item pairing when one input item returns multiple rows" do
+ items =
+ execute_node_output(
+ configuration: {
+ "operation" => "get",
+ "data_table_id" => data_table.id.to_s,
+ "sort_column" => "email",
+ "sort_direction" => "asc",
+ },
+ input_items: [{ "json" => {} }],
+ ).first
+
+ expect(items.map { |item| item["json"]["email"] }).to eq(%w[[email protected] [email protected]])
+ expect(items.map { |item| item["pairedItem"] }).to eq([{ "item" => 0 }, { "item" => 0 }])
+ end
+
+ it "defaults to the maximum result limit" do
+ 99.times do |index|
+ insert_data_table_row(data_table, "email" => "extra-#{index}@example.com", "score" => index)
+ end
+
+ items =
+ execute_data_table(
+ "operation" => "get",
+ "data_table_id" => data_table.id.to_s,
+ "sort_column" => "email",
+ "sort_direction" => "asc",
+ )
+
+ expect(items.size).to eq(DiscourseWorkflows::DataTables::Facade::MAX_LIMIT)
+ end
+
+ it "treats empty as null only" do
+ insert_data_table_row(data_table, "email" => nil, "score" => 30)
+ insert_data_table_row(data_table, "email" => "", "score" => 40)
+
+ items =
+ execute_data_table(
+ "operation" => "get",
+ "data_table_id" => data_table.id.to_s,
+ "filter" => [filter_condition("email", "empty")],
+ )
+
+ expect(items.map { |item| item["json"]["email"] }).to contain_exactly(nil)
+ end
+
+ it "treats empty strings as not empty" do
+ insert_data_table_row(data_table, "email" => nil, "score" => 30)
+ insert_data_table_row(data_table, "email" => "", "score" => 40)
+
+ items =
+ execute_data_table(
+ "operation" => "get",
+ "data_table_id" => data_table.id.to_s,
+ "filter" => [filter_condition("email", "notEmpty")],
+ )
+
+ expect(items.map { |item| item["json"]["email"] }).to contain_exactly(
+ "",
+ )
+ end
+ end
+
+ describe "update operation" do
+ fab!(:row) { insert_data_table_row(data_table, "email" => "[email protected]", "score" => 1) }
+
+ it "requires a filter" do
+ insert_data_table_row(data_table, "email" => "[email protected]", "score" => 2)
+
+ expect {
+ execute_data_table(
+ "operation" => "update",
+ "data_table_id" => data_table.id.to_s,
+ "columns" => {
+ "score" => "77",
+ },
+ )
+ }.to raise_error(DiscourseWorkflows::NodeError, /Filter must not be empty/)
+ end
+
+ it "updates matching rows and returns the updated rows" do
+ insert_data_table_row(data_table, "email" => "[email protected]", "score" => 2)
+
+ items =
+ execute_data_table(
+ "operation" => "update",
+ "data_table_id" => data_table.id.to_s,
+ "filter" => [filter_condition("email", "equals", value: "[email protected]")],
+ "columns" => {
+ "score" => "77",
+ },
+ )
+
+ expect(items.map { |item| item["json"].slice("email", "score") }).to eq(
+ [{ "email" => "[email protected]", "score" => 77 }],
+ )
+ expect(count_data_table_rows(data_table)).to eq(2)
+ end
+
+ it "raises when the storage limit is exceeded" do
+ allow(DiscourseWorkflows::DataTables::Facade).to receive(:within_storage_limit?).and_return(
+ false,
+ )
+
+ expect {
+ execute_data_table(
+ "operation" => "update",
+ "data_table_id" => data_table.id.to_s,
+ "filter" => [filter_condition("email", "equals", value: "[email protected]")],
+ "columns" => {
+ "score" => "99",
+ },
+ )
+ }.to raise_error(DiscourseWorkflows::NodeError, "Data table storage limit exceeded")
+ end
+ end
+
+ describe "delete operation" do
+ before { insert_data_table_row(data_table, "email" => "[email protected]", "score" => 5) }
+
+ it "requires a filter" do
+ insert_data_table_row(data_table, "email" => "[email protected]", "score" => 10)
+
+ expect {
+ execute_data_table("operation" => "delete", "data_table_id" => data_table.id.to_s)
+ }.to raise_error(DiscourseWorkflows::NodeError, /Filter must not be empty/)
+ end
+
+ it "deletes matching rows and returns the deleted rows" do
+ insert_data_table_row(data_table, "email" => "[email protected]", "score" => 10)
+
+ items =
+ execute_data_table(
+ "operation" => "delete",
+ "data_table_id" => data_table.id.to_s,
+ "filter" => [filter_condition("email", "equals", value: "[email protected]")],
+ )
+
+ expect(items.map { |item| item["json"].slice("email", "score") }).to eq(
+ [{ "email" => "[email protected]", "score" => 5 }],
+ )
+ expect(count_data_table_rows(data_table)).to eq(1)
+ end
+
+ it "deletes when storage is over the limit" do
+ allow(DiscourseWorkflows::DataTables::Facade).to receive(:within_storage_limit?).and_return(
+ false,
+ )
+
+ items =
+ execute_data_table(
+ "operation" => "delete",
+ "data_table_id" => data_table.id.to_s,
+ "filter" => [filter_condition("email", "equals", value: "[email protected]")],
+ )
+
+ expect(items.map { |item| item["json"].slice("email", "score") }).to eq(
+ [{ "email" => "[email protected]", "score" => 5 }],
+ )
+ expect(count_data_table_rows(data_table)).to eq(0)
+ end
+ end
+
+ describe "row_exists operation" do
+ before { insert_data_table_row(data_table, "email" => "[email protected]", "score" => 10) }
+
+ it "emits the input item unchanged when at least one row matches" do
+ items =
+ execute_data_table_with_item(
+ {
+ "operation" => "row_exists",
+ "data_table_id" => data_table.id.to_s,
+ "filter" => [filter_condition("email", "equals", value: "[email protected]")],
+ },
+ { "json" => { "input_marker" => "keep-me" } },
+ )
+
+ expect(items.length).to eq(1)
+ expect(items.first["json"]).to eq("input_marker" => "keep-me")
+ expect(items.first["json"]).not_to have_key("email")
+ expect(items.first["pairedItem"]).to eq("item" => 0)
+ end
+
+ it "drops the input item when no row matches" do
+ items =
+ execute_data_table_with_item(
+ {
+ "operation" => "row_exists",
+ "data_table_id" => data_table.id.to_s,
+ "filter" => [filter_condition("email", "equals", value: "[email protected]")],
+ },
+ { "json" => { "input_marker" => "drop-me" } },
+ )
+
+ expect(items).to eq([])
+ end
+
+ it "raises when the filter is missing" do
+ expect {
+ execute_data_table("operation" => "row_exists", "data_table_id" => data_table.id.to_s)
+ }.to raise_error(DiscourseWorkflows::NodeError, /Filter must not be empty/)
+ end
+
+ it "raises when the filter is an empty array" do
+ expect {
+ execute_data_table(
+ "operation" => "row_exists",
+ "data_table_id" => data_table.id.to_s,
+ "filter" => [],
+ )
+ }.to raise_error(DiscourseWorkflows::NodeError, /Filter must not be empty/)
+ end
+ end
+
+ describe "row_not_exists operation" do
+ before { insert_data_table_row(data_table, "email" => "[email protected]", "score" => 10) }
+
+ it "emits the input item unchanged when no row matches" do
+ items =
+ execute_data_table_with_item(
+ {
+ "operation" => "row_not_exists",
+ "data_table_id" => data_table.id.to_s,
+ "filter" => [filter_condition("email", "equals", value: "[email protected]")],
+ },
+ { "json" => { "input_marker" => "keep-me" } },
+ )
+
+ expect(items.length).to eq(1)
+ expect(items.first["json"]).to eq("input_marker" => "keep-me")
+ expect(items.first["pairedItem"]).to eq("item" => 0)
+ end
+
+ it "drops the input item when at least one row matches" do
+ items =
+ execute_data_table_with_item(
+ {
+ "operation" => "row_not_exists",
+ "data_table_id" => data_table.id.to_s,
+ "filter" => [filter_condition("email", "equals", value: "[email protected]")],
+ },
+ { "json" => { "input_marker" => "drop-me" } },
+ )
+
+ expect(items).to eq([])
+ end
+
+ it "raises when the filter is missing" do
+ expect {
+ execute_data_table("operation" => "row_not_exists", "data_table_id" => data_table.id.to_s)
+ }.to raise_error(DiscourseWorkflows::NodeError, /Filter must not be empty/)
+ end
+ end
+
+ describe "upsert operation" do
+ it "requires a filter" do
+ insert_data_table_row(data_table, "email" => "[email protected]", "score" => 1)
+
+ expect {
+ execute_data_table(
+ "operation" => "upsert",
+ "data_table_id" => data_table.id.to_s,
+ "columns" => {
+ "email" => "[email protected]",
+ "score" => "10",
+ },
+ )
+ }.to raise_error(DiscourseWorkflows::NodeError, /Filter must not be empty/)
+ end
+
+ it "inserts when the filter does not match a row" do
+ insert_data_table_row(data_table, "email" => "[email protected]", "score" => 1)
+
+ items =
+ execute_data_table(
+ "operation" => "upsert",
+ "data_table_id" => data_table.id.to_s,
+ "filter" => [filter_condition("email", "equals", value: "[email protected]")],
+ "columns" => {
+ "email" => "[email protected]",
+ "score" => "10",
+ },
+ )
+
+ expect(items.map { |item| item["json"].slice("email", "score") }).to eq(
+ [{ "email" => "[email protected]", "score" => 10 }],
+ )
+ expect(count_data_table_rows(data_table)).to eq(2)
+ end
+
+ it "updates when the filter matches an existing row" do
+ insert_data_table_row(data_table, "email" => "[email protected]", "score" => 1)
+
+ items =
+ execute_data_table(
+ "operation" => "upsert",
+ "data_table_id" => data_table.id.to_s,
+ "filter" => [filter_condition("email", "equals", value: "[email protected]")],
+ "columns" => {
+ "score" => "10",
+ },
+ )
+
+ expect(items.map { |item| item["json"].slice("email", "score") }).to eq(
+ [{ "email" => "[email protected]", "score" => 10 }],
+ )
+ expect(count_data_table_rows(data_table)).to eq(1)
+ end
+
+ it "raises when the storage limit is exceeded" do
+ allow(DiscourseWorkflows::DataTables::Facade).to receive(:within_storage_limit?).and_return(
+ false,
+ )
+
+ expect {
+ execute_data_table(
+ "operation" => "upsert",
+ "data_table_id" => data_table.id.to_s,
+ "filter" => [filter_condition("email", "equals", value: "[email protected]")],
+ "columns" => {
+ "email" => "[email protected]",
+ "score" => "50",
+ },
+ )
+ }.to raise_error(DiscourseWorkflows::NodeError, "Data table storage limit exceeded")
+ end
+ end
+end
diff --git a/plugins/discourse-workflows/spec/lib/discourse_workflows/nodes/filter_spec.rb b/plugins/discourse-workflows/spec/lib/discourse_workflows/nodes/filter_spec.rb
new file mode 100644
index 00000000000..48b64e27052
--- /dev/null
+++ b/plugins/discourse-workflows/spec/lib/discourse_workflows/nodes/filter_spec.rb
@@ -0,0 +1,97 @@
+# frozen_string_literal: true
+
+RSpec.describe DiscourseWorkflows::Nodes::Filter::V1 do
+ describe "#execute" do
+ let(:category_id_equals_5_config) do
+ {
+ "conditions" => [
+ {
+ "id" => "1",
+ "leftValue" => "={{ $json.category_id }}",
+ "rightValue" => "5",
+ "operator" => {
+ "type" => "number",
+ "operation" => "equals",
+ },
+ },
+ ],
+ "combinator" => "and",
+ }
+ end
+
+ it "routes passing items to true" do
+ items = [{ "json" => { "category_id" => 5 } }]
+ result = execute_node_output(configuration: category_id_equals_5_config, input_items: items)
+ expect(result[0]).to eq(items)
+ expect(result[1]).to eq([])
+ end
+
+ it "routes failing items to false" do
+ items = [{ "json" => { "category_id" => 10 } }]
+ result = execute_node_output(configuration: category_id_equals_5_config, input_items: items)
+ expect(result[0]).to eq([])
+ expect(result[1]).to eq(items)
+ end
+
+ it "uses already-resolved string literals as values" do
+ config = {
+ "conditions" => [
+ {
+ "id" => "1",
+ "leftValue" => "2",
+ "rightValue" => "2",
+ "operator" => {
+ "type" => "string",
+ "operation" => "equals",
+ },
+ },
+ ],
+ "combinator" => "and",
+ }
+ items = [{ "json" => { "category_id" => 5 } }]
+ result = execute_node_output(configuration: config, input_items: items)
+ expect(result[0]).to eq(items)
+ end
+
+ it "works with expression-resolved left values" do
+ config = {
+ "conditions" => [
+ {
+ "id" => "1",
+ "leftValue" => %w[bug help],
+ "rightValue" => "bug",
+ "operator" => {
+ "type" => "array",
+ "operation" => "contains",
+ },
+ },
+ ],
+ "combinator" => "and",
+ }
+ items = [{ "json" => {} }]
+ result = execute_node_output(configuration: config, input_items: items)
+ expect(result[0]).to eq(items)
+ end
+
+ it "filters out null array values for empty checks" do
+ config = {
+ "conditions" => [
+ {
+ "id" => "1",
+ "leftValue" => "={{ $json.tags }}",
+ "operator" => {
+ "type" => "array",
+ "operation" => "empty",
+ "singleValue" => true,
+ },
+ },
+ ],
+ "combinator" => "and",
+ }
+ items = [{ "json" => { "tags" => nil } }]
+ result = execute_node_output(configuration: config, input_items: items)
+ expect(result[0]).to eq([])
+ expect(result[1]).to eq(items)
+ end
+ end
+end
diff --git a/plugins/discourse-workflows/spec/lib/discourse_workflows/nodes/form_spec.rb b/plugins/discourse-workflows/spec/lib/discourse_workflows/nodes/form_spec.rb
new file mode 100644
index 00000000000..3f424e23a6f
--- /dev/null
+++ b/plugins/discourse-workflows/spec/lib/discourse_workflows/nodes/form_spec.rb
@@ -0,0 +1,46 @@
+# frozen_string_literal: true
+
+RSpec.describe DiscourseWorkflows::Nodes::Form::V1 do
+ let(:sandbox) { DiscourseWorkflows::JsSandbox.new({ "$json" => {} }) }
+ after { sandbox.dispose }
+
+ def build_exec_ctx(configuration, resume_token: nil)
+ DiscourseWorkflows::Executor::NodeExecutionContext.new(
+ input_items: [{ "json" => {} }],
+ parameters: configuration,
+ property_schema: described_class.property_schema,
+ node_context: {
+ },
+ resolver: DiscourseWorkflows::ExpressionResolver.new({ "$json" => {} }, sandbox: sandbox),
+ resume_token: resume_token,
+ )
+ end
+
+ describe "#execute" do
+ it "returns input items for non-completion forms" do
+ config = {
+ "form_title" => "Approval",
+ "form_description" => "Please approve",
+ "form_fields" => [{ "field_label" => "Reason", "field_type" => "text" }],
+ }
+ exec_ctx = build_exec_ctx(config, resume_token: "tok-xyz")
+
+ result = described_class.new(parameters: config).execute(exec_ctx)
+
+ expect(result).to eq([exec_ctx.input_items])
+ end
+
+ it "passes completion forms through without reaching into flow context" do
+ config = {
+ "page_type" => "completion",
+ "on_submission" => "completion_screen",
+ "completion_title" => "Done",
+ }
+ exec_ctx = build_exec_ctx(config, resume_token: "tok-xyz")
+
+ result = described_class.new(parameters: config).execute(exec_ctx)
+
+ expect(result).to eq([exec_ctx.input_items])
+ end
+ end
+end
diff --git a/plugins/discourse-workflows/spec/lib/discourse_workflows/nodes/form_trigger_spec.rb b/plugins/discourse-workflows/spec/lib/discourse_workflows/nodes/form_trigger_spec.rb
new file mode 100644
index 00000000000..26ac56d86e0
--- /dev/null
+++ b/plugins/discourse-workflows/spec/lib/discourse_workflows/nodes/form_trigger_spec.rb
@@ -0,0 +1,27 @@
+# frozen_string_literal: true
+
+RSpec.describe DiscourseWorkflows::Nodes::FormTrigger::V1 do
+ describe "#output" do
+ it "returns compatible form data and metadata" do
+ trigger =
+ described_class.new(
+ form_data: {
+ name: "Test",
+ },
+ submitted_at: "2026-01-01T00:00:00.000Z",
+ query_parameters: {
+ source: "email",
+ },
+ )
+
+ expect(trigger.output).to eq(
+ "name" => "Test",
+ "submitted_at" => "2026-01-01T00:00:00.000Z",
+ "form_mode" => "production",
+ "form_query_parameters" => {
+ "source" => "email",
+ },
+ )
+ end
+ end
+end
diff --git a/plugins/discourse-workflows/spec/lib/discourse_workflows/nodes/group_spec.rb b/plugins/discourse-workflows/spec/lib/discourse_workflows/nodes/group_spec.rb
new file mode 100644
index 00000000000..597547c7afa
--- /dev/null
+++ b/plugins/discourse-workflows/spec/lib/discourse_workflows/nodes/group_spec.rb
@@ -0,0 +1,224 @@
+# frozen_string_literal: true
+
+RSpec.describe DiscourseWorkflows::Nodes::Group::V1 do
+ fab!(:user)
+ fab!(:admin)
+ fab!(:group)
+ fab!(:group_2) { Fabricate(:group, name: "another_group") }
+
+ describe ".load_options_context" do
+ def load_options(parameters: {}, filter: nil)
+ context =
+ DiscourseWorkflows::LoadOptionsContext.new(
+ method_name: "groups",
+ parameters: parameters,
+ filter: filter,
+ node_class: described_class,
+ )
+
+ described_class.load_options_context(context)
+ end
+
+ it "returns non-automatic groups for the chooser" do
+ expect(load_options).to include(
+ { id: group.id, name: group.name },
+ { id: group_2.id, name: group_2.name },
+ )
+ end
+
+ it "excludes automatic groups" do
+ auto_group_ids = load_options.map { |g| g[:id] }
+ expect(auto_group_ids).not_to include(*Group::AUTO_GROUPS.values)
+ end
+
+ it "can include automatic groups when the current operation only reads a group" do
+ group_ids = load_options(parameters: { operation: "get" }).map { |g| g[:id] }
+
+ expect(group_ids).to include(*Group::AUTO_GROUPS.values)
+ end
+
+ it "filters groups by the filter term" do
+ expect(load_options(filter: "another")).to contain_exactly(
+ { id: group_2.id, name: group_2.name },
+ )
+ end
+ end
+
+ describe "#execute" do
+ let(:item) { { "json" => {} } }
+
+ context "with add operation" do
+ it "adds the user to the group" do
+ config = { "operation" => "add", "username" => user.username, "group_id" => group.id.to_s }
+
+ result = execute_node(configuration: config, item: item)
+
+ expect(result["group"]["id"]).to eq(group.id)
+ expect(result["group"]["name"]).to eq(group.name)
+ expect(result["user"]["id"]).to eq(user.id)
+ expect(result["user"]["username"]).to eq(user.username)
+ expect(GroupUser.exists?(user: user, group: group)).to be(true)
+ end
+
+ it "is idempotent when user is already a member" do
+ group.add(user)
+
+ config = { "operation" => "add", "username" => user.username, "group_id" => group.id.to_s }
+
+ expect { execute_node(configuration: config, item: item) }.not_to change {
+ GroupUser.where(user: user, group: group).count
+ }
+ end
+
+ it "logs the action in group history" do
+ config = { "operation" => "add", "username" => user.username, "group_id" => group.id.to_s }
+
+ expect { execute_node(configuration: config, item: item) }.to change {
+ GroupHistory.where(
+ group: group,
+ target_user: user,
+ action: GroupHistory.actions[:add_user_to_group],
+ ).count
+ }.by(1)
+ end
+
+ it "raises when actor_username cannot edit the group" do
+ config = {
+ "operation" => "add",
+ "username" => user.username,
+ "group_id" => group.id.to_s,
+ "actor_username" => user.username,
+ }
+
+ expect { execute_node(configuration: config, item: item) }.to raise_error(
+ Discourse::InvalidAccess,
+ )
+ end
+ end
+
+ context "with remove operation" do
+ it "removes the user from the group" do
+ group.add(user)
+
+ config = {
+ "operation" => "remove",
+ "username" => user.username,
+ "group_id" => group.id.to_s,
+ }
+
+ result = execute_node(configuration: config, item: item)
+
+ expect(result["group"]["id"]).to eq(group.id)
+ expect(result["group"]["name"]).to eq(group.name)
+ expect(result["user"]["id"]).to eq(user.id)
+ expect(result["user"]["username"]).to eq(user.username)
+ expect(GroupUser.exists?(user: user, group: group)).to be(false)
+ end
+
+ it "logs the removal in group history" do
+ group.add(user)
+
+ config = {
+ "operation" => "remove",
+ "username" => user.username,
+ "group_id" => group.id.to_s,
+ }
+
+ expect { execute_node(configuration: config, item: item) }.to change {
+ GroupHistory.where(
+ group: group,
+ target_user: user,
+ action: GroupHistory.actions[:remove_user_from_group],
+ ).count
+ }.by(1)
+ end
+
+ it "raises when actor_username cannot edit the group" do
+ config = {
+ "operation" => "remove",
+ "username" => user.username,
+ "group_id" => group.id.to_s,
+ "actor_username" => user.username,
+ }
+
+ expect { execute_node(configuration: config, item: item) }.to raise_error(
+ Discourse::InvalidAccess,
+ )
+ end
+ end
+
+ it "raises when user does not exist" do
+ config = {
+ "operation" => "add",
+ "username" => "nonexistent_user",
+ "group_id" => group.id.to_s,
+ }
+
+ expect { execute_node(configuration: config, item: item) }.to raise_error(
+ DiscourseWorkflows::NodeError,
+ "User 'nonexistent_user' not found",
+ )
+ end
+
+ it "raises when group does not exist" do
+ config = { "operation" => "add", "username" => user.username, "group_id" => "-1" }
+
+ expect { execute_node(configuration: config, item: item) }.to raise_error(
+ ActiveRecord::RecordNotFound,
+ )
+ end
+
+ it "uses actor_username for group action logging" do
+ config = {
+ "operation" => "add",
+ "username" => user.username,
+ "group_id" => group.id.to_s,
+ "actor_username" => admin.username,
+ }
+
+ execute_node(configuration: config, item: item)
+
+ expect(
+ GroupHistory.find_by(
+ group: group,
+ target_user: user,
+ action: GroupHistory.actions[:add_user_to_group],
+ ).acting_user_id,
+ ).to eq(admin.id)
+ end
+
+ context "with get operation" do
+ it "returns group data" do
+ config = { "operation" => "get", "group_id" => group.id.to_s }
+
+ result = execute_node(configuration: config, item: item)
+
+ expect(result["group"]["id"]).to eq(group.id)
+ expect(result["group"]["name"]).to eq(group.name)
+ expect(result["group"]["user_count"]).to eq(group.user_count)
+ expect(result["group"]["automatic"]).to be(false)
+ end
+
+ it "raises when group does not exist" do
+ config = { "operation" => "get", "group_id" => "-1" }
+
+ expect { execute_node(configuration: config, item: item) }.to raise_error(
+ ActiveRecord::RecordNotFound,
+ )
+ end
+
+ it "raises when actor_username cannot see the group" do
+ group.update!(visibility_level: Group.visibility_levels[:staff])
+ config = {
+ "operation" => "get",
+ "group_id" => group.id.to_s,
+ "actor_username" => user.username,
+ }
+
+ expect { execute_node(configuration: config, item: item) }.to raise_error(
+ Discourse::InvalidAccess,
+ )
+ end
+ end
+ end
+end
diff --git a/plugins/discourse-workflows/spec/lib/discourse_workflows/nodes/http_request/authenticator_spec.rb b/plugins/discourse-workflows/spec/lib/discourse_workflows/nodes/http_request/authenticator_spec.rb
new file mode 100644
index 00000000000..11d4edc083e
--- /dev/null
+++ b/plugins/discourse-workflows/spec/lib/discourse_workflows/nodes/http_request/authenticator_spec.rb
@@ -0,0 +1,67 @@
+# frozen_string_literal: true
+
+RSpec.describe DiscourseWorkflows::Nodes::HttpRequest::Authenticator do
+ describe ".apply" do
+ it "does nothing when authentication is none" do
+ headers = {}
+ described_class.apply({ "authentication" => "none" }, headers, nil)
+
+ expect(headers).not_to have_key("Authorization")
+ end
+
+ it "does nothing when authentication is not specified" do
+ headers = {}
+ described_class.apply({}, headers, nil)
+
+ expect(headers).not_to have_key("Authorization")
+ end
+
+ it "raises when the auth credential slot is missing for auth modes" do
+ exec_ctx =
+ instance_double(DiscourseWorkflows::Executor::NodeExecutionContext, get_credentials: nil)
+ allow(exec_ctx).to receive(:get_credentials).with("auth", 0).and_raise(
+ Discourse::InvalidAccess,
+ )
+
+ expect {
+ described_class.apply({ "authentication" => "basic_auth" }, {}, exec_ctx)
+ }.to raise_error(Discourse::InvalidAccess)
+ end
+
+ context "with basic_auth" do
+ it "sets Authorization header with Base64 credentials" do
+ headers = {}
+ exec_ctx =
+ instance_double(
+ DiscourseWorkflows::Executor::NodeExecutionContext,
+ get_credentials: {
+ "user" => "api_user",
+ "password" => "api_pass",
+ },
+ )
+
+ described_class.apply({ "authentication" => "basic_auth" }, headers, exec_ctx)
+
+ expected = "Basic #{Base64.strict_encode64("api_user:api_pass")}"
+ expect(headers["Authorization"]).to eq(expected)
+ end
+ end
+
+ context "with bearer_token" do
+ it "sets Bearer Authorization header" do
+ headers = {}
+ exec_ctx =
+ instance_double(
+ DiscourseWorkflows::Executor::NodeExecutionContext,
+ get_credentials: {
+ "token" => "my-secret-token",
+ },
+ )
+
+ described_class.apply({ "authentication" => "bearer_token" }, headers, exec_ctx)
+
+ expect(headers["Authorization"]).to eq("Bearer my-secret-token")
+ end
+ end
+ end
+end
diff --git a/plugins/discourse-workflows/spec/lib/discourse_workflows/nodes/http_request/request_builder_spec.rb b/plugins/discourse-workflows/spec/lib/discourse_workflows/nodes/http_request/request_builder_spec.rb
new file mode 100644
index 00000000000..2ed9218603b
--- /dev/null
+++ b/plugins/discourse-workflows/spec/lib/discourse_workflows/nodes/http_request/request_builder_spec.rb
@@ -0,0 +1,108 @@
+# frozen_string_literal: true
+
+RSpec.describe DiscourseWorkflows::Nodes::HttpRequest::RequestBuilder do
+ describe "#build" do
+ it "builds a GET request with method, uri, headers, and nil body" do
+ config = { "method" => "GET", "url" => "https://example.com/api" }
+ method, uri, headers, body = described_class.new(config).build
+
+ expect(method).to eq(:get)
+ expect(uri.to_s).to eq("https://example.com/api")
+ expect(headers).to eq({})
+ expect(body).to be_nil
+ end
+
+ it "raises when URL is blank" do
+ expect { described_class.new("method" => "GET", "url" => "").build }.to raise_error(
+ DiscourseWorkflows::NodeError,
+ "URL is required.",
+ )
+ end
+
+ it "raises for non-HTTP schemes" do
+ expect { described_class.new("url" => "ftp://example.com").build }.to raise_error(
+ DiscourseWorkflows::NodeError,
+ /Only HTTP and HTTPS/,
+ )
+ end
+
+ it "allows non-standard ports" do
+ config = { "method" => "GET", "url" => "https://example.com:8443/api" }
+ _, uri, _, _ = described_class.new(config).build
+
+ expect(uri.port).to eq(8443)
+ end
+
+ it "appends query params to the URL" do
+ config = {
+ "method" => "GET",
+ "url" => "https://example.com/api",
+ "query_params" => [
+ { "key" => "page", "value" => "1" },
+ { "key" => "per", "value" => "10" },
+ ],
+ }
+ _, uri, _, _ = described_class.new(config).build
+
+ expect(uri.query).to include("page=1")
+ expect(uri.query).to include("per=10")
+ end
+
+ it "merges query params with existing ones" do
+ config = {
+ "method" => "GET",
+ "url" => "https://example.com/api?existing=true",
+ "query_params" => [{ "key" => "extra", "value" => "yes" }],
+ }
+ _, uri, _, _ = described_class.new(config).build
+
+ expect(uri.query).to include("existing=true")
+ expect(uri.query).to include("extra=yes")
+ end
+
+ it "uses normalized headers" do
+ config = {
+ "method" => "GET",
+ "url" => "https://example.com/api",
+ "headers" => {
+ "X-Custom" => "test",
+ "Accept" => "application/json",
+ },
+ }
+ _, _, headers, _ = described_class.new(config).build
+
+ expect(headers).to include("X-Custom" => "test", "Accept" => "application/json")
+ end
+
+ it "sets Content-Type and returns body for POST requests" do
+ config = {
+ "method" => "POST",
+ "url" => "https://example.com/api",
+ "body_json" => '{"name":"test"}',
+ }
+ method, _, headers, body = described_class.new(config).build
+
+ expect(method).to eq(:post)
+ expect(headers["Content-Type"]).to eq("application/json")
+ expect(body).to eq('{"name":"test"}')
+ end
+
+ it "does not set body for GET requests even if body is provided" do
+ config = {
+ "method" => "GET",
+ "url" => "https://example.com/api",
+ "body_json" => '{"name":"test"}',
+ }
+ _, _, _, body = described_class.new(config).build
+
+ expect(body).to be_nil
+ end
+
+ it "defaults method to GET" do
+ config = { "url" => "https://example.com/api" }
+ method, _, _, _ = described_class.new(config).build
+
+ expect(method).to eq(:get)
+ end
+ end
+end
diff --git a/plugins/discourse-workflows/spec/lib/discourse_workflows/nodes/http_request/response_parser_spec.rb b/plugins/discourse-workflows/spec/lib/discourse_workflows/nodes/http_request/response_parser_spec.rb
new file mode 100644
index 00000000000..1782d436657
--- /dev/null
+++ b/plugins/discourse-workflows/spec/lib/discourse_workflows/nodes/http_request/response_parser_spec.rb
@@ -0,0 +1,118 @@
+# frozen_string_literal: true
+
+RSpec.describe DiscourseWorkflows::Nodes::HttpRequest::ResponseParser do
+ def build_response(status:, body:, headers: {})
+ instance_double(Faraday::Response, status: status, body: body, headers: headers)
+ end
+
+ describe ".parse" do
+ it "parses a JSON response" do
+ response =
+ build_response(
+ status: 200,
+ body: '{"result":"ok"}',
+ headers: {
+ "content-type" => "application/json",
+ },
+ )
+ result = described_class.parse(response)
+
+ expect(result[:status]).to eq(200)
+ expect(result[:body]).to eq("result" => "ok")
+ expect(result[:headers]).to include("content-type" => "application/json")
+ end
+
+ it "wraps non-JSON responses in a data key" do
+ response =
+ build_response(
+ status: 200,
+ body: "<html>hello</html>",
+ headers: {
+ "content-type" => "text/html",
+ },
+ )
+ result = described_class.parse(response)
+
+ expect(result[:body]).to eq("data" => "<html>hello</html>")
+ end
+
+ it "handles missing content-type as non-JSON" do
+ response = build_response(status: 200, body: "plain text", headers: {})
+ result = described_class.parse(response)
+
+ expect(result[:body]).to eq("data" => "plain text")
+ end
+
+ it "handles invalid JSON gracefully" do
+ response =
+ build_response(
+ status: 200,
+ body: "not json{",
+ headers: {
+ "content-type" => "application/json",
+ },
+ )
+ result = described_class.parse(response)
+
+ expect(result[:body]).to eq("data" => "not json{")
+ end
+
+ it "truncates responses exceeding size limit" do
+ large_body = "x" * (described_class::MAX_RESPONSE_BODY_SIZE + 100)
+ response =
+ build_response(status: 200, body: large_body, headers: { "content-type" => "text/plain" })
+ result = described_class.parse(response)
+
+ expect(result[:body]["data"].bytesize).to eq(described_class::MAX_RESPONSE_BODY_SIZE)
+ end
+
+ it "emits a warning log when truncation occurs" do
+ large_body = "x" * (described_class::MAX_RESPONSE_BODY_SIZE + 100)
+ response =
+ build_response(status: 200, body: large_body, headers: { "content-type" => "text/plain" })
+ log = instance_spy(DiscourseWorkflows::Executor::StepLog)
+
+ described_class.parse(response, log: log)
+
+ expect(log).to have_received(:warn).with(a_string_including("truncated"))
+ end
+
+ it "respects a custom max_response_size_kb" do
+ response =
+ build_response(status: 200, body: "x" * 3000, headers: { "content-type" => "text/plain" })
+ log = instance_spy(DiscourseWorkflows::Executor::StepLog)
+
+ result = described_class.parse(response, max_size_kb: 2, log: log)
+
+ expect(log).to have_received(:warn).with(a_string_including("truncated"))
+ expect(result[:body]["data"].bytesize).to eq(2.kilobytes)
+ end
+
+ it "clamps max_response_size_kb to a minimum of 1 KB" do
+ response =
+ build_response(status: 200, body: "x" * 2048, headers: { "content-type" => "text/plain" })
+ log = instance_spy(DiscourseWorkflows::Executor::StepLog)
+
+ result = described_class.parse(response, max_size_kb: 0, log: log)
+
+ expect(result[:body]["data"].bytesize).to eq(1.kilobyte)
+ end
+
+ it "clamps max_response_size_kb to the hard cap" do
+ response =
+ build_response(
+ status: 200,
+ body: "x" * (described_class::MAX_ALLOWED_SIZE + 100),
+ headers: {
+ "content-type" => "text/plain",
+ },
+ )
+ log = instance_spy(DiscourseWorkflows::Executor::StepLog)
+
+ result = described_class.parse(response, max_size_kb: 999_999, log: log)
+
+ expect(log).to have_received(:warn).with(a_string_including("truncated"))
+ expect(result[:body]["data"].bytesize).to eq(described_class::MAX_ALLOWED_SIZE)
+ end
+ end
+end
diff --git a/plugins/discourse-workflows/spec/lib/discourse_workflows/nodes/http_request_spec.rb b/plugins/discourse-workflows/spec/lib/discourse_workflows/nodes/http_request_spec.rb
new file mode 100644
index 00000000000..fda739bfdd4
--- /dev/null
+++ b/plugins/discourse-workflows/spec/lib/discourse_workflows/nodes/http_request_spec.rb
@@ -0,0 +1,478 @@
+# frozen_string_literal: true
+
+RSpec.describe DiscourseWorkflows::Nodes::HttpRequest::V1 do
+ describe "#execute" do
+ let(:item) { { "json" => {} } }
+
+ it "makes a GET request and returns parsed JSON response" do
+ stub_request(:get, "https://api.example.com/data").to_return(
+ status: 200,
+ body: { result: "ok" }.to_json,
+ headers: {
+ "content-type" => "application/json",
+ },
+ )
+
+ config = { "method" => "GET", "url" => "https://api.example.com/data" }
+ result = execute_node(configuration: config, item: item)
+
+ expect(result).to eq("result" => "ok")
+ end
+
+ it "returns full response data when enabled" do
+ stub_request(:get, "https://api.example.com/data").to_return(
+ status: 200,
+ body: { result: "ok" }.to_json,
+ headers: {
+ "content-type" => "application/json",
+ },
+ )
+
+ config = {
+ "method" => "GET",
+ "url" => "https://api.example.com/data",
+ "full_response" => true,
+ }
+ result = execute_node(configuration: config, item: item)
+
+ expect(result).to include(
+ "body" => {
+ "result" => "ok",
+ },
+ "headers" => include("content-type" => "application/json"),
+ "status_code" => 200,
+ )
+ expect(result).to have_key("status_message")
+ end
+
+ it "splits top-level JSON array responses into separate output items" do
+ stub_request(:get, "https://api.example.com/users").to_return(
+ status: 200,
+ body: [{ id: 1 }, { id: 2 }].to_json,
+ headers: {
+ "content-type" => "application/json",
+ },
+ )
+
+ config = { "method" => "GET", "url" => "https://api.example.com/users" }
+ result = execute_node_output(configuration: config, item: item).first
+
+ expect(result.map { |output_item| output_item["json"] }).to eq([{ "id" => 1 }, { "id" => 2 }])
+ expect(result.map { |output_item| output_item["pairedItem"] }).to eq(
+ [{ "item" => 0 }, { "item" => 0 }],
+ )
+ end
+
+ it "sends a JSON body with POST requests" do
+ stub_request(:post, "https://api.example.com/data").with(body: '{"name":"test"}').to_return(
+ status: 201,
+ body: { id: 1 }.to_json,
+ headers: {
+ "content-type" => "application/json",
+ },
+ )
+
+ config = {
+ "method" => "POST",
+ "url" => "https://api.example.com/data",
+ "body_json" => '{"name":"test"}',
+ }
+
+ result = execute_node(configuration: config, item: item)
+
+ expect(result).to eq("id" => 1)
+ end
+
+ it "sends fixed-collection query params resolved through the execution context" do
+ stub_request(:get, "https://api.example.com/search").with(
+ query: {
+ "q" => "discourse",
+ "page" => "2",
+ },
+ ).to_return(
+ status: 200,
+ body: { ok: true }.to_json,
+ headers: {
+ "content-type" => "application/json",
+ },
+ )
+
+ config = {
+ "method" => "GET",
+ "url" => "https://api.example.com/search",
+ "query_params" => {
+ "values" => [
+ { "key" => "q", "value" => "={{ $json.query }}" },
+ { "key" => "page", "value" => "2" },
+ ],
+ },
+ }
+
+ result = execute_node(configuration: config, item: { "json" => { "query" => "discourse" } })
+
+ expect(result).to eq("ok" => true)
+ end
+
+ it "sends fixed-collection form params resolved through the execution context" do
+ stub_request(:post, "https://api.example.com/form").with(
+ body: "name=Ada&role=admin",
+ headers: {
+ "Content-Type" => "application/x-www-form-urlencoded",
+ },
+ ).to_return(
+ status: 200,
+ body: { ok: true }.to_json,
+ headers: {
+ "content-type" => "application/json",
+ },
+ )
+
+ config = {
+ "method" => "POST",
+ "url" => "https://api.example.com/form",
+ "content_type" => "form_urlencoded",
+ "body_form" => {
+ "values" => [
+ { "key" => "name", "value" => "={{ $json.name }}" },
+ { "key" => "role", "value" => "admin" },
+ ],
+ },
+ }
+
+ result = execute_node(configuration: config, item: { "json" => { "name" => "Ada" } })
+
+ expect(result).to eq("ok" => true)
+ end
+
+ it "raises an error for non-2xx status codes by default" do
+ stub_request(:get, "https://api.example.com/fail").to_return(status: 404, body: "Not Found")
+
+ config = { "method" => "GET", "url" => "https://api.example.com/fail" }
+
+ expect { execute_node(configuration: config, item: item) }.to raise_error(
+ DiscourseWorkflows::NodeError,
+ %r{HTTP GET https://api\.example\.com/fail failed with status 404},
+ )
+ end
+
+ it "raises an error for server errors" do
+ stub_request(:post, "https://api.example.com/error").to_return(
+ status: 500,
+ body: "Internal Server Error",
+ )
+
+ config = { "method" => "POST", "url" => "https://api.example.com/error", "body_json" => "{}" }
+
+ expect { execute_node(configuration: config, item: item) }.to raise_error(
+ DiscourseWorkflows::NodeError,
+ %r{HTTP POST https://api\.example\.com/error failed with status 500},
+ )
+ end
+
+ it "filters query values in error messages" do
+ stub_request(:get, "https://api.example.com/fail?token=secret-token").to_return(
+ status: 404,
+ body: "Not Found",
+ )
+
+ config = { "method" => "GET", "url" => "https://api.example.com/fail?token=secret-token" }
+
+ expect { execute_node(configuration: config, item: item) }.to raise_error(
+ DiscourseWorkflows::NodeError,
+ "HTTP GET https://api.example.com/fail?token=[FILTERED] failed with status 404",
+ )
+ end
+
+ it "returns non-JSON responses wrapped in a data key" do
+ stub_request(:get, "https://example.com/page").to_return(
+ status: 200,
+ body: "<html>hello</html>",
+ headers: {
+ "content-type" => "text/html",
+ },
+ )
+
+ config = { "method" => "GET", "url" => "https://example.com/page" }
+ result = execute_node(configuration: config, item: item)
+
+ expect(result).to eq("data" => "<html>hello</html>")
+ end
+
+ it "records request details in logs" do
+ stub_request(:post, "https://api.example.com/data").with(
+ headers: {
+ "X-Custom-Header" => "my-value",
+ },
+ ).to_return(
+ status: 200,
+ body: { ok: true }.to_json,
+ headers: {
+ "content-type" => "application/json",
+ },
+ )
+
+ config = {
+ "method" => "POST",
+ "url" => "https://api.example.com/data",
+ "headers" => {
+ "values" => [{ "key" => "X-Custom-Header", "value" => "my-value" }],
+ },
+ "body_json" => '{"name":"test"}',
+ }
+
+ action = described_class.new(parameters: config)
+ sandbox = DiscourseWorkflows::JsSandbox.new({ "$json" => {} })
+ resolver = DiscourseWorkflows::ExpressionResolver.new({ "$json" => {} }, sandbox: sandbox)
+ exec_ctx =
+ DiscourseWorkflows::Executor::NodeExecutionContext.new(
+ input_items: [item],
+ resolver: resolver,
+ parameters: config,
+ property_schema: described_class.property_schema,
+ )
+ action.execute(exec_ctx)
+
+ messages = exec_ctx.log.entries.map { |e| e["message"] }
+ expect(messages).to eq(
+ [
+ "POST https://api.example.com/data",
+ "X-Custom-Header: my-value",
+ "Content-Type: application/json",
+ "[body omitted]",
+ ],
+ )
+ expect(exec_ctx.log.entries).to all(include("level" => "info"))
+ ensure
+ resolver&.dispose
+ sandbox&.dispose
+ end
+
+ it "filters query values in logs" do
+ stub_request(:get, "https://api.example.com/data?token=secret-token&page=2").to_return(
+ status: 200,
+ body: { ok: true }.to_json,
+ headers: {
+ "content-type" => "application/json",
+ },
+ )
+
+ config = {
+ "method" => "GET",
+ "url" => "https://api.example.com/data?token=secret-token",
+ "query_params" => {
+ "values" => [{ "key" => "page", "value" => "2" }],
+ },
+ }
+ messages = nil
+
+ execute_node_output(configuration: config, item: item) do |exec_ctx|
+ messages = exec_ctx.log.entries.map { |entry| entry["message"] }
+ end
+
+ expect(messages).to eq(["GET https://api.example.com/data?token=[FILTERED]&page=[FILTERED]"])
+ end
+
+ it "raises when URL has no host" do
+ config = { "method" => "GET", "url" => "http:///path" }
+
+ expect { execute_node(configuration: config, item: item) }.to raise_error(
+ DiscourseWorkflows::NodeError,
+ "URL must include a host.",
+ )
+ end
+
+ context "with never_error enabled" do
+ it "returns non-2xx responses without raising" do
+ stub_request(:get, "https://api.example.com/missing").to_return(
+ status: 404,
+ body: { error: "not found" }.to_json,
+ headers: {
+ "content-type" => "application/json",
+ },
+ )
+
+ config = {
+ "method" => "GET",
+ "url" => "https://api.example.com/missing",
+ "never_error" => true,
+ }
+
+ result = execute_node(configuration: config, item: item)
+
+ expect(result).to eq("error" => "not found")
+ end
+
+ it "returns non-2xx response status when full response is enabled" do
+ stub_request(:get, "https://api.example.com/missing").to_return(
+ status: 404,
+ body: { error: "not found" }.to_json,
+ headers: {
+ "content-type" => "application/json",
+ },
+ )
+
+ config = {
+ "method" => "GET",
+ "url" => "https://api.example.com/missing",
+ "never_error" => true,
+ "full_response" => true,
+ }
+
+ result = execute_node(configuration: config, item: item)
+
+ expect(result).to include("status_code" => 404, "body" => { "error" => "not found" })
+ end
+ end
+
+ context "with basic_auth authentication" do
+ fab!(:credential) do
+ Fabricate(
+ :discourse_workflows_credential,
+ credential_type: "basic_auth",
+ data: {
+ "user" => "api_user",
+ "password" => "api_pass",
+ },
+ )
+ end
+
+ it "injects Authorization header" do
+ stub_request(:get, "https://api.example.com/data").with(
+ headers: {
+ "Authorization" => "Basic #{Base64.strict_encode64("api_user:api_pass")}",
+ },
+ ).to_return(
+ status: 200,
+ body: { ok: true }.to_json,
+ headers: {
+ "content-type" => "application/json",
+ },
+ )
+
+ config = {
+ "method" => "GET",
+ "url" => "https://api.example.com/data",
+ "authentication" => "basic_auth",
+ "credentials" => {
+ "auth" => {
+ "id" => credential.id,
+ "credential_type" => "basic_auth",
+ },
+ },
+ }
+
+ result = execute_node(configuration: config, item: item)
+ expect(result).to eq("ok" => true)
+ end
+
+ it "resolves credential expressions against each input item" do
+ credential.update!(data: { "user" => "={{ $json.username }}", "password" => "api_pass" })
+
+ stub_request(:get, "https://api.example.com/data").with(
+ headers: {
+ "Authorization" => "Basic #{Base64.strict_encode64("alice:api_pass")}",
+ },
+ ).to_return(
+ status: 200,
+ body: { user: "alice" }.to_json,
+ headers: {
+ "content-type" => "application/json",
+ },
+ )
+ stub_request(:get, "https://api.example.com/data").with(
+ headers: {
+ "Authorization" => "Basic #{Base64.strict_encode64("bob:api_pass")}",
+ },
+ ).to_return(
+ status: 200,
+ body: { user: "bob" }.to_json,
+ headers: {
+ "content-type" => "application/json",
+ },
+ )
+
+ config = {
+ "method" => "GET",
+ "url" => "https://api.example.com/data",
+ "authentication" => "basic_auth",
+ "credentials" => {
+ "auth" => {
+ "id" => credential.id,
+ "credential_type" => "basic_auth",
+ },
+ },
+ }
+ input_items = [
+ { "json" => { "username" => "alice" } },
+ { "json" => { "username" => "bob" } },
+ ]
+
+ result = execute_node_output(configuration: config, input_items: input_items).first
+
+ expect(result.map { |output_item| output_item["json"]["user"] }).to eq(%w[alice bob])
+ end
+ end
+
+ context "with bearer_token authentication" do
+ fab!(:credential) do
+ Fabricate(
+ :discourse_workflows_credential,
+ credential_type: "bearer_token",
+ data: {
+ "token" => "my-secret-token",
+ },
+ )
+ end
+
+ it "injects Bearer Authorization header" do
+ stub_request(:get, "https://api.example.com/data").with(
+ headers: {
+ "Authorization" => "Bearer my-secret-token",
+ },
+ ).to_return(
+ status: 200,
+ body: { ok: true }.to_json,
+ headers: {
+ "content-type" => "application/json",
+ },
+ )
+
+ config = {
+ "method" => "GET",
+ "url" => "https://api.example.com/data",
+ "authentication" => "bearer_token",
+ "credentials" => {
+ "auth" => {
+ "id" => credential.id,
+ "credential_type" => "bearer_token",
+ },
+ },
+ }
+
+ result = execute_node(configuration: config, item: item)
+ expect(result).to eq("ok" => true)
+ end
+ end
+
+ context "with authentication set to none" do
+ it "does not add Authorization header" do
+ stub_request(:get, "https://api.example.com/data").to_return(
+ status: 200,
+ body: { ok: true }.to_json,
+ headers: {
+ "content-type" => "application/json",
+ },
+ )
+
+ config = {
+ "method" => "GET",
+ "url" => "https://api.example.com/data",
+ "authentication" => "none",
+ }
+
+ result = execute_node(configuration: config, item: item)
+ expect(result).to eq("ok" => true)
+ end
+ end
+ end
+end
diff --git a/plugins/discourse-workflows/spec/lib/discourse_workflows/nodes/if_spec.rb b/plugins/discourse-workflows/spec/lib/discourse_workflows/nodes/if_spec.rb
new file mode 100644
index 00000000000..17f91abf956
--- /dev/null
+++ b/plugins/discourse-workflows/spec/lib/discourse_workflows/nodes/if_spec.rb
@@ -0,0 +1,134 @@
+# frozen_string_literal: true
+
+RSpec.describe DiscourseWorkflows::Nodes::If::V1 do
+ def build_config(conditions:, combinator: "and", options: {})
+ { "conditions" => conditions, "combinator" => combinator, "options" => options }
+ end
+
+ def wrap_items(*jsons)
+ jsons.map { |json| { "json" => json } }
+ end
+
+ describe "#execute" do
+ context "with combinators" do
+ it "and: all conditions must pass" do
+ config =
+ build_config(
+ conditions: [
+ {
+ "id" => "1",
+ "leftValue" => "={{ $json.status }}",
+ "rightValue" => "closed",
+ "operator" => {
+ "type" => "string",
+ "operation" => "equals",
+ },
+ },
+ {
+ "id" => "2",
+ "leftValue" => "={{ $json.enabled }}",
+ "operator" => {
+ "type" => "boolean",
+ "operation" => "true",
+ "singleValue" => true,
+ },
+ },
+ ],
+ combinator: "and",
+ )
+
+ items = wrap_items({ "status" => "closed", "enabled" => true })
+ result = execute_node_output(configuration: config, input_items: items)
+ expect(result[0]).to eq(items)
+
+ items = wrap_items({ "status" => "closed", "enabled" => false })
+ result = execute_node_output(configuration: config, input_items: items)
+ expect(result[1]).to eq(items)
+ end
+
+ it "or: any condition passing is enough" do
+ config =
+ build_config(
+ conditions: [
+ {
+ "id" => "1",
+ "leftValue" => "={{ $json.status }}",
+ "rightValue" => "closed",
+ "operator" => {
+ "type" => "string",
+ "operation" => "equals",
+ },
+ },
+ {
+ "id" => "2",
+ "leftValue" => "={{ $json.status }}",
+ "rightValue" => "archived",
+ "operator" => {
+ "type" => "string",
+ "operation" => "equals",
+ },
+ },
+ ],
+ combinator: "or",
+ )
+
+ items = wrap_items({ "status" => "archived" })
+ result = execute_node_output(configuration: config, input_items: items)
+ expect(result[0]).to eq(items)
+
+ items = wrap_items({ "status" => "open" })
+ result = execute_node_output(configuration: config, input_items: items)
+ expect(result[1]).to eq(items)
+ end
+ end
+
+ context "with per-item routing" do
+ it "routes items to different outputs based on condition" do
+ config =
+ build_config(
+ conditions: [
+ {
+ "id" => "1",
+ "leftValue" => "={{ $json.status }}",
+ "rightValue" => "closed",
+ "operator" => {
+ "type" => "string",
+ "operation" => "equals",
+ },
+ },
+ ],
+ )
+
+ items = wrap_items({ "status" => "closed", "id" => 1 }, { "status" => "open", "id" => 2 })
+ result = execute_node_output(configuration: config, input_items: items)
+ expect(result[0].length).to eq(1)
+ expect(result[0].first["json"]["id"]).to eq(1)
+ expect(result[1].length).to eq(1)
+ expect(result[1].first["json"]["id"]).to eq(2)
+ end
+ end
+
+ context "with missing context values" do
+ it "treats missing fields as nil" do
+ config =
+ build_config(
+ conditions: [
+ {
+ "id" => "1",
+ "leftValue" => "={{ $json.nonexistent }}",
+ "rightValue" => "something",
+ "operator" => {
+ "type" => "string",
+ "operation" => "equals",
+ },
+ },
+ ],
+ )
+
+ items = wrap_items({ "status" => "closed" })
+ result = execute_node_output(configuration: config, input_items: items)
+ expect(result[1]).to eq(items)
+ end
+ end
+ end
+end
diff --git a/plugins/discourse-workflows/spec/lib/discourse_workflows/nodes/limit_spec.rb b/plugins/discourse-workflows/spec/lib/discourse_workflows/nodes/limit_spec.rb
new file mode 100644
index 00000000000..3ea28bb235d
--- /dev/null
+++ b/plugins/discourse-workflows/spec/lib/discourse_workflows/nodes/limit_spec.rb
@@ -0,0 +1,79 @@
+# frozen_string_literal: true
+
+RSpec.describe DiscourseWorkflows::Nodes::Limit::V1 do
+ def execute(input_items, configuration = {})
+ config = { "max_items" => 10, "keep" => "first" }.merge(configuration)
+ execute_node_output(configuration: config, input_items: input_items).first
+ end
+
+ def make_indexed_items(count)
+ Array.new(count) { |i| { "json" => { "index" => i } } }
+ end
+
+ describe "#execute" do
+ it "keeps the first N items by default" do
+ result = execute(make_indexed_items(5), "max_items" => 3)
+
+ expect(result.length).to eq(3)
+ expect(result[0]["json"]["index"]).to eq(0)
+ expect(result[1]["json"]["index"]).to eq(1)
+ expect(result[2]["json"]["index"]).to eq(2)
+ end
+
+ it "keeps the last N items when keep is last" do
+ result = execute(make_indexed_items(5), "max_items" => 2, "keep" => "last")
+
+ expect(result.length).to eq(2)
+ expect(result[0]["json"]["index"]).to eq(3)
+ expect(result[1]["json"]["index"]).to eq(4)
+ end
+
+ it "returns all items when max_items exceeds input size" do
+ result = execute(make_indexed_items(3), "max_items" => 10)
+
+ expect(result.length).to eq(3)
+ end
+
+ it "returns empty array when input is empty" do
+ result = execute([], "max_items" => 5)
+
+ expect(result).to eq([])
+ end
+
+ it "defaults to 10 items" do
+ result = execute(make_indexed_items(15))
+
+ expect(result.length).to eq(10)
+ end
+
+ it "handles max_items of 1" do
+ result = execute(make_indexed_items(5), "max_items" => 1)
+
+ expect(result.length).to eq(1)
+ expect(result[0]["json"]["index"]).to eq(0)
+ end
+
+ it "clamps max_items below 1 to 1" do
+ result = execute(make_indexed_items(5), "max_items" => 0)
+
+ expect(result.length).to eq(1)
+ expect(result[0]["json"]["index"]).to eq(0)
+ end
+
+ it "handles max_items of 1 with keep last" do
+ result = execute(make_indexed_items(5), "max_items" => 1, "keep" => "last")
+
+ expect(result.length).to eq(1)
+ expect(result[0]["json"]["index"]).to eq(4)
+ end
+
+ it "resolves max_items expressions through the execution context" do
+ items = make_indexed_items(5)
+ items.first["json"]["limit"] = 2
+
+ result = execute(items, "max_items" => "={{ $json.limit }}")
+
+ expect(result.map { |item| item["json"]["index"] }).to eq([0, 1])
+ end
+ end
+end
diff --git a/plugins/discourse-workflows/spec/lib/discourse_workflows/nodes/log/v1_spec.rb b/plugins/discourse-workflows/spec/lib/discourse_workflows/nodes/log/v1_spec.rb
new file mode 100644
index 00000000000..b4f20a701e5
--- /dev/null
+++ b/plugins/discourse-workflows/spec/lib/discourse_workflows/nodes/log/v1_spec.rb
@@ -0,0 +1,146 @@
+# frozen_string_literal: true
+
+RSpec.describe DiscourseWorkflows::Nodes::Log::V1 do
+ def entries(*rows)
+ { "values" => rows }
+ end
+
+ describe "#execute" do
+ it "returns no output items" do
+ items = [{ "json" => { "name" => "Alice" } }, { "json" => { "count" => 42 } }]
+ result =
+ execute_node_output(
+ configuration: {
+ "entries" => entries({ "key" => "tag", "value" => "hello" }),
+ },
+ input_items: items,
+ )
+ expect(result.first).to eq([])
+ end
+
+ it "records structured key/value logs" do
+ items = [{ "json" => { "id" => 1 } }]
+ log_entries =
+ entries({ "key" => "user_id", "value" => "1" }, { "key" => "status", "value" => "ok" })
+ execute_node_output(configuration: { "entries" => log_entries }, input_items: items) do |ctx|
+ expect(ctx.log.entries.size).to eq(2)
+ expect(ctx.log.entries.first).to include(
+ "level" => "info",
+ "key" => "user_id",
+ "value" => "1",
+ )
+ expect(ctx.log.entries.second).to include(
+ "level" => "info",
+ "key" => "status",
+ "value" => "ok",
+ )
+ end
+ end
+
+ it "resolves expressions in entry values" do
+ items = [{ "json" => { "user_name" => "Bob" } }]
+ result =
+ execute_node_output(
+ configuration: {
+ "entries" => entries({ "key" => "name", "value" => "={{ $json.user_name }}" }),
+ },
+ input_items: items,
+ ) do |ctx|
+ expect(ctx.log.entries.first).to include(
+ "level" => "info",
+ "key" => "name",
+ "value" => "Bob",
+ )
+ end
+ expect(result.first).to eq([])
+ end
+
+ it "handles empty entries gracefully" do
+ items = [{ "json" => { "x" => 1 } }]
+ result =
+ execute_node_output(configuration: { "entries" => entries }, input_items: items) do |ctx|
+ expect(ctx.log.entries).to be_empty
+ end
+ expect(result.first).to eq([])
+ end
+
+ it "handles missing entries key" do
+ items = [{ "json" => { "x" => 1 } }]
+ result =
+ execute_node_output(configuration: {}, input_items: items) do |ctx|
+ expect(ctx.log.entries).to be_empty
+ end
+ expect(result.first).to eq([])
+ end
+
+ it "defaults to runOnceForEachItem, resolving expressions per item" do
+ items = [
+ { "json" => { "name" => "Alice" } },
+ { "json" => { "name" => "Bob" } },
+ { "json" => { "name" => "Carol" } },
+ ]
+ execute_node_output(
+ configuration: {
+ "entries" => entries({ "key" => "name", "value" => "={{ $json.name }}" }),
+ },
+ input_items: items,
+ ) do |ctx|
+ expect(ctx.log.entries.map { |entry| entry["value"] }).to eq(%w[Alice Bob Carol])
+ expect(ctx.log.entries.map { |entry| entry["key"] }).to eq(%w[name name name])
+ end
+ end
+
+ it "emits items.size * entries.size logs in runOnceForEachItem mode" do
+ items = [{ "json" => { "id" => 1 } }, { "json" => { "id" => 2 } }]
+ log_entries =
+ entries(
+ { "key" => "id", "value" => "={{ $json.id }}" },
+ { "key" => "tag", "value" => "static" },
+ )
+ execute_node_output(
+ configuration: {
+ "mode" => "runOnceForEachItem",
+ "entries" => log_entries,
+ },
+ input_items: items,
+ ) do |ctx|
+ expect(ctx.log.entries.size).to eq(4)
+ expect(ctx.log.entries.map { |entry| [entry["key"], entry["value"]] }).to eq(
+ [%w[id 1], %w[tag static], %w[id 2], %w[tag static]],
+ )
+ end
+ end
+
+ it "logs entries once in runOnceForAllItems mode" do
+ items = [
+ { "json" => { "name" => "Alice" } },
+ { "json" => { "name" => "Bob" } },
+ { "json" => { "name" => "Carol" } },
+ ]
+ execute_node_output(
+ configuration: {
+ "mode" => "runOnceForAllItems",
+ "entries" => entries({ "key" => "name", "value" => "={{ $json.name }}" }),
+ },
+ input_items: items,
+ ) do |ctx|
+ expect(ctx.log.entries.size).to eq(1)
+ expect(ctx.log.entries.first).to include("key" => "name", "value" => "Alice")
+ end
+ end
+
+ it "still logs once when input items are empty" do
+ result =
+ execute_node_output(
+ configuration: {
+ "entries" => entries({ "key" => "marker", "value" => "ran" }),
+ },
+ input_items: [],
+ ) do |ctx|
+ expect(ctx.log.entries.size).to eq(1)
+ expect(ctx.log.entries.first).to include("key" => "marker", "value" => "ran")
+ end
+ expect(result.first).to eq([])
+ end
+ end
+end
diff --git a/plugins/discourse-workflows/spec/lib/discourse_workflows/nodes/loop_over_items_spec.rb b/plugins/discourse-workflows/spec/lib/discourse_workflows/nodes/loop_over_items_spec.rb
new file mode 100644
index 00000000000..a715ac171c0
--- /dev/null
+++ b/plugins/discourse-workflows/spec/lib/discourse_workflows/nodes/loop_over_items_spec.rb
@@ -0,0 +1,133 @@
+# frozen_string_literal: true
+
+RSpec.describe DiscourseWorkflows::Nodes::LoopOverItems::V1 do
+ def make_items(*values)
+ values.map { |v| { "json" => v.deep_stringify_keys } }
+ end
+
+ def run_loop(items, node_context:, batch_size:)
+ execute_node_output(
+ configuration: {
+ "batch_size" => batch_size,
+ },
+ input_items: items,
+ node_context: node_context,
+ )
+ end
+
+ describe "#execute" do
+ it "sends first batch to loop output on first execution" do
+ items = make_items({ id: 1 }, { id: 2 }, { id: 3 })
+ node_context = {}
+
+ result = run_loop(items, node_context: node_context, batch_size: 2)
+
+ expect(result[0]).to eq([])
+ expect(result[1].length).to eq(2)
+ expect(result[1][0]["json"]).to include("id" => 1)
+ expect(result[1][1]["json"]).to include("id" => 2)
+ expect(node_context).to include("current_run_index" => 0)
+ expect(node_context["items"].length).to eq(1)
+ end
+
+ it "sends next batch on subsequent execution" do
+ items = make_items({ id: 1 }, { id: 2 }, { id: 3 }, { id: 4 }, { id: 5 })
+ node_context = {}
+
+ run_loop(items, node_context: node_context, batch_size: 2)
+
+ loop_back_items = make_items({ id: 1, processed: true }, { id: 2, processed: true })
+ result = run_loop(loop_back_items, node_context: node_context, batch_size: 2)
+
+ expect(result[0]).to eq([])
+ expect(result[1].length).to eq(2)
+ expect(result[1][0]["json"]).to include("id" => 3)
+ expect(result[1][1]["json"]).to include("id" => 4)
+ expect(node_context).to include("current_run_index" => 1)
+ end
+
+ it "sends all processed items to done on final execution" do
+ items = make_items({ id: 1 }, { id: 2 }, { id: 3 })
+ node_context = {}
+
+ run_loop(items, node_context: node_context, batch_size: 2)
+ run_loop(
+ make_items({ id: 1, done: true }, { id: 2, done: true }),
+ node_context: node_context,
+ batch_size: 2,
+ )
+
+ result =
+ run_loop(make_items({ id: 3, done: true }), node_context: node_context, batch_size: 2)
+
+ expect(result[1]).to eq([])
+ expect(result[0].length).to eq(3)
+ expect(result[0].map { |i| i["json"]["id"] }).to eq([1, 2, 3])
+ expect(node_context).to include("done" => true, "no_items_left" => true)
+ end
+
+ it "handles batch_size of 1" do
+ node_context = {}
+
+ result = run_loop(make_items({ id: 1 }, { id: 2 }), node_context: node_context, batch_size: 1)
+ expect(result[1].length).to eq(1)
+ expect(result[1][0]["json"]["id"]).to eq(1)
+
+ result = run_loop(make_items({ id: 1 }), node_context: node_context, batch_size: 1)
+ expect(result[1].length).to eq(1)
+ expect(result[1][0]["json"]["id"]).to eq(2)
+
+ result = run_loop(make_items({ id: 2 }), node_context: node_context, batch_size: 1)
+ expect(result[1]).to eq([])
+ expect(result[0].length).to eq(2)
+ end
+
+ it "handles batch_size larger than item count" do
+ node_context = {}
+
+ result =
+ run_loop(make_items({ id: 1 }, { id: 2 }), node_context: node_context, batch_size: 10)
+
+ expect(result[0]).to eq([])
+ expect(result[1].length).to eq(2)
+ end
+
+ it "handles empty input" do
+ node_context = {}
+
+ result = run_loop([], node_context: node_context, batch_size: 1)
+
+ expect(result[1]).to eq([])
+ expect(result[0]).to eq([])
+ end
+
+ it "defaults batch_size to 1 when invalid" do
+ node_context = {}
+
+ result = run_loop(make_items({ id: 1 }, { id: 2 }), node_context: node_context, batch_size: 0)
+
+ expect(result[1].length).to eq(1)
+ end
+
+ it "sets max_run_index correctly" do
+ node_context = {}
+
+ run_loop(
+ make_items({ id: 1 }, { id: 2 }, { id: 3 }, { id: 4 }, { id: 5 }),
+ node_context: node_context,
+ batch_size: 3,
+ )
+
+ expect(node_context["max_run_index"]).to eq(2)
+ end
+
+ it "resolves batch_size expressions through the execution context" do
+ node_context = {}
+ items = make_items({ id: 1, batch_size: 2 }, { id: 2 }, { id: 3 })
+
+ result = run_loop(items, node_context: node_context, batch_size: "={{ $json.batch_size }}")
+
+ expect(result[1].map { |item| item["json"]["id"] }).to eq([1, 2])
+ end
+ end
+end
diff --git a/plugins/discourse-workflows/spec/lib/discourse_workflows/nodes/markdown_table_spec.rb b/plugins/discourse-workflows/spec/lib/discourse_workflows/nodes/markdown_table_spec.rb
new file mode 100644
index 00000000000..d123eac0bd7
--- /dev/null
+++ b/plugins/discourse-workflows/spec/lib/discourse_workflows/nodes/markdown_table_spec.rb
@@ -0,0 +1,173 @@
+# frozen_string_literal: true
+
+RSpec.describe DiscourseWorkflows::Nodes::MarkdownTable::V1 do
+ def execute(input_items, configuration = {})
+ config = { "mapping_mode" => "manual", "columns" => columns }.merge(configuration)
+ execute_node_output(configuration: config, input_items: input_items).first.first&.dig(
+ "json",
+ "markdown",
+ )
+ end
+
+ def columns(*rows)
+ { "values" => rows }
+ end
+
+ describe "#execute" do
+ it "renders a table with a header row, separator, and one data row per input item" do
+ items = [
+ { "json" => { "name" => "Alice", "age" => "30" } },
+ { "json" => { "name" => "Bob", "age" => "25" } },
+ ]
+ config = {
+ "columns" =>
+ columns(
+ { "header" => "Name", "value" => "={{ $json.name }}" },
+ { "header" => "Age", "value" => "={{ $json.age }}" },
+ ),
+ }
+
+ markdown = execute(items, config)
+
+ expect(markdown).to eq(<<~MD.strip)
+ | Name | Age |
+ | --- | --- |
+ | Alice | 30 |
+ | Bob | 25 |
+ MD
+ end
+
+ it "JSON-encodes Hash cell values" do
+ items = [{ "json" => { "h" => { "a" => 1, "b" => 2 } } }]
+ config = { "columns" => columns({ "header" => "H", "value" => "={{ $json.h }}" }) }
+
+ markdown = execute(items, config)
+
+ expect(markdown.split("\n").last).to eq('| {"a":1,"b":2} |')
+ end
+
+ it "JSON-encodes Array cell values" do
+ items = [{ "json" => { "arr" => [1, 2, 3] } }]
+ config = { "columns" => columns({ "header" => "Arr", "value" => "={{ $json.arr }}" }) }
+
+ markdown = execute(items, config)
+
+ expect(markdown.split("\n").last).to eq("| [1,2,3] |")
+ end
+
+ it "renders nil cells as empty and stringifies scalars" do
+ items = [{ "json" => { "maybe_nil" => nil, "int_val" => 42, "bool_val" => true } }]
+ config = {
+ "columns" =>
+ columns(
+ { "header" => "Nil", "value" => "={{ $json.maybe_nil }}" },
+ { "header" => "Int", "value" => "={{ $json.int_val }}" },
+ { "header" => "Bool", "value" => "={{ $json.bool_val }}" },
+ ),
+ }
+
+ markdown = execute(items, config)
+
+ expect(markdown.split("\n").last).to eq("| | 42 | true |")
+ end
+
+ it "escapes pipe characters in cell values" do
+ items = [{ "json" => { "text" => "a | b | c" } }]
+ config = { "columns" => columns({ "header" => "Text", "value" => "={{ $json.text }}" }) }
+
+ markdown = execute(items, config)
+
+ expect(markdown.split("\n").last).to eq("| a \\| b \\| c |")
+ end
+
+ it "replaces newlines in cell values with <br>" do
+ items = [{ "json" => { "text" => "line1\nline2\r\nline3" } }]
+ config = { "columns" => columns({ "header" => "Text", "value" => "={{ $json.text }}" }) }
+
+ markdown = execute(items, config)
+
+ expect(markdown.split("\n").last).to eq("| line1<br>line2<br>line3 |")
+ end
+
+ it "keeps headers literal while resolving cell values through the execution context" do
+ items = [{ "json" => { "header" => "Resolved header", "name" => "Alice" } }]
+ config = {
+ "columns" => columns({ "header" => "={{ $json.header }}", "value" => "={{ $json.name }}" }),
+ }
+
+ markdown = execute(items, config)
+
+ expect(markdown).to eq(<<~MD.strip)
+ | ={{ $json.header }} |
+ | --- |
+ | Alice |
+ MD
+ end
+
+ it "renders headers and separator only when input items are empty" do
+ items = []
+ config = {
+ "columns" =>
+ columns(
+ { "header" => "Name", "value" => "={{ $json.name }}" },
+ { "header" => "Age", "value" => "={{ $json.age }}" },
+ ),
+ }
+
+ markdown = execute(items, config)
+
+ expect(markdown).to eq(<<~MD.strip)
+ | Name | Age |
+ | --- | --- |
+ MD
+ end
+
+ it "returns an empty string when no columns are configured and no input items" do
+ markdown = execute([], { "columns" => columns })
+
+ expect(markdown).to eq("")
+ end
+
+ context "when mapping_mode is auto" do
+ it "derives headers from the keys of input items" do
+ items = [
+ { "json" => { "name" => "Alice", "age" => 30 } },
+ { "json" => { "name" => "Bob", "age" => 25 } },
+ ]
+
+ markdown = execute(items, { "mapping_mode" => "auto" })
+
+ expect(markdown).to eq(<<~MD.strip)
+ | name | age |
+ | --- | --- |
+ | Alice | 30 |
+ | Bob | 25 |
+ MD
+ end
+
+ it "unions keys across items preserving first-appearance order" do
+ items = [
+ { "json" => { "name" => "Alice", "age" => 30 } },
+ { "json" => { "name" => "Bob", "city" => "Paris" } },
+ ]
+
+ markdown = execute(items, { "mapping_mode" => "auto" })
+
+ expect(markdown).to eq(<<~MD.strip)
+ | name | age | city |
+ | --- | --- | --- |
+ | Alice | 30 | |
+ | Bob | | Paris |
+ MD
+ end
+
+ it "JSON-encodes Hash and Array values" do
+ items = [{ "json" => { "h" => { "a" => 1 }, "arr" => [1, 2] } }]
+
+ markdown = execute(items, { "mapping_mode" => "auto" })
+
+ expect(markdown.split("\n").last).to eq('| {"a":1} | [1,2] |')
+ end
+ end
+ end
+end
diff --git a/plugins/discourse-workflows/spec/lib/discourse_workflows/nodes/merge_spec.rb b/plugins/discourse-workflows/spec/lib/discourse_workflows/nodes/merge_spec.rb
new file mode 100644
index 00000000000..abd88eb63ad
--- /dev/null
+++ b/plugins/discourse-workflows/spec/lib/discourse_workflows/nodes/merge_spec.rb
@@ -0,0 +1,219 @@
+# frozen_string_literal: true
+
+RSpec.describe DiscourseWorkflows::Nodes::Merge::V1 do
+ def item(json)
+ { "json" => json }
+ end
+
+ def json_items(items)
+ items.map { |entry| { "json" => entry["json"] } }
+ end
+
+ def fields_to_match(*fields)
+ { "values" => fields }
+ end
+
+ def execute_merge(configuration:, input_1:, input_2:, input_groups: {})
+ execute_node_output(
+ configuration: configuration,
+ input_items: input_1,
+ input_groups: { "input_1" => input_1, "input_2" => input_2 }.merge(input_groups),
+ ).first
+ end
+
+ it "uses imported input wait semantics" do
+ expect(described_class.input_ports("mode" => "append", "number_inputs" => 3)).to all(
+ include(required: false),
+ )
+ expect(described_class.input_ports("mode" => "combine")).to all(include(required: false))
+ expect(described_class.required_inputs("mode" => "append")).to eq(1)
+ expect(described_class.required_inputs("mode" => "combine")).to eq(1)
+ expect(described_class.required_inputs("mode" => "choose_branch")).to eq([0, 1])
+ end
+
+ it "appends items from both inputs" do
+ output =
+ execute_merge(
+ configuration: {
+ "mode" => "append",
+ },
+ input_1: [item("a" => 1)],
+ input_2: [item("b" => 2)],
+ input_groups: {
+ "main" => [item("a" => 1), item("b" => 2)],
+ },
+ )
+
+ expect(output).to eq([item("a" => 1), item("b" => 2)])
+ end
+
+ it "appends items from indexed append inputs" do
+ output =
+ execute_merge(
+ configuration: {
+ "mode" => "append",
+ "number_inputs" => 3,
+ },
+ input_1: [item("a" => 1)],
+ input_2: [item("b" => 2)],
+ input_groups: {
+ "input_3" => [item("c" => 3)],
+ },
+ )
+
+ expect(output).to eq([item("a" => 1), item("b" => 2), item("c" => 3)])
+ end
+
+ it "chooses a specific input branch" do
+ output =
+ execute_merge(
+ configuration: {
+ "mode" => "choose_branch",
+ "use_data_of_input" => "input_2",
+ },
+ input_1: [item("a" => 1)],
+ input_2: [item("b" => 2)],
+ )
+
+ expect(output).to eq([item("b" => 2)])
+ end
+
+ it "combines items by position" do
+ output =
+ execute_merge(
+ configuration: {
+ "mode" => "combine",
+ "combine_by" => "position",
+ },
+ input_1: [item("id" => 1, "a" => "A")],
+ input_2: [item("b" => "B")],
+ )
+
+ expect(json_items(output)).to eq([item("id" => 1, "a" => "A", "b" => "B")])
+ end
+
+ it "combines all possible item pairs" do
+ output =
+ execute_merge(
+ configuration: {
+ "mode" => "combine",
+ "combine_by" => "all",
+ },
+ input_1: [item("a" => 1), item("a" => 2)],
+ input_2: [item("b" => 3), item("b" => 4)],
+ )
+
+ expect(json_items(output)).to eq(
+ [
+ item("a" => 1, "b" => 3),
+ item("a" => 1, "b" => 4),
+ item("a" => 2, "b" => 3),
+ item("a" => 2, "b" => 4),
+ ],
+ )
+ end
+
+ it "combines matching items by fields" do
+ output =
+ execute_merge(
+ configuration: {
+ "mode" => "combine",
+ "combine_by" => "matching_fields",
+ "fields_to_match" => fields_to_match({ "field_1" => "id", "field_2" => "topic_id" }),
+ },
+ input_1: [item("id" => 1, "title" => "One"), item("id" => 2, "title" => "Two")],
+ input_2: [item("topic_id" => 1, "tag" => "bug")],
+ )
+
+ expect(json_items(output)).to eq(
+ [item("id" => 1, "title" => "One", "topic_id" => 1, "tag" => "bug")],
+ )
+ expect(output.first["pairedItem"]).to eq(
+ [{ "input" => 0, "item" => 0 }, { "input" => 1, "item" => 0 }],
+ )
+ end
+
+ it "keeps everything from the available input when matching fields has an empty input" do
+ output =
+ execute_merge(
+ configuration: {
+ "mode" => "combine",
+ "combine_by" => "matching_fields",
+ "fields_to_match" => fields_to_match({ "field_1" => "id", "field_2" => "topic_id" }),
+ "join_mode" => "keep_everything",
+ },
+ input_1: [item("id" => 1, "title" => "One")],
+ input_2: [],
+ )
+
+ expect(output).to eq([item("id" => 1, "title" => "One")])
+ end
+
+ it "honors the requested non-match input when matching fields has an empty input" do
+ output =
+ execute_merge(
+ configuration: {
+ "mode" => "combine",
+ "combine_by" => "matching_fields",
+ "fields_to_match" => fields_to_match({ "field_1" => "id", "field_2" => "topic_id" }),
+ "join_mode" => "keep_non_matches",
+ "output_data_from" => "input_2",
+ },
+ input_1: [item("id" => 1, "title" => "One")],
+ input_2: [],
+ )
+
+ expect(output).to eq([])
+ end
+
+ it "treats missing match fields as non-matches" do
+ output =
+ execute_merge(
+ configuration: {
+ "mode" => "combine",
+ "combine_by" => "matching_fields",
+ "fields_to_match" => fields_to_match({ "field_1" => "id", "field_2" => "topic_id" }),
+ "join_mode" => "keep_non_matches",
+ "output_data_from" => "input_1",
+ },
+ input_1: [item("id" => 1), item("title" => "Missing id")],
+ input_2: [item("topic_id" => 1)],
+ )
+
+ expect(output).to eq([item("title" => "Missing id")])
+ end
+
+ it "raises node errors when no matching fields are configured" do
+ expect {
+ execute_merge(
+ configuration: {
+ "mode" => "combine",
+ "combine_by" => "matching_fields",
+ "fields_to_match" => fields_to_match,
+ },
+ input_1: [item("id" => 1)],
+ input_2: [item("id" => 1)],
+ )
+ }.to raise_error(
+ DiscourseWorkflows::NodeError,
+ 'Missing fields to match: You need to define at least one pair of fields in "Fields to match"',
+ )
+ end
+
+ it "raises node errors when a matching field pair is incomplete" do
+ expect {
+ execute_merge(
+ configuration: {
+ "mode" => "combine",
+ "combine_by" => "matching_fields",
+ "fields_to_match" => fields_to_match({ "field_1" => "", "field_2" => "topic_id" }),
+ },
+ input_1: [item("id" => 1)],
+ input_2: [item("topic_id" => 1)],
+ )
+ }.to raise_error(
+ DiscourseWorkflows::NodeError,
+ "Invalid fields to match: Fields to match pair 1 must define both input fields",
+ )
+ end
+end
diff --git a/plugins/discourse-workflows/spec/lib/discourse_workflows/nodes/post_created_spec.rb b/plugins/discourse-workflows/spec/lib/discourse_workflows/nodes/post_created_spec.rb
new file mode 100644
index 00000000000..adb06ea53f2
--- /dev/null
+++ b/plugins/discourse-workflows/spec/lib/discourse_workflows/nodes/post_created_spec.rb
@@ -0,0 +1,98 @@
+# frozen_string_literal: true
+
+RSpec.describe DiscourseWorkflows::Nodes::PostCreated::V1 do
+ fab!(:topic_owner) { Fabricate(:user, refresh_auto_groups: true) }
+ fab!(:reply_user) { Fabricate(:user, refresh_auto_groups: true) }
+ fab!(:first_post) { create_post(user: topic_owner, raw: "First post") }
+ fab!(:topic) { first_post.topic }
+ fab!(:tag) { Fabricate(:tag, name: "test-tag") }
+ fab!(:reply) do
+ PostCreator.create!(
+ reply_user,
+ topic_id: topic.id,
+ raw: "This is a reply",
+ reply_to_post_number: topic.first_post.post_number,
+ )
+ end
+ fab!(:small_action) do
+ Fabricate(:post, topic: topic, user: reply_user, post_type: Post.types[:small_action])
+ end
+
+ before do
+ SiteSetting.tagging_enabled = true
+ topic.tags << tag
+ end
+
+ describe "#valid?" do
+ it "returns true for regular posts" do
+ trigger = described_class.new(reply)
+ expect(trigger).to be_valid
+ end
+
+ it "returns false when post is nil" do
+ trigger = described_class.new(nil)
+ expect(trigger).not_to be_valid
+ end
+
+ it "returns false for non-regular posts" do
+ trigger = described_class.new(small_action)
+ expect(trigger).not_to be_valid
+ end
+
+ it "returns false when workflows are explicitly skipped" do
+ trigger = described_class.new(reply, { skip_workflows: true })
+ expect(trigger).not_to be_valid
+ end
+ end
+
+ describe "#output" do
+ it "returns post and topic data" do
+ trigger = described_class.new(reply)
+ output = trigger.output
+
+ expect(output[:post][:id]).to eq(reply.id)
+ expect(output[:post][:post_number]).to eq(reply.post_number)
+ expect(output[:post][:raw]).to eq(reply.raw)
+ expect(output[:post][:reply_to_post_number]).to eq(topic.first_post.post_number)
+ expect(output[:post][:user_id]).to eq(reply_user.id)
+ expect(output[:post][:username]).to eq(reply_user.username)
+ expect(output[:topic][:id]).to eq(topic.id)
+ expect(output[:topic][:title]).to eq(topic.title)
+ expect(output[:topic][:tags].map { |topic_tag| topic_tag[:name] }).to eq(["test-tag"])
+ expect(output[:topic][:category_id]).to eq(topic.category_id)
+ expect(output[:topic][:archetype]).to eq(topic.archetype)
+ end
+ end
+
+ describe "#matches?" do
+ it "returns true when category and tags are blank" do
+ trigger = described_class.new(reply)
+
+ expect(trigger.matches?(trigger_context({}))).to eq(true)
+ end
+
+ it "returns true when the post topic matches the configured category and tags" do
+ trigger = described_class.new(reply)
+
+ expect(
+ trigger.matches?(
+ trigger_context("category_id" => topic.category_id.to_s, "tag_names" => [tag.name]),
+ ),
+ ).to eq(true)
+ end
+
+ it "returns false when the post topic does not match the configured category or tags" do
+ other_category = Fabricate(:category)
+ trigger = described_class.new(reply)
+
+ expect(trigger.matches?(trigger_context("category_id" => other_category.id.to_s))).to eq(
+ false,
+ )
+ expect(trigger.matches?(trigger_context("tag_names" => ["missing"]))).to eq(false)
+ end
+ end
+
+ def trigger_context(parameters)
+ DiscourseWorkflows::TriggerNodeContext.new({ "parameters" => parameters })
+ end
+end
diff --git a/plugins/discourse-workflows/spec/lib/discourse_workflows/nodes/respond_to_webhook_spec.rb b/plugins/discourse-workflows/spec/lib/discourse_workflows/nodes/respond_to_webhook_spec.rb
new file mode 100644
index 00000000000..35358b4385f
--- /dev/null
+++ b/plugins/discourse-workflows/spec/lib/discourse_workflows/nodes/respond_to_webhook_spec.rb
@@ -0,0 +1,139 @@
+# frozen_string_literal: true
+
+RSpec.describe DiscourseWorkflows::Nodes::RespondToWebhook::V1 do
+ def rows(*values)
+ { "values" => values }
+ end
+
+ def execute_response_node(configuration:, item:)
+ request =
+ DiscourseWorkflows::WebhookRequest.new(
+ method: "POST",
+ path: "test",
+ webhook_url: "http://test.localhost/workflows/webhooks/test",
+ )
+ webhook_context = DiscourseWorkflows::WebhookContext.new(request: request)
+ node = described_class.new(parameters: configuration)
+ sandbox = DiscourseWorkflows::JsSandbox.new({ "$json" => item["json"] })
+ resolver =
+ DiscourseWorkflows::ExpressionResolver.new({ "$json" => item["json"] }, sandbox: sandbox)
+ exec_ctx =
+ DiscourseWorkflows::Executor::NodeExecutionContext.new(
+ input_items: [item],
+ resolver: resolver,
+ parameters: configuration,
+ property_schema: described_class.property_schema,
+ webhook_context: webhook_context,
+ )
+
+ node.execute(exec_ctx)
+ webhook_context.response
+ ensure
+ resolver&.dispose
+ sandbox&.dispose
+ end
+
+ describe "#execute" do
+ let(:item) { { "json" => { "user_id" => 42 } } }
+
+ it "rejects redirects to domains not in the allow list" do
+ config = { "response_type" => "redirect", "redirect_url" => "https://example.com/thanks" }
+ response = execute_response_node(configuration: config, item: item)
+
+ expect(response.status_code).to eq(400)
+ expect(response.body).to eq(error: "invalid_redirect_url")
+ end
+
+ it "rejects protocol-relative redirect URLs" do
+ config = {
+ "response_type" => "redirect",
+ "redirect_url" => "//example.com/thanks",
+ "allowed_redirect_domains" => rows({ "domain" => "example.com" }),
+ }
+ response = execute_response_node(configuration: config, item: item)
+
+ expect(response.status_code).to eq(400)
+ expect(response.body).to eq(error: "invalid_redirect_url")
+ end
+
+ it "returns normalized allowed redirect domains" do
+ config = {
+ "response_type" => "redirect",
+ "redirect_url" => "https://example.com/thanks",
+ "allowed_redirect_domains" =>
+ rows(
+ { "domain" => " Example.com " },
+ { "domain" => "*.Example.org" },
+ { "domain" => "" },
+ ),
+ }
+ response = execute_response_node(configuration: config, item: item)
+
+ expect(response.status_code).to eq(302)
+ expect(response.headers["Location"]).to eq("https://example.com/thanks")
+ end
+
+ it "returns JSON response data" do
+ config = {
+ "response_type" => "json",
+ "status_code" => "201",
+ "response_body" => '{"created": true}',
+ }
+ response = execute_response_node(configuration: config, item: item)
+
+ expect(response.status_code).to eq(201)
+ expect(response.body).to eq("created" => true)
+ end
+
+ it "keeps JSON null distinct from no data" do
+ config = { "response_type" => "json", "response_body" => "null" }
+ response = execute_response_node(configuration: config, item: item)
+
+ expect(response.body).to be_nil
+ expect(response).not_to be_no_body
+ end
+
+ it "returns text response data" do
+ config = { "response_type" => "text", "status_code" => "200", "response_body" => "OK thanks" }
+ response = execute_response_node(configuration: config, item: item)
+
+ expect(response.status_code).to eq(200)
+ expect(response.body).to eq("OK thanks")
+ expect(response.headers["Content-Type"]).to eq("text/plain; charset=utf-8")
+ end
+
+ it "returns no data response" do
+ config = { "response_type" => "no_data", "status_code" => "204" }
+ response = execute_response_node(configuration: config, item: item)
+
+ expect(response.status_code).to eq(204)
+ expect(response.body).to be_nil
+ expect(response).to be_no_body
+ end
+
+ it "defaults status code to 200 for json" do
+ config = { "response_type" => "json", "response_body" => "{}" }
+ response = execute_response_node(configuration: config, item: item)
+
+ expect(response.status_code).to eq(200)
+ end
+
+ it "includes custom headers when provided" do
+ config = {
+ "response_type" => "json",
+ "response_body" => "{}",
+ "response_headers" => rows({ "key" => "X-Custom", "value" => "hello" }),
+ }
+ response = execute_response_node(configuration: config, item: item)
+
+ expect(response.headers).to eq({ "X-Custom" => "hello" })
+ end
+
+ it "responds with the first incoming item" do
+ config = { "response_type" => "first_incoming_item" }
+ response = execute_response_node(configuration: config, item: item)
+
+ expect(response.body).to eq("user_id" => 42)
+ end
+ end
+end
diff --git a/plugins/discourse-workflows/spec/lib/discourse_workflows/nodes/schedule/payload_spec.rb b/plugins/discourse-workflows/spec/lib/discourse_workflows/nodes/schedule/payload_spec.rb
new file mode 100644
index 00000000000..17cdf361b5b
--- /dev/null
+++ b/plugins/discourse-workflows/spec/lib/discourse_workflows/nodes/schedule/payload_spec.rb
@@ -0,0 +1,33 @@
+# frozen_string_literal: true
+
+RSpec.describe DiscourseWorkflows::Nodes::Schedule::Payload do
+ describe ".build" do
+ it "returns compatible timestamp fields" do
+ payload = described_class.build(time: Time.utc(2026, 3, 18, 9, 0), timezone: "UTC")
+
+ expect(payload).to include(
+ "timestamp" => "2026-03-18T09:00:00.000Z",
+ "readable_date" => "March 18th 2026, 9:00:00 am",
+ "readable_time" => "9:00:00 am",
+ "day_of_week" => "Wednesday",
+ "year" => "2026",
+ "month" => "March",
+ "day_of_month" => "18",
+ "hour" => "09",
+ "minute" => "00",
+ "second" => "00",
+ "timezone" => "UTC (UTC+00:00)",
+ )
+ end
+
+ it "formats fields in the resolved workflow timezone" do
+ payload = described_class.build(time: Time.utc(2026, 3, 18, 8, 0), timezone: "Europe/Paris")
+
+ expect(payload).to include(
+ "timestamp" => "2026-03-18T09:00:00.000+01:00",
+ "hour" => "09",
+ "timezone" => "Europe/Paris (UTC+01:00)",
+ )
+ end
+ end
+end
diff --git a/plugins/discourse-workflows/spec/lib/discourse_workflows/nodes/schedule/recurrence_spec.rb b/plugins/discourse-workflows/spec/lib/discourse_workflows/nodes/schedule/recurrence_spec.rb
new file mode 100644
index 00000000000..783ab715382
--- /dev/null
+++ b/plugins/discourse-workflows/spec/lib/discourse_workflows/nodes/schedule/recurrence_spec.rb
@@ -0,0 +1,17 @@
+# frozen_string_literal: true
+
+RSpec.describe DiscourseWorkflows::Nodes::Schedule::Recurrence do
+ describe ".due?" do
+ it "requires an exact modular interval match" do
+ recurrence = { activated: true, index: 0, interval_size: 3, type_interval: "days" }
+ last_day = Time.utc(2026, 3, 18, 9, 0).yday
+
+ expect(
+ described_class.due?(recurrence, [last_day], Time.utc(2026, 3, 22, 9, 0), "UTC"),
+ ).to be(false)
+ expect(
+ described_class.due?(recurrence, [last_day], Time.utc(2026, 3, 21, 9, 0), "UTC"),
+ ).to be(true)
+ end
+ end
+end
diff --git a/plugins/discourse-workflows/spec/lib/discourse_workflows/nodes/schedule/rules_spec.rb b/plugins/discourse-workflows/spec/lib/discourse_workflows/nodes/schedule/rules_spec.rb
new file mode 100644
index 00000000000..c95789cfb08
--- /dev/null
+++ b/plugins/discourse-workflows/spec/lib/discourse_workflows/nodes/schedule/rules_spec.rb
@@ -0,0 +1,74 @@
+# frozen_string_literal: true
+
+RSpec.describe DiscourseWorkflows::Nodes::Schedule::Rules do
+ describe ".to_cron_expression" do
+ it "converts minute intervals" do
+ rule = { "field" => "minutes", "minutesInterval" => 5 }
+
+ expect(described_class.to_cron_expression(rule)).to eq("*/5 * * * *")
+ end
+
+ it "converts weekly intervals" do
+ rule = {
+ "field" => "weeks",
+ "triggerAtDay" => [1, 3],
+ "triggerAtHour" => 9,
+ "triggerAtMinute" => 15,
+ }
+
+ expect(described_class.to_cron_expression(rule)).to eq("15 9 * * 1,3")
+ end
+
+ it "passes cron expressions through" do
+ rule = { "field" => "cronExpression", "expression" => "0 9 * * *" }
+
+ expect(described_class.to_cron_expression(rule)).to eq("0 9 * * *")
+ end
+ end
+
+ describe ".valid?" do
+ it "accepts valid interval rules" do
+ expect(described_class.valid?({ "field" => "minutes", "minutesInterval" => 5 })).to be(true)
+ expect(
+ described_class.valid?(
+ {
+ "field" => "months",
+ "monthsInterval" => 2,
+ "triggerAtDayOfMonth" => 15,
+ "triggerAtHour" => 9,
+ "triggerAtMinute" => 0,
+ },
+ ),
+ ).to be(true)
+ end
+
+ it "rejects seconds rules" do
+ expect(described_class.valid?({ "field" => "seconds", "secondsInterval" => 30 })).to be(false)
+ end
+
+ it "rejects out-of-range values" do
+ expect(described_class.valid?({ "field" => "minutes", "minutesInterval" => 0 })).to be(false)
+ expect(described_class.valid?({ "field" => "hours", "hoursInterval" => 24 })).to be(false)
+ expect(
+ described_class.valid?({ "field" => "weeks", "weeksInterval" => 1, "triggerAtDay" => [7] }),
+ ).to be(false)
+ end
+
+ it "rejects non-numeric weekdays" do
+ expect(
+ described_class.valid?(
+ { "field" => "weeks", "weeksInterval" => 1, "triggerAtDay" => ["Sunday"] },
+ ),
+ ).to be(false)
+ end
+
+ it "requires cron expressions to have minute granularity" do
+ expect(
+ described_class.valid?({ "field" => "cronExpression", "expression" => "0 9 * * *" }),
+ ).to be(true)
+ expect(
+ described_class.valid?({ "field" => "cronExpression", "expression" => "*/10 * * * * *" }),
+ ).to be(false)
+ end
+ end
+end
diff --git a/plugins/discourse-workflows/spec/lib/discourse_workflows/nodes/schedule_spec.rb b/plugins/discourse-workflows/spec/lib/discourse_workflows/nodes/schedule_spec.rb
new file mode 100644
index 00000000000..042e677d59b
--- /dev/null
+++ b/plugins/discourse-workflows/spec/lib/discourse_workflows/nodes/schedule_spec.rb
@@ -0,0 +1,59 @@
+# frozen_string_literal: true
+
+RSpec.describe DiscourseWorkflows::Nodes::Schedule::V1 do
+ describe ".validate_configuration" do
+ it "accepts valid rules" do
+ config = { "rule" => { "interval" => [{ "field" => "minutes", "minutesInterval" => 5 }] } }
+ errors = ActiveModel::Errors.new(Object.new)
+ described_class.validate_configuration(config, errors)
+ expect(errors).to be_empty
+ end
+
+ it "accepts valid cron rules" do
+ config = {
+ "rule" => {
+ "interval" => [{ "field" => "cronExpression", "expression" => "0 9 * * *" }],
+ },
+ }
+ errors = ActiveModel::Errors.new(Object.new)
+ described_class.validate_configuration(config, errors)
+ expect(errors).to be_empty
+ end
+
+ it "rejects empty rules" do
+ config = { "rule" => { "interval" => [] } }
+ errors = ActiveModel::Errors.new(Object.new)
+ described_class.validate_configuration(config, errors)
+ expect(errors).not_to be_empty
+ end
+
+ it "rejects invalid cron rules" do
+ config = {
+ "rule" => {
+ "interval" => [{ "field" => "cronExpression", "expression" => "invalid" }],
+ },
+ }
+ errors = ActiveModel::Errors.new(Object.new)
+ described_class.validate_configuration(config, errors)
+ expect(errors).not_to be_empty
+ end
+
+ it "accepts multiple rules" do
+ config = {
+ "rule" => {
+ "interval" => Array.new(8) { { "field" => "minutes", "minutesInterval" => 5 } },
+ },
+ }
+ errors = ActiveModel::Errors.new(Object.new)
+ described_class.validate_configuration(config, errors)
+ expect(errors).to be_empty
+ end
+
+ it "rejects seconds rules" do
+ config = { "rule" => { "interval" => [{ "field" => "seconds", "secondsInterval" => 30 }] } }
+ errors = ActiveModel::Errors.new(Object.new)
+ described_class.validate_configuration(config, errors)
+ expect(errors).not_to be_empty
+ end
+ end
+end
diff --git a/plugins/discourse-workflows/spec/lib/discourse_workflows/nodes/set_fields_spec.rb b/plugins/discourse-workflows/spec/lib/discourse_workflows/nodes/set_fields_spec.rb
new file mode 100644
index 00000000000..667afc80328
--- /dev/null
+++ b/plugins/discourse-workflows/spec/lib/discourse_workflows/nodes/set_fields_spec.rb
@@ -0,0 +1,256 @@
+# frozen_string_literal: true
+
+RSpec.describe DiscourseWorkflows::Nodes::SetFields::V1 do
+ describe "#execute" do
+ let(:item) { { "json" => { "topic_id" => "42", "username" => "alice" } } }
+
+ def assignments(*rows)
+ { "assignments" => { "assignments" => rows } }
+ end
+
+ def assignment(name, value, type = "string")
+ { "name" => name, "value" => value, "type" => type }
+ end
+
+ it "returns typed fields from fixed values" do
+ config = { "include_other_fields" => false }.merge(
+ assignments(
+ assignment("priority", "high"),
+ assignment("days", "7", "integer"),
+ assignment("notify", "true", "boolean"),
+ ),
+ )
+
+ result = execute_node(configuration: config, item: item)
+
+ expect(result).to eq({ "priority" => "high", "days" => 7, "notify" => true })
+ end
+
+ it "merges with item json when include_input is true" do
+ config = { "include_other_fields" => true }.merge(assignments(assignment("priority", "high")))
+
+ result = execute_node(configuration: config, item: item)
+
+ expect(result).to eq({ "topic_id" => "42", "username" => "alice", "priority" => "high" })
+ end
+
+ it "set fields win on merge conflict" do
+ config = { "include_other_fields" => true }.merge(assignments(assignment("username", "bob")))
+
+ result = execute_node(configuration: config, item: item)
+
+ expect(result["username"]).to eq("bob")
+ end
+
+ it "defaults include_other_fields to true when not specified" do
+ config = assignments(assignment("status", "open"))
+
+ result = execute_node(configuration: config, item: item)
+
+ expect(result).to include("topic_id" => "42", "status" => "open")
+ end
+
+ it "casts boolean falsy values correctly" do
+ config = { "include_other_fields" => false }.merge(
+ assignments(
+ assignment("a", "false", "boolean"),
+ assignment("b", "0", "boolean"),
+ assignment("c", "no", "boolean"),
+ assignment("d", "1", "boolean"),
+ ),
+ )
+
+ result = execute_node(configuration: config, item: item)
+
+ expect(result).to eq({ "a" => false, "b" => false, "c" => false, "d" => true })
+ end
+
+ it "casts float values" do
+ config = { "include_other_fields" => false }.merge(
+ assignments(assignment("score", "3.14", "float"), assignment("whole", "7", "float")),
+ )
+
+ result = execute_node(configuration: config, item: item)
+
+ expect(result).to eq({ "score" => 3.14, "whole" => 7.0 })
+ end
+
+ it "raises on non-numeric float cast" do
+ config = { "include_other_fields" => false }.merge(
+ assignments(assignment("score", "abc", "float")),
+ )
+
+ expect { execute_node(configuration: config, item: item) }.to raise_error(
+ DiscourseWorkflows::NodeError,
+ )
+ end
+
+ it "raises on non-numeric integer cast" do
+ config = { "include_other_fields" => false }.merge(
+ assignments(assignment("count", "abc", "integer")),
+ )
+
+ expect { execute_node(configuration: config, item: item) }.to raise_error(
+ DiscourseWorkflows::NodeError,
+ )
+ end
+
+ it "returns empty hash when fields are empty and include_input is false" do
+ config = { "include_other_fields" => false }.merge(assignments)
+
+ result = execute_node(configuration: config, item: item)
+
+ expect(result).to eq({})
+ end
+
+ it "returns item json when fields are empty and include_input is true" do
+ config = { "include_other_fields" => true }.merge(assignments)
+
+ result = execute_node(configuration: config, item: item)
+
+ expect(result).to eq(item["json"])
+ end
+
+ it "skips fields with blank keys" do
+ config = { "include_other_fields" => false }.merge(
+ assignments(assignment("", "ignored"), assignment("kept", "yes")),
+ )
+
+ result = execute_node(configuration: config, item: item)
+
+ expect(result).to eq({ "kept" => "yes" })
+ end
+
+ it "sets nested fields with dot notation" do
+ config = { "include_other_fields" => false }.merge(
+ assignments(assignment("profile.name", "Alice")),
+ )
+
+ result = execute_node(configuration: config, item: item)
+
+ expect(result).to eq({ "profile" => { "name" => "Alice" } })
+ end
+
+ it "can disable dot notation from optional options" do
+ config = { "include_other_fields" => false, "options" => { "dot_notation" => false } }.merge(
+ assignments(assignment("profile.name", "Alice")),
+ )
+
+ result = execute_node(configuration: config, item: item)
+
+ expect(result).to eq({ "profile.name" => "Alice" })
+ end
+
+ it "keeps raw values when conversion errors are ignored" do
+ config = {
+ "include_other_fields" => false,
+ "options" => {
+ "ignore_conversion_errors" => true,
+ },
+ }.merge(assignments(assignment("score", "abc", "float")))
+
+ result = execute_node(configuration: config, item: item)
+
+ expect(result).to eq({ "score" => "abc" })
+ end
+
+ it "includes only selected input fields" do
+ nested_item = { "json" => item["json"].merge("profile" => { "name" => "Alice" }) }
+ config = { "include" => "selected", "include_fields" => "topic_id, profile.name" }.merge(
+ assignments,
+ )
+
+ result = execute_node(configuration: config, item: nested_item)
+
+ expect(result).to eq({ "topic_id" => "42", "name" => "Alice" })
+ end
+
+ it "excludes selected input fields" do
+ config = { "include" => "except", "exclude_fields" => "username" }.merge(assignments)
+
+ result = execute_node(configuration: config, item: item)
+
+ expect(result).to eq({ "topic_id" => "42" })
+ end
+
+ context "with raw JSON mode" do
+ it "parses valid JSON and returns typed values" do
+ config = {
+ "mode" => "raw",
+ "include_other_fields" => false,
+ "json_output" => '{"status": "active", "count": 42, "enabled": true}',
+ }
+
+ result = execute_node(configuration: config, item: item)
+
+ expect(result).to eq({ "status" => "active", "count" => 42, "enabled" => true })
+ end
+
+ it "merges with item json when include_input is true" do
+ config = {
+ "mode" => "raw",
+ "include_other_fields" => true,
+ "json_output" => '{"priority": "high"}',
+ }
+
+ result = execute_node(configuration: config, item: item)
+
+ expect(result).to eq({ "topic_id" => "42", "username" => "alice", "priority" => "high" })
+ end
+
+ it "returns only parsed JSON when include_input is false" do
+ config = {
+ "mode" => "raw",
+ "include_other_fields" => false,
+ "json_output" => '{"only": "this"}',
+ }
+
+ result = execute_node(configuration: config, item: item)
+
+ expect(result).to eq({ "only" => "this" })
+ end
+
+ it "raises on invalid JSON" do
+ config = {
+ "mode" => "raw",
+ "include_other_fields" => false,
+ "json_output" => "not valid json{",
+ }
+
+ expect { execute_node(configuration: config, item: item) }.to raise_error(
+ DiscourseWorkflows::NodeError,
+ )
+ end
+
+ it "raises when JSON is not an object" do
+ config = {
+ "mode" => "raw",
+ "include_other_fields" => false,
+ "json_output" => '["an", "array"]',
+ }
+
+ expect { execute_node(configuration: config, item: item) }.to raise_error(
+ DiscourseWorkflows::NodeError,
+ "JSON must be an object.",
+ )
+ end
+
+ it "raises when JSON string is blank" do
+ config = { "mode" => "raw", "include_other_fields" => false, "json_output" => "" }
+
+ expect { execute_node(configuration: config, item: item) }.to raise_error(
+ DiscourseWorkflows::NodeError,
+ "JSON string is blank.",
+ )
+ end
+ end
+
+ it "defaults to manual mode when no mode key is present" do
+ config = { "include_other_fields" => false }.merge(assignments(assignment("status", "open")))
+
+ result = execute_node(configuration: config, item: item)
+
+ expect(result).to eq({ "status" => "open" })
+ end
+ end
+end
diff --git a/plugins/discourse-workflows/spec/lib/discourse_workflows/nodes/sort_spec.rb b/plugins/discourse-workflows/spec/lib/discourse_workflows/nodes/sort_spec.rb
new file mode 100644
index 00000000000..54d3779359c
--- /dev/null
+++ b/plugins/discourse-workflows/spec/lib/discourse_workflows/nodes/sort_spec.rb
@@ -0,0 +1,198 @@
+# frozen_string_literal: true
+
+RSpec.describe DiscourseWorkflows::Nodes::Sort::V1 do
+ def execute(input_items, configuration = {})
+ config = { "type" => "simple" }.merge(configuration)
+ execute_node_output(configuration: config, input_items: input_items).first
+ end
+
+ def sort_fields(*fields)
+ { "values" => fields }
+ end
+
+ describe "simple mode" do
+ it "sorts items ascending by a single field" do
+ input = [
+ { "json" => { "name" => "Charlie" } },
+ { "json" => { "name" => "Alice" } },
+ { "json" => { "name" => "Bob" } },
+ ]
+ result =
+ execute(
+ input,
+ "sort_fields" => sort_fields({ "field_name" => "name", "order" => "ascending" }),
+ )
+
+ expect(result.map { |i| i["json"]["name"] }).to eq(%w[Alice Bob Charlie])
+ end
+
+ it "sorts items descending by a single field" do
+ input = [
+ { "json" => { "score" => 10 } },
+ { "json" => { "score" => 30 } },
+ { "json" => { "score" => 20 } },
+ ]
+ result =
+ execute(
+ input,
+ "sort_fields" => sort_fields({ "field_name" => "score", "order" => "descending" }),
+ )
+
+ expect(result.map { |i| i["json"]["score"] }).to eq([30, 20, 10])
+ end
+
+ it "is case-insensitive for string comparisons" do
+ input = [
+ { "json" => { "name" => "banana" } },
+ { "json" => { "name" => "Apple" } },
+ { "json" => { "name" => "cherry" } },
+ ]
+ result =
+ execute(
+ input,
+ "sort_fields" => sort_fields({ "field_name" => "name", "order" => "ascending" }),
+ )
+
+ expect(result.map { |i| i["json"]["name"] }).to eq(%w[Apple banana cherry])
+ end
+
+ it "places nil values first" do
+ input = [
+ { "json" => { "name" => "Bob" } },
+ { "json" => { "other" => "no name field" } },
+ { "json" => { "name" => "Alice" } },
+ ]
+ result =
+ execute(
+ input,
+ "sort_fields" => sort_fields({ "field_name" => "name", "order" => "ascending" }),
+ )
+
+ expect(result[0]["json"]).not_to have_key("name")
+ expect(result[1]["json"]["name"]).to eq("Alice")
+ expect(result[2]["json"]["name"]).to eq("Bob")
+ end
+
+ it "sorts by multiple fields with priority order" do
+ input = [
+ { "json" => { "dept" => "Sales", "name" => "Charlie" } },
+ { "json" => { "dept" => "Engineering", "name" => "Bob" } },
+ { "json" => { "dept" => "Sales", "name" => "Alice" } },
+ { "json" => { "dept" => "Engineering", "name" => "Alice" } },
+ ]
+ result =
+ execute(
+ input,
+ "sort_fields" =>
+ sort_fields(
+ { "field_name" => "dept", "order" => "ascending" },
+ { "field_name" => "name", "order" => "ascending" },
+ ),
+ )
+
+ expect(result.map { |i| [i["json"]["dept"], i["json"]["name"]] }).to eq(
+ [%w[Engineering Alice], %w[Engineering Bob], %w[Sales Alice], %w[Sales Charlie]],
+ )
+ end
+
+ it "supports dot notation for nested fields" do
+ input = [
+ { "json" => { "address" => { "city" => "New York" } } },
+ { "json" => { "address" => { "city" => "Boston" } } },
+ { "json" => { "address" => { "city" => "Chicago" } } },
+ ]
+ result =
+ execute(
+ input,
+ "sort_fields" => sort_fields({ "field_name" => "address.city", "order" => "ascending" }),
+ )
+
+ expect(result.map { |i| i["json"]["address"]["city"] }).to eq(%w[Boston Chicago New\ York])
+ end
+
+ it "returns items unchanged when sort_fields is empty" do
+ input = [{ "json" => { "a" => 2 } }, { "json" => { "a" => 1 } }]
+ result = execute(input, "sort_fields" => sort_fields)
+
+ expect(result.map { |i| i["json"]["a"] }).to eq([2, 1])
+ end
+ end
+
+ describe "random mode" do
+ it "returns all items in a shuffled order" do
+ input = (1..20).map { |i| { "json" => { "n" => i } } }
+ result = execute(input, "type" => "random")
+
+ expect(result.map { |i| i["json"]["n"] }).to contain_exactly(*(1..20))
+ end
+ end
+
+ describe "code mode" do
+ it "sorts items using a custom JavaScript comparator" do
+ input = [{ "json" => { "n" => 3 } }, { "json" => { "n" => 1 } }, { "json" => { "n" => 2 } }]
+ result = execute(input, "type" => "code", "code" => "return a.json.n - b.json.n;")
+
+ expect(result.map { |i| i["json"]["n"] }).to eq([1, 2, 3])
+ end
+
+ it "supports descending sort via custom comparator" do
+ input = [{ "json" => { "n" => 1 } }, { "json" => { "n" => 3 } }, { "json" => { "n" => 2 } }]
+ result = execute(input, "type" => "code", "code" => "return b.json.n - a.json.n;")
+
+ expect(result.map { |i| i["json"]["n"] }).to eq([3, 2, 1])
+ end
+
+ it "raises when code is missing a return statement" do
+ input = [{ "json" => { "n" => 1 } }]
+
+ expect { execute(input, "type" => "code", "code" => "a.json.n - b.json.n;") }.to raise_error(
+ DiscourseWorkflows::NodeError,
+ /return/,
+ )
+ end
+
+ it "raises on invalid JavaScript" do
+ input = [{ "json" => { "n" => 1 } }]
+
+ expect { execute(input, "type" => "code", "code" => "return {{{invalid;") }.to raise_error(
+ DiscourseWorkflows::JsSandbox::SandboxError,
+ )
+ end
+
+ it "raises node errors for task runner failures without exception objects" do
+ job_result =
+ DiscourseWorkflows::Executor::NodeExecutionContext::JobResult.new(
+ ok: false,
+ result: nil,
+ error: "broken",
+ )
+ parameters = { "type" => "code", "code" => "return 0;" }
+ exec_ctx =
+ double(
+ input_items: [{ "json" => { "n" => 1 } }],
+ get_mode: "manual",
+ continue_on_fail: false,
+ get_node: double(parameters: parameters),
+ start_job: job_result,
+ )
+ allow(exec_ctx).to receive(:get_node_parameter) { |key, _item_index| parameters[key] }
+
+ expect { described_class.new.execute(exec_ctx) }.to raise_error(
+ DiscourseWorkflows::NodeError,
+ "JavaScript execution failed: broken",
+ )
+ end
+
+ it "captures console.log output" do
+ input = [{ "json" => { "n" => 2 } }, { "json" => { "n" => 1 } }]
+ configuration = {
+ "type" => "code",
+ "code" => 'console.log("comparing", a.json.n, b.json.n); return a.json.n - b.json.n;',
+ }
+ execute_node_output(configuration: configuration, input_items: input) do |ctx|
+ messages = ctx.log.entries.map { |e| e["message"] }
+ expect(messages).to include(a_string_matching(/comparing/))
+ end
+ end
+ end
+end
diff --git a/plugins/discourse-workflows/spec/lib/discourse_workflows/nodes/split_out_spec.rb b/plugins/discourse-workflows/spec/lib/discourse_workflows/nodes/split_out_spec.rb
new file mode 100644
index 00000000000..e04ae07920c
--- /dev/null
+++ b/plugins/discourse-workflows/spec/lib/discourse_workflows/nodes/split_out_spec.rb
@@ -0,0 +1,215 @@
+# frozen_string_literal: true
+
+RSpec.describe DiscourseWorkflows::Nodes::SplitOut::V1 do
+ def execute(input_items, configuration = {}, &block)
+ config = { "field" => "items" }.merge(configuration)
+ execute_node_output(configuration: config, input_items: input_items, &block).first
+ end
+
+ describe "basic array splitting" do
+ it "splits an array field into separate items" do
+ input = [{ "json" => { "name" => "test", "items" => [{ "a" => 1 }, { "a" => 2 }] } }]
+ result = execute(input)
+
+ expect(result.length).to eq(2)
+ expect(result[0]["json"]).to include("a" => 1)
+ expect(result[1]["json"]).to include("a" => 2)
+ end
+
+ it "keeps the original field name for non-object array elements" do
+ input = [{ "json" => { "tags" => %w[foo bar baz] } }]
+ result = execute(input, "field" => "tags")
+
+ expect(result.length).to eq(3)
+ expect(result[0]["json"]).to eq({ "tags" => "foo" })
+ expect(result[1]["json"]).to eq({ "tags" => "bar" })
+ end
+
+ it "wraps non-array values in an array (type coercion)" do
+ input = [{ "json" => { "items" => "single" } }]
+ result = execute(input)
+
+ expect(result.length).to eq(1)
+ expect(result[0]["json"]).to eq({ "items" => "single" })
+ end
+
+ it "converts non-array objects using values" do
+ input = [{ "json" => { "items" => { "x" => 1, "y" => 2 } } }]
+ result = execute(input)
+
+ expect(result.length).to eq(2)
+ expect(result.map { |item| item["json"] }).to eq([{ "items" => 1 }, { "items" => 2 }])
+ end
+
+ it "emits no items when field is missing" do
+ input = [{ "json" => { "name" => "test" } }]
+ hints = nil
+ result = execute(input) { |ctx| hints = ctx.execution_hints }
+
+ expect(result).to eq([])
+ expect(hints).to eq(
+ [
+ {
+ "message" => "The field 'items' wasn't found in any input item.",
+ "location" => "outputPane",
+ },
+ ],
+ )
+ end
+
+ it "emits no items when field is empty" do
+ input = [{ "json" => { "items" => [] } }]
+ hints = nil
+ result = execute(input) { |ctx| hints = ctx.execution_hints }
+
+ expect(result).to eq([])
+ expect(hints).to eq([])
+ end
+
+ it "does not add a missing field hint when any input item has the field" do
+ input = [{ "json" => { "name" => "test" } }, { "json" => { "items" => [1] } }]
+ hints = nil
+ result = execute(input) { |ctx| hints = ctx.execution_hints }
+
+ expect(result.map { |item| item["json"] }).to eq([{ "items" => 1 }])
+ expect(hints).to eq([])
+ end
+
+ it "resolves split field and destination expressions for each input item" do
+ input = [
+ { "json" => { "field" => "items", "destination" => "item", "items" => [1] } },
+ { "json" => { "field" => "values", "destination" => "value", "values" => [2] } },
+ ]
+ result =
+ execute(
+ input,
+ "field" => "={{ $json.field }}",
+ "destination_field_name" => "={{ $json.destination }}",
+ )
+
+ expect(result.map { |item| item["json"] }).to eq([{ "item" => 1 }, { "value" => 2 }])
+ end
+
+ it "handles multiple input items" do
+ input = [{ "json" => { "items" => [1, 2] } }, { "json" => { "items" => [3] } }]
+ result = execute(input)
+
+ expect(result.length).to eq(3)
+ end
+
+ it "links split output items to their source input item" do
+ input = [{ "json" => { "items" => [1, 2] } }, { "json" => { "items" => [3] } }]
+ result = execute(input)
+
+ expect(result.map { |item| item["pairedItem"] }).to eq(
+ [{ "item" => 0 }, { "item" => 0 }, { "item" => 1 }],
+ )
+ end
+ end
+
+ describe "include modes" do
+ it "includes all other fields" do
+ input = [{ "json" => { "company" => "Acme", "items" => [{ "n" => 1 }] } }]
+ result = execute(input, "include" => "all_other_fields")
+
+ expect(result.length).to eq(1)
+ expect(result[0]["json"]).to include("company" => "Acme", "items" => { "n" => 1 })
+ end
+
+ it "includes selected other fields" do
+ input = [{ "json" => { "company" => "Acme", "country" => "US", "items" => [{ "n" => 1 }] } }]
+ result =
+ execute(input, "include" => "selected_other_fields", "fields_to_include" => "company")
+
+ expect(result[0]["json"]["company"]).to eq("Acme")
+ expect(result[0]["json"]["items"]).to eq("n" => 1)
+ expect(result[0]["json"]).not_to have_key("country")
+ end
+
+ it "resolves include mode expressions" do
+ input = [{ "json" => { "company" => "Acme", "items" => [1] } }]
+ result = execute(input, "include" => "={{ 'all_other_fields' }}")
+
+ expect(result.first["json"]).to eq("company" => "Acme", "items" => 1)
+ end
+
+ it "raises DiscourseWorkflows::NodeError when selected fields are blank" do
+ input = [{ "json" => { "items" => [{ "n" => 1 }] } }]
+
+ expect { execute(input, "include" => "selected_other_fields") }.to raise_error(
+ DiscourseWorkflows::NodeError,
+ /No fields specified/,
+ )
+ end
+
+ it "does not validate selected fields when there are no split items" do
+ input = [{ "json" => { "items" => [] } }]
+
+ expect(execute(input, "include" => "selected_other_fields")).to eq([])
+ end
+ end
+
+ describe "dot notation" do
+ it "accesses nested fields" do
+ input = [{ "json" => { "data" => { "items" => [1, 2] } } }]
+ result = execute(input, "field" => "data.items")
+
+ expect(result.length).to eq(2)
+ expect(result.first["json"]).to eq("data.items" => 1)
+ end
+
+ it "strips a leading $json prefix from field names" do
+ input = [{ "json" => { "items" => [1] } }]
+ result = execute(input, "field" => "$json.items")
+
+ expect(result.first["json"]).to eq("items" => 1)
+ end
+
+ it "can disable dot notation for literal field names" do
+ input = [{ "json" => { "data.items" => [1] } }]
+ result = execute(input, "field" => "data.items", "disable_dot_notation" => true)
+
+ expect(result.first["json"]).to eq("data.items" => 1)
+ end
+ end
+
+ describe "multiple fields" do
+ it "splits multiple fields simultaneously" do
+ input = [{ "json" => { "names" => %w[a b], "ages" => [1, 2] } }]
+ result = execute(input, "field" => "names, ages")
+
+ expect(result.length).to eq(2)
+ expect(result[0]["json"]).to include("names" => "a", "ages" => 1)
+ end
+
+ it "omits fields that have no element at the split index" do
+ input = [{ "json" => { "names" => %w[a b], "ages" => [1] } }]
+ result = execute(input, "field" => "names, ages")
+
+ expect(result.map { |item| item["json"] }).to eq(
+ [{ "names" => "a", "ages" => 1 }, { "names" => "b" }],
+ )
+ end
+ end
+
+ describe "destination field name" do
+ it "renames the output field" do
+ input = [{ "json" => { "items" => [{ "a" => 1 }] } }]
+ result = execute(input, "destination_field_name" => "result")
+
+ expect(result[0]["json"]).to have_key("result")
+ end
+ end
+
+ describe "item limit" do
+ it "raises DiscourseWorkflows::NodeError when array exceeds MAX_SPLIT_ITEMS" do
+ oversized_array = (1..(described_class::MAX_SPLIT_ITEMS + 1)).map { |n| { "n" => n } }
+ input = [{ "json" => { "items" => oversized_array } }]
+
+ expect { execute(input) }.to raise_error(
+ DiscourseWorkflows::NodeError,
+ /Cannot split into more than/,
+ )
+ end
+ end
+end
diff --git a/plugins/discourse-workflows/spec/lib/discourse_workflows/nodes/stale_topic_spec.rb b/plugins/discourse-workflows/spec/lib/discourse_workflows/nodes/stale_topic_spec.rb
new file mode 100644
index 00000000000..57567abbe25
--- /dev/null
+++ b/plugins/discourse-workflows/spec/lib/discourse_workflows/nodes/stale_topic_spec.rb
@@ -0,0 +1,105 @@
+# frozen_string_literal: true
+
+RSpec.describe DiscourseWorkflows::Nodes::StaleTopic::V1 do
+ describe ".trigger_data_for" do
+ fab!(:stale_topic) { Fabricate(:topic, created_at: 48.hours.ago, last_posted_at: 48.hours.ago) }
+ fab!(:fresh_topic) { Fabricate(:topic, created_at: 1.hour.ago, last_posted_at: 1.hour.ago) }
+ fab!(:tag) { Fabricate(:tag, name: "stale-tag") }
+
+ before do
+ SiteSetting.tagging_enabled = true
+ stale_topic.tags << tag
+ end
+
+ let(:trigger_node) do
+ { "id" => "trigger-1", "type" => "trigger:stale_topic", "parameters" => { "hours" => 24 } }
+ end
+
+ it "returns one item per stale topic" do
+ items = described_class.trigger_data_for(trigger_context)
+
+ expect(items.size).to eq(1)
+ expect(items.first[:topic][:id]).to eq(stale_topic.id)
+ expect(items.first[:topic][:tags].map { |t| t[:name] }).to eq(["stale-tag"])
+ end
+
+ context "with category filter" do
+ fab!(:category)
+ fab!(:other_category, :category)
+ fab!(:stale_topic_in_category) do
+ Fabricate(
+ :topic,
+ category: category,
+ created_at: 48.hours.ago,
+ last_posted_at: 48.hours.ago,
+ )
+ end
+ fab!(:stale_topic_in_other_category) do
+ Fabricate(
+ :topic,
+ category: other_category,
+ created_at: 48.hours.ago,
+ last_posted_at: 48.hours.ago,
+ )
+ end
+
+ let(:trigger_node) do
+ {
+ "id" => "trigger-1",
+ "type" => "trigger:stale_topic",
+ "parameters" => {
+ "hours" => 24,
+ "category_id" => category.id.to_s,
+ },
+ }
+ end
+
+ it "only returns topics in the configured category" do
+ items = described_class.trigger_data_for(trigger_context)
+
+ topic_ids = items.map { |item| item[:topic][:id] }
+ expect(topic_ids).to contain_exactly(stale_topic_in_category.id)
+ end
+ end
+
+ context "with tag filter" do
+ fab!(:other_tag) { Fabricate(:tag, name: "other-tag") }
+ fab!(:stale_topic_with_other_tag) do
+ Fabricate(:topic, created_at: 48.hours.ago, last_posted_at: 48.hours.ago).tap do |t|
+ t.tags << other_tag
+ end
+ end
+
+ let(:trigger_node) do
+ {
+ "id" => "trigger-1",
+ "type" => "trigger:stale_topic",
+ "parameters" => {
+ "hours" => 24,
+ "tag_names" => %w[stale-tag],
+ },
+ }
+ end
+
+ it "only returns topics that have at least one of the configured tags" do
+ items = described_class.trigger_data_for(trigger_context)
+
+ topic_ids = items.map { |item| item[:topic][:id] }
+ expect(topic_ids).to contain_exactly(stale_topic.id)
+ end
+
+ it "accepts comma-separated strings" do
+ trigger_node["parameters"]["tag_names"] = "stale-tag, other-tag"
+
+ items = described_class.trigger_data_for(trigger_context)
+
+ topic_ids = items.map { |item| item[:topic][:id] }
+ expect(topic_ids).to contain_exactly(stale_topic.id, stale_topic_with_other_tag.id)
+ end
+ end
+
+ def trigger_context
+ DiscourseWorkflows::TriggerNodeContext.new(trigger_node)
+ end
+ end
+end
diff --git a/plugins/discourse-workflows/spec/lib/discourse_workflows/nodes/topic_admin_button_spec.rb b/plugins/discourse-workflows/spec/lib/discourse_workflows/nodes/topic_admin_button_spec.rb
new file mode 100644
index 00000000000..16a0448efd3
--- /dev/null
+++ b/plugins/discourse-workflows/spec/lib/discourse_workflows/nodes/topic_admin_button_spec.rb
@@ -0,0 +1,35 @@
+# frozen_string_literal: true
+
+RSpec.describe DiscourseWorkflows::Nodes::TopicAdminButton::V1 do
+ fab!(:topic)
+ fab!(:tag) { Fabricate(:tag, name: "test-tag") }
+
+ before do
+ SiteSetting.tagging_enabled = true
+ topic.tags << tag
+ end
+
+ describe "#valid?" do
+ it "returns true when topic is present" do
+ trigger = described_class.new(topic)
+ expect(trigger).to be_valid
+ end
+
+ it "returns false when topic is nil" do
+ trigger = described_class.new(nil)
+ expect(trigger).not_to be_valid
+ end
+ end
+
+ describe "#output" do
+ it "returns topic data" do
+ output = described_class.new(topic).output
+
+ expect(output).to include(
+ topic: include(id: topic.id, title: topic.title, category_id: topic.category_id),
+ )
+ expect(output[:topic][:tags].map { |topic_tag| topic_tag[:name] }).to eq(["test-tag"])
+ expect(output[:topic][:posters].map { |poster| poster[:user_id] }).to include(topic.user_id)
+ end
+ end
+end
diff --git a/plugins/discourse-workflows/spec/lib/discourse_workflows/nodes/topic_category_changed_spec.rb b/plugins/discourse-workflows/spec/lib/discourse_workflows/nodes/topic_category_changed_spec.rb
new file mode 100644
index 00000000000..e4cfc832822
--- /dev/null
+++ b/plugins/discourse-workflows/spec/lib/discourse_workflows/nodes/topic_category_changed_spec.rb
@@ -0,0 +1,44 @@
+# frozen_string_literal: true
+
+RSpec.describe DiscourseWorkflows::Nodes::TopicCategoryChanged::V1 do
+ fab!(:category)
+ fab!(:other_category, :category)
+ fab!(:topic) { Fabricate(:topic, category: other_category) }
+ fab!(:tag) { Fabricate(:tag, name: "test-tag") }
+
+ before do
+ SiteSetting.tagging_enabled = true
+ topic.tags << tag
+ end
+
+ describe "#valid?" do
+ it "returns true when topic and old_category are present" do
+ trigger = described_class.new(topic, category)
+ expect(trigger).to be_valid
+ end
+
+ it "returns false when topic is nil" do
+ trigger = described_class.new(nil, category)
+ expect(trigger).not_to be_valid
+ end
+
+ it "returns false when old_category is nil" do
+ trigger = described_class.new(topic, nil)
+ expect(trigger).not_to be_valid
+ end
+ end
+
+ describe "#output" do
+ it "returns topic data with both category ids" do
+ trigger = described_class.new(topic, category)
+ output = trigger.output
+
+ expect(output[:topic][:id]).to eq(topic.id)
+ expect(output[:topic][:title]).to eq(topic.title)
+ expect(output[:topic][:tags].map { |topic_tag| topic_tag[:name] }).to eq(["test-tag"])
+ expect(output[:topic][:category_id]).to eq(topic.category_id)
+ expect(output[:old_category_id]).to eq(category.id)
+ expect(output[:topic][:posters].map { |poster| poster[:user_id] }).to include(topic.user_id)
+ end
+ end
+end
diff --git a/plugins/discourse-workflows/spec/lib/discourse_workflows/nodes/topic_closed_spec.rb b/plugins/discourse-workflows/spec/lib/discourse_workflows/nodes/topic_closed_spec.rb
new file mode 100644
index 00000000000..24a54c5cc50
--- /dev/null
+++ b/plugins/discourse-workflows/spec/lib/discourse_workflows/nodes/topic_closed_spec.rb
@@ -0,0 +1,38 @@
+# frozen_string_literal: true
+
+RSpec.describe DiscourseWorkflows::Nodes::TopicClosed::V1 do
+ fab!(:topic)
+ fab!(:tag) { Fabricate(:tag, name: "test-tag") }
+
+ before do
+ SiteSetting.tagging_enabled = true
+ topic.tags << tag
+ end
+
+ describe "#valid?" do
+ it "returns true when topic is closed" do
+ trigger = described_class.new(topic, "closed", true)
+ expect(trigger).to be_valid
+ end
+
+ it "returns false when topic is reopened" do
+ trigger = described_class.new(topic, "closed", false)
+ expect(trigger).not_to be_valid
+ end
+
+ it "returns false for non-closed status changes" do
+ trigger = described_class.new(topic, "visible", true)
+ expect(trigger).not_to be_valid
+ end
+ end
+
+ describe "#output" do
+ it "returns topic_id and tags" do
+ trigger = described_class.new(topic, "closed", true)
+ output = trigger.output
+
+ expect(output[:topic][:id]).to eq(topic.id)
+ expect(output[:topic][:tags].map { |topic_tag| topic_tag[:name] }).to eq(["test-tag"])
+ end
+ end
+end
diff --git a/plugins/discourse-workflows/spec/lib/discourse_workflows/nodes/topic_created_spec.rb b/plugins/discourse-workflows/spec/lib/discourse_workflows/nodes/topic_created_spec.rb
new file mode 100644
index 00000000000..69bf2c1e19f
--- /dev/null
+++ b/plugins/discourse-workflows/spec/lib/discourse_workflows/nodes/topic_created_spec.rb
@@ -0,0 +1,58 @@
+# frozen_string_literal: true
+
+RSpec.describe DiscourseWorkflows::Nodes::TopicCreated::V1 do
+ fab!(:user) { Fabricate(:user, refresh_auto_groups: true) }
+ fab!(:first_post) { create_post(user: user, raw: "First post") }
+ fab!(:topic) { first_post.topic }
+ fab!(:tag) { Fabricate(:tag, name: "test-tag") }
+
+ before do
+ SiteSetting.tagging_enabled = true
+ topic.tags << tag
+ end
+
+ describe "#valid?" do
+ it "returns true when topic is present" do
+ trigger = described_class.new(topic)
+ expect(trigger).to be_valid
+ end
+
+ it "returns false when topic is nil" do
+ trigger = described_class.new(nil)
+ expect(trigger).not_to be_valid
+ end
+
+ it "returns false when skip_workflows is true" do
+ trigger = described_class.new(topic, { skip_workflows: true })
+ expect(trigger).not_to be_valid
+ end
+ end
+
+ describe "#output" do
+ it "returns post and topic data" do
+ trigger = described_class.new(topic)
+ output = trigger.output
+
+ expect(output[:post][:id]).to eq(first_post.id)
+ expect(output[:post][:post_number]).to eq(first_post.post_number)
+ expect(output[:post][:raw]).to eq(first_post.raw)
+ expect(output[:post][:user_id]).to eq(user.id)
+ expect(output[:post][:username]).to eq(user.username)
+ expect(output[:topic][:id]).to eq(topic.id)
+ expect(output[:topic][:title]).to eq(topic.title)
+ expect(output[:topic][:tags].map { |topic_tag| topic_tag[:name] }).to eq(["test-tag"])
+ expect(output[:topic][:category_id]).to eq(topic.category_id)
+ expect(output[:topic][:posters].map { |poster| poster[:user_id] }).to include(topic.user_id)
+ end
+
+ it "includes assignment data when assign is available" do
+ SiteSetting.assign_enabled = true
+ assignee = Fabricate(:user)
+ Fabricate(:topic_assignment, topic: topic, assigned_to: assignee)
+
+ output = described_class.new(topic).output
+
+ expect(output[:topic][:assigned_to_user][:username]).to eq(assignee.username)
+ end
+ end
+end
diff --git a/plugins/discourse-workflows/spec/lib/discourse_workflows/nodes/topic_spec.rb b/plugins/discourse-workflows/spec/lib/discourse_workflows/nodes/topic_spec.rb
new file mode 100644
index 00000000000..31083d0690f
--- /dev/null
+++ b/plugins/discourse-workflows/spec/lib/discourse_workflows/nodes/topic_spec.rb
@@ -0,0 +1,341 @@
+# frozen_string_literal: true
+
+RSpec.describe DiscourseWorkflows::Nodes::Topic::V1 do
+ fab!(:admin)
+ fab!(:user)
+ fab!(:other_user, :user)
+ fab!(:category)
+ fab!(:other_category, :category)
+ fab!(:tag)
+
+ before { SiteSetting.tagging_enabled = true }
+
+ describe "#execute" do
+ let(:item) { { "json" => {} } }
+
+ context "with operation 'create'" do
+ it "creates a topic for the configured actor" do
+ result = nil
+
+ expect do
+ result =
+ execute_node(
+ configuration: {
+ "operation" => "create",
+ "title" => "Workflow topic",
+ "raw" => "First post body",
+ "category_id" => category.id.to_s,
+ "actor_username" => admin.username,
+ },
+ item: item,
+ )
+ end.to change(Topic, :count).by(1).and change(Post, :count).by(1)
+
+ topic = Topic.last
+
+ expect(topic.title).to eq("Workflow topic")
+ expect(topic.first_post.raw).to eq("First post body")
+ expect(topic.category_id).to eq(category.id)
+ expect(topic.user_id).to eq(admin.id)
+
+ expect(result["topic"]).to include(
+ "id" => topic.id,
+ "title" => topic.title,
+ "category_id" => category.id,
+ "archetype" => Archetype.default,
+ )
+ expect(result["topic"]["last_poster_username"]).to eq(admin.username)
+ expect(result["topic"]["posters"].map { |poster| poster["user_id"] }).to include(admin.id)
+ expect(result).to include("post_id" => topic.first_post.id, "post_number" => 1)
+ end
+
+ it "creates a topic as the system user when actor_username is 'system'" do
+ execute_node(
+ configuration: {
+ "operation" => "create",
+ "title" => "System topic",
+ "raw" => "Created by workflows",
+ "actor_username" => "system",
+ },
+ item: item,
+ )
+
+ expect(Topic.last.user_id).to eq(Discourse.system_user.id)
+ end
+
+ it "accepts tags from an array" do
+ execute_node(
+ configuration: {
+ "operation" => "create",
+ "title" => "Tagged topic",
+ "raw" => "With tags",
+ "tag_names" => ["alpha", " beta "],
+ "actor_username" => "system",
+ },
+ item: item,
+ )
+
+ expect(Topic.last.tags.pluck(:name)).to contain_exactly("alpha", "beta")
+ end
+
+ it "raises when the user cannot be found" do
+ expect do
+ execute_node(
+ configuration: {
+ "operation" => "create",
+ "title" => "Workflow topic",
+ "raw" => "First post body",
+ "actor_username" => "nonexistent_user",
+ },
+ item: item,
+ )
+ end.to raise_error(DiscourseWorkflows::NodeError, "User 'nonexistent_user' not found")
+ end
+
+ it "raises when topic creation fails validation" do
+ expect do
+ execute_node(
+ configuration: {
+ "operation" => "create",
+ "title" => "",
+ "raw" => "",
+ "actor_username" => "system",
+ },
+ item: item,
+ )
+ end.to raise_error(DiscourseWorkflows::NodeError)
+ end
+ end
+
+ context "with operation 'get'" do
+ fab!(:topic) { Fabricate(:topic, category: category, user: user) }
+ fab!(:post) { Fabricate(:post, topic: topic, user: user, raw: "This is the topic body") }
+
+ it "returns all expected topic fields" do
+ result =
+ execute_node(
+ configuration: {
+ "operation" => "get",
+ "topic_id" => topic.id.to_s,
+ },
+ item: {
+ "json" => {
+ "topic_id" => topic.id.to_s,
+ },
+ },
+ )
+
+ expect(result["topic"]["id"]).to eq(topic.id)
+ expect(result["topic"]["title"]).to eq(topic.title)
+ expect(result["topic"]["category_id"]).to eq(category.id)
+ expect(result["topic"]["tags"]).to eq([])
+ end
+
+ it "returns tag names when topic has tags" do
+ topic.tags << tag
+
+ result =
+ execute_node(
+ configuration: {
+ "operation" => "get",
+ "topic_id" => topic.id.to_s,
+ },
+ item: {
+ "json" => {
+ "topic_id" => topic.id.to_s,
+ },
+ },
+ )
+
+ expect(result["topic"]["tags"].map { |topic_tag| topic_tag["name"] }).to contain_exactly(
+ tag.name,
+ )
+ end
+
+ it "raises when topic is not found" do
+ expect do
+ execute_node(
+ configuration: {
+ "operation" => "get",
+ "topic_id" => "-1",
+ },
+ item: {
+ "json" => {
+ },
+ },
+ )
+ end.to raise_error(ActiveRecord::RecordNotFound)
+ end
+
+ it "raises when actor_username cannot see the topic" do
+ pm = Fabricate(:private_message_topic)
+
+ expect do
+ execute_node(
+ configuration: {
+ "operation" => "get",
+ "topic_id" => pm.id.to_s,
+ "actor_username" => user.username,
+ },
+ item: {
+ "json" => {
+ "topic_id" => pm.id.to_s,
+ },
+ },
+ )
+ end.to raise_error(Discourse::InvalidAccess)
+ end
+ end
+
+ context "with operation 'list'" do
+ fab!(:topic_1, :topic) do
+ Fabricate(:topic, category: category, user: user, title: "First topic about workflows")
+ end
+ fab!(:post_1) { Fabricate(:post, topic: topic_1, user: user) }
+ fab!(:topic_2, :topic) do
+ Fabricate(:topic, category: category, user: user, title: "Second topic about workflows")
+ end
+ fab!(:post_2) { Fabricate(:post, topic: topic_2, user: user) }
+
+ def execute_list(configuration:)
+ execute_node_output(configuration: configuration).first
+ end
+
+ it "returns topics matching the query" do
+ result =
+ execute_list(
+ configuration: {
+ "operation" => "list",
+ "query" => "category:#{category.slug}",
+ "limit" => "10",
+ },
+ )
+
+ expect(result.length).to eq(2)
+ expect(result.map { |r| r["json"]["topic"]["id"] }).to contain_exactly(
+ topic_1.id,
+ topic_2.id,
+ )
+ end
+
+ it "respects the limit parameter" do
+ result =
+ execute_list(
+ configuration: {
+ "operation" => "list",
+ "query" => "category:#{category.slug}",
+ "limit" => "1",
+ },
+ )
+
+ expect(result.length).to eq(1)
+ end
+
+ it "defaults limit to 30 when not provided" do
+ result =
+ execute_list(
+ configuration: {
+ "operation" => "list",
+ "query" => "category:#{category.slug}",
+ },
+ )
+
+ expect(result.length).to eq(2)
+ end
+
+ it "returns expected fields for each topic" do
+ topic_1.tags << tag
+
+ result =
+ execute_list(
+ configuration: {
+ "operation" => "list",
+ "query" => "category:#{category.slug}",
+ "limit" => "10",
+ },
+ )
+
+ topic_data = result.find { |r| r["json"]["topic"]["id"] == topic_1.id }.dig("json", "topic")
+ expect(topic_data).to include(
+ "title" => topic_1.title,
+ "category_id" => category.id,
+ "closed" => false,
+ "visible" => true,
+ )
+ expect(topic_data["tags"].map { |topic_tag| topic_tag["name"] }).to contain_exactly(
+ tag.name,
+ )
+ expect(topic_data["posts_count"]).to be_present
+ expect(topic_data["views"]).to be_present
+ expect(topic_data["like_count"]).to be_present
+ expect(topic_data["created_at"]).to be_present
+ expect(topic_data["bumped_at"]).to be_present
+ end
+
+ it "returns empty array when no topics match" do
+ result =
+ execute_list(
+ configuration: {
+ "operation" => "list",
+ "query" => "category:#{other_category.slug}",
+ "limit" => "10",
+ },
+ )
+
+ expect(result).to eq([])
+ end
+
+ it "clamps limit to 100" do
+ captured_opts = nil
+ original_new = TopicQuery.method(:new)
+ allow(TopicQuery).to receive(:new).and_wrap_original do |_method, *args|
+ captured_opts = args[1]
+ original_new.call(*args)
+ end
+
+ execute_list(
+ configuration: {
+ "operation" => "list",
+ "query" => "category:#{category.slug}",
+ "limit" => "200",
+ },
+ )
+
+ expect(captured_opts[:per_page]).to eq(100)
+ end
+
+ it "defaults to system user for topic queries" do
+ restricted = Fabricate(:category, read_restricted: true)
+ Fabricate(:category_group, category: restricted, group: Group[:staff], permission_type: 0)
+ Fabricate(:topic, category: restricted)
+
+ result =
+ execute_list(
+ configuration: {
+ "operation" => "list",
+ "query" => "category:#{restricted.slug}",
+ },
+ )
+
+ expect(result.length).to eq(1)
+ end
+
+ it "uses actor_username when set" do
+ restricted = Fabricate(:category, read_restricted: true)
+ Fabricate(:category_group, category: restricted, group: Group[:staff], permission_type: 0)
+ Fabricate(:topic, category: restricted)
+
+ result =
+ execute_list(
+ configuration: {
+ "operation" => "list",
+ "query" => "category:#{restricted.slug}",
+ "actor_username" => other_user.username,
+ },
+ )
+
+ expect(result.length).to eq(0)
+ end
+ end
+ end
+end
diff --git a/plugins/discourse-workflows/spec/lib/discourse_workflows/nodes/topic_tag_changed_spec.rb b/plugins/discourse-workflows/spec/lib/discourse_workflows/nodes/topic_tag_changed_spec.rb
new file mode 100644
index 00000000000..dff1986b44c
--- /dev/null
+++ b/plugins/discourse-workflows/spec/lib/discourse_workflows/nodes/topic_tag_changed_spec.rb
@@ -0,0 +1,92 @@
+# frozen_string_literal: true
+
+RSpec.describe DiscourseWorkflows::Nodes::TopicTagChanged::V1 do
+ fab!(:topic)
+
+ describe "#valid?" do
+ it "returns true when topic is present" do
+ trigger = described_class.new(topic, old_tag_names: ["bug"], new_tag_names: %w[bug urgent])
+ expect(trigger).to be_valid
+ end
+
+ it "returns false when topic is nil" do
+ trigger = described_class.new(nil)
+ expect(trigger).not_to be_valid
+ end
+
+ it "returns true when tags are removed" do
+ trigger = described_class.new(topic, old_tag_names: %w[bug urgent], new_tag_names: ["bug"])
+ expect(trigger).to be_valid
+ end
+
+ it "returns false when the tag diff is empty" do
+ trigger = described_class.new(topic, old_tag_names: ["bug"], new_tag_names: ["bug"])
+ expect(trigger).not_to be_valid
+ end
+ end
+
+ describe "#output" do
+ it "returns tag change data with computed diffs" do
+ trigger =
+ described_class.new(
+ topic,
+ old_tag_names: %w[bug help],
+ new_tag_names: %w[bug urgent],
+ user: topic.user,
+ )
+ output = trigger.output
+
+ expect(output[:topic][:id]).to eq(topic.id)
+ expect(output[:topic][:title]).to eq(topic.title)
+ expect(output[:topic][:category_id]).to eq(topic.category_id)
+ expect(output[:old_tags]).to eq(%w[bug help])
+ expect(output[:new_tags]).to eq(%w[bug urgent])
+ expect(output[:added_tags]).to eq(%w[urgent])
+ expect(output[:removed_tags]).to eq(%w[help])
+ expect(output[:topic][:posters].map { |poster| poster[:user_id] }).to include(topic.user_id)
+ end
+
+ it "handles tags added from empty" do
+ trigger = described_class.new(topic, old_tag_names: [], new_tag_names: %w[bug urgent])
+ output = trigger.output
+
+ expect(output[:added_tags]).to eq(%w[bug urgent])
+ expect(output[:removed_tags]).to be_empty
+ end
+
+ it "handles all tags removed" do
+ trigger = described_class.new(topic, old_tag_names: %w[bug urgent], new_tag_names: [])
+ output = trigger.output
+
+ expect(output[:added_tags]).to be_empty
+ expect(output[:removed_tags]).to eq(%w[bug urgent])
+ end
+ end
+
+ describe "#matches?" do
+ it "returns true when no category parameter is configured" do
+ trigger = described_class.new(topic, old_tag_names: ["bug"], new_tag_names: %w[bug urgent])
+
+ expect(trigger.matches?(trigger_context({}))).to eq(true)
+ end
+
+ it "returns true when the category parameter matches the topic category" do
+ trigger = described_class.new(topic, old_tag_names: ["bug"], new_tag_names: %w[bug urgent])
+
+ expect(trigger.matches?(trigger_context("category_id" => topic.category_id.to_s))).to eq(true)
+ end
+
+ it "returns false when the category parameter does not match the topic category" do
+ other_category = Fabricate(:category)
+ trigger = described_class.new(topic, old_tag_names: ["bug"], new_tag_names: %w[bug urgent])
+
+ expect(trigger.matches?(trigger_context("category_id" => other_category.id.to_s))).to eq(
+ false,
+ )
+ end
+ end
+
+ def trigger_context(parameters)
+ DiscourseWorkflows::TriggerNodeContext.new({ "parameters" => parameters })
+ end
+end
diff --git a/plugins/discourse-workflows/spec/lib/discourse_workflows/nodes/topic_tags_spec.rb b/plugins/discourse-workflows/spec/lib/discourse_workflows/nodes/topic_tags_spec.rb
new file mode 100644
index 00000000000..acf64bbb69c
--- /dev/null
+++ b/plugins/discourse-workflows/spec/lib/discourse_workflows/nodes/topic_tags_spec.rb
@@ -0,0 +1,197 @@
+# frozen_string_literal: true
+
+RSpec.describe DiscourseWorkflows::Nodes::TopicTags::V1 do
+ fab!(:topic)
+ fab!(:tag) { Fabricate(:tag, name: "existing") }
+ fab!(:tag_2) { Fabricate(:tag, name: "second") }
+
+ before { SiteSetting.tagging_enabled = true }
+
+ describe "#execute" do
+ let(:item) { { "json" => {} } }
+
+ context "with add operation" do
+ it "adds a new tag to the topic" do
+ config = { "operation" => "add", "topic_id" => topic.id.to_s, "tag_names" => "new-tag" }
+
+ result = execute_node(configuration: config, item: item)
+
+ expect(result["tag_names"]).to contain_exactly("new-tag")
+ expect(topic.reload.tags.pluck(:name)).to include("new-tag")
+ end
+
+ it "adds multiple comma-separated tags" do
+ config = {
+ "operation" => "add",
+ "topic_id" => topic.id.to_s,
+ "tag_names" => "alpha, beta, gamma",
+ }
+
+ result = execute_node(configuration: config, item: item)
+
+ expect(result["tag_names"]).to contain_exactly("alpha", "beta", "gamma")
+ end
+
+ it "normalizes tag arrays and comma-separated tag values" do
+ config = {
+ "operation" => "add",
+ "topic_id" => topic.id.to_s,
+ "tag_names" => ["alpha, beta", " ", "gamma"],
+ }
+
+ result = execute_node(configuration: config, item: item)
+
+ expect(result["tag_names"]).to contain_exactly("alpha", "beta", "gamma")
+ end
+
+ it "does not duplicate tags the topic already has" do
+ topic.tags << tag
+
+ config = {
+ "operation" => "add",
+ "topic_id" => topic.id.to_s,
+ "tag_names" => "existing, fresh",
+ }
+
+ result = execute_node(configuration: config, item: item)
+
+ expect(result["tag_names"]).to contain_exactly("existing", "fresh")
+ expect(topic.reload.tags.pluck(:name)).to contain_exactly("existing", "fresh")
+ end
+
+ it "creates tags that do not exist" do
+ config = { "operation" => "add", "topic_id" => topic.id.to_s, "tag_names" => "brand-new" }
+
+ expect { execute_node(configuration: config, item: item) }.to change(Tag, :count).by(1)
+ end
+
+ it "defaults to add when no operation is specified" do
+ config = { "topic_id" => topic.id.to_s, "tag_names" => "default-tag" }
+
+ result = execute_node(configuration: config, item: item)
+
+ expect(result["tag_names"]).to contain_exactly("default-tag")
+ expect(topic.reload.tags.pluck(:name)).to include("default-tag")
+ end
+ end
+
+ context "with remove operation" do
+ it "removes tags from the topic" do
+ topic.tags << tag
+
+ config = { "operation" => "remove", "topic_id" => topic.id.to_s, "tag_names" => "existing" }
+
+ result = execute_node(configuration: config, item: item)
+
+ expect(result["tag_names"]).to contain_exactly("existing")
+ expect(topic.reload.tags.pluck(:name)).to be_empty
+ end
+
+ it "removes multiple comma-separated tags" do
+ topic.tags << [tag, tag_2]
+
+ config = {
+ "operation" => "remove",
+ "topic_id" => topic.id.to_s,
+ "tag_names" => "existing, second",
+ }
+
+ result = execute_node(configuration: config, item: item)
+
+ expect(result["tag_names"]).to contain_exactly("existing", "second")
+ expect(topic.reload.tags).to be_empty
+ end
+
+ it "silently skips tags not present on the topic" do
+ topic.tags << tag
+
+ config = {
+ "operation" => "remove",
+ "topic_id" => topic.id.to_s,
+ "tag_names" => "existing, nonexistent",
+ }
+
+ result = execute_node(configuration: config, item: item)
+
+ expect(result["tag_names"]).to contain_exactly("existing")
+ expect(topic.reload.tags).to be_empty
+ end
+ end
+
+ it "raises when topic does not exist" do
+ config = { "operation" => "add", "topic_id" => "-1", "tag_names" => "anything" }
+
+ expect { execute_node(configuration: config, item: item) }.to raise_error(
+ ActiveRecord::RecordNotFound,
+ )
+ end
+
+ it "raises when no tag names are provided" do
+ config = { "operation" => "add", "topic_id" => topic.id.to_s, "tag_names" => "" }
+
+ expect { execute_node(configuration: config, item: item) }.to raise_error(
+ DiscourseWorkflows::NodeError,
+ "No tag names provided.",
+ )
+ end
+
+ context "with restricted tags" do
+ fab!(:regular_user, :user)
+ fab!(:admin)
+ fab!(:staff_tag_group) do
+ Fabricate(
+ :tag_group,
+ permissions: {
+ "staff" => TagGroupPermission.permission_types[:full],
+ },
+ )
+ end
+ fab!(:staff_tag) do
+ tag = Fabricate(:tag, name: "staff-only")
+ staff_tag_group.tags << tag
+ tag
+ end
+
+ it "prevents adding staff-only tags when actor_username is a regular user" do
+ config = {
+ "operation" => "add",
+ "topic_id" => topic.id.to_s,
+ "tag_names" => "staff-only",
+ "actor_username" => regular_user.username,
+ }
+
+ expect { execute_node(configuration: config, item: item) }.to raise_error(
+ DiscourseWorkflows::NodeError,
+ )
+ expect(topic.reload.tags.pluck(:name)).not_to include("staff-only")
+ end
+
+ it "allows adding staff-only tags when actor_username is staff" do
+ config = {
+ "operation" => "add",
+ "topic_id" => topic.id.to_s,
+ "tag_names" => "staff-only",
+ "actor_username" => admin.username,
+ }
+
+ result = execute_node(configuration: config, item: item)
+
+ expect(result["tag_names"]).to include("staff-only")
+ expect(topic.reload.tags.pluck(:name)).to include("staff-only")
+ end
+ end
+
+ context "with tag synonyms" do
+ fab!(:target_tag) { Fabricate(:tag, name: "target") }
+ fab!(:synonym_tag) { Fabricate(:tag, name: "synonym", target_tag: target_tag) }
+
+ it "resolves tag synonyms when adding" do
+ config = { "operation" => "add", "topic_id" => topic.id.to_s, "tag_names" => "synonym" }
+
+ execute_node(configuration: config, item: item)
+
+ expect(topic.reload.tags.pluck(:name)).to include("target")
+ end
+ end
+ end
+end
diff --git a/plugins/discourse-workflows/spec/lib/discourse_workflows/nodes/wait/v1_spec.rb b/plugins/discourse-workflows/spec/lib/discourse_workflows/nodes/wait/v1_spec.rb
new file mode 100644
index 00000000000..cc6752de1ff
--- /dev/null
+++ b/plugins/discourse-workflows/spec/lib/discourse_workflows/nodes/wait/v1_spec.rb
@@ -0,0 +1,72 @@
+# frozen_string_literal: true
+
+RSpec.describe DiscourseWorkflows::Nodes::Wait::V1 do
+ let(:sandbox) { DiscourseWorkflows::JsSandbox.new({ "$json" => {} }) }
+ after { sandbox.dispose }
+
+ def build_exec_ctx(configuration, resume_token: nil)
+ DiscourseWorkflows::Executor::NodeExecutionContext.new(
+ input_items: [{ "json" => {} }],
+ parameters: configuration,
+ property_schema: described_class.property_schema,
+ node_context: {
+ },
+ resolver: DiscourseWorkflows::ExpressionResolver.new({ "$json" => {} }, sandbox: sandbox),
+ resume_token: resume_token,
+ )
+ end
+
+ describe "#execute" do
+ it "returns input items for interval mode" do
+ config = { "resume" => "time_interval", "wait_amount" => 2, "wait_unit" => "hours" }
+ exec_ctx = build_exec_ctx(config)
+
+ result = described_class.new(parameters: config).execute(exec_ctx)
+
+ expect(result.first).to eq(exec_ctx.input_items)
+ end
+
+ it "returns input items for webhook mode" do
+ config = { "resume" => "webhook" }
+ exec_ctx = build_exec_ctx(config, resume_token: "tok-abc")
+
+ result = described_class.new(parameters: config).execute(exec_ctx)
+
+ expect(result.first).to eq(exec_ctx.input_items)
+ end
+
+ it "returns input items for bounded webhook waits" do
+ config = {
+ "resume" => "webhook",
+ "limit_wait_time" => true,
+ "timeout_amount" => 3,
+ "timeout_unit" => "hours",
+ }
+ exec_ctx = build_exec_ctx(config, resume_token: "tok-abc")
+
+ result = described_class.new(parameters: config).execute(exec_ctx)
+
+ expect(result.first).to eq(exec_ctx.input_items)
+ end
+
+ it "raises on a non-positive wait amount" do
+ config = { "resume" => "time_interval", "wait_amount" => 0, "wait_unit" => "hours" }
+ exec_ctx = build_exec_ctx(config)
+
+ expect { described_class.new(parameters: config).execute(exec_ctx) }.to raise_error(
+ DiscourseWorkflows::NodeError,
+ /Wait amount/,
+ )
+ end
+
+ it "raises on an invalid wait unit" do
+ config = { "resume" => "time_interval", "wait_amount" => 1, "wait_unit" => "weeks" }
+ exec_ctx = build_exec_ctx(config)
+
+ expect { described_class.new(parameters: config).execute(exec_ctx) }.to raise_error(
+ DiscourseWorkflows::NodeError,
+ /Invalid wait unit/,
+ )
+ end
+ end
+end
diff --git a/plugins/discourse-workflows/spec/lib/discourse_workflows/nodes/webhook_spec.rb b/plugins/discourse-workflows/spec/lib/discourse_workflows/nodes/webhook_spec.rb
new file mode 100644
index 00000000000..bb314f4d844
--- /dev/null
+++ b/plugins/discourse-workflows/spec/lib/discourse_workflows/nodes/webhook_spec.rb
@@ -0,0 +1,35 @@
+# frozen_string_literal: true
+
+RSpec.describe DiscourseWorkflows::Nodes::Webhook::V1 do
+ describe "#output" do
+ it "returns request data" do
+ trigger =
+ described_class.new(
+ body: {
+ "foo" => "bar",
+ },
+ headers: {
+ "content-type" => "application/json",
+ },
+ params: {
+ "path" => "my-hook",
+ },
+ query: {
+ "page" => "1",
+ },
+ method: "POST",
+ webhook_url: "http://test.localhost/workflows/webhooks/my-hook",
+ raw_body: '{"foo":"bar"}',
+ )
+ output = trigger.output
+
+ expect(output[:body]).to eq({ "foo" => "bar" })
+ expect(output[:headers]).to eq({ "content-type" => "application/json" })
+ expect(output[:params]).to eq({ "path" => "my-hook" })
+ expect(output[:query]).to eq({ "page" => "1" })
+ expect(output[:method]).to eq("POST")
+ expect(output[:webhook_url]).to eq("http://test.localhost/workflows/webhooks/my-hook")
+ expect(output[:raw_body]).to eq('{"foo":"bar"}')
+ end
+ end
+end
diff --git a/plugins/discourse-workflows/spec/lib/discourse_workflows/pagination_spec.rb b/plugins/discourse-workflows/spec/lib/discourse_workflows/pagination_spec.rb
new file mode 100644
index 00000000000..8e7faf73c6f
--- /dev/null
+++ b/plugins/discourse-workflows/spec/lib/discourse_workflows/pagination_spec.rb
@@ -0,0 +1,69 @@
+# frozen_string_literal: true
+
+RSpec.describe DiscourseWorkflows::Pagination do
+ describe ".normalize_limit" do
+ it "defaults blank limits and clamps out-of-range values" do
+ expect(described_class.normalize_limit(nil)).to eq(described_class::DEFAULT_LIMIT)
+ expect(described_class.normalize_limit(0)).to eq(1)
+ expect(described_class.normalize_limit(999)).to eq(described_class::MAX_LIMIT)
+ end
+ end
+
+ describe ".cursor_page" do
+ fab!(:first_variable) { Fabricate(:discourse_workflows_variable, key: "FIRST") }
+ fab!(:second_variable) { Fabricate(:discourse_workflows_variable, key: "SECOND") }
+ fab!(:third_variable) { Fabricate(:discourse_workflows_variable, key: "THIRD") }
+
+ let(:scope) { DiscourseWorkflows::Variable.order(id: :desc) }
+
+ it "returns records, total rows, and a cursor URL when more records exist" do
+ page =
+ described_class.cursor_page(
+ scope: scope,
+ cursor: nil,
+ limit: 2,
+ path: "/admin/plugins/discourse-workflows/variables.json",
+ )
+
+ expect(page.records.map(&:id)).to eq([third_variable.id, second_variable.id])
+ expect(page.total_rows).to eq(3)
+ expect(page.load_more_url).to eq(
+ "/admin/plugins/discourse-workflows/variables.json?cursor=#{second_variable.id}&limit=2",
+ )
+ end
+
+ it "applies the cursor and keeps query params in the next URL" do
+ page =
+ described_class.cursor_page(
+ scope: scope,
+ cursor: third_variable.id,
+ limit: 1,
+ path: "/admin/plugins/discourse-workflows/variables.json",
+ query: {
+ filter: "active",
+ },
+ )
+
+ expect(page.records.map(&:id)).to eq([second_variable.id])
+ expect(page.load_more_url).to start_with("/admin/plugins/discourse-workflows/variables.json?")
+ expect(page.load_more_url).to include(
+ "cursor=#{second_variable.id}",
+ "filter=active",
+ "limit=1",
+ )
+ end
+
+ it "omits the cursor URL when all matching records fit" do
+ page =
+ described_class.cursor_page(
+ scope: scope,
+ cursor: second_variable.id,
+ limit: 2,
+ path: "/admin/plugins/discourse-workflows/variables.json",
+ )
+
+ expect(page.records.map(&:id)).to eq([first_variable.id])
+ expect(page.load_more_url).to be_nil
+ end
+ end
+end
diff --git a/plugins/discourse-workflows/spec/lib/discourse_workflows/plugin_enable_handler_spec.rb b/plugins/discourse-workflows/spec/lib/discourse_workflows/plugin_enable_handler_spec.rb
new file mode 100644
index 00000000000..31689ce040d
--- /dev/null
+++ b/plugins/discourse-workflows/spec/lib/discourse_workflows/plugin_enable_handler_spec.rb
@@ -0,0 +1,63 @@
+# frozen_string_literal: true
+
+RSpec.describe DiscourseWorkflows::PluginEnableHandler do
+ describe ".handle!" do
+ it "reschedules waiting executions that have a waiting_until" do
+ workflow = Fabricate(:discourse_workflows_workflow, published: true)
+ execution =
+ Fabricate(
+ :discourse_workflows_execution,
+ workflow: workflow,
+ status: :waiting,
+ waiting_until: 1.minute.ago,
+ )
+ Fabricate(
+ :discourse_workflows_execution,
+ workflow: workflow,
+ status: :waiting,
+ waiting_until: nil,
+ )
+
+ Jobs::DiscourseWorkflows::ResumeWaitingExecution.jobs.clear
+
+ described_class.handle!
+
+ enqueued = Jobs::DiscourseWorkflows::ResumeWaitingExecution.jobs
+ expect(enqueued.size).to eq(1)
+ expect(enqueued.first["args"].first["execution_id"]).to eq(execution.id)
+ end
+
+ it "activates published workflow triggers" do
+ graph =
+ build_workflow_graph do |g|
+ g.node "trigger-1",
+ "trigger:schedule",
+ configuration: {
+ "rule" => {
+ "interval" => [{ "field" => "minutes", "minutesInterval" => 5 }],
+ },
+ }
+ end
+ workflow = Fabricate(:discourse_workflows_workflow, published: true, **graph)
+
+ unpublished_graph =
+ build_workflow_graph do |g|
+ g.node "trigger-1",
+ "trigger:schedule",
+ configuration: {
+ "rule" => {
+ "interval" => [{ "field" => "minutes", "minutesInterval" => 5 }],
+ },
+ }
+ end
+ Fabricate(:discourse_workflows_workflow, published: false, **unpublished_graph)
+
+ DiscourseWorkflows::TriggerRuntime.expects(:activate_workflow!).with(
+ workflow,
+ workflow_version: workflow.active_version,
+ )
+
+ described_class.handle!
+ end
+ end
+end
diff --git a/plugins/discourse-workflows/spec/lib/discourse_workflows/property_schema_validator_spec.rb b/plugins/discourse-workflows/spec/lib/discourse_workflows/property_schema_validator_spec.rb
new file mode 100644
index 00000000000..6484e7b90c9
--- /dev/null
+++ b/plugins/discourse-workflows/spec/lib/discourse_workflows/property_schema_validator_spec.rb
@@ -0,0 +1,345 @@
+# frozen_string_literal: true
+
+RSpec.describe DiscourseWorkflows::PropertySchemaValidator do
+ def validate(schema)
+ described_class.call("test:node", schema).map(&:to_s)
+ end
+
+ describe ".call" do
+ it "accepts a valid schema" do
+ schema = {
+ method: {
+ type: :options,
+ required: true,
+ default: "GET",
+ options: %w[GET POST],
+ no_data_expression: true,
+ },
+ url: {
+ type: :string,
+ required: true,
+ display_options: {
+ show: {
+ method: %w[POST],
+ },
+ },
+ ui: {
+ dynamic_value: :url,
+ },
+ },
+ }
+ expect(validate(schema)).to eq([])
+ end
+
+ it "flags unknown field types" do
+ errors = validate(age: { type: :age })
+ expect(errors.first).to include("age.type")
+ expect(errors.first).to include("unknown type: :age")
+ end
+
+ it "rejects camelCase field type aliases" do
+ expect(validate(rows: { type: :fixedCollection }).first).to include(
+ "unknown type: :fixedCollection",
+ )
+ expect(validate(rows: { type: :assignmentCollection }).first).to include(
+ "unknown type: :assignmentCollection",
+ )
+ end
+
+ it "flags unknown top-level field keys" do
+ errors = validate(title: { type: :string, expression: true })
+ expect(errors.first).to include("[:expression]")
+ end
+
+ it "rejects camelCase field option aliases" do
+ errors =
+ validate(
+ title: {
+ type: :string,
+ displayOptions: {
+ show: {
+ },
+ },
+ typeOptions: {
+ maxAllowedFields: 1,
+ },
+ },
+ )
+ expect(errors.first).to include(":displayOptions")
+ expect(errors.first).to include(":typeOptions")
+ end
+
+ it "flags unknown ui keys" do
+ errors = validate(title: { type: :string, ui: { rowz: 6 } })
+ expect(errors.first).to include("title.ui")
+ expect(errors.first).to include(":rowz")
+ end
+
+ it "flags unknown ui.control values" do
+ errors = validate(title: { type: :string, ui: { control: :neon } })
+ expect(errors.first).to include("title.ui.control")
+ expect(errors.first).to include(":neon")
+ end
+
+ it "accepts control_options with known keys" do
+ schema = {
+ picker: {
+ type: :integer,
+ ui: {
+ control: :combo_box,
+ },
+ control_options: {
+ action_icon: "plus",
+ action_label: "discourse_workflows.actions.manage",
+ action_route: "adminPlugins.show.example",
+ action_route_models: ["example-plugin"],
+ filterable: true,
+ value_property: "id",
+ name_property: "name",
+ },
+ },
+ }
+ expect(validate(schema)).to eq([])
+ end
+
+ it "flags unknown control_options keys" do
+ errors = validate(picker: { type: :integer, control_options: { rowz: 3 } })
+ expect(errors.first).to include("picker.control_options")
+ expect(errors.first).to include(":rowz")
+ end
+
+ it "rejects camelCase type_options keys" do
+ errors =
+ validate(
+ rows: {
+ type: :fixed_collection,
+ options: [{ name: "values", values: { cell: { type: :string } } }],
+ type_options: {
+ maxAllowedFields: 3,
+ },
+ },
+ )
+ expect(errors.first).to include("rows.type_options")
+ expect(errors.first).to include(":maxAllowedFields")
+ end
+
+ it "requires :options for option-typed fields" do
+ errors = validate(choice: { type: :options, default: "a" })
+ expect(errors.first).to include("type :options requires")
+ end
+
+ it "allows dynamic option fields to declare a load options method" do
+ schema = {
+ choice: {
+ type: :options,
+ default: "a",
+ type_options: {
+ load_options_method: "choices",
+ },
+ },
+ }
+
+ expect(validate(schema)).to eq([])
+ end
+
+ it "allows credential_type on credential fields" do
+ schema = { credential_id: { type: :credential, credential_type: :basic_auth } }
+ expect(validate(schema)).to eq([])
+ end
+
+ it "rejects credential_type on non-credential fields" do
+ errors = validate(title: { type: :string, credential_type: :basic_auth })
+ expect(errors.first).to include(":credential_type")
+ end
+
+ it "lets fixed collection fields reference siblings in the same group" do
+ schema = {
+ rows: {
+ type: :fixed_collection,
+ options: [
+ {
+ name: "values",
+ values: {
+ kind: {
+ type: :options,
+ options: %w[text dropdown],
+ },
+ choices: {
+ type: :fixed_collection,
+ display_options: {
+ show: {
+ kind: %w[dropdown],
+ },
+ },
+ options: [{ name: "values", values: { label: { type: :string } } }],
+ },
+ },
+ },
+ ],
+ },
+ }
+ expect(validate(schema)).to eq([])
+ end
+
+ it "requires :options for multi_options fields" do
+ errors = validate(choices: { type: :multi_options })
+ expect(errors.first).to include(":multi_options")
+ end
+
+ it "requires :options for collection fields" do
+ errors = validate(rows: { type: :collection })
+ expect(errors.first).to include("type :collection requires")
+ end
+
+ it "requires :options for fixed collection fields" do
+ errors = validate(rows: { type: :fixed_collection })
+ expect(errors.first).to include("type :fixed_collection requires")
+ end
+
+ it "recurses into fixed collection group values" do
+ errors =
+ validate(
+ rows: {
+ type: :fixed_collection,
+ options: [{ name: "values", values: { cell: { type: :unknown } } }],
+ },
+ )
+ expect(errors.first).to include("rows.options.0.values.cell.type")
+ end
+
+ it "recurses into collection option bag fields" do
+ errors = validate(rows: { type: :collection, options: [{ name: "enabled", type: :unknown }] })
+ expect(errors.first).to include("rows.options.enabled.type")
+ end
+
+ it "rejects camelCase display names in collection definitions" do
+ option_errors =
+ validate(
+ rows: {
+ type: :collection,
+ options: [{ name: "enabled", type: :boolean, displayName: "Enabled" }],
+ },
+ )
+
+ expect(option_errors.first).to include("rows.options.enabled")
+ expect(option_errors.first).to include(":displayName")
+
+ group_errors =
+ validate(
+ rows: {
+ type: :fixed_collection,
+ options: [
+ { name: "values", displayName: "Values", values: { cell: { type: :string } } },
+ ],
+ },
+ )
+
+ expect(group_errors.first).to include("rows.options.0")
+ expect(group_errors.first).to include(":displayName")
+ end
+
+ it "flags display_options references to nonexistent sibling fields" do
+ errors = validate(body: { type: :string, display_options: { show: { methud: %w[POST] } } })
+ expect(errors.first).to include("display_options")
+ expect(errors.first).to include(":methud")
+ end
+
+ it "accepts display_options show rules within the same scope" do
+ schema = {
+ method: {
+ type: :options,
+ options: %w[GET POST],
+ },
+ body: {
+ type: :string,
+ display_options: {
+ show: {
+ method: %w[POST],
+ },
+ },
+ },
+ }
+ expect(validate(schema)).to eq([])
+ end
+
+ it "accepts display_options hide rules" do
+ schema = {
+ method: {
+ type: :options,
+ options: %w[GET POST],
+ },
+ warning: {
+ type: :notice,
+ display_options: {
+ hide: {
+ method: %w[POST],
+ },
+ },
+ },
+ }
+ expect(validate(schema)).to eq([])
+ end
+
+ it "requires visibility rules to be a hash" do
+ errors = validate(body: { type: :string, display_options: { show: "yes" } })
+ expect(errors.first).to include("display_options.show")
+ expect(errors.first).to include("Hash")
+ end
+
+ it "requires display_options rule values to be arrays" do
+ errors =
+ validate(
+ method: {
+ type: :options,
+ options: %w[GET POST],
+ },
+ body: {
+ type: :string,
+ display_options: {
+ show: {
+ method: "POST",
+ },
+ },
+ },
+ )
+
+ expect(errors.first).to include("display_options.show.method")
+ expect(errors.first).to include("Array")
+ end
+
+ it "scopes sibling checks to the current schema level" do
+ schema = {
+ rules: {
+ type: :fixed_collection,
+ options: [
+ {
+ name: "values",
+ values: {
+ kind: {
+ type: :options,
+ options: %w[a b],
+ },
+ detail: {
+ type: :string,
+ display_options: {
+ show: {
+ kind: %w[a],
+ },
+ },
+ },
+ },
+ },
+ ],
+ },
+ }
+ expect(validate(schema)).to eq([])
+ end
+ end
+
+ describe ".validate_all" do
+ it "passes for every registered node" do
+ errors = described_class.validate_all
+ expect(errors).to eq([]), -> { errors.map(&:to_s).join("\n") }
+ end
+ end
+end
diff --git a/plugins/discourse-workflows/spec/lib/discourse_workflows/registry_credential_types_spec.rb b/plugins/discourse-workflows/spec/lib/discourse_workflows/registry_credential_types_spec.rb
new file mode 100644
index 00000000000..b006a1c6b2f
--- /dev/null
+++ b/plugins/discourse-workflows/spec/lib/discourse_workflows/registry_credential_types_spec.rb
@@ -0,0 +1,16 @@
+# frozen_string_literal: true
+
+RSpec.describe DiscourseWorkflows::Registry do
+ before { described_class.reset_indexes! }
+
+ describe ".find_credential_type" do
+ it "finds a credential type by identifier" do
+ result = described_class.find_credential_type("basic_auth")
+ expect(result).to eq(DiscourseWorkflows::CredentialTypes::BasicAuth)
+ end
+
+ it "returns nil for unknown identifier" do
+ expect(described_class.find_credential_type("unknown")).to be_nil
+ end
+ end
+end
diff --git a/plugins/discourse-workflows/spec/lib/discourse_workflows/registry_spec.rb b/plugins/discourse-workflows/spec/lib/discourse_workflows/registry_spec.rb
new file mode 100644
index 00000000000..c8c68a2e415
--- /dev/null
+++ b/plugins/discourse-workflows/spec/lib/discourse_workflows/registry_spec.rb
@@ -0,0 +1,188 @@
+# frozen_string_literal: true
+
+RSpec.describe DiscourseWorkflows::Registry do
+ before { described_class.reset_indexes! }
+
+ describe "plugin node registration hook" do
+ it "registers a loaded node class" do
+ plugin = Plugin::Instance.new
+ node_class =
+ Class.new(DiscourseWorkflows::NodeType) do
+ description(name: "action:plugin_hook_direct_test", version: "1.0")
+ end
+
+ DiscourseWorkflows.node_registration_ready = true
+ plugin.register_discourse_workflows_node(node_class)
+ described_class.reset_indexes!
+
+ expect(described_class.find_node_type("action:plugin_hook_direct_test")).to eq(node_class)
+ ensure
+ DiscoursePluginRegistry._raw_discourse_workflows_nodes.reject! do |entry|
+ entry[:value] == node_class
+ end
+ described_class.reset_indexes!
+ end
+
+ it "defers a node registration block until workflow node registration is ready" do
+ plugin = Plugin::Instance.new
+ node_class = nil
+
+ DiscourseWorkflows.node_registration_ready = false
+ plugin.register_discourse_workflows_node do
+ node_class =
+ Class.new(DiscourseWorkflows::NodeType) do
+ description(name: "action:plugin_hook_deferred_test", version: "1.0")
+ end
+ end
+
+ expect(plugin.discourse_workflows_node_registrations.size).to eq(1)
+
+ allow(Discourse).to receive(:plugins).and_return([plugin])
+ DiscourseWorkflows.node_registration_ready = true
+ DiscourseWorkflows.flush_plugin_node_registrations!
+ described_class.reset_indexes!
+
+ expect(described_class.find_node_type("action:plugin_hook_deferred_test")).to eq(node_class)
+ expect(plugin.discourse_workflows_node_registrations).to be_empty
+ ensure
+ DiscourseWorkflows.node_registration_ready = true
+ DiscoursePluginRegistry._raw_discourse_workflows_nodes.reject! do |entry|
+ entry[:value] == node_class
+ end
+ described_class.reset_indexes!
+ end
+
+ it "resets registry indexes when the registering plugin is enabled or disabled" do
+ plugin = Plugin::Instance.new
+ plugin.enabled_site_setting(:discourse_sample_plugin_enabled)
+ SiteSetting.discourse_sample_plugin_enabled = true
+ node_class =
+ Class.new(DiscourseWorkflows::NodeType) do
+ description(name: "action:plugin_hook_enabled_test", version: "1.0")
+ end
+
+ DiscourseWorkflows.node_registration_ready = true
+ plugin.register_discourse_workflows_node(node_class)
+ described_class.reset_indexes!
+
+ expect(described_class.find_node_type("action:plugin_hook_enabled_test")).to eq(node_class)
+
+ SiteSetting.discourse_sample_plugin_enabled = false
+ expect(described_class.find_node_type("action:plugin_hook_enabled_test")).to be_nil
+
+ SiteSetting.discourse_sample_plugin_enabled = true
+ expect(described_class.find_node_type("action:plugin_hook_enabled_test")).to eq(node_class)
+ ensure
+ if plugin
+ handler = plugin.instance_variable_get(:@discourse_workflows_node_cache_reset_handler)
+ DiscourseEvent.off(:site_setting_changed, &handler) if handler
+ end
+ SiteSetting.discourse_sample_plugin_enabled = true
+ DiscoursePluginRegistry._raw_discourse_workflows_nodes.reject! do |entry|
+ entry[:value] == node_class
+ end
+ described_class.reset_indexes!
+ end
+
+ it "reflects the current filtered registry without requiring an index reset" do
+ plugin = Plugin::Instance.new
+ node_class =
+ Class.new(DiscourseWorkflows::NodeType) do
+ description(name: "action:plugin_hook_filter_test", version: "1.0")
+ end
+
+ DiscoursePluginRegistry.register_discourse_workflows_node(node_class, plugin)
+
+ expect(described_class.available_versions("action:plugin_hook_filter_test")).to eq(["1.0"])
+
+ allow(plugin).to receive(:enabled?).and_return(false)
+
+ expect(described_class.available_versions("action:plugin_hook_filter_test")).to eq([])
+ expect(described_class.find_node_type("action:plugin_hook_filter_test")).to be_nil
+ expect(
+ described_class.available_versions(
+ "action:plugin_hook_filter_test",
+ include_disabled_plugins: true,
+ ),
+ ).to eq(["1.0"])
+ expect(
+ described_class.find_node_type(
+ "action:plugin_hook_filter_test",
+ include_disabled_plugins: true,
+ ),
+ ).to eq(node_class)
+ ensure
+ DiscoursePluginRegistry._raw_discourse_workflows_nodes.reject! do |entry|
+ entry[:value] == node_class
+ end
+ described_class.reset_indexes!
+ end
+ end
+
+ describe ".find_node_type" do
+ it "finds a registered node type by identifier" do
+ trigger = described_class.triggers.first
+ expect(described_class.find_node_type(trigger.identifier)).to eq(trigger)
+ end
+
+ it "returns nil for unknown identifiers" do
+ expect(described_class.find_node_type("trigger:nonexistent")).to be_nil
+ end
+
+ it "finds a registered node type by identifier and version" do
+ v1 =
+ Class.new(DiscourseWorkflows::NodeType) do
+ description(name: "action:registry_versioned_test", version: "1.0")
+ end
+ v2 =
+ Class.new(DiscourseWorkflows::NodeType) do
+ description(name: "action:registry_versioned_test", version: "2.0")
+ end
+
+ DiscoursePluginRegistry.register_discourse_workflows_node(v1, Plugin::Instance.new)
+ DiscoursePluginRegistry.register_discourse_workflows_node(v2, Plugin::Instance.new)
+ described_class.reset_indexes!
+
+ expect(
+ described_class.find_node_type("action:registry_versioned_test", version: "1.0"),
+ ).to eq(v1)
+ expect(
+ described_class.find_node_type("action:registry_versioned_test", version: "2.0"),
+ ).to eq(v2)
+ expect(described_class.available_versions("action:registry_versioned_test")).to eq(
+ %w[1.0 2.0],
+ )
+ expect(described_class.latest_version("action:registry_versioned_test")).to eq("2.0")
+ ensure
+ DiscoursePluginRegistry._raw_discourse_workflows_nodes.reject! do |entry|
+ [v1, v2].include?(entry[:value])
+ end
+ described_class.reset_indexes!
+ end
+
+ it "rejects duplicate node identifier and version registrations" do
+ first =
+ Class.new(DiscourseWorkflows::NodeType) do
+ description(name: "action:registry_duplicate_test", version: "1.0")
+ end
+ duplicate =
+ Class.new(DiscourseWorkflows::NodeType) do
+ description(name: "action:registry_duplicate_test", version: "1.0")
+ end
+
+ DiscoursePluginRegistry.register_discourse_workflows_node(first, Plugin::Instance.new)
+ DiscoursePluginRegistry.register_discourse_workflows_node(duplicate, Plugin::Instance.new)
+ described_class.reset_indexes!
+
+ expect { described_class.find_node_type("action:registry_duplicate_test") }.to raise_error(
+ ArgumentError,
+ "Duplicate workflow node type action:registry_duplicate_test v1.0",
+ )
+ ensure
+ DiscoursePluginRegistry._raw_discourse_workflows_nodes.reject! do |entry|
+ [first, duplicate].include?(entry[:value])
+ end
+ described_class.reset_indexes!
+ end
+ end
+end
diff --git a/plugins/discourse-workflows/spec/lib/discourse_workflows/schemas/form_fields_spec.rb b/plugins/discourse-workflows/spec/lib/discourse_workflows/schemas/form_fields_spec.rb
new file mode 100644
index 00000000000..6f96b22003c
--- /dev/null
+++ b/plugins/discourse-workflows/spec/lib/discourse_workflows/schemas/form_fields_spec.rb
@@ -0,0 +1,315 @@
+# frozen_string_literal: true
+
+RSpec.describe DiscourseWorkflows::Schemas::FormFields do
+ describe ".with_keys" do
+ it "uses field_name when present and falls back to a parameterized label" do
+ fields =
+ described_class.with_keys(
+ [
+ { "field_label" => "First Name", "field_type" => "text" },
+ { "field_label" => "Email", "field_name" => "user_email", "field_type" => "text" },
+ ],
+ )
+
+ expect(fields.map { |field| field["key"] }).to eq(%w[first_name user_email])
+ end
+ end
+
+ describe ".validate_submission" do
+ it "returns valid result with coerced data when all fields are valid" do
+ fields = [
+ { "field_label" => "Name", "field_type" => "text" },
+ { "field_label" => "Age", "field_type" => "number" },
+ { "field_label" => "Subscribe", "field_type" => "checkbox" },
+ ]
+
+ result =
+ described_class.validate_submission(
+ fields,
+ { "name" => "Joffrey", "age" => "42", "subscribe" => "true" },
+ )
+
+ expect(result).to be_valid
+ expect(result.errors).to be_empty
+ expect(result.data).to eq("name" => "Joffrey", "age" => 42, "subscribe" => true)
+ end
+
+ it "treats values with a decimal as floats and integers otherwise" do
+ result =
+ described_class.validate_submission(
+ [{ "field_label" => "Amount", "field_type" => "number" }],
+ { "amount" => "12.5" },
+ )
+
+ expect(result).to be_valid
+ expect(result.data["amount"]).to eq(12.5)
+ expect(result.data["amount"]).to be_a(Float)
+ end
+
+ it "leaves blank optional number fields out without error" do
+ result =
+ described_class.validate_submission(
+ [{ "field_label" => "Age", "field_type" => "number", "required" => false }],
+ { "age" => "" },
+ )
+
+ expect(result).to be_valid
+ expect(result.data["age"]).to be_nil
+ end
+
+ it "truncates long string field values" do
+ result =
+ described_class.validate_submission(
+ [{ "field_label" => "Feedback", "field_type" => "text" }],
+ { "feedback" => "a" * 10_001 },
+ )
+
+ expect(result).to be_valid
+ expect(result.data["feedback"].length).to eq(described_class::MAX_FIELD_VALUE_LENGTH)
+ end
+
+ it "reports missing required fields" do
+ fields = [
+ { "field_label" => "Name", "field_type" => "text", "required" => true },
+ { "field_label" => "Age", "field_type" => "number", "required" => true },
+ ]
+
+ result = described_class.validate_submission(fields, { "name" => "" })
+
+ expect(result).not_to be_valid
+ expect(result.errors).to contain_exactly(
+ described_class::ValidationError.new(field_label: "Name", code: :missing),
+ described_class::ValidationError.new(field_label: "Age", code: :missing),
+ )
+ end
+
+ it "does not flag required checkboxes as missing when blank" do
+ result =
+ described_class.validate_submission(
+ [{ "field_label" => "Agree", "field_type" => "checkbox", "required" => true }],
+ { "agree" => "false" },
+ )
+
+ expect(result).to be_valid
+ expect(result.data["agree"]).to be(false)
+ end
+
+ it "does not flag required checkboxes as missing when key is absent" do
+ result =
+ described_class.validate_submission(
+ [{ "field_label" => "Agree", "field_type" => "checkbox", "required" => true }],
+ {},
+ )
+
+ expect(result).to be_valid
+ end
+
+ it "reports invalid number values without raising" do
+ result =
+ described_class.validate_submission(
+ [{ "field_label" => "Age", "field_type" => "number", "required" => true }],
+ { "age" => "abc" },
+ )
+
+ expect(result).not_to be_valid
+ expect(result.errors).to contain_exactly(
+ described_class::ValidationError.new(field_label: "Age", code: :invalid_value),
+ )
+ end
+
+ it "reports invalid number values when the input is a hash or array" do
+ fields = [{ "field_label" => "Age", "field_type" => "number" }]
+
+ [{ "age" => { "nested" => 1 } }, { "age" => [1, 2] }].each do |params|
+ result = described_class.validate_submission(fields, params)
+ expect(result).not_to be_valid
+ expect(result.errors.first.code).to eq(:invalid_value)
+ end
+ end
+
+ it "combines missing and invalid errors in one pass" do
+ fields = [
+ { "field_label" => "Name", "field_type" => "text", "required" => true },
+ { "field_label" => "Age", "field_type" => "number", "required" => true },
+ ]
+
+ result = described_class.validate_submission(fields, { "name" => "", "age" => "abc" })
+
+ expect(result).not_to be_valid
+ expect(result.errors.map(&:code)).to contain_exactly(:missing, :invalid_value)
+ end
+
+ it "stops coercion of an invalid field but keeps coerced data for the rest" do
+ fields = [
+ { "field_label" => "Name", "field_type" => "text" },
+ { "field_label" => "Age", "field_type" => "number" },
+ ]
+
+ result = described_class.validate_submission(fields, { "name" => "Joffrey", "age" => "abc" })
+
+ expect(result).not_to be_valid
+ expect(result.data).to eq("name" => "Joffrey")
+ end
+
+ it "uses field names as submission keys when present" do
+ fields = [
+ { "field_label" => "First Name", "field_type" => "text" },
+ { "field_label" => "Email", "field_name" => "user_email", "field_type" => "text" },
+ ]
+
+ result =
+ described_class.validate_submission(
+ fields,
+ { "first_name" => "Joffrey", "user_email" => "[email protected]" },
+ )
+
+ expect(result.data).to eq("first_name" => "Joffrey", "user_email" => "[email protected]")
+ end
+
+ it "supports scalar form field types" do
+ fields = [
+ { "field_label" => "Email", "field_type" => "email", "required" => true },
+ { "field_label" => "Password", "field_type" => "password" },
+ { "field_label" => "Start Date", "field_type" => "date" },
+ { "field_label" => "Plan", "field_type" => "radio" },
+ {
+ "field_label" => "Tracking ID",
+ "field_type" => "hiddenField",
+ "field_value" => "server-value",
+ },
+ { "field_label" => "Intro", "field_type" => "html", "html" => "<strong>Hello</strong>" },
+ ]
+
+ result =
+ described_class.validate_submission(
+ fields,
+ {
+ "email" => "[email protected]",
+ "password" => "secret",
+ "start_date" => "2026-05-18",
+ "plan" => "pro",
+ "tracking_id" => "client-value",
+ },
+ )
+
+ expect(result).to be_valid
+ expect(result.data).to eq(
+ "email" => "[email protected]",
+ "password" => "secret",
+ "start_date" => "2026-05-18",
+ "plan" => "pro",
+ "tracking_id" => "server-value",
+ )
+ end
+
+ it "uses signed query parameters for hidden fields without configured values" do
+ fields = [
+ { "field_label" => "Tracking ID", "field_type" => "hiddenField", "key" => "tracking_id" },
+ ]
+
+ result =
+ described_class.validate_submission(
+ fields,
+ { "tracking_id" => "client-value" },
+ query_parameters: {
+ "tracking_id" => "query-value",
+ },
+ )
+
+ expect(result).to be_valid
+ expect(result.data).to eq("tracking_id" => "query-value")
+ end
+
+ it "reports invalid email values" do
+ result =
+ described_class.validate_submission(
+ [{ "field_label" => "Email", "field_type" => "email" }],
+ { "email" => "not-an-email" },
+ )
+
+ expect(result).not_to be_valid
+ expect(result.errors).to contain_exactly(
+ described_class::ValidationError.new(field_label: "Email", code: :invalid_value),
+ )
+ end
+
+ it "applies query defaults without pre-filling password or HTML fields" do
+ fields =
+ described_class.with_keys(
+ [
+ { "field_label" => "Name", "field_type" => "text" },
+ { "field_label" => "Password", "field_type" => "password" },
+ { "field_label" => "Intro", "field_type" => "html" },
+ { "field_label" => "Tracking ID", "field_type" => "hiddenField" },
+ {
+ "field_label" => "Configured ID",
+ "field_type" => "hiddenField",
+ "field_value" => "configured",
+ },
+ ],
+ )
+
+ result =
+ described_class.apply_query_defaults(
+ fields,
+ {
+ "name" => "Query User",
+ "password" => "secret",
+ "intro" => "<strong>Query</strong>",
+ "tracking_id" => "query-tracking",
+ "configured_id" => "query-configured",
+ },
+ )
+
+ expect(result).to contain_exactly(
+ a_hash_including("key" => "name", "default_value" => "Query User"),
+ a_hash_including("key" => "password"),
+ a_hash_including("key" => "intro"),
+ a_hash_including("key" => "tracking_id", "field_value" => "query-tracking"),
+ a_hash_including("key" => "configured_id", "field_value" => "configured"),
+ )
+ expect(result.find { |field| field["key"] == "password" }).not_to have_key("default_value")
+ expect(result.find { |field| field["key"] == "intro" }).not_to have_key("default_value")
+ end
+
+ it "removes hidden values and password defaults from public fields" do
+ fields = [
+ {
+ "field_label" => "Tracking ID",
+ "field_type" => "hiddenField",
+ "field_value" => "secret-tracking",
+ "default_value" => "old-secret",
+ },
+ {
+ "field_label" => "Password",
+ "field_type" => "password",
+ "default_value" => "secret-password",
+ },
+ ]
+
+ expect(described_class.public_fields(fields)).to eq(
+ [
+ { "field_label" => "Tracking ID", "field_type" => "hiddenField" },
+ { "field_label" => "Password", "field_type" => "password" },
+ ],
+ )
+ end
+
+ it "tolerates empty fields" do
+ result = described_class.validate_submission([], { "anything" => "value" })
+
+ expect(result).to be_valid
+ expect(result.data).to be_empty
+ end
+
+ it "tolerates nil submitted params" do
+ result =
+ described_class.validate_submission(
+ [{ "field_label" => "Name", "field_type" => "text" }],
+ nil,
+ )
+
+ expect(result).to be_valid
+ end
+ end
+end
diff --git a/plugins/discourse-workflows/spec/lib/discourse_workflows/trigger_node_context_spec.rb b/plugins/discourse-workflows/spec/lib/discourse_workflows/trigger_node_context_spec.rb
new file mode 100644
index 00000000000..07f71ab8b69
--- /dev/null
+++ b/plugins/discourse-workflows/spec/lib/discourse_workflows/trigger_node_context_spec.rb
@@ -0,0 +1,26 @@
+# frozen_string_literal: true
+
+RSpec.describe DiscourseWorkflows::TriggerNodeContext do
+ describe "#get_node_parameter" do
+ it "reads top-level and nested parameters" do
+ ctx =
+ described_class.new(
+ {
+ "parameters" => {
+ "category_id" => "1",
+ "rules" => [{ "tag_names" => %w[bug urgent] }],
+ },
+ },
+ )
+
+ expect(ctx.get_node_parameter("category_id")).to eq("1")
+ expect(ctx.get_node_parameter("rules.0.tag_names")).to eq(%w[bug urgent])
+ end
+
+ it "returns the default for missing parameters" do
+ ctx = described_class.new({ "parameters" => {} })
+
+ expect(ctx.get_node_parameter("hours", 24)).to eq(24)
+ end
+ end
+end
diff --git a/plugins/discourse-workflows/spec/lib/discourse_workflows/trigger_runtime_spec.rb b/plugins/discourse-workflows/spec/lib/discourse_workflows/trigger_runtime_spec.rb
new file mode 100644
index 00000000000..604d7502300
--- /dev/null
+++ b/plugins/discourse-workflows/spec/lib/discourse_workflows/trigger_runtime_spec.rb
@@ -0,0 +1,38 @@
+# frozen_string_literal: true
+
+RSpec.describe DiscourseWorkflows::TriggerRuntime do
+ describe ".activate_workflow!" do
+ it "does not invoke passive triggers during activation" do
+ passive_trigger_class =
+ Class.new(DiscourseWorkflows::NodeType) do
+ description(name: "trigger:passive_activation_test")
+
+ def trigger(_trigger_ctx)
+ raise "passive trigger was activated"
+ end
+ end
+
+ DiscoursePluginRegistry.register_discourse_workflows_node(
+ passive_trigger_class,
+ Plugin::Instance.new,
+ )
+ DiscourseWorkflows::Registry.reset_indexes!
+
+ graph =
+ build_workflow_graph do |graph_builder|
+ graph_builder.node "trigger-1", "trigger:passive_activation_test"
+ end
+ workflow = Fabricate(:discourse_workflows_workflow, published: true, **graph)
+
+ expect {
+ described_class.activate_workflow!(workflow, workflow_version: workflow.active_version)
+ }.not_to raise_error
+ ensure
+ DiscoursePluginRegistry._raw_discourse_workflows_nodes.reject! do |entry|
+ entry[:value] == passive_trigger_class
+ end
+ DiscourseWorkflows::NodeType.registered_nodes.delete(passive_trigger_class)
+ DiscourseWorkflows::Registry.reset_indexes!
+ end
+ end
+end
diff --git a/plugins/discourse-workflows/spec/lib/discourse_workflows/waiting_execution_spec.rb b/plugins/discourse-workflows/spec/lib/discourse_workflows/waiting_execution_spec.rb
new file mode 100644
index 00000000000..56bbd0b7a5d
--- /dev/null
+++ b/plugins/discourse-workflows/spec/lib/discourse_workflows/waiting_execution_spec.rb
@@ -0,0 +1,48 @@
+# frozen_string_literal: true
+
+RSpec.describe DiscourseWorkflows::WaitingExecution do
+ fab!(:workflow, :discourse_workflows_workflow)
+ fab!(:execution) do
+ Fabricate(
+ :discourse_workflows_waiting_execution,
+ workflow: workflow,
+ resume_token: "raw-resume-token",
+ )
+ end
+
+ def signature_from(url)
+ Rack::Utils.parse_query(URI.parse(url).query).fetch("signature")
+ end
+
+ it "uses a derived signature in waiting form URLs" do
+ url = described_class.form_waiting_url(execution)
+ signature = signature_from(url)
+
+ expect(signature).to be_present
+ expect(url).not_to include(execution.resume_token)
+ expect(described_class.find(execution_id: execution.id, signature: signature)).to eq(execution)
+ end
+
+ it "uses a derived signature in waiting webhook URLs" do
+ url =
+ described_class.webhook_url(execution_id: execution.id, resume_token: execution.resume_token)
+
+ expect(url).not_to include(execution.resume_token)
+ expect(described_class.find(execution_id: execution.id, signature: signature_from(url))).to eq(
+ execution,
+ )
+ end
+
+ it "does not accept the raw resume token as a signature" do
+ expect(
+ described_class.find(execution_id: execution.id, signature: execution.resume_token),
+ ).to be_nil
+ end
+
+ it "claims an execution using a derived signature" do
+ signature = signature_from(described_class.form_waiting_url(execution))
+
+ expect(described_class.claim(execution, signature: signature)).to be_present
+ expect(execution.reload.status).to eq("running")
+ end
+end
diff --git a/plugins/discourse-workflows/spec/lib/discourse_workflows/waiting_webhook_runner_spec.rb b/plugins/discourse-workflows/spec/lib/discourse_workflows/waiting_webhook_runner_spec.rb
new file mode 100644
index 00000000000..2d3751a732c
--- /dev/null
+++ b/plugins/discourse-workflows/spec/lib/discourse_workflows/waiting_webhook_runner_spec.rb
@@ -0,0 +1,157 @@
+# frozen_string_literal: true
+
+RSpec.describe DiscourseWorkflows::WaitingWebhookRunner do
+ fab!(:user)
+ fab!(:workflow) do
+ graph =
+ build_workflow_graph do |g|
+ g.node "trigger-1", "trigger:manual", name: "Manual"
+ g.node "form-action-1",
+ "action:form",
+ name: "Waiting Form",
+ configuration: {
+ "form_title" => "={{ $execution.workflow_name }}",
+ "form_description" => '=Counter was {{ $("Manual").context["counter"] }}',
+ "form_fields" => [
+ { "field_label" => "Feedback", "field_type" => "text", "required" => true },
+ ],
+ }
+ g.chain "trigger-1", "form-action-1"
+ end
+ Fabricate(:discourse_workflows_workflow, name: "Published workflow", published: true, **graph)
+ end
+
+ let(:guardian) { Guardian.new(user) }
+
+ before { allow(MessageBus).to receive(:publish) }
+
+ let!(:execution) do
+ exec = DiscourseWorkflows::Executor.new(workflow, "trigger-1", {}).run
+ ed = exec.execution_data
+ ed.update!(
+ data: {
+ "entries" => ed.entries,
+ "context" => ed.context_data,
+ "node_contexts" => {
+ "trigger-1" => {
+ "counter" => 42,
+ },
+ },
+ },
+ workflow_data: ed.workflow_data,
+ )
+ exec
+ end
+
+ let(:signature) do
+ DiscourseWorkflows::WaitingExecution.resume_signature(
+ execution_id: execution.id,
+ resume_token: execution.resume_token,
+ )
+ end
+
+ def dispatch(http_method:, path: "", params: {}, signature: self.signature)
+ described_class.call(
+ execution_id: execution.id,
+ signature: signature,
+ http_method: http_method,
+ path: path,
+ node_type: "form",
+ params: params,
+ service_params: {
+ guardian: guardian,
+ },
+ )
+ end
+
+ describe ".call" do
+ it "serves waiting form status through the node webhook descriptor" do
+ result = dispatch(http_method: "GET", path: "status")
+
+ expect(result.status).to eq(:ok)
+ expect(result.body).to eq(status: "form_waiting")
+ end
+
+ it "serves waiting form data through the node webhook context" do
+ result = dispatch(http_method: "GET")
+
+ expect(result.status).to eq(:ok)
+ expect(result.body[:form_title]).to eq("Published workflow")
+ expect(result.body[:form_description]).to eq("Counter was 42")
+ expect(result.body).not_to have_key(:form_fields)
+ expect(result.body).to include(
+ data: {
+ "feedback" => "",
+ },
+ fields: [
+ {
+ name: "feedback",
+ title: "Feedback",
+ type: "input",
+ validation: "required",
+ autofocus: false,
+ },
+ ],
+ )
+ expect(result.body[:form_waiting_url]).to be_present
+ expect(result.body[:form_submit_url]).to be_present
+ expect(result.body[:form_status_url]).to be_present
+ expect(result.body.to_json).not_to include(execution.resume_token)
+ end
+
+ it "uses trigger query parameters as waiting form defaults" do
+ execution.update!(trigger_data: { "form_query_parameters" => { "feedback" => "Prefill" } })
+
+ result = dispatch(http_method: "GET")
+
+ expect(result.body[:data]["feedback"]).to eq("Prefill")
+ end
+
+ it "returns structured validation errors from the waiting form webhook" do
+ result = dispatch(http_method: "POST", params: { form_data: {} })
+
+ expect(result.status).to eq(:unprocessable_entity)
+ expect(result.body[:errors]).to contain_exactly(field_label: "Feedback", code: :missing)
+ end
+
+ it "resumes the execution with node returned workflow data" do
+ freeze_time Time.utc(2026, 1, 1)
+
+ result = dispatch(http_method: "POST", params: { form_data: { "feedback" => "Approved" } })
+
+ expect(result.status).to eq(:ok)
+ expect(result.body[:status]).to eq("success")
+ expect(execution.reload.status).to eq("success")
+ output = execution.execution_data.entries.dig("form-action-1", 0, "output", 0, "json")
+ expect(output).to include(
+ "feedback" => "Approved",
+ "submitted_at" => "2026-01-01T00:00:00.000Z",
+ "form_mode" => "production",
+ )
+ end
+
+ it "returns not_found when the signature does not match" do
+ result = dispatch(http_method: "GET", signature: "invalid")
+
+ expect(result.status).to eq(:not_found)
+ expect(result.body).to eq(error: "not_found")
+ end
+
+ it "returns not_found for paths the waiting node did not declare" do
+ result = dispatch(http_method: "GET", path: "unknown")
+
+ expect(result.status).to eq(:not_found)
+ expect(result.body).to eq(error: "not_found")
+ end
+ end
+
+ describe ".waiting_for?" do
+ it "detects waiting executions handled by form restart webhooks" do
+ expect(described_class.waiting_for?(execution, node_type: "form")).to eq(true)
+
+ dispatch(http_method: "POST", params: { form_data: { "feedback" => "Approved" } })
+
+ expect(described_class.waiting_for?(execution.reload, node_type: "form")).to eq(false)
+ end
+ end
+end
diff --git a/plugins/discourse-workflows/spec/lib/discourse_workflows/webhook_request_parser_spec.rb b/plugins/discourse-workflows/spec/lib/discourse_workflows/webhook_request_parser_spec.rb
new file mode 100644
index 00000000000..bc6535f636e
--- /dev/null
+++ b/plugins/discourse-workflows/spec/lib/discourse_workflows/webhook_request_parser_spec.rb
@@ -0,0 +1,127 @@
+# frozen_string_literal: true
+
+RSpec.describe DiscourseWorkflows::WebhookRequestParser do
+ def build_request(
+ body: "",
+ content_type: "application/json",
+ content_length: nil,
+ env_overrides: {}
+ )
+ env = {
+ "CONTENT_TYPE" => content_type,
+ "CONTENT_LENGTH" => (content_length || body.bytesize).to_s,
+ "HTTP_ACCEPT" => "application/json",
+ "HTTP_X_CUSTOM" => "custom-value",
+ "HTTP_AUTHORIZATION" => "Bearer secret",
+ "HTTP_COOKIE" => "session=abc",
+ "SERVER_NAME" => "localhost",
+ }.merge(env_overrides)
+
+ req = instance_double(ActionDispatch::Request)
+ allow(req).to receive(:content_type).and_return(content_type)
+ allow(req).to receive(:content_length).and_return(content_length || body.bytesize)
+ allow(req).to receive(:raw_post).and_return(body)
+
+ headers = instance_double(ActionDispatch::Http::Headers)
+ allow(headers).to receive(:env).and_return(env)
+ allow(req).to receive(:headers).and_return(headers)
+
+ req
+ end
+
+ let(:params) do
+ ActionController::Parameters.new(
+ path: "my-hook",
+ listener_id: "listener-1",
+ controller: "webhooks",
+ action: "receive",
+ format: "json",
+ data: "test",
+ )
+ end
+
+ describe "#parse_body" do
+ it "parses a valid JSON body" do
+ request = build_request(body: '{"foo": "bar"}')
+ parser = described_class.new(request, params)
+ expect(parser.parse_body).to eq("foo" => "bar")
+ end
+
+ it "returns empty hash for empty JSON body" do
+ request = build_request(body: "{}")
+ parser = described_class.new(request, params)
+ expect(parser.parse_body).to eq({})
+ end
+
+ it "raises on invalid JSON" do
+ request = build_request(body: "not json{")
+ parser = described_class.new(request, params)
+ expect { parser.parse_body }.to raise_error(Discourse::InvalidParameters, /Invalid JSON/)
+ end
+
+ it "falls back to params for non-JSON content type" do
+ request = build_request(body: "data=test", content_type: "application/x-www-form-urlencoded")
+ parser = described_class.new(request, params)
+ result = parser.parse_body
+ expect(result).to eq("data" => "test")
+ expect(result).not_to have_key("path")
+ expect(result).not_to have_key("listener_id")
+ end
+
+ it "raises when content_length exceeds max" do
+ request = build_request(body: "x", content_length: 2.megabytes)
+ parser = described_class.new(request, params)
+ expect { parser.parse_body }.to raise_error(
+ Discourse::InvalidParameters,
+ /Request body too large/,
+ )
+ end
+
+ it "raises when raw_post exceeds max" do
+ large_body = "x" * (1.megabyte + 1)
+ request = build_request(body: large_body, content_length: 100)
+ parser = described_class.new(request, params)
+ expect { parser.parse_body }.to raise_error(
+ Discourse::InvalidParameters,
+ /Request body too large/,
+ )
+ end
+ end
+
+ describe "#extract_headers" do
+ it "extracts HTTP_ prefixed headers as lowercase dashed names" do
+ request = build_request
+ parser = described_class.new(request, params)
+ headers = parser.extract_headers
+
+ expect(headers["accept"]).to eq("application/json")
+ expect(headers["x-custom"]).to eq("custom-value")
+ end
+
+ it "includes unprefixed content-type and content-length" do
+ request = build_request
+ parser = described_class.new(request, params)
+ headers = parser.extract_headers
+
+ expect(headers["content-type"]).to eq("application/json")
+ end
+
+ it "filters sensitive headers" do
+ request = build_request
+ parser = described_class.new(request, params)
+ headers = parser.extract_headers
+
+ expect(headers["authorization"]).to eq("[FILTERED]")
+ expect(headers["cookie"]).to eq("[FILTERED]")
+ end
+
+ it "skips non-HTTP rack variables" do
+ request = build_request
+ parser = described_class.new(request, params)
+ headers = parser.extract_headers
+
+ expect(headers).not_to have_key("SERVER_NAME")
+ expect(headers).not_to have_key("server-name")
+ end
+ end
+end
diff --git a/plugins/discourse-workflows/spec/lib/discourse_workflows/webhook_test_listener_spec.rb b/plugins/discourse-workflows/spec/lib/discourse_workflows/webhook_test_listener_spec.rb
new file mode 100644
index 00000000000..17a5b8e77cc
--- /dev/null
+++ b/plugins/discourse-workflows/spec/lib/discourse_workflows/webhook_test_listener_spec.rb
@@ -0,0 +1,140 @@
+# frozen_string_literal: true
+
+RSpec.describe DiscourseWorkflows::WebhookTestListener do
+ fab!(:admin)
+ fab!(:workflow) do
+ graph =
+ build_workflow_graph do |g|
+ g.node "webhook-1",
+ "trigger:webhook",
+ configuration: {
+ "path" => "test-hook",
+ "http_method" => "POST",
+ }
+ end
+ Fabricate(:discourse_workflows_workflow, created_by: admin, published: false, **graph)
+ end
+
+ let(:trigger_node) { workflow.find_node("webhook-1") }
+
+ describe ".create!" do
+ it "stores a short-lived listener with a draft workflow snapshot" do
+ listener =
+ described_class.create!(workflow: workflow, user: admin, trigger_node: trigger_node)
+
+ expect(described_class.find(listener.listener_id)).to have_attributes(
+ listener_id: listener.listener_id,
+ workflow_id: workflow.id,
+ user_id: admin.id,
+ trigger_node_id: "webhook-1",
+ http_method: "POST",
+ path: "test-hook",
+ )
+ expect(listener.test_url).to eq("/workflows/webhook-test/#{listener.listener_id}/test-hook")
+ expect(listener.expires_at).to be_between(
+ Time.current,
+ Time.current + described_class::TTL,
+ ).inclusive
+ end
+ end
+
+ describe ".purge_expired!" do
+ it "deletes only listeners past their expires_at" do
+ listener =
+ described_class.create!(workflow: workflow, user: admin, trigger_node: trigger_node)
+
+ DiscourseWorkflows::Webhook.where(webhook_id: listener.listener_id).update_all(
+ expires_at: 1.minute.ago,
+ )
+
+ expect { described_class.purge_expired! }.to change {
+ DiscourseWorkflows::Webhook.test_listeners.count
+ }.by(-1)
+ end
+ end
+
+ describe ".find_for_request" do
+ it "returns the listener only when the id and route match" do
+ listener =
+ described_class.create!(workflow: workflow, user: admin, trigger_node: trigger_node)
+
+ expect(
+ described_class.find_for_request(
+ listener_id: listener.listener_id,
+ method: "POST",
+ path: "test-hook",
+ ),
+ ).to have_attributes(listener_id: listener.listener_id)
+ expect(
+ described_class.find_for_request(
+ listener_id: listener.listener_id,
+ method: "GET",
+ path: "test-hook",
+ ),
+ ).to be_nil
+ expect(
+ described_class.find_for_request(
+ listener_id: SecureRandom.uuid,
+ method: "POST",
+ path: "test-hook",
+ ),
+ ).to be_nil
+ end
+ end
+
+ describe ".claim" do
+ it "returns and consumes the matching listener once" do
+ listener =
+ described_class.create!(workflow: workflow, user: admin, trigger_node: trigger_node)
+
+ claimed =
+ described_class.claim(described_class.find_by_route(method: "POST", path: "test-hook"))
+
+ expect(claimed.listener_id).to eq(listener.listener_id)
+ expect(described_class.find_by_route(method: "POST", path: "test-hook")).to be_nil
+ expect(described_class.find(listener.listener_id)).to be_nil
+ end
+
+ it "does not consume the listener when the HTTP method does not match" do
+ listener =
+ described_class.create!(workflow: workflow, user: admin, trigger_node: trigger_node)
+
+ expect(described_class.find_by_route(method: "GET", path: "test-hook")).to be_nil
+ expect(described_class.find_by_route(method: "POST", path: "test-hook").listener_id).to eq(
+ listener.listener_id,
+ )
+ end
+
+ it "does not replace another active listener on the same route" do
+ other_admin = Fabricate(:admin)
+ described_class.create!(workflow: workflow, user: admin, trigger_node: trigger_node)
+
+ expect do
+ described_class.create!(workflow: workflow, user: other_admin, trigger_node: trigger_node)
+ end.to raise_error(described_class::ActiveRouteExists)
+ end
+
+ it "replaces the same user's active listener for the same node" do
+ first = described_class.create!(workflow: workflow, user: admin, trigger_node: trigger_node)
+
+ second = described_class.create!(workflow: workflow, user: admin, trigger_node: trigger_node)
+
+ expect(described_class.find(first.listener_id)).to be_nil
+ expect(described_class.find_by_route(method: "POST", path: "test-hook").listener_id).to eq(
+ second.listener_id,
+ )
+ end
+ end
+
+ describe ".cancel!" do
+ it "removes the listener and route lookup" do
+ listener =
+ described_class.create!(workflow: workflow, user: admin, trigger_node: trigger_node)
+
+ described_class.cancel!(listener)
+
+ expect(described_class.find(listener.listener_id)).to be_nil
+ expect(described_class.find_by_route(method: "POST", path: "test-hook")).to be_nil
+ end
+ end
+end
diff --git a/plugins/discourse-workflows/spec/lib/discourse_workflows/workflow_dependency_indexer_spec.rb b/plugins/discourse-workflows/spec/lib/discourse_workflows/workflow_dependency_indexer_spec.rb
new file mode 100644
index 00000000000..750f097f8b2
--- /dev/null
+++ b/plugins/discourse-workflows/spec/lib/discourse_workflows/workflow_dependency_indexer_spec.rb
@@ -0,0 +1,187 @@
+# frozen_string_literal: true
+
+RSpec.describe DiscourseWorkflows::WorkflowDependencyIndexer do
+ fab!(:admin)
+
+ def index(workflow)
+ version = workflow.workflow_versions.find_by(version_id: workflow.version_id)
+ described_class.call(workflow, version: version)
+ end
+
+ def dependency_rows(workflow)
+ DiscourseWorkflows::WorkflowDependency.where(workflow_id: workflow.id)
+ end
+
+ describe ".call" do
+ it "extracts node_type dependencies for every node" do
+ graph =
+ build_workflow_graph do |g|
+ g.node "t1", "trigger:webhook", configuration: { "path" => "test" }
+ g.node "a1", "action:topic"
+ end
+ workflow = Fabricate(:discourse_workflows_workflow, created_by: admin, **graph)
+
+ index(workflow)
+
+ node_types = dependency_rows(workflow).of_type("node_type").pluck(:dependency_key, :node_id)
+ expect(node_types).to contain_exactly(%w[trigger:webhook t1], %w[action:topic a1])
+ end
+
+ it "extracts credential_id dependencies" do
+ credential = Fabricate(:discourse_workflows_credential)
+ graph =
+ build_workflow_graph do |g|
+ g.node "t1",
+ "trigger:webhook",
+ parameters: {
+ "path" => "hook1",
+ "authentication" => "basic_auth",
+ },
+ credentials: {
+ "auth" => {
+ "id" => credential.id,
+ "credential_type" => "basic_auth",
+ },
+ }
+ end
+ workflow = Fabricate(:discourse_workflows_workflow, created_by: admin, **graph)
+
+ index(workflow)
+
+ creds = dependency_rows(workflow).of_type("credential_id").pluck(:dependency_key, :node_id)
+ expect(creds).to contain_exactly([credential.id.to_s, "t1"])
+ end
+
+ it "ignores undeclared and hidden credential dependencies" do
+ credential = Fabricate(:discourse_workflows_credential)
+ graph =
+ build_workflow_graph do |g|
+ g.node "a1",
+ "action:log",
+ parameters: {
+ "message" => "hello",
+ },
+ credentials: {
+ "auth" => {
+ "id" => credential.id,
+ "credential_type" => "basic_auth",
+ },
+ }
+ g.node "t1",
+ "trigger:webhook",
+ parameters: {
+ "path" => "hook1",
+ "authentication" => "none",
+ },
+ credentials: {
+ "auth" => {
+ "id" => credential.id,
+ "credential_type" => "basic_auth",
+ },
+ }
+ end
+ workflow = Fabricate(:discourse_workflows_workflow, created_by: admin, **graph)
+
+ index(workflow)
+
+ expect(dependency_rows(workflow).of_type("credential_id")).to be_empty
+ end
+
+ it "extracts data_table_id dependencies" do
+ data_table = Fabricate(:discourse_workflows_data_table)
+ graph =
+ build_workflow_graph do |g|
+ g.node "a1", "action:data_table", configuration: { "data_table_id" => data_table.id }
+ end
+ workflow = Fabricate(:discourse_workflows_workflow, created_by: admin, **graph)
+
+ index(workflow)
+
+ tables = dependency_rows(workflow).of_type("data_table_id").pluck(:dependency_key, :node_id)
+ expect(tables).to contain_exactly([data_table.id.to_s, "a1"])
+ end
+
+ it "extracts error_workflow dependencies" do
+ error_wf = Fabricate(:discourse_workflows_workflow, created_by: admin)
+ graph = build_workflow_graph { |g| g.node "t1", "trigger:schedule" }
+ workflow =
+ Fabricate(
+ :discourse_workflows_workflow,
+ created_by: admin,
+ error_workflow_id: error_wf.id,
+ **graph,
+ )
+
+ index(workflow)
+
+ error_deps =
+ dependency_rows(workflow).of_type("error_workflow").pluck(:dependency_key, :node_id)
+ expect(error_deps).to contain_exactly([error_wf.id.to_s, nil])
+ end
+
+ it "replaces dependencies for the same version on re-index" do
+ first_table = Fabricate(:discourse_workflows_data_table)
+ second_table = Fabricate(:discourse_workflows_data_table)
+ graph =
+ build_workflow_graph do |g|
+ g.node "a1", "action:data_table", configuration: { "data_table_id" => first_table.id }
+ end
+ workflow = Fabricate(:discourse_workflows_workflow, created_by: admin, **graph)
+
+ index(workflow)
+ expect(dependency_rows(workflow).of_type("data_table_id").pluck(:dependency_key)).to eq(
+ [first_table.id.to_s],
+ )
+
+ # Reindexing the same versionId should clear and rewrite that version's
+ # dependency rows; mutate the snapshot in place to test this.
+ snapshot = workflow.workflow_versions.find_by(version_id: workflow.version_id)
+ updated_nodes = snapshot.nodes.deep_dup
+ updated_nodes.first["parameters"]["data_table_id"] = second_table.id
+ snapshot.update!(nodes: updated_nodes)
+ index(workflow)
+
+ expect(dependency_rows(workflow).of_type("data_table_id").pluck(:dependency_key)).to eq(
+ [second_table.id.to_s],
+ )
+ expect(dependency_rows(workflow).of_type("node_type").count).to eq(1)
+ end
+
+ it "scopes dependency rows per version" do
+ first_table = Fabricate(:discourse_workflows_data_table)
+ second_table = Fabricate(:discourse_workflows_data_table)
+ graph =
+ build_workflow_graph do |g|
+ g.node "a1", "action:data_table", configuration: { "data_table_id" => first_table.id }
+ end
+ workflow = Fabricate(:discourse_workflows_workflow, created_by: admin, **graph)
+ index(workflow)
+ old_version_id = workflow.version_id
+
+ updated =
+ build_workflow_graph do |g|
+ g.node "a1", "action:data_table", configuration: { "data_table_id" => second_table.id }
+ end
+ workflow.update!(nodes: updated[:nodes])
+ workflow.snapshot!(user: workflow.created_by)
+ index(workflow)
+
+ expect(
+ dependency_rows(workflow).where(workflow_version_id: old_version_id).pluck(:dependency_key),
+ ).to include(first_table.id.to_s)
+ expect(
+ dependency_rows(workflow).where(workflow_version_id: workflow.version_id).pluck(
+ :dependency_key,
+ ),
+ ).to include(second_table.id.to_s)
+ end
+
+ it "handles workflows with no nodes" do
+ workflow = Fabricate(:discourse_workflows_workflow, created_by: admin, nodes: [])
+
+ index(workflow)
+
+ expect(dependency_rows(workflow).count).to eq(0)
+ end
+ end
+end
diff --git a/plugins/discourse-workflows/spec/models/discourse_workflows/credential_spec.rb b/plugins/discourse-workflows/spec/models/discourse_workflows/credential_spec.rb
new file mode 100644
index 00000000000..0eed099d828
--- /dev/null
+++ b/plugins/discourse-workflows/spec/models/discourse_workflows/credential_spec.rb
@@ -0,0 +1,86 @@
+# frozen_string_literal: true
+
+RSpec.describe DiscourseWorkflows::Credential do
+ describe "validations" do
+ describe "data schema validation" do
+ it "is valid when all required fields are present" do
+ credential =
+ described_class.new(
+ name: "Auth",
+ credential_type: "basic_auth",
+ data: {
+ "user" => "admin",
+ "password" => "secret",
+ },
+ )
+
+ expect(credential).to be_valid
+ end
+
+ it "is invalid when a required field is missing" do
+ credential =
+ described_class.new(
+ name: "Auth",
+ credential_type: "basic_auth",
+ data: {
+ "user" => "admin",
+ },
+ )
+
+ expect(credential).not_to be_valid
+ expect(credential.errors[:data]).to include(
+ I18n.t("discourse_workflows.errors.credential.missing_required_field", field: "password"),
+ )
+ end
+
+ it "is invalid when a required field is empty" do
+ credential =
+ described_class.new(
+ name: "Auth",
+ credential_type: "basic_auth",
+ data: {
+ "user" => "admin",
+ "password" => "",
+ },
+ )
+
+ expect(credential).not_to be_valid
+ expect(credential.errors[:data]).to include(
+ I18n.t("discourse_workflows.errors.credential.missing_required_field", field: "password"),
+ )
+ end
+
+ it "skips schema validation when credential_type is unregistered" do
+ credential =
+ described_class.new(
+ name: "Auth",
+ credential_type: "unknown_type",
+ data: {
+ "anything" => "goes",
+ },
+ )
+
+ expect(credential).to be_valid
+ end
+ end
+ end
+
+ describe "#merge_data" do
+ fab!(:credential, :discourse_workflows_credential)
+
+ it "preserves redacted values from original data" do
+ credential.merge_data(
+ "user" => DiscourseWorkflows::Credential::REDACTED_VALUE,
+ "password" => "new_secret",
+ )
+
+ expect(credential.data).to eq("user" => "admin", "password" => "new_secret")
+ end
+
+ it "adds new keys while preserving originals" do
+ credential.merge_data("extra" => "value")
+
+ expect(credential.data).to eq("user" => "admin", "password" => "secret", "extra" => "value")
+ end
+ end
+end
diff --git a/plugins/discourse-workflows/spec/models/discourse_workflows/data_table_row_spec.rb b/plugins/discourse-workflows/spec/models/discourse_workflows/data_table_row_spec.rb
new file mode 100644
index 00000000000..78850032b81
--- /dev/null
+++ b/plugins/discourse-workflows/spec/models/discourse_workflows/data_table_row_spec.rb
@@ -0,0 +1,111 @@
+# frozen_string_literal: true
+
+RSpec.describe DiscourseWorkflows::DataTableRow do
+ fab!(:data_table) do
+ Fabricate(
+ :discourse_workflows_data_table,
+ columns: [
+ { "name" => "email", "type" => "string" },
+ { "name" => "score", "type" => "number" },
+ { "name" => "active", "type" => "boolean" },
+ { "name" => "joined_at", "type" => "date" },
+ ],
+ )
+ end
+
+ describe ".normalize_row_data" do
+ it "casts known values" do
+ result =
+ described_class.normalize_row_data(
+ data_table,
+ {
+ "email" => "[email protected]",
+ "score" => "42",
+ "active" => "true",
+ "joined_at" => "2024-01-15",
+ },
+ fill_missing: true,
+ )
+
+ expect(result).to include(
+ "email" => "[email protected]",
+ "score" => 42,
+ "active" => true,
+ "joined_at" => a_kind_of(Time),
+ )
+ end
+
+ it "fills omitted columns with nil when requested" do
+ result =
+ described_class.normalize_row_data(
+ data_table,
+ { "email" => "[email protected]" },
+ fill_missing: true,
+ )
+
+ expect(result).to eq(
+ "email" => "[email protected]",
+ "score" => nil,
+ "active" => nil,
+ "joined_at" => nil,
+ )
+ end
+
+ it "rejects unknown columns" do
+ expect {
+ described_class.normalize_row_data(
+ data_table,
+ { "email" => "[email protected]", "unknown_field" => "value" },
+ fill_missing: false,
+ )
+ }.to raise_error(ArgumentError, "Unknown column name 'unknown_field'")
+ end
+
+ it "rejects invalid numbers" do
+ expect {
+ described_class.normalize_row_data(
+ data_table,
+ { "score" => "not a number" },
+ fill_missing: false,
+ )
+ }.to raise_error(ArgumentError, "Value 'not a number' does not match column type 'number'")
+ end
+
+ it "rejects invalid booleans" do
+ expect {
+ described_class.normalize_row_data(data_table, { "active" => "maybe" }, fill_missing: false)
+ }.to raise_error(ArgumentError, "Value 'maybe' does not match column type 'boolean'")
+ end
+
+ it "converts blank numeric and date values to nil" do
+ result =
+ described_class.normalize_row_data(
+ data_table,
+ { "score" => "", "joined_at" => "" },
+ fill_missing: false,
+ )
+
+ expect(result).to eq("score" => nil, "joined_at" => nil)
+ end
+
+ it "allows text values at the maximum cell length" do
+ value = "a" * described_class::MAX_CELL_LENGTH
+
+ result =
+ described_class.normalize_row_data(data_table, { "email" => value }, fill_missing: false)
+
+ expect(result).to eq("email" => value)
+ end
+
+ it "rejects text values over the maximum cell length" do
+ value = "a" * (described_class::MAX_CELL_LENGTH + 1)
+
+ expect {
+ described_class.normalize_row_data(data_table, { "email" => value }, fill_missing: false)
+ }.to raise_error(
+ ArgumentError,
+ "Value exceeds maximum cell length of #{described_class::MAX_CELL_LENGTH} characters",
+ )
+ end
+ end
+end
diff --git a/plugins/discourse-workflows/spec/models/discourse_workflows/execution_data_spec.rb b/plugins/discourse-workflows/spec/models/discourse_workflows/execution_data_spec.rb
new file mode 100644
index 00000000000..af3e8091a26
--- /dev/null
+++ b/plugins/discourse-workflows/spec/models/discourse_workflows/execution_data_spec.rb
@@ -0,0 +1,28 @@
+# frozen_string_literal: true
+
+RSpec.describe DiscourseWorkflows::ExecutionData do
+ describe "#node_contexts" do
+ it "defaults to an empty hash when absent" do
+ data = described_class.new(data: { "entries" => {}, "context" => {} })
+ expect(data.node_contexts).to eq({})
+ end
+
+ it "returns the node_contexts key from the stored hash" do
+ data =
+ described_class.new(
+ data: {
+ "entries" => {
+ },
+ "context" => {
+ },
+ "node_contexts" => {
+ "node-1" => {
+ "k" => "v",
+ },
+ },
+ },
+ )
+ expect(data.node_contexts).to eq("node-1" => { "k" => "v" })
+ end
+ end
+end
diff --git a/plugins/discourse-workflows/spec/models/discourse_workflows/execution_spec.rb b/plugins/discourse-workflows/spec/models/discourse_workflows/execution_spec.rb
new file mode 100644
index 00000000000..b14e4666057
--- /dev/null
+++ b/plugins/discourse-workflows/spec/models/discourse_workflows/execution_spec.rb
@@ -0,0 +1,222 @@
+# frozen_string_literal: true
+
+RSpec.describe DiscourseWorkflows::Execution do
+ describe ".claim_for_resume" do
+ fab!(:workflow, :discourse_workflows_workflow)
+ fab!(:execution) do
+ Fabricate(
+ :discourse_workflows_execution,
+ workflow: workflow,
+ status: :waiting,
+ resume_token: "tok-abc",
+ )
+ end
+
+ it "transitions a waiting execution to running and returns it" do
+ claimed = described_class.claim_for_resume(execution, resume_token: "tok-abc")
+
+ expect(claimed).to be_present
+ expect(claimed.status).to eq("running")
+ expect(execution.reload.status).to eq("running")
+ end
+
+ it "returns nil when the resume token does not match" do
+ expect(described_class.claim_for_resume(execution, resume_token: "wrong")).to be_nil
+ expect(execution.reload.status).to eq("waiting")
+ end
+
+ it "returns nil when the execution is no longer waiting" do
+ execution.update!(status: :running)
+
+ expect(described_class.claim_for_resume(execution, resume_token: "tok-abc")).to be_nil
+ end
+
+ it "returns nil when the execution does not exist" do
+ execution.destroy!
+
+ expect(described_class.claim_for_resume(execution, resume_token: "tok-abc")).to be_nil
+ end
+
+ it "matches without a resume token (job entry points)" do
+ claimed = described_class.claim_for_resume(execution)
+
+ expect(claimed).to be_present
+ expect(claimed.status).to eq("running")
+ end
+
+ it "is idempotent — only the first call claims the execution" do
+ first = described_class.claim_for_resume(execution, resume_token: "tok-abc")
+ second = described_class.claim_for_resume(execution, resume_token: "tok-abc")
+
+ expect(first).to be_present
+ expect(second).to be_nil
+ end
+ end
+
+ describe "#fail_with_timeout!" do
+ fab!(:workflow, :discourse_workflows_workflow)
+ fab!(:execution) do
+ Fabricate(
+ :discourse_workflows_execution,
+ workflow: workflow,
+ status: :waiting,
+ waiting_node_id: "node-1",
+ waiting_until: 1.minute.ago,
+ resume_token: "tok",
+ timeout_action: "fail",
+ )
+ end
+
+ it "transitions a waiting execution to error and clears waiting fields" do
+ expect(execution.fail_with_timeout!).to eq(true)
+
+ execution.reload
+ expect(execution).to have_attributes(
+ status: "error",
+ waiting_node_id: nil,
+ waiting_until: nil,
+ resume_token: nil,
+ timeout_action: nil,
+ )
+ end
+
+ it "returns false and does not transition when the execution is no longer waiting" do
+ execution.update!(status: :running)
+
+ expect(execution.fail_with_timeout!).to eq(false)
+ expect(execution.reload.status).to eq("running")
+ end
+ end
+
+ describe ".compute_run_time_ms" do
+ def build_step(node_type: "action:code", started_at: nil, finished_at: nil)
+ node = Struct.new(:id, :name, :type).new(SecureRandom.uuid, "Node", node_type)
+ DiscourseWorkflows::Executor::Step.build(
+ node: node,
+ position: 0,
+ input: [],
+ started_at: started_at,
+ finished_at: finished_at,
+ )
+ end
+
+ it "sums durations across multiple steps" do
+ steps = [
+ build_step(started_at: "2026-01-01T00:00:00.000Z", finished_at: "2026-01-01T00:00:00.150Z"),
+ build_step(started_at: "2026-01-01T00:00:00.150Z", finished_at: "2026-01-01T00:00:00.400Z"),
+ ]
+
+ expect(described_class.compute_run_time_ms(steps)).to eq(400)
+ end
+
+ it "excludes waiting node types" do
+ steps = [
+ build_step(started_at: "2026-01-01T00:00:00.000Z", finished_at: "2026-01-01T00:00:00.200Z"),
+ build_step(
+ node_type: "flow:wait",
+ started_at: "2026-01-01T00:00:00.200Z",
+ finished_at: "2026-01-01T00:05:00.000Z",
+ ),
+ ]
+
+ expect(described_class.compute_run_time_ms(steps)).to eq(200)
+ end
+
+ it "skips steps without finished_at" do
+ running_step = build_step(started_at: "2026-01-01T00:00:00.000Z")
+ running_step.mark_waiting!
+
+ finished_step =
+ build_step(started_at: "2026-01-01T00:00:00.000Z", finished_at: "2026-01-01T00:00:01.000Z")
+
+ expect(described_class.compute_run_time_ms([running_step, finished_step])).to eq(1000)
+ end
+
+ it "returns nil when no steps have timing data" do
+ step = build_step
+ step.mark_waiting!
+
+ expect(described_class.compute_run_time_ms([step])).to be_nil
+ end
+
+ it "works with hashes from deserialized execution data" do
+ steps = [
+ {
+ "started_at" => "2026-01-01T00:00:00.000Z",
+ "finished_at" => "2026-01-01T00:00:00.500Z",
+ "node_type" => "action:code",
+ },
+ ]
+
+ expect(described_class.compute_run_time_ms(steps)).to eq(500)
+ end
+ end
+
+ describe ".purge_old" do
+ fab!(:workflow, :discourse_workflows_workflow)
+
+ let(:old_time) { 60.days.ago }
+ let(:recent_time) { 1.day.ago }
+
+ before { SiteSetting.workflow_executions_retention_days = 30 }
+
+ def fabricate_at(status, created_at)
+ execution = Fabricate(:discourse_workflows_execution, workflow: workflow, status: status)
+ Fabricate(:discourse_workflows_execution_data, execution: execution)
+ described_class.where(id: execution.id).update_all(created_at: created_at)
+ execution
+ end
+
+ it "deletes old terminal executions and their execution_data" do
+ old_success = fabricate_at(:success, old_time)
+ old_error = fabricate_at(:error, old_time)
+ old_skipped = fabricate_at(:skipped, old_time)
+ old_rate_limited = fabricate_at(:rate_limited, old_time)
+ recent_success = fabricate_at(:success, recent_time)
+
+ described_class.purge_old
+
+ expect(described_class.where(id: old_success.id)).to be_empty
+ expect(described_class.where(id: old_error.id)).to be_empty
+ expect(described_class.where(id: old_skipped.id)).to be_empty
+ expect(described_class.where(id: old_rate_limited.id)).to be_empty
+ expect(described_class.where(id: recent_success.id)).to exist
+ expect(
+ DiscourseWorkflows::ExecutionData.where(
+ execution_id: [old_success.id, old_error.id, old_skipped.id, old_rate_limited.id],
+ ),
+ ).to be_empty
+ end
+
+ it "preserves in-flight statuses even when older than the cutoff" do
+ old_waiting = fabricate_at(:waiting, old_time)
+ old_running = fabricate_at(:running, old_time)
+ old_pending = fabricate_at(:pending, old_time)
+
+ described_class.purge_old
+
+ expect(described_class.where(id: old_waiting.id)).to exist
+ expect(described_class.where(id: old_running.id)).to exist
+ expect(described_class.where(id: old_pending.id)).to exist
+ end
+
+ it "is a no-op when retention is set to 0" do
+ SiteSetting.workflow_executions_retention_days = 0
+ old_success = fabricate_at(:success, old_time)
+
+ described_class.purge_old
+
+ expect(described_class.where(id: old_success.id)).to exist
+ end
+
+ it "batches through more rows than PURGE_BATCH_SIZE" do
+ stub_const(DiscourseWorkflows::Execution, :PURGE_BATCH_SIZE, 2) do
+ 4.times { fabricate_at(:success, old_time) }
+
+ described_class.purge_old
+
+ expect(described_class.where(workflow: workflow, status: :success)).to be_empty
+ end
+ end
+ end
+end
diff --git a/plugins/discourse-workflows/spec/models/discourse_workflows/normalized_filter_spec.rb b/plugins/discourse-workflows/spec/models/discourse_workflows/normalized_filter_spec.rb
new file mode 100644
index 00000000000..00dad9a26b1
--- /dev/null
+++ b/plugins/discourse-workflows/spec/models/discourse_workflows/normalized_filter_spec.rb
@@ -0,0 +1,117 @@
+# frozen_string_literal: true
+
+RSpec.describe DiscourseWorkflows::NormalizedFilter do
+ fab!(:data_table) do
+ Fabricate(
+ :discourse_workflows_data_table,
+ columns: [
+ { "name" => "email", "type" => "string" },
+ { "name" => "score", "type" => "number" },
+ ],
+ )
+ end
+
+ describe "with a valid filter" do
+ subject(:model) do
+ described_class.new(
+ data_table:,
+ filter: {
+ "type" => "and",
+ "filters" => [{ "columnName" => "email", "condition" => "eq", "value" => "[email protected]" }],
+ },
+ )
+ end
+
+ it "returns normalized value" do
+ expect(model.value).to eq(
+ "type" => "and",
+ "filters" => [{ "columnName" => "email", "condition" => "eq", "value" => "[email protected]" }],
+ )
+ end
+ end
+
+ describe "with an empty filter" do
+ subject(:model) { described_class.new(data_table:, filter: {}) }
+
+ it "is invalid" do
+ expect(model).not_to be_valid
+ expect(model.errors[:base]).to include(match(/must not be empty/))
+ end
+ end
+
+ describe "with an empty optional filter" do
+ subject(:model) { described_class.new(data_table:, filter: {}, optional: true) }
+
+ it "returns nil value" do
+ expect(model.value).to be_nil
+ end
+ end
+
+ describe "with an unknown column name" do
+ subject(:model) do
+ described_class.new(
+ data_table:,
+ filter: {
+ "type" => "and",
+ "filters" => [{ "columnName" => "nonexistent", "condition" => "eq", "value" => "x" }],
+ },
+ )
+ end
+
+ it "is invalid" do
+ expect(model).not_to be_valid
+ expect(model.errors[:base]).to include(match(/Unknown column name/))
+ end
+ end
+
+ describe "with an unsupported condition" do
+ subject(:model) do
+ described_class.new(
+ data_table:,
+ filter: {
+ "type" => "and",
+ "filters" => [{ "columnName" => "email", "condition" => "regex", "value" => "x" }],
+ },
+ )
+ end
+
+ it "is invalid" do
+ expect(model).not_to be_valid
+ expect(model.errors[:base]).to include(match(/Unsupported filter condition/))
+ end
+ end
+
+ describe "with too many filter conditions" do
+ subject(:model) do
+ filters =
+ (described_class::MAX_FILTER_CONDITIONS + 1).times.map do
+ { "columnName" => "email", "condition" => "eq", "value" => "[email protected]" }
+ end
+
+ described_class.new(data_table:, filter: { "type" => "and", "filters" => filters })
+ end
+
+ it "is invalid" do
+ expect(model).not_to be_valid
+ expect(model.errors[:base]).to include(
+ match(/more than #{described_class::MAX_FILTER_CONDITIONS} conditions/),
+ )
+ end
+ end
+
+ describe "with an ilike condition" do
+ subject(:model) do
+ described_class.new(
+ data_table:,
+ filter: {
+ "type" => "and",
+ "filters" => [{ "columnName" => "email", "condition" => "ilike", "value" => "alice" }],
+ },
+ )
+ end
+
+ it "passes the value through without wrapping" do
+ expect(model.value.dig("filters", 0, "value")).to eq("alice")
+ end
+ end
+end
diff --git a/plugins/discourse-workflows/spec/models/discourse_workflows/template_store_spec.rb b/plugins/discourse-workflows/spec/models/discourse_workflows/template_store_spec.rb
new file mode 100644
index 00000000000..2bd8ecb08dd
--- /dev/null
+++ b/plugins/discourse-workflows/spec/models/discourse_workflows/template_store_spec.rb
@@ -0,0 +1,101 @@
+# frozen_string_literal: true
+
+RSpec.describe DiscourseWorkflows::TemplateStore do
+ before { described_class.reset_cache! }
+ after { described_class.reset_cache! }
+
+ let(:template_path) { File.join(DiscourseWorkflows::TEMPLATES_PATH, "cached-template.json") }
+ let(:broken_template_path) do
+ File.join(DiscourseWorkflows::TEMPLATES_PATH, "broken-template.json")
+ end
+ let(:template_json) do
+ {
+ name: "Cached template",
+ description: "A cached template",
+ nodes: [{ type: "trigger:topic_created" }, { type: "action:topic" }],
+ }.to_json
+ end
+
+ it "returns template summaries" do
+ Dir
+ .stubs(:glob)
+ .with(File.join(DiscourseWorkflows::TEMPLATES_PATH, "*.json"))
+ .returns([template_path])
+ File.stubs(:read).with(template_path).returns(template_json)
+
+ expect(described_class.summaries).to contain_exactly(
+ {
+ id: "cached-template",
+ name: "Cached template",
+ description: "A cached template",
+ node_types: %w[trigger:topic_created action:topic],
+ },
+ )
+ end
+
+ it "returns a duplicated template" do
+ Dir
+ .stubs(:glob)
+ .with(File.join(DiscourseWorkflows::TEMPLATES_PATH, "*.json"))
+ .returns([template_path])
+ File.stubs(:read).with(template_path).returns(template_json)
+
+ template = described_class.find("cached-template")
+ template["name"] = "Mutated"
+
+ expect(described_class.find("cached-template")["name"]).to eq("Cached template")
+ end
+
+ it "returns duplicated summaries" do
+ Dir
+ .stubs(:glob)
+ .with(File.join(DiscourseWorkflows::TEMPLATES_PATH, "*.json"))
+ .returns([template_path])
+ File.stubs(:read).with(template_path).returns(template_json)
+
+ summary = described_class.summaries.first
+ summary[:name].upcase!
+ summary[:node_types].first.upcase!
+
+ expect(described_class.summaries.first).to include(
+ name: "Cached template",
+ node_types: %w[trigger:topic_created action:topic],
+ )
+ end
+
+ it "reuses parsed templates until the cache is reset" do
+ Dir
+ .stubs(:glob)
+ .with(File.join(DiscourseWorkflows::TEMPLATES_PATH, "*.json"))
+ .returns([template_path])
+ File.expects(:read).with(template_path).once.returns(template_json)
+
+ described_class.summaries
+ described_class.find("cached-template")
+ end
+
+ it "skips malformed template JSON" do
+ Dir
+ .stubs(:glob)
+ .with(File.join(DiscourseWorkflows::TEMPLATES_PATH, "*.json"))
+ .returns([template_path, broken_template_path])
+ File.stubs(:read).with(template_path).returns(template_json)
+ File.stubs(:read).with(broken_template_path).returns("not valid json{{{")
+
+ ids = described_class.summaries.map { |template| template[:id] }
+
+ expect(ids).to contain_exactly("cached-template")
+ end
+
+ it "reloads templates after reset" do
+ Dir
+ .stubs(:glob)
+ .with(File.join(DiscourseWorkflows::TEMPLATES_PATH, "*.json"))
+ .returns([template_path])
+ File.expects(:read).with(template_path).twice.returns(template_json)
+
+ described_class.find("cached-template")
+ described_class.reset_cache!
+ described_class.find("cached-template")
+ end
+end
diff --git a/plugins/discourse-workflows/spec/models/discourse_workflows/webhook_spec.rb b/plugins/discourse-workflows/spec/models/discourse_workflows/webhook_spec.rb
new file mode 100644
index 00000000000..39bfb072da9
--- /dev/null
+++ b/plugins/discourse-workflows/spec/models/discourse_workflows/webhook_spec.rb
@@ -0,0 +1,63 @@
+# frozen_string_literal: true
+
+RSpec.describe DiscourseWorkflows::Webhook do
+ describe ".normalize_method" do
+ it "uppercases the value" do
+ expect(described_class.normalize_method("post")).to eq("POST")
+ end
+
+ it "stringifies non-string input" do
+ expect(described_class.normalize_method(nil)).to eq("")
+ end
+ end
+
+ describe ".normalize_path" do
+ it "strips a single leading slash" do
+ expect(described_class.normalize_path("/users/42")).to eq("users/42")
+ end
+
+ it "leaves a path without a leading slash unchanged" do
+ expect(described_class.normalize_path("hooks/inbound")).to eq("hooks/inbound")
+ end
+ end
+
+ describe ".segments_for" do
+ it "splits on slashes and discards empties" do
+ expect(described_class.segments_for("/users/42/posts/")).to eq(%w[users 42 posts])
+ end
+ end
+
+ describe ".dynamic_path?" do
+ it "is true when any segment is a :name placeholder" do
+ expect(described_class.dynamic_path?("users/:id")).to be(true)
+ end
+
+ it "is false when every segment is literal" do
+ expect(described_class.dynamic_path?("users/list")).to be(false)
+ end
+ end
+
+ describe ".path_length_for" do
+ it "counts segments including dynamic ones" do
+ expect(described_class.path_length_for("users/:id/posts")).to eq(3)
+ end
+ end
+
+ describe ".match_dynamic_path" do
+ it "captures values for :name segments and returns them" do
+ result = described_class.match_dynamic_path(template: "users/:id", segments: %w[users 42])
+ expect(result).to eq("id" => "42")
+ end
+
+ it "returns nil when literal segments do not match" do
+ result = described_class.match_dynamic_path(template: "posts/:id", segments: %w[users 42])
+ expect(result).to be_nil
+ end
+
+ it "returns nil when segment counts differ" do
+ result =
+ described_class.match_dynamic_path(template: "users/:id", segments: %w[users 42 extra])
+ expect(result).to be_nil
+ end
+ end
+end
diff --git a/plugins/discourse-workflows/spec/models/discourse_workflows/workflow_spec.rb b/plugins/discourse-workflows/spec/models/discourse_workflows/workflow_spec.rb
new file mode 100644
index 00000000000..b2a2cbf609c
--- /dev/null
+++ b/plugins/discourse-workflows/spec/models/discourse_workflows/workflow_spec.rb
@@ -0,0 +1,296 @@
+# frozen_string_literal: true
+
+RSpec.describe DiscourseWorkflows::Workflow do
+ fab!(:user)
+
+ describe "defaults" do
+ it "uses a connection map by default" do
+ expect(described_class.new.connections).to eq({})
+ end
+
+ it "uses empty static data by default" do
+ expect(described_class.new.static_data).to eq({})
+ end
+ end
+
+ describe "#has_unpublished_changes?" do
+ fab!(:workflow) { Fabricate(:discourse_workflows_workflow, created_by: user) }
+
+ it "is false for workflows that have never been published" do
+ expect(workflow).not_to have_unpublished_changes
+ end
+
+ it "is false for published workflows without a draft" do
+ workflow.update!(active_version_id: workflow.version_id)
+
+ expect(workflow).not_to have_unpublished_changes
+ end
+
+ it "is true for published workflows with draft changes" do
+ workflow.update!(active_version_id: workflow.version_id)
+ workflow.snapshot!(user: user)
+
+ expect(workflow).to have_unpublished_changes
+ end
+ end
+
+ describe "#node_static_data" do
+ fab!(:workflow) do
+ Fabricate(
+ :discourse_workflows_workflow,
+ created_by: user,
+ static_data: {
+ "global" => {
+ "tenant_id" => "acme",
+ },
+ "node:Schedule" => {
+ "cursor" => "abc",
+ },
+ "node:Removed Node" => {
+ "cursor" => "stale",
+ },
+ },
+ )
+ end
+
+ it "reads node-scoped data from flat keys" do
+ expect(workflow.node_static_data("Schedule")).to eq("cursor" => "abc")
+ end
+
+ it "maps flat node keys to entries by node name" do
+ expect(workflow.node_static_data_entries).to eq(
+ "Schedule" => {
+ "cursor" => "abc",
+ },
+ "Removed Node" => {
+ "cursor" => "stale",
+ },
+ )
+ end
+
+ it "commits global and node state as flat keys" do
+ workflow.commit_static_data!(
+ global: {
+ "tenant_id" => "meta",
+ },
+ node: {
+ "Schedule" => {
+ "cursor" => "def",
+ },
+ "Fresh" => {
+ "seen" => 1,
+ },
+ },
+ )
+
+ expect(workflow.reload.static_data).to eq(
+ "global" => {
+ "tenant_id" => "meta",
+ },
+ "node:Schedule" => {
+ "cursor" => "def",
+ },
+ "node:Fresh" => {
+ "seen" => 1,
+ },
+ )
+ end
+
+ it "ignores non-object static data slots when reading runtime state" do
+ workflow.update!(static_data: { "global" => "bad", "node:Schedule" => "bad" })
+
+ expect(workflow.global_static_data).to eq({})
+ expect(workflow.node_static_data("Schedule")).to eq({})
+ expect(workflow.node_static_data_entries).to eq("Schedule" => {})
+ end
+ end
+
+ describe "#trigger_node" do
+ it "returns the trigger node" do
+ graph =
+ build_workflow_graph do |g|
+ g.node "trigger-1", "trigger:topic_closed"
+ g.node "action-1", "action:topic_tags"
+ end
+ workflow = Fabricate(:discourse_workflows_workflow, created_by: user, **graph)
+
+ trigger = workflow.trigger_node
+ expect(trigger).to be_a(Hash)
+ expect(trigger["id"]).to eq("trigger-1")
+ expect(trigger["type"]).to eq("trigger:topic_closed")
+ end
+ end
+
+ describe "#node_has_reachable_downstream_of_type?" do
+ it "returns true when the target type is a direct downstream" do
+ graph =
+ build_workflow_graph do |g|
+ g.node "trigger-1", "trigger:form"
+ g.node "action-1", "action:form"
+ g.chain "trigger-1", "action-1"
+ end
+ workflow = Fabricate(:discourse_workflows_workflow, created_by: user, **graph)
+
+ expect(workflow.node_has_reachable_downstream_of_type?("trigger-1", "action:form")).to be(
+ true,
+ )
+ end
+
+ it "returns true when the target type is separated by intermediate nodes" do
+ graph =
+ build_workflow_graph do |g|
+ g.node "trigger-1", "trigger:form"
+ g.node "action-1", "action:send_message"
+ g.node "action-2", "action:form"
+ g.chain "trigger-1", "action-1", "action-2"
+ end
+ workflow = Fabricate(:discourse_workflows_workflow, created_by: user, **graph)
+
+ expect(workflow.node_has_reachable_downstream_of_type?("trigger-1", "action:form")).to be(
+ true,
+ )
+ end
+
+ it "returns false when no downstream node matches" do
+ graph =
+ build_workflow_graph do |g|
+ g.node "trigger-1", "trigger:form"
+ g.node "action-1", "action:send_message"
+ g.chain "trigger-1", "action-1"
+ end
+ workflow = Fabricate(:discourse_workflows_workflow, created_by: user, **graph)
+
+ expect(workflow.node_has_reachable_downstream_of_type?("trigger-1", "action:form")).to be(
+ false,
+ )
+ end
+
+ it "handles cycles without infinite looping" do
+ graph =
+ build_workflow_graph do |g|
+ g.node "trigger-1", "trigger:form"
+ g.node "condition-1", "condition:boolean"
+ g.connect "trigger-1", "condition-1"
+ g.connect "condition-1", "trigger-1"
+ end
+ workflow = Fabricate(:discourse_workflows_workflow, created_by: user, **graph)
+
+ expect(workflow.node_has_reachable_downstream_of_type?("trigger-1", "action:form")).to be(
+ false,
+ )
+ end
+ end
+
+ describe "dependent destroy" do
+ it "destroys associated executions" do
+ graph =
+ build_workflow_graph do |g|
+ g.node "trigger-1", "trigger:topic_closed"
+ g.node "action-1", "action:topic_tags"
+ g.chain "trigger-1", "action-1"
+ end
+ workflow = Fabricate(:discourse_workflows_workflow, created_by: user, **graph)
+ Fabricate(:discourse_workflows_execution, workflow: workflow)
+
+ workflow.destroy!
+
+ expect(DiscourseWorkflows::Execution.count).to eq(0)
+ end
+ end
+
+ describe "errorWorkflowId validation" do
+ fab!(:workflow) { Fabricate(:discourse_workflows_workflow, created_by: user) }
+
+ it "rejects pointing at itself" do
+ workflow.error_workflow_id = workflow.id
+
+ expect(workflow).not_to be_valid
+ expect(workflow.errors[:error_workflow_id]).to include(
+ I18n.t(
+ "activerecord.errors.models.discourse_workflows/workflow.attributes.error_workflow_id.cannot_be_self",
+ ),
+ )
+ end
+
+ it "allows pointing at a different workflow" do
+ other = Fabricate(:discourse_workflows_workflow, created_by: user)
+ workflow.error_workflow_id = other.id
+
+ expect(workflow).to be_valid
+ end
+
+ it "allows a nil error workflow" do
+ workflow.error_workflow_id = nil
+
+ expect(workflow).to be_valid
+ end
+ end
+
+ describe "errorWorkflowId back-references on destroy" do
+ fab!(:target, :discourse_workflows_workflow)
+ fab!(:referrer) do
+ Fabricate(:discourse_workflows_workflow, created_by: user, error_workflow_id: target.id)
+ end
+
+ it "nullifies errorWorkflowId on workflows that point at the destroyed one" do
+ expect { target.destroy! }.to change { referrer.reload.error_workflow_id }.from(target.id).to(
+ nil,
+ )
+ end
+
+ it "leaves unrelated workflows untouched" do
+ other = Fabricate(:discourse_workflows_workflow, created_by: user)
+
+ target.destroy!
+
+ expect(other.reload.error_workflow_id).to be_nil
+ end
+
+ it "does not stop the destroy" do
+ target.destroy!
+
+ expect(DiscourseWorkflows::Workflow.exists?(target.id)).to be(false)
+ end
+ end
+
+ describe "#last_successful_execution" do
+ fab!(:workflow, :discourse_workflows_workflow)
+
+ it "returns nil when there are no executions" do
+ expect(workflow.last_successful_execution).to be_nil
+ end
+
+ it "returns nil when no execution is successful" do
+ Fabricate(:discourse_workflows_execution, workflow: workflow, status: :error)
+ Fabricate(:discourse_workflows_execution, workflow: workflow, status: :pending)
+
+ expect(workflow.last_successful_execution).to be_nil
+ end
+
+ it "returns the most recent successful execution" do
+ Fabricate(
+ :discourse_workflows_execution,
+ workflow: workflow,
+ status: :success,
+ created_at: 2.days.ago,
+ )
+ latest =
+ Fabricate(
+ :discourse_workflows_execution,
+ workflow: workflow,
+ status: :success,
+ created_at: 1.minute.ago,
+ )
+ Fabricate(:discourse_workflows_execution, workflow: workflow, status: :error)
+
+ expect(workflow.last_successful_execution).to eq(latest)
+ end
+
+ it "eager-loads execution_data" do
+ execution = Fabricate(:discourse_workflows_execution, workflow: workflow, status: :success)
+ Fabricate(:discourse_workflows_execution_data, execution: execution)
+
+ expect(workflow.last_successful_execution.association(:execution_data)).to be_loaded
+ end
+ end
+end
diff --git a/plugins/discourse-workflows/spec/models/discourse_workflows/workflow_version_spec.rb b/plugins/discourse-workflows/spec/models/discourse_workflows/workflow_version_spec.rb
new file mode 100644
index 00000000000..c1ca847d633
--- /dev/null
+++ b/plugins/discourse-workflows/spec/models/discourse_workflows/workflow_version_spec.rb
@@ -0,0 +1,48 @@
+# frozen_string_literal: true
+
+RSpec.describe DiscourseWorkflows::WorkflowVersion do
+ fab!(:user)
+ fab!(:workflow) { Fabricate(:discourse_workflows_workflow, created_by: user) }
+
+ describe "defaults" do
+ it "uses a connection map by default" do
+ expect(described_class.new.connections).to eq({})
+ end
+ end
+
+ describe "before_destroy guard" do
+ it "refuses when the version matches the workflow's current versionId" do
+ current = workflow.workflow_versions.find_by(version_id: workflow.version_id)
+
+ expect(current.destroy).to be(false)
+ expect(current.errors[:base]).to be_present
+ expect(DiscourseWorkflows::WorkflowVersion.exists?(version_id: current.version_id)).to be(
+ true,
+ )
+ end
+
+ it "refuses when the version matches the workflow's activeVersionId" do
+ published = Fabricate(:discourse_workflows_workflow, created_by: user, published: true)
+ active = published.workflow_versions.find_by(version_id: published.active_version_id)
+
+ published.snapshot!(user: user)
+
+ expect(active.destroy).to be(false)
+ expect(DiscourseWorkflows::WorkflowVersion.exists?(version_id: active.version_id)).to be(true)
+ end
+
+ it "allows destroy of a superseded version no pointer references" do
+ old_version_id = workflow.version_id
+ workflow.snapshot!(user: user)
+ old = DiscourseWorkflows::WorkflowVersion.find(old_version_id)
+
+ expect { old.destroy! }.to change(DiscourseWorkflows::WorkflowVersion, :count).by(-1)
+ end
+
+ it "allows the parent workflow cascade to remove all versions" do
+ workflow.snapshot!(user: user)
+
+ expect { workflow.destroy! }.to change(DiscourseWorkflows::WorkflowVersion, :count).by(-2)
+ end
+ end
+end
diff --git a/plugins/discourse-workflows/spec/plugin_helper.rb b/plugins/discourse-workflows/spec/plugin_helper.rb
new file mode 100644
index 00000000000..6e6df6781ae
--- /dev/null
+++ b/plugins/discourse-workflows/spec/plugin_helper.rb
@@ -0,0 +1,26 @@
+# frozen_string_literal: true
+
+Dir[File.join(__dir__, "support", "**", "*.rb")].each { |f| require f }
+
+module DiscourseWorkflowsSpecHelper
+ extend ActiveSupport::Concern
+
+ included do
+ before do
+ SiteSetting.discourse_workflows_enabled = true
+ SiteSetting.external_system_avatars_url = "https://example.com/avatar/{username}.png"
+ DiscourseWorkflows::Registry.reset_indexes!
+ Jobs::DiscourseWorkflows::ExecuteWorkflow.jobs.clear
+ Jobs::DiscourseWorkflows::ResumeWebhookWaiting.jobs.clear
+ Jobs::DiscourseWorkflows::ResumeWaitingExecution.jobs.clear
+ end
+ end
+end
+
+RSpec.configure do |config|
+ config.define_derived_metadata(file_path: %r{/plugins/discourse-workflows/spec/}) do |metadata|
+ metadata[:discourse_workflows] = true
+ end
+
+ config.include DiscourseWorkflowsSpecHelper, discourse_workflows: true
+end
diff --git a/plugins/discourse-workflows/spec/requests/discourse_workflows/credentials_controller_spec.rb b/plugins/discourse-workflows/spec/requests/discourse_workflows/credentials_controller_spec.rb
new file mode 100644
index 00000000000..1afc83824a0
--- /dev/null
+++ b/plugins/discourse-workflows/spec/requests/discourse_workflows/credentials_controller_spec.rb
@@ -0,0 +1,162 @@
+# frozen_string_literal: true
+
+RSpec.describe DiscourseWorkflows::CredentialsController do
+ fab!(:admin)
+
+ before { sign_in(admin) }
+
+ context "when not logged in as admin" do
+ fab!(:user)
+
+ before { sign_in(user) }
+
+ it "returns 404" do
+ get "/admin/plugins/discourse-workflows/credentials.json"
+ expect(response).to have_http_status(:not_found)
+ end
+ end
+
+ describe "GET /admin/plugins/discourse-workflows/credentials" do
+ it "returns credentials with redacted data" do
+ credential = Fabricate(:discourse_workflows_credential, name: "Test Auth")
+
+ get "/admin/plugins/discourse-workflows/credentials.json"
+
+ expect(response).to have_http_status(:ok)
+ json = response.parsed_body
+ expect(json["credentials"].length).to eq(1)
+ expect(json["credentials"][0]["name"]).to eq("Test Auth")
+ expect(json["credentials"][0]["data"]["user"]).to eq("admin")
+ expect(json["credentials"][0]["data"]["password"]).to eq(
+ DiscourseWorkflows::Credential::REDACTED_VALUE,
+ )
+ expect(json["credentials"][0]["data_modes"]["user"]).to eq("fixed")
+ expect(json["credentials"][0]["data_modes"]["password"]).to eq("fixed")
+ end
+
+ it "returns shared pagination meta" do
+ Fabricate(:discourse_workflows_credential, name: "First")
+ credential = Fabricate(:discourse_workflows_credential, name: "Second")
+
+ get "/admin/plugins/discourse-workflows/credentials.json", params: { limit: 1 }
+
+ json = response.parsed_body
+ expect(json["meta"]).to include(
+ "total_rows" => 2,
+ "load_more_url" =>
+ "/admin/plugins/discourse-workflows/credentials.json?cursor=#{credential.id}&limit=1",
+ )
+ end
+
+ it "filters by type param" do
+ Fabricate(:discourse_workflows_credential, credential_type: "basic_auth")
+ Fabricate(:discourse_workflows_credential, credential_type: "api_key", name: "API")
+
+ get "/admin/plugins/discourse-workflows/credentials.json", params: { type: "basic_auth" }
+
+ json = response.parsed_body
+ expect(json["credentials"].length).to eq(1)
+ expect(json["credentials"][0]["credential_type"]).to eq("basic_auth")
+ end
+ end
+
+ describe "POST /admin/plugins/discourse-workflows/credentials" do
+ it "creates a credential" do
+ post "/admin/plugins/discourse-workflows/credentials.json",
+ params: {
+ name: "My Auth",
+ credential_type: "basic_auth",
+ data: {
+ user: "admin",
+ password: "secret",
+ },
+ }
+
+ expect(response).to have_http_status(:created)
+ json = response.parsed_body
+ expect(json["credential"]["name"]).to eq("My Auth")
+ expect(json["credential"]["data"]["user"]).to eq("admin")
+ end
+
+ it "returns 400 when name is missing" do
+ post "/admin/plugins/discourse-workflows/credentials.json",
+ params: {
+ credential_type: "basic_auth",
+ data: {
+ },
+ }
+
+ expect(response).to have_http_status(:bad_request)
+ end
+ end
+
+ describe "PUT /admin/plugins/discourse-workflows/credentials/:id" do
+ it "updates a credential with sentinel merging" do
+ credential = Fabricate(:discourse_workflows_credential)
+
+ put "/admin/plugins/discourse-workflows/credentials/#{credential.id}.json",
+ params: {
+ name: "Updated",
+ data: {
+ user: "new_user",
+ password: DiscourseWorkflows::Credential::REDACTED_VALUE,
+ },
+ }
+
+ expect(response).to have_http_status(:ok)
+ expect(response.parsed_body["credential"]["name"]).to eq("Updated")
+ expect(credential.reload.data["user"]).to eq("new_user")
+ expect(credential.reload.data["password"]).to eq("secret")
+ end
+
+ it "returns 404 when credential does not exist" do
+ put "/admin/plugins/discourse-workflows/credentials/-1.json", params: { name: "X" }
+
+ expect(response).to have_http_status(:not_found)
+ end
+ end
+
+ describe "DELETE /admin/plugins/discourse-workflows/credentials/:id" do
+ it "deletes a credential" do
+ credential = Fabricate(:discourse_workflows_credential)
+
+ delete "/admin/plugins/discourse-workflows/credentials/#{credential.id}.json"
+
+ expect(response).to have_http_status(:no_content)
+ expect(DiscourseWorkflows::Credential.exists?(credential.id)).to be(false)
+ end
+
+ it "returns 404 when credential does not exist" do
+ delete "/admin/plugins/discourse-workflows/credentials/-1.json"
+ expect(response).to have_http_status(:not_found)
+ end
+
+ it "returns 422 when credential is referenced by a node" do
+ credential = Fabricate(:discourse_workflows_credential)
+ graph =
+ build_workflow_graph do |g|
+ g.node "webhook-1",
+ "trigger:webhook",
+ parameters: {
+ "authentication" => "basic_auth",
+ },
+ credentials: {
+ "auth" => {
+ "id" => credential.id,
+ "credential_type" => "basic_auth",
+ },
+ }
+ end
+ workflow =
+ Fabricate(:discourse_workflows_workflow, name: "My Workflow", created_by: admin, **graph)
+
+ delete "/admin/plugins/discourse-workflows/credentials/#{credential.id}.json"
+
+ expect(response).to have_http_status(:unprocessable_entity)
+ expect(response.parsed_body["type"]).to eq("credential_in_use")
+ expect(response.parsed_body["referencing_workflows"]).to contain_exactly(
+ { "id" => workflow.id, "name" => "My Workflow" },
+ )
+ end
+ end
+end
diff --git a/plugins/discourse-workflows/spec/requests/discourse_workflows/data_table_columns_controller_spec.rb b/plugins/discourse-workflows/spec/requests/discourse_workflows/data_table_columns_controller_spec.rb
new file mode 100644
index 00000000000..96e87e568e6
--- /dev/null
+++ b/plugins/discourse-workflows/spec/requests/discourse_workflows/data_table_columns_controller_spec.rb
@@ -0,0 +1,122 @@
+# frozen_string_literal: true
+
+RSpec.describe DiscourseWorkflows::DataTableColumnsController do
+ fab!(:admin)
+ fab!(:user)
+
+ before { sign_in(admin) }
+
+ shared_examples "requires admin" do |method, path_proc, params_proc = nil|
+ it "returns 404 when not logged in" do
+ sign_in(Fabricate(:anonymous))
+ public_send(
+ method,
+ instance_exec(&path_proc),
+ params: params_proc&.then { instance_exec(&_1) },
+ )
+ expect(response).to have_http_status(:not_found)
+ end
+
+ it "returns 404 when not admin" do
+ sign_in(user)
+ public_send(
+ method,
+ instance_exec(&path_proc),
+ params: params_proc&.then { instance_exec(&_1) },
+ )
+ expect(response).to have_http_status(:not_found)
+ end
+ end
+
+ describe "POST /admin/plugins/discourse-workflows/data-tables/:id/columns" do
+ fab!(:data_table) do
+ Fabricate(
+ :discourse_workflows_data_table,
+ columns: [{ "name" => "email", "type" => "string" }],
+ )
+ end
+ fab!(:row) { insert_data_table_row(data_table, "email" => "[email protected]") }
+
+ include_examples "requires admin",
+ :post,
+ -> do
+ "/admin/plugins/discourse-workflows/data-tables/#{data_table.id}/columns.json"
+ end,
+ -> { { name: "c", column_type: "string" } }
+
+ it "creates a column without losing existing rows" do
+ post "/admin/plugins/discourse-workflows/data-tables/#{data_table.id}/columns.json",
+ params: {
+ name: "score",
+ column_type: "number",
+ }
+
+ expect(response).to have_http_status(:created)
+ column_names = response.parsed_body["data_table"]["columns"].map { |column| column["name"] }
+ expect(column_names).to include("email", "score")
+ expect(find_data_table_row(data_table, row["id"])).to include(
+ "email" => "[email protected]",
+ "score" => nil,
+ )
+ end
+ end
+
+ describe "PATCH /admin/plugins/discourse-workflows/data-tables/:id/columns/:column_name/rename" do
+ fab!(:data_table) do
+ Fabricate(
+ :discourse_workflows_data_table,
+ columns: [{ "name" => "email", "type" => "string" }],
+ )
+ end
+ fab!(:row) { insert_data_table_row(data_table, "email" => "[email protected]") }
+
+ include_examples "requires admin",
+ :patch,
+ -> do
+ "/admin/plugins/discourse-workflows/data-tables/#{data_table.id}/columns/email/rename.json"
+ end,
+ -> { { name: "renamed" } }
+
+ it "renames a column without losing existing rows" do
+ patch "/admin/plugins/discourse-workflows/data-tables/#{data_table.id}/columns/email/rename.json",
+ params: {
+ name: "contact_email",
+ }
+
+ expect(response).to have_http_status(:ok)
+ expect(response.parsed_body["data_table"]["columns"]).to include(
+ include("name" => "contact_email", "type" => "string"),
+ )
+
+ row_data = find_data_table_row(data_table, row["id"])
+ expect(row_data["contact_email"]).to eq("[email protected]")
+ expect(row_data).not_to have_key("email")
+ end
+ end
+
+ describe "DELETE /admin/plugins/discourse-workflows/data-tables/:id/columns/:column_name" do
+ fab!(:data_table) do
+ Fabricate(
+ :discourse_workflows_data_table,
+ columns: [
+ { "name" => "email", "type" => "string" },
+ { "name" => "score", "type" => "number" },
+ ],
+ )
+ end
+ fab!(:row) { insert_data_table_row(data_table, "email" => "[email protected]", "score" => 7) }
+
+ include_examples "requires admin",
+ :delete,
+ -> do
+ "/admin/plugins/discourse-workflows/data-tables/#{data_table.id}/columns/email.json"
+ end
+
+ it "deletes the column and preserves remaining row data" do
+ delete "/admin/plugins/discourse-workflows/data-tables/#{data_table.id}/columns/email.json"
+
+ expect(response).to have_http_status(:no_content)
+ expect(find_data_table_row(data_table, row["id"])).to include("score" => 7)
+ end
+ end
+end
diff --git a/plugins/discourse-workflows/spec/requests/discourse_workflows/data_table_rows_controller_spec.rb b/plugins/discourse-workflows/spec/requests/discourse_workflows/data_table_rows_controller_spec.rb
new file mode 100644
index 00000000000..3099002dedc
--- /dev/null
+++ b/plugins/discourse-workflows/spec/requests/discourse_workflows/data_table_rows_controller_spec.rb
@@ -0,0 +1,266 @@
+# frozen_string_literal: true
+
+RSpec.describe DiscourseWorkflows::DataTableRowsController do
+ fab!(:admin)
+ fab!(:user)
+ fab!(:data_table) do
+ Fabricate(
+ :discourse_workflows_data_table,
+ columns: [
+ { "name" => "email", "type" => "string" },
+ { "name" => "score", "type" => "number" },
+ ],
+ )
+ end
+
+ before { sign_in(admin) }
+
+ shared_examples "requires admin" do |method, path_proc, params_proc = nil|
+ it "returns 404 when not logged in" do
+ sign_in(Fabricate(:anonymous))
+ public_send(
+ method,
+ instance_exec(&path_proc),
+ params: params_proc&.then { instance_exec(&_1) },
+ )
+ expect(response).to have_http_status(:not_found)
+ end
+
+ it "returns 404 when not admin" do
+ sign_in(user)
+ public_send(
+ method,
+ instance_exec(&path_proc),
+ params: params_proc&.then { instance_exec(&_1) },
+ )
+ expect(response).to have_http_status(:not_found)
+ end
+ end
+
+ describe "GET /admin/plugins/discourse-workflows/data-tables/:id/rows" do
+ fab!(:row) { insert_data_table_row(data_table, "email" => "[email protected]") }
+
+ include_examples "requires admin",
+ :get,
+ -> do
+ "/admin/plugins/discourse-workflows/data-tables/#{data_table.id}/rows.json"
+ end
+
+ it "lists rows" do
+ get "/admin/plugins/discourse-workflows/data-tables/#{data_table.id}/rows.json"
+ expect(response).to have_http_status(:ok)
+ json = response.parsed_body
+ expect(json["rows"].length).to eq(1)
+ expect(json["rows"][0]["email"]).to eq("[email protected]")
+ expect(json["count"]).to eq(1)
+ end
+
+ it "filters rows" do
+ get "/admin/plugins/discourse-workflows/data-tables/#{data_table.id}/rows.json",
+ params: {
+ filter: {
+ type: "and",
+ filters: [{ columnName: "email", condition: "eq", value: "[email protected]" }],
+ },
+ }
+ expect(response).to have_http_status(:ok)
+ expect(response.parsed_body["rows"].length).to eq(0)
+ end
+
+ it "returns 400 for an invalid filter" do
+ get "/admin/plugins/discourse-workflows/data-tables/#{data_table.id}/rows.json",
+ params: {
+ filter: {
+ type: "and",
+ filters: [{ columnName: "email", condition: "invalid", value: "[email protected]" }],
+ },
+ }
+
+ expect(response).to have_http_status(:bad_request)
+ end
+ end
+
+ describe "POST /admin/plugins/discourse-workflows/data-tables/:id/rows" do
+ include_examples "requires admin",
+ :post,
+ -> do
+ "/admin/plugins/discourse-workflows/data-tables/#{data_table.id}/rows.json"
+ end,
+ -> { { data: { email: "[email protected]" } } }
+
+ it "inserts a row" do
+ post "/admin/plugins/discourse-workflows/data-tables/#{data_table.id}/rows.json",
+ params: {
+ data: {
+ email: "[email protected]",
+ },
+ }
+ expect(response).to have_http_status(:created)
+ expect(response.parsed_body["row"]["email"]).to eq("[email protected]")
+ end
+ end
+
+ describe "PUT /admin/plugins/discourse-workflows/data-tables/:id/rows" do
+ fab!(:row) { insert_data_table_row(data_table, "email" => "[email protected]", "score" => 1) }
+
+ include_examples "requires admin",
+ :put,
+ -> do
+ "/admin/plugins/discourse-workflows/data-tables/#{data_table.id}/rows.json"
+ end,
+ -> { { data: { score: 99 } } }
+
+ it "updates matching rows" do
+ put "/admin/plugins/discourse-workflows/data-tables/#{data_table.id}/rows.json",
+ params: {
+ filter: {
+ type: "and",
+ filters: [{ columnName: "email", condition: "eq", value: "[email protected]" }],
+ },
+ data: {
+ score: 99,
+ },
+ }
+ expect(response).to have_http_status(:ok)
+ expect(response.parsed_body["updated_count"]).to eq(1)
+ expect(find_data_table_row(data_table, row["id"])["score"]).to eq(99)
+ end
+
+ it "returns 422 when no rows match" do
+ put "/admin/plugins/discourse-workflows/data-tables/#{data_table.id}/rows.json",
+ params: {
+ filter: {
+ type: "and",
+ filters: [{ columnName: "email", condition: "eq", value: "[email protected]" }],
+ },
+ data: {
+ score: 99,
+ },
+ }
+
+ expect(response).to have_http_status(:unprocessable_entity)
+ end
+ end
+
+ describe "DELETE /admin/plugins/discourse-workflows/data-tables/:id/rows" do
+ fab!(:row) { insert_data_table_row(data_table, "email" => "[email protected]") }
+ fab!(:row_1) { insert_data_table_row(data_table, "email" => "[email protected]") }
+ fab!(:row_2) { insert_data_table_row(data_table, "email" => "[email protected]") }
+
+ include_examples "requires admin",
+ :delete,
+ -> do
+ "/admin/plugins/discourse-workflows/data-tables/#{data_table.id}/rows.json"
+ end
+
+ it "deletes matching rows by filter" do
+ row_id = row["id"]
+ delete "/admin/plugins/discourse-workflows/data-tables/#{data_table.id}/rows.json",
+ params: {
+ filter: {
+ type: "and",
+ filters: [{ columnName: "email", condition: "eq", value: "[email protected]" }],
+ },
+ }
+ expect(response).to have_http_status(:ok)
+ expect(response.parsed_body["deleted_count"]).to eq(1)
+ expect(find_data_table_row(data_table, row_id)).to be_nil
+ end
+
+ it "bulk deletes rows by ids" do
+ id_1 = row_1["id"]
+ id_2 = row_2["id"]
+ delete "/admin/plugins/discourse-workflows/data-tables/#{data_table.id}/rows.json",
+ params: {
+ row_ids: [id_1, id_2],
+ }
+ expect(response).to have_http_status(:ok)
+ expect(response.parsed_body["deleted_count"]).to eq(2)
+ expect(find_data_table_row(data_table, id_1)).to be_nil
+ expect(find_data_table_row(data_table, id_2)).to be_nil
+ end
+
+ it "returns 404 for non-existent data table" do
+ delete "/admin/plugins/discourse-workflows/data-tables/999999/rows.json",
+ params: {
+ row_ids: [row_1["id"]],
+ }
+ expect(response).to have_http_status(:not_found)
+ end
+
+ it "returns 400 when no target is provided" do
+ delete "/admin/plugins/discourse-workflows/data-tables/#{data_table.id}/rows.json", params: {}
+ expect(response).to have_http_status(:bad_request)
+ end
+ end
+
+ describe "PUT /admin/plugins/discourse-workflows/data-tables/:id/rows/:row_id" do
+ fab!(:row) { insert_data_table_row(data_table, "email" => "[email protected]", "score" => 1) }
+
+ include_examples "requires admin",
+ :put,
+ -> do
+ "/admin/plugins/discourse-workflows/data-tables/#{data_table.id}/rows/#{row["id"]}.json"
+ end,
+ -> { { data: { score: 1 } } }
+
+ it "updates a single row by id" do
+ put "/admin/plugins/discourse-workflows/data-tables/#{data_table.id}/rows/#{row["id"]}.json",
+ params: {
+ data: {
+ score: 42,
+ },
+ }
+ expect(response).to have_http_status(:ok)
+ expect(response.parsed_body["row"]["score"]).to eq(42)
+ expect(find_data_table_row(data_table, row["id"])["email"]).to eq("[email protected]")
+ end
+
+ it "returns 404 for non-existent row" do
+ put "/admin/plugins/discourse-workflows/data-tables/#{data_table.id}/rows/999999.json",
+ params: {
+ data: {
+ score: 1,
+ },
+ }
+ expect(response).to have_http_status(:not_found)
+ end
+
+ it "returns 404 for non-existent data table" do
+ put "/admin/plugins/discourse-workflows/data-tables/999999/rows/#{row["id"]}.json",
+ params: {
+ data: {
+ score: 1,
+ },
+ }
+ expect(response).to have_http_status(:not_found)
+ end
+ end
+
+ describe "DELETE /admin/plugins/discourse-workflows/data-tables/:id/rows/:row_id" do
+ fab!(:row) { insert_data_table_row(data_table, "email" => "[email protected]") }
+
+ include_examples "requires admin",
+ :delete,
+ -> do
+ "/admin/plugins/discourse-workflows/data-tables/#{data_table.id}/rows/#{row["id"]}.json"
+ end
+
+ it "deletes a single row by id" do
+ row_id = row["id"]
+ delete "/admin/plugins/discourse-workflows/data-tables/#{data_table.id}/rows/#{row_id}.json"
+ expect(response).to have_http_status(:no_content)
+ expect(find_data_table_row(data_table, row_id)).to be_nil
+ end
+
+ it "returns 404 for non-existent row" do
+ delete "/admin/plugins/discourse-workflows/data-tables/#{data_table.id}/rows/999999.json"
+ expect(response).to have_http_status(:not_found)
+ end
+
+ it "returns 404 for non-existent data table" do
+ delete "/admin/plugins/discourse-workflows/data-tables/999999/rows/#{row["id"]}.json"
+ expect(response).to have_http_status(:not_found)
+ end
+ end
+end
diff --git a/plugins/discourse-workflows/spec/requests/discourse_workflows/data_tables_controller_spec.rb b/plugins/discourse-workflows/spec/requests/discourse_workflows/data_tables_controller_spec.rb
new file mode 100644
index 00000000000..125fb4cdae2
--- /dev/null
+++ b/plugins/discourse-workflows/spec/requests/discourse_workflows/data_tables_controller_spec.rb
@@ -0,0 +1,207 @@
+# frozen_string_literal: true
+
+RSpec.describe DiscourseWorkflows::DataTablesController do
+ fab!(:admin)
+ fab!(:user)
+
+ before { sign_in(admin) }
+
+ shared_examples "requires admin" do |method, path_proc, params_proc = nil|
+ it "returns 404 when not logged in" do
+ sign_in(Fabricate(:anonymous))
+ public_send(
+ method,
+ instance_exec(&path_proc),
+ params: params_proc&.then { instance_exec(&_1) },
+ )
+ expect(response).to have_http_status(:not_found)
+ end
+
+ it "returns 404 when not admin" do
+ sign_in(user)
+ public_send(
+ method,
+ instance_exec(&path_proc),
+ params: params_proc&.then { instance_exec(&_1) },
+ )
+ expect(response).to have_http_status(:not_found)
+ end
+ end
+
+ describe "GET /admin/plugins/discourse-workflows/data-tables" do
+ fab!(:data_table, :discourse_workflows_data_table)
+
+ include_examples "requires admin",
+ :get,
+ -> { "/admin/plugins/discourse-workflows/data-tables.json" }
+
+ it "lists data tables" do
+ get "/admin/plugins/discourse-workflows/data-tables.json"
+ expect(response).to have_http_status(:ok)
+ json = response.parsed_body
+ expect(json["data_tables"].length).to eq(1)
+ expect(json["data_tables"][0]["name"]).to eq(data_table.name)
+ end
+
+ it "returns shared pagination meta" do
+ data_table_2 = Fabricate(:discourse_workflows_data_table, name: "Second")
+
+ get "/admin/plugins/discourse-workflows/data-tables.json", params: { limit: 1 }
+
+ json = response.parsed_body
+ expect(json["meta"]).to include(
+ "total_rows" => 2,
+ "load_more_url" =>
+ "/admin/plugins/discourse-workflows/data-tables.json?cursor=#{data_table_2.id}&limit=1",
+ )
+ end
+
+ it "paginates with cursor param" do
+ data_table_2 = Fabricate(:discourse_workflows_data_table, name: "Second")
+
+ get "/admin/plugins/discourse-workflows/data-tables.json",
+ params: {
+ cursor: data_table_2.id,
+ limit: 10,
+ }
+
+ json = response.parsed_body
+ expect(json["data_tables"].length).to eq(1)
+ expect(json["data_tables"][0]["id"]).to eq(data_table.id)
+ end
+ end
+
+ describe "GET /admin/plugins/discourse-workflows/data-tables/:id" do
+ fab!(:data_table, :discourse_workflows_data_table)
+
+ include_examples "requires admin",
+ :get,
+ -> { "/admin/plugins/discourse-workflows/data-tables/#{data_table.id}.json" }
+
+ it "returns the data table" do
+ get "/admin/plugins/discourse-workflows/data-tables/#{data_table.id}.json"
+ expect(response).to have_http_status(:ok)
+ json = response.parsed_body
+ expect(json["data_table"]).to include("id" => data_table.id, "name" => data_table.name)
+ end
+
+ it "returns 404 for non-existent data table" do
+ get "/admin/plugins/discourse-workflows/data-tables/999999.json"
+ expect(response).to have_http_status(:not_found)
+ end
+ end
+
+ describe "POST /admin/plugins/discourse-workflows/data-tables" do
+ include_examples "requires admin",
+ :post,
+ -> { "/admin/plugins/discourse-workflows/data-tables.json" },
+ -> { { name: "t" } }
+
+ it "creates a data table" do
+ post "/admin/plugins/discourse-workflows/data-tables.json",
+ params: {
+ name: "users",
+ columns: [{ "name" => "email", "type" => "string" }],
+ },
+ as: :json
+ expect(response).to have_http_status(:created)
+ json = response.parsed_body
+ expect(json["data_table"]["name"]).to eq("users")
+ expect(json["data_table"]["columns"]).to include(
+ include("name" => "email", "type" => "string"),
+ )
+ end
+
+ it "creates a data table when the modal submits only a name" do
+ post "/admin/plugins/discourse-workflows/data-tables.json", params: { name: "empty_table" }
+
+ expect(response).to have_http_status(:created)
+ body = response.parsed_body["data_table"]
+ expect(body["name"]).to eq("empty_table")
+ expect(body["columns"].map { |c| c["name"] }).to eq(%w[id created_at updated_at])
+ end
+ end
+
+ describe "PUT /admin/plugins/discourse-workflows/data-tables/:id" do
+ fab!(:data_table, :discourse_workflows_data_table)
+
+ include_examples "requires admin",
+ :put,
+ -> { "/admin/plugins/discourse-workflows/data-tables/#{data_table.id}.json" },
+ -> { { name: "t" } }
+
+ it "updates a data table" do
+ put "/admin/plugins/discourse-workflows/data-tables/#{data_table.id}.json",
+ params: {
+ name: "renamed",
+ }
+ expect(response).to have_http_status(:ok)
+ expect(response.parsed_body["data_table"]["name"]).to eq("renamed")
+ end
+
+ it "returns 404 for non-existent data table" do
+ put "/admin/plugins/discourse-workflows/data-tables/999999.json", params: { name: "test" }
+ expect(response).to have_http_status(:not_found)
+ end
+ end
+
+ describe "DELETE /admin/plugins/discourse-workflows/data-tables/:id" do
+ fab!(:data_table, :discourse_workflows_data_table)
+
+ include_examples "requires admin",
+ :delete,
+ -> { "/admin/plugins/discourse-workflows/data-tables/#{data_table.id}.json" }
+
+ it "deletes a data table" do
+ delete "/admin/plugins/discourse-workflows/data-tables/#{data_table.id}.json"
+ expect(response).to have_http_status(:no_content)
+ end
+
+ context "when data table is referenced by a workflow" do
+ fab!(:workflow) do
+ Fabricate(
+ :discourse_workflows_workflow,
+ name: "My Workflow",
+ created_by: admin,
+ nodes: [
+ {
+ "id" => "data-table-1",
+ "type" => "action:data_table",
+ "typeVersion" => "1.0",
+ "name" => "Data Table",
+ "position" => {
+ "x" => 0,
+ "y" => 0,
+ },
+ "parameters" => {
+ "data_table_id" => data_table.id,
+ },
+ "credentials" => {
+ },
+ },
+ ],
+ connections: {
+ },
+ )
+ end
+
+ before { DiscourseWorkflows::WorkflowDependencyIndexer.call(workflow) }
+
+ it "returns 422 with referencing workflow details" do
+ delete "/admin/plugins/discourse-workflows/data-tables/#{data_table.id}.json"
+
+ expect(response).to have_http_status(:unprocessable_entity)
+ body = response.parsed_body
+ expect(body["type"]).to eq("data_table_in_use")
+ expect(body["referencing_workflows"]).to contain_exactly(
+ { "id" => workflow.id, "name" => "My Workflow" },
+ )
+ end
+ end
+
+ it "returns 404 for non-existent data table" do
+ delete "/admin/plugins/discourse-workflows/data-tables/999999.json"
+ expect(response).to have_http_status(:not_found)
+ end
+ end
+end
diff --git a/plugins/discourse-workflows/spec/requests/discourse_workflows/dynamic_node_parameters_controller_spec.rb b/plugins/discourse-workflows/spec/requests/discourse_workflows/dynamic_node_parameters_controller_spec.rb
new file mode 100644
index 00000000000..7269756c1f4
--- /dev/null
+++ b/plugins/discourse-workflows/spec/requests/discourse_workflows/dynamic_node_parameters_controller_spec.rb
@@ -0,0 +1,311 @@
+# frozen_string_literal: true
+
+RSpec.describe DiscourseWorkflows::DynamicNodeParametersController do
+ fab!(:admin)
+
+ before { sign_in(admin) }
+
+ describe "POST /admin/plugins/discourse-workflows/dynamic-node-parameters/options" do
+ fab!(:badge) { Fabricate(:badge, name: "Helpful") }
+ fab!(:group_1) { Fabricate(:group, name: "alpha") }
+
+ it "returns options for a known load options method" do
+ post "/admin/plugins/discourse-workflows/dynamic-node-parameters/options.json",
+ params: {
+ nodeTypeAndVersion: {
+ name: "action:badge",
+ version: "1.0",
+ },
+ path: "badge_id",
+ methodName: "badges",
+ currentNodeParameters: {
+ },
+ },
+ as: :json
+
+ expect(response).to have_http_status(:ok)
+ expect(response.parsed_body).to include("id" => badge.id, "name" => badge.name)
+ end
+
+ it "returns groups for the group node" do
+ post "/admin/plugins/discourse-workflows/dynamic-node-parameters/options.json",
+ params: {
+ nodeTypeAndVersion: {
+ name: "action:group",
+ version: "1.0",
+ },
+ path: "group_id",
+ methodName: "groups",
+ currentNodeParameters: {
+ },
+ },
+ as: :json
+
+ expect(response).to have_http_status(:ok)
+ expect(response.parsed_body).to include("id" => group_1.id, "name" => group_1.name)
+ end
+
+ it "returns 404 for an unknown node type" do
+ post "/admin/plugins/discourse-workflows/dynamic-node-parameters/options.json",
+ params: {
+ nodeTypeAndVersion: {
+ name: "action:unknown",
+ version: "1.0",
+ },
+ path: "badge_id",
+ methodName: "badges",
+ },
+ as: :json
+
+ expect(response).to have_http_status(:not_found)
+ end
+
+ it "returns 404 for an unknown load options method" do
+ post "/admin/plugins/discourse-workflows/dynamic-node-parameters/options.json",
+ params: {
+ nodeTypeAndVersion: {
+ name: "action:badge",
+ version: "1.0",
+ },
+ path: "badge_id",
+ methodName: "nonexistent",
+ },
+ as: :json
+
+ expect(response).to have_http_status(:not_found)
+ end
+
+ it "passes compatible dynamic parameter context to context-aware nodes" do
+ credential =
+ Fabricate(
+ :discourse_workflows_credential,
+ credential_type: "basic_auth",
+ data: {
+ "user" => "static-user",
+ "password" => "static-password",
+ },
+ )
+ node_class =
+ Class.new(DiscourseWorkflows::NodeType) do
+ description(
+ name: "action:load_options_context_test",
+ credentials: [
+ {
+ name: "auth",
+ credential_types: %w[basic_auth],
+ display_options: {
+ show: {
+ authentication: %w[basic_auth],
+ },
+ },
+ },
+ ],
+ )
+
+ def self.load_options_context(context)
+ [
+ {
+ id: context.get_current_node_parameter("operation"),
+ name: context.filter,
+ method_name: context.method_name,
+ property_name: context.property_name,
+ workflow_id: context.workflow_id,
+ credential_slots: context.credentials.keys,
+ credential_user: context.get_credentials("auth")["user"],
+ node_id: context.node_id,
+ input_subject: context.input_context.dig("item", "json", "subject"),
+ execution_value: context.execution_context.dig("preview", "value"),
+ user_id: context.user.id,
+ },
+ ]
+ end
+ end
+
+ DiscoursePluginRegistry.register_discourse_workflows_node(node_class, Plugin::Instance.new)
+ DiscourseWorkflows::Registry.reset_indexes!
+
+ post "/admin/plugins/discourse-workflows/dynamic-node-parameters/options.json",
+ params: {
+ nodeTypeAndVersion: {
+ name: "action:load_options_context_test",
+ version: "1.0",
+ },
+ path: "thing_id",
+ methodName: "things",
+ currentNodeParameters: {
+ authentication: "basic_auth",
+ operation: "list",
+ },
+ credentials: {
+ auth: {
+ id: credential.id,
+ credential_type: "basic_auth",
+ },
+ ignored: {
+ id: credential.id,
+ credential_type: "basic_auth",
+ },
+ },
+ node: {
+ id: "node-1",
+ name: "Context test",
+ },
+ workflowId: "42",
+ inputContext: {
+ item: {
+ json: {
+ subject: "From input item",
+ },
+ },
+ },
+ executionContext: {
+ preview: {
+ value: "from-preview",
+ },
+ },
+ filter: "alp",
+ },
+ as: :json
+
+ expect(response).to have_http_status(:ok)
+ expect(response.parsed_body).to contain_exactly(
+ "id" => "list",
+ "name" => "alp",
+ "method_name" => "things",
+ "property_name" => "thing_id",
+ "workflow_id" => "42",
+ "credential_slots" => ["auth"],
+ "credential_user" => "static-user",
+ "node_id" => "node-1",
+ "input_subject" => "From input item",
+ "execution_value" => "from-preview",
+ "user_id" => admin.id,
+ )
+ ensure
+ DiscoursePluginRegistry._raw_discourse_workflows_nodes.reject! do |entry|
+ entry[:value] == node_class
+ end
+ DiscourseWorkflows::Registry.reset_indexes!
+ end
+
+ it "uses the requested node version when loading options" do
+ v1 =
+ Class.new(DiscourseWorkflows::NodeType) do
+ description(name: "action:load_options_version_test", version: "1.0")
+
+ def self.load_options_context(_context)
+ [{ id: "v1", name: "Version 1" }]
+ end
+ end
+ v2 =
+ Class.new(DiscourseWorkflows::NodeType) do
+ description(name: "action:load_options_version_test", version: "2.0")
+
+ def self.load_options_context(_context)
+ [{ id: "v2", name: "Version 2" }]
+ end
+ end
+
+ DiscoursePluginRegistry.register_discourse_workflows_node(v1, Plugin::Instance.new)
+ DiscoursePluginRegistry.register_discourse_workflows_node(v2, Plugin::Instance.new)
+ DiscourseWorkflows::Registry.reset_indexes!
+
+ post "/admin/plugins/discourse-workflows/dynamic-node-parameters/options.json",
+ params: {
+ nodeTypeAndVersion: {
+ name: "action:load_options_version_test",
+ version: "1.0",
+ },
+ path: "thing_id",
+ methodName: "things",
+ },
+ as: :json
+
+ expect(response).to have_http_status(:ok)
+ expect(response.parsed_body).to contain_exactly("id" => "v1", "name" => "Version 1")
+
+ post "/admin/plugins/discourse-workflows/dynamic-node-parameters/options.json",
+ params: {
+ nodeTypeAndVersion: {
+ name: "action:load_options_version_test",
+ version: "2.0",
+ },
+ path: "thing_id",
+ methodName: "things",
+ },
+ as: :json
+
+ expect(response).to have_http_status(:ok)
+ expect(response.parsed_body).to contain_exactly("id" => "v2", "name" => "Version 2")
+ ensure
+ DiscoursePluginRegistry._raw_discourse_workflows_nodes.reject! do |entry|
+ [v1, v2].include?(entry[:value])
+ end
+ DiscourseWorkflows::Registry.reset_indexes!
+ end
+
+ it "requires exact node versions when loading options" do
+ node_class =
+ Class.new(DiscourseWorkflows::NodeType) do
+ description(name: "action:exact_load_options_version_test", version: "1.0")
+
+ def self.load_options_context(_context)
+ [{ id: "v1", name: "Version 1" }]
+ end
+ end
+
+ DiscoursePluginRegistry.register_discourse_workflows_node(node_class, Plugin::Instance.new)
+ DiscourseWorkflows::Registry.reset_indexes!
+
+ post "/admin/plugins/discourse-workflows/dynamic-node-parameters/options.json",
+ params: {
+ nodeTypeAndVersion: {
+ name: "action:exact_load_options_version_test",
+ version: 1,
+ },
+ path: "thing_id",
+ methodName: "things",
+ },
+ as: :json
+
+ expect(response).to have_http_status(:not_found)
+ ensure
+ DiscoursePluginRegistry._raw_discourse_workflows_nodes.reject! do |entry|
+ entry[:value] == node_class
+ end
+ DiscourseWorkflows::Registry.reset_indexes!
+ end
+
+ it "requires the context-aware option loader" do
+ node_class =
+ Class.new(DiscourseWorkflows::NodeType) do
+ description(name: "action:load_options_method_test")
+
+ def self.load_options(method_name)
+ [{ id: method_name, name: method_name.upcase }]
+ end
+ end
+
+ DiscoursePluginRegistry.register_discourse_workflows_node(node_class, Plugin::Instance.new)
+ DiscourseWorkflows::Registry.reset_indexes!
+
+ post "/admin/plugins/discourse-workflows/dynamic-node-parameters/options.json",
+ params: {
+ nodeTypeAndVersion: {
+ name: "action:load_options_method_test",
+ version: "1.0",
+ },
+ path: "thing_id",
+ methodName: "things",
+ },
+ as: :json
+
+ expect(response).to have_http_status(:not_found)
+ ensure
+ DiscoursePluginRegistry._raw_discourse_workflows_nodes.reject! do |entry|
+ entry[:value] == node_class
+ end
+ DiscourseWorkflows::Registry.reset_indexes!
+ end
+ end
+end
diff --git a/plugins/discourse-workflows/spec/requests/discourse_workflows/executions_controller_spec.rb b/plugins/discourse-workflows/spec/requests/discourse_workflows/executions_controller_spec.rb
new file mode 100644
index 00000000000..044cb2fc9ca
--- /dev/null
+++ b/plugins/discourse-workflows/spec/requests/discourse_workflows/executions_controller_spec.rb
@@ -0,0 +1,201 @@
+# frozen_string_literal: true
+
+RSpec.describe DiscourseWorkflows::ExecutionsController do
+ fab!(:admin)
+ fab!(:workflow) { Fabricate(:discourse_workflows_workflow, created_by: admin) }
+
+ before { sign_in(admin) }
+
+ def workflow_snapshot_data(name)
+ { "name" => name, "nodes" => [], "connections" => {} }
+ end
+
+ context "when not logged in as admin" do
+ fab!(:user)
+
+ before { sign_in(user) }
+
+ it "returns 404" do
+ get "/admin/plugins/discourse-workflows/executions.json"
+ expect(response).to have_http_status(:not_found)
+ end
+ end
+
+ describe "POST /admin/plugins/discourse-workflows/executions" do
+ fab!(:published_workflow) do
+ graph = build_workflow_graph { |g| g.node "trigger-1", "trigger:manual" }
+ Fabricate(:discourse_workflows_workflow, created_by: admin, published: true, **graph)
+ end
+
+ it "creates an execution" do
+ post "/admin/plugins/discourse-workflows/executions.json",
+ params: {
+ workflow_id: published_workflow.id,
+ trigger_node_id: "trigger-1",
+ }
+
+ expect(response).to have_http_status(:created)
+ end
+
+ it "returns 404 when trigger node does not exist" do
+ post "/admin/plugins/discourse-workflows/executions.json",
+ params: {
+ workflow_id: workflow.id,
+ trigger_node_id: "nonexistent",
+ }
+ expect(response).to have_http_status(:not_found)
+ end
+
+ it "forwards the current user id in service params" do
+ DiscourseWorkflows::Workflow::ManualExecute
+ .expects(:call)
+ .with { |kwargs| kwargs.dig(:params, :user_id) == admin.id }
+ .returns(Service::Base::Context.build)
+
+ post "/admin/plugins/discourse-workflows/executions.json",
+ params: {
+ workflow_id: published_workflow.id,
+ trigger_node_id: "trigger-1",
+ }
+
+ expect(response).to have_http_status(:no_content)
+ end
+ end
+
+ describe "GET /admin/plugins/discourse-workflows/executions" do
+ it "returns executions" do
+ execution = Fabricate(:discourse_workflows_completed_execution, workflow: workflow)
+
+ get "/admin/plugins/discourse-workflows/executions.json"
+
+ expect(response).to have_http_status(:ok)
+ json = response.parsed_body
+ expect(json["executions"].length).to eq(1)
+ expect(json["executions"][0]).to include(
+ "id" => execution.id,
+ "workflow_name" => workflow.name,
+ )
+ end
+
+ it "returns the stored snapshot workflow name" do
+ execution = Fabricate(:discourse_workflows_completed_execution, workflow: workflow)
+ Fabricate(
+ :discourse_workflows_execution_data,
+ execution: execution,
+ workflow_data: workflow_snapshot_data("Original workflow"),
+ )
+ workflow.update!(name: "Renamed workflow")
+
+ get "/admin/plugins/discourse-workflows/executions.json"
+
+ expect(response).to have_http_status(:ok)
+ json = response.parsed_body
+ expect(json["executions"][0]).to include(
+ "id" => execution.id,
+ "workflow_name" => "Original workflow",
+ )
+ end
+
+ it "paginates with cursor param" do
+ execution_1 = Fabricate(:discourse_workflows_execution, workflow: workflow)
+ execution_2 = Fabricate(:discourse_workflows_execution, workflow: workflow)
+
+ get "/admin/plugins/discourse-workflows/executions.json",
+ params: {
+ cursor: execution_2.id,
+ limit: 10,
+ }
+
+ json = response.parsed_body
+ expect(json["executions"].length).to eq(1)
+ expect(json["executions"][0]["id"]).to eq(execution_1.id)
+ end
+ end
+
+ describe "GET /admin/plugins/discourse-workflows/workflows/:workflow_id/executions" do
+ it "returns executions for the workflow" do
+ execution = Fabricate(:discourse_workflows_completed_execution, workflow: workflow)
+ Fabricate(:discourse_workflows_completed_execution)
+
+ get "/admin/plugins/discourse-workflows/workflows/#{workflow.id}/executions.json"
+
+ expect(response).to have_http_status(:ok)
+ json = response.parsed_body
+ expect(json["executions"].length).to eq(1)
+ expect(json["executions"][0]["id"]).to eq(execution.id)
+ end
+
+ it "returns the stored snapshot workflow name" do
+ execution = Fabricate(:discourse_workflows_completed_execution, workflow: workflow)
+ Fabricate(:discourse_workflows_completed_execution)
+ Fabricate(
+ :discourse_workflows_execution_data,
+ execution: execution,
+ workflow_data: workflow_snapshot_data("Original workflow"),
+ )
+ workflow.update!(name: "Renamed workflow")
+
+ get "/admin/plugins/discourse-workflows/workflows/#{workflow.id}/executions.json"
+
+ expect(response).to have_http_status(:ok)
+ json = response.parsed_body
+ expect(json["executions"][0]).to include(
+ "id" => execution.id,
+ "workflow_name" => "Original workflow",
+ )
+ end
+
+ it "returns empty when no executions exist" do
+ get "/admin/plugins/discourse-workflows/workflows/#{workflow.id}/executions.json"
+
+ expect(response).to have_http_status(:ok)
+ expect(response.parsed_body["executions"]).to be_empty
+ end
+ end
+
+ describe "DELETE /admin/plugins/discourse-workflows/executions" do
+ fab!(:execution) { Fabricate(:discourse_workflows_completed_execution, workflow: workflow) }
+
+ it "deletes executions" do
+ delete "/admin/plugins/discourse-workflows/executions.json", params: { ids: [execution.id] }
+
+ expect(response).to have_http_status(:no_content)
+ expect(DiscourseWorkflows::Execution.exists?(execution.id)).to be(false)
+ end
+ end
+
+ describe "GET /admin/plugins/discourse-workflows/executions/:id" do
+ fab!(:execution) { Fabricate(:discourse_workflows_completed_execution, workflow: workflow) }
+
+ before { Fabricate(:discourse_workflows_execution_data_with_steps, execution: execution) }
+
+ it "returns the execution with steps" do
+ get "/admin/plugins/discourse-workflows/executions/#{execution.id}.json"
+
+ expect(response).to have_http_status(:ok)
+ json = response.parsed_body
+ expect(json["execution"]["id"]).to eq(execution.id)
+ expect(json["execution"]["workflow_name"]).to eq(workflow.name)
+ expect(json["execution"]["steps"].length).to eq(1)
+ end
+
+ it "returns the stored snapshot workflow name" do
+ execution.execution_data.update!(workflow_data: workflow_snapshot_data("Original workflow"))
+ workflow.update!(name: "Renamed workflow")
+
+ get "/admin/plugins/discourse-workflows/executions/#{execution.id}.json"
+
+ expect(response).to have_http_status(:ok)
+ json = response.parsed_body
+ expect(json["execution"]).to include(
+ "id" => execution.id,
+ "workflow_name" => "Original workflow",
+ )
+ end
+
+ it "returns 404 when execution does not exist" do
+ get "/admin/plugins/discourse-workflows/executions/-1.json"
+ expect(response).to have_http_status(:not_found)
+ end
+ end
+end
diff --git a/plugins/discourse-workflows/spec/requests/discourse_workflows/expressions_controller_spec.rb b/plugins/discourse-workflows/spec/requests/discourse_workflows/expressions_controller_spec.rb
new file mode 100644
index 00000000000..4aaebf70cc0
--- /dev/null
+++ b/plugins/discourse-workflows/spec/requests/discourse_workflows/expressions_controller_spec.rb
@@ -0,0 +1,48 @@
+# frozen_string_literal: true
+
+RSpec.describe DiscourseWorkflows::ExpressionsController do
+ fab!(:admin)
+ fab!(:user_1, :user)
+
+ before { sign_in(admin) }
+
+ describe "POST /admin/plugins/discourse-workflows/expressions/evaluate" do
+ let(:endpoint) { "/admin/plugins/discourse-workflows/expressions/evaluate.json" }
+
+ it "returns the resolved segments for a valid template" do
+ post endpoint, params: { template: "Hello world" }
+
+ expect(response).to have_http_status(:ok)
+ expect(response.parsed_body["segments"]).to contain_exactly(
+ { "kind" => "plaintext", "text" => "Hello world" },
+ )
+ end
+
+ it "is rate limited" do
+ RateLimiter.enable
+
+ freeze_time do
+ 30.times do
+ post endpoint, params: { template: "test" }
+ expect(response).to have_http_status(:ok)
+ end
+
+ post endpoint, params: { template: "test" }
+ expect(response).to have_http_status(:too_many_requests)
+ end
+ ensure
+ RateLimiter.disable
+ end
+
+ it "requires the template parameter" do
+ post endpoint, params: {}
+ expect(response).to have_http_status(:bad_request)
+ end
+
+ it "requires admin access" do
+ sign_in(user_1)
+ post endpoint, params: { template: "test" }
+ expect(response).to have_http_status(:not_found)
+ end
+ end
+end
diff --git a/plugins/discourse-workflows/spec/requests/discourse_workflows/form_test_sessions_controller_spec.rb b/plugins/discourse-workflows/spec/requests/discourse_workflows/form_test_sessions_controller_spec.rb
new file mode 100644
index 00000000000..128be1b03f6
--- /dev/null
+++ b/plugins/discourse-workflows/spec/requests/discourse_workflows/form_test_sessions_controller_spec.rb
@@ -0,0 +1,34 @@
+# frozen_string_literal: true
+
+RSpec.describe DiscourseWorkflows::FormTestSessionsController do
+ fab!(:admin)
+ fab!(:workflow) do
+ graph = build_workflow_graph { |g| g.node "trigger-1", "trigger:form" }
+ Fabricate(:discourse_workflows_workflow, created_by: admin, published: false, **graph)
+ end
+
+ describe "POST /admin/plugins/discourse-workflows/workflows/:id/form-test-sessions.json" do
+ it "requires an admin" do
+ sign_in(Fabricate(:user))
+
+ post "/admin/plugins/discourse-workflows/workflows/#{workflow.id}/form-test-sessions.json",
+ params: {
+ trigger_node_id: "trigger-1",
+ }
+
+ expect(response).to have_http_status(:not_found)
+ end
+
+ it "creates a short-lived form test session" do
+ sign_in(admin)
+
+ post "/admin/plugins/discourse-workflows/workflows/#{workflow.id}/form-test-sessions.json",
+ params: {
+ trigger_node_id: "trigger-1",
+ }
+
+ expect(response).to have_http_status(:created)
+ expect(response.parsed_body["test_url"]).to match(%r{\A/workflows/form-test/[0-9a-f-]{36}\z})
+ end
+ end
+end
diff --git a/plugins/discourse-workflows/spec/requests/discourse_workflows/forms_controller_spec.rb b/plugins/discourse-workflows/spec/requests/discourse_workflows/forms_controller_spec.rb
new file mode 100644
index 00000000000..604b0dad99f
--- /dev/null
+++ b/plugins/discourse-workflows/spec/requests/discourse_workflows/forms_controller_spec.rb
@@ -0,0 +1,830 @@
+# frozen_string_literal: true
+
+RSpec.describe DiscourseWorkflows::FormsController do
+ fab!(:workflow) do
+ graph =
+ build_workflow_graph do |g|
+ g.node "trigger-1",
+ "trigger:form",
+ name: "Form Trigger",
+ configuration: {
+ "uuid" => "a1b2c3d4-e5f6-7890-abcd-ef0123456789",
+ "form_title" => "Test Form",
+ "form_fields" => [
+ { "field_label" => "Name", "field_type" => "text", "required" => true },
+ ],
+ "response_mode" => "on_received",
+ }
+ end
+ Fabricate(:discourse_workflows_workflow, published: true, **graph)
+ end
+
+ let(:form_uuid) { workflow.nodes.find { |n| n["type"] == "trigger:form" }["webhookId"] }
+ let(:form_path) { "/workflows/form/#{form_uuid}.json" }
+
+ let(:origin_headers) { { "Origin" => "http://#{Discourse.current_hostname}" } }
+ let(:initial_resume_token) do
+ get form_path
+ expect(response).to have_http_status(:ok)
+ response.parsed_body["resume_token"]
+ end
+
+ describe "GET /workflows/form/:uuid.json" do
+ it "returns form schema" do
+ expect { get form_path }.not_to change { DiscourseWorkflows::Execution.count }
+
+ expect(response).to have_http_status(:ok)
+ json = response.parsed_body
+ expect(json["form_title"]).to eq("Test Form")
+ expect(json["fields"].length).to eq(1)
+ expect(json["fields"].first["name"]).to eq("name")
+ expect(json["data"]).to eq("name" => "")
+ expect(json["form_submit_url"]).to eq(form_path)
+ expect(json).not_to have_key("form_fields")
+ expect(json["resume_token"]).to be_present
+ end
+
+ it "returns 404 for unknown uuid" do
+ get "/workflows/form/00000000-0000-0000-0000-000000000000.json"
+ expect(response).to have_http_status(:not_found)
+ end
+
+ it "returns 404 for unpublished workflow" do
+ unpublish_workflow!(workflow)
+ get form_path
+ expect(response).to have_http_status(:not_found)
+ end
+
+ it "rate limits repeated show requests" do
+ RateLimiter.any_instance.expects(:performed!).raises(RateLimiter::LimitExceeded.new(60))
+
+ get form_path
+
+ expect(response).to have_http_status(:too_many_requests)
+ end
+
+ context "when the form requires a logged-in user" do
+ fab!(:user)
+
+ before do
+ trigger_node = workflow.nodes.find { |n| n["type"] == "trigger:form" }
+ trigger_node["parameters"]["authentication"] = "login_required"
+ workflow.update!(nodes: workflow.nodes)
+ publish_workflow!(workflow)
+ end
+
+ it "returns 403 for anonymous users" do
+ get form_path
+ expect(response).to have_http_status(:forbidden)
+ end
+
+ it "returns form schema for logged-in users" do
+ sign_in(user)
+ get form_path
+ expect(response).to have_http_status(:ok)
+ end
+ end
+ end
+
+ describe "POST /workflows/form/:uuid.json" do
+ it "executes workflow without returning a raw waiting token" do
+ post form_path,
+ params: {
+ resume_token: initial_resume_token,
+ form_data: {
+ name: "Test User",
+ },
+ },
+ headers: origin_headers
+ expect(response).to have_http_status(:ok)
+
+ json = response.parsed_body
+ expect(json).not_to have_key("resume_token")
+
+ execution = DiscourseWorkflows::Execution.last
+ expect(execution.trigger_node_id).to eq("trigger-1")
+ expect(execution.execution_data.context_data["__resume_token"]).to be_present
+ end
+
+ it "stores initial URL query parameters in the trigger payload" do
+ get form_path, params: { source: "email", ref: "spring" }
+ expect(response).to have_http_status(:ok)
+
+ post form_path,
+ params: {
+ resume_token: response.parsed_body["resume_token"],
+ form_data: {
+ name: "Test User",
+ },
+ },
+ headers: origin_headers
+
+ execution = DiscourseWorkflows::Execution.last
+ expect(execution.trigger_data).to include(
+ "name" => "Test User",
+ "form_mode" => "production",
+ "form_query_parameters" => {
+ "source" => "email",
+ "ref" => "spring",
+ },
+ )
+ expect(execution.trigger_data).not_to have_key("form_data")
+ end
+
+ context "when response mode waits for the workflow to finish" do
+ before do
+ update_workflow_node(workflow, "trigger-1") do |node|
+ node["parameters"]["response_mode"] = "workflow_finishes"
+ end
+ publish_workflow!(workflow)
+ end
+
+ it "returns no response body after a successful execution without Form Ending output" do
+ post form_path,
+ params: {
+ resume_token: initial_resume_token,
+ form_data: {
+ name: "Test User",
+ },
+ },
+ headers: origin_headers
+ expect(response).to have_http_status(:ok)
+ expect(response.body).to be_blank
+ end
+
+ it "returns an error response when the workflow fails" do
+ extra =
+ build_workflow_graph do |g|
+ g.node "wait-1",
+ "flow:wait",
+ configuration: {
+ "resume" => "time_interval",
+ "wait_amount" => 0,
+ "wait_unit" => "seconds",
+ }
+ end
+ workflow.update!(
+ nodes: workflow.nodes + extra[:nodes],
+ connections:
+ workflow_connections_for(workflow.nodes + extra[:nodes], %w[trigger-1 wait-1]),
+ )
+ publish_workflow!(workflow)
+
+ post form_path,
+ params: {
+ resume_token: initial_resume_token,
+ form_data: {
+ name: "Test User",
+ },
+ },
+ headers: origin_headers
+ expect(response).to have_http_status(:internal_server_error)
+ expect(response.parsed_body).to include(
+ "response_mode" => "workflow_finishes",
+ "status" => "error",
+ "errors" => [I18n.t("discourse_workflows.errors.workflow_failed")],
+ )
+ expect(response.parsed_body).not_to have_key("error")
+ expect(DiscourseWorkflows::Execution.last).to have_attributes(status: "error")
+ end
+
+ it "returns no response body for non-form waits" do
+ extra =
+ build_workflow_graph do |g|
+ g.node "wait-1",
+ "flow:wait",
+ configuration: {
+ "resume" => "time_interval",
+ "wait_amount" => 1,
+ "wait_unit" => "hours",
+ }
+ end
+ workflow.update!(
+ nodes: workflow.nodes + extra[:nodes],
+ connections:
+ workflow_connections_for(workflow.nodes + extra[:nodes], %w[trigger-1 wait-1]),
+ )
+ publish_workflow!(workflow)
+
+ post form_path,
+ params: {
+ resume_token: initial_resume_token,
+ form_data: {
+ name: "Test User",
+ },
+ },
+ headers: origin_headers
+ expect(response).to have_http_status(:ok)
+ expect(response.body).to be_blank
+ expect(DiscourseWorkflows::Execution.last).to have_attributes(status: "waiting")
+ end
+ end
+
+ it "returns 422 when the initial submission token is missing" do
+ post form_path, params: { form_data: { name: "Test User" } }, headers: origin_headers
+
+ expect(response).to have_http_status(:unprocessable_entity)
+ expect(response.parsed_body).to include(
+ "errors" => [I18n.t("discourse_workflows.errors.invalid_form_token")],
+ )
+ expect(response.parsed_body).not_to have_key("error")
+ end
+
+ it "returns 422 with structured errors when required fields are omitted" do
+ post form_path,
+ params: {
+ resume_token: initial_resume_token,
+ form_data: {
+ },
+ },
+ headers: origin_headers
+ expect(response).to have_http_status(:unprocessable_entity)
+ expect(response.parsed_body["errors"]).to eq(
+ [{ "field_label" => "Name", "code" => "missing" }],
+ )
+ expect(response.parsed_body).not_to have_key("error")
+ end
+
+ context "when the form requires a logged-in user" do
+ fab!(:user)
+
+ before do
+ trigger_node = workflow.nodes.find { |n| n["type"] == "trigger:form" }
+ trigger_node["parameters"]["authentication"] = "login_required"
+ workflow.update!(nodes: workflow.nodes)
+ publish_workflow!(workflow)
+ end
+
+ it "returns 403 for anonymous users" do
+ post form_path, params: { form_data: { name: "Test User" } }, headers: origin_headers
+ expect(response).to have_http_status(:forbidden)
+ end
+
+ it "executes workflow for logged-in users" do
+ sign_in(user)
+ post form_path,
+ params: {
+ resume_token: initial_resume_token,
+ form_data: {
+ name: "Test User",
+ },
+ },
+ headers: origin_headers
+ expect(response).to have_http_status(:ok)
+ end
+ end
+ end
+
+ describe "/workflows/form-test/:token.json" do
+ fab!(:admin)
+
+ let(:test_path) do
+ sign_in(admin)
+ post "/admin/plugins/discourse-workflows/workflows/#{workflow.id}/form-test-sessions.json",
+ params: {
+ trigger_node_id: "trigger-1",
+ }
+ response.parsed_body["test_url"]
+ end
+
+ before do
+ update_workflow_node(workflow, "trigger-1") do |node|
+ node["parameters"]["form_title"] = "Draft Test Form"
+ node["parameters"]["form_fields"] = [
+ { "field_label" => "Draft name", "field_type" => "text", "required" => true },
+ ]
+ end
+ workflow.update!(active_version_id: nil)
+ end
+
+ it "serves the draft form schema for the test session owner" do
+ get "#{test_path}.json", params: { draft_name: "Ignored default" }
+
+ expect(response).to have_http_status(:ok)
+ expect(response.parsed_body).to include(
+ "form_title" => "Draft Test Form",
+ "form_mode" => "test",
+ "form_submit_url" => "#{test_path}.json",
+ )
+ expect(response.parsed_body["data"]).to eq("draft_name" => "")
+ end
+
+ it "serves the app shell for the public test form URL" do
+ get test_path
+
+ expect(response).to have_http_status(:ok)
+ expect(response.media_type).to eq("text/html")
+ end
+
+ it "returns 404 for an expired or invalid test session" do
+ get "/workflows/form-test/00000000-0000-0000-0000-000000000000.json"
+
+ expect(response).to have_http_status(:not_found)
+ end
+
+ it "rejects a test session opened by another user" do
+ path = test_path
+ other_admin = Fabricate(:admin)
+ sign_in(other_admin)
+
+ get path
+
+ expect(response).to have_http_status(:ok)
+ expect(response.media_type).to eq("text/html")
+
+ get "#{path}.json"
+
+ expect(response).to have_http_status(:forbidden)
+ end
+
+ it "runs a manual draft execution with test form mode and no query parameters" do
+ messages =
+ MessageBus.track_publish("/discourse-workflows/workflow/#{workflow.id}") do
+ post "#{test_path}.json?source=query-param",
+ params: {
+ form_data: {
+ draft_name: "Test User",
+ },
+ },
+ headers: origin_headers
+ end
+
+ expect(response).to have_http_status(:ok)
+
+ execution = DiscourseWorkflows::Execution.last
+ expect(execution).to be_manual
+ expect(execution.trigger_data).to include("draft_name" => "Test User", "form_mode" => "test")
+ expect(execution.trigger_data).not_to have_key("form_query_parameters")
+ expect(execution.execution_data.workflow_data["nodes"]).to contain_exactly(
+ include("id" => "trigger-1", "parameters" => include("form_title" => "Draft Test Form")),
+ )
+ expect(messages.length).to eq(1)
+ expect(messages.first.data).to include(type: "execution_completed")
+ expect(
+ messages.first.data.dig(:lastExecutionRunData, "Form Trigger", 0, "outputs"),
+ ).to contain_exactly(
+ include(
+ "index" => 0,
+ "items" =>
+ contain_exactly(
+ include("json" => include("draft_name" => "Test User", "form_mode" => "test")),
+ ),
+ ),
+ )
+ end
+
+ it "preserves test form mode through downstream form pages" do
+ extra =
+ build_workflow_graph do |g|
+ g.node "form-action-1",
+ "action:form",
+ configuration: {
+ "page_type" => "page",
+ "form_fields" => [
+ { "field_label" => "Email", "field_type" => "text", "required" => false },
+ ],
+ }
+ end
+ workflow.update!(
+ nodes: workflow.nodes + extra[:nodes],
+ connections:
+ workflow_connections_for(workflow.nodes + extra[:nodes], %w[trigger-1 form-action-1]),
+ )
+
+ post "#{test_path}.json",
+ params: {
+ form_data: {
+ draft_name: "Test User",
+ },
+ },
+ headers: origin_headers
+ expect(response).to have_http_status(:ok)
+ expect(response.parsed_body["form_waiting_url"]).to be_present
+
+ post response.parsed_body["form_submit_url"],
+ params: {
+ form_data: {
+ email: "[email protected]",
+ },
+ },
+ headers: origin_headers
+ expect(response).to have_http_status(:ok)
+
+ form_step =
+ DiscourseWorkflows::Execution.last.execution_data.steps_array.find do |step|
+ step["node_id"] == "form-action-1"
+ end
+ expect(form_step.dig("output", 0, "json")).to include(
+ "email" => "[email protected]",
+ "form_mode" => "test",
+ )
+ end
+ end
+
+ describe "/workflows/forms/waiting/:execution_id.json" do
+ context "with a workflow containing a downstream form action" do
+ before do
+ extra =
+ build_workflow_graph do |g|
+ g.node "form-action-1",
+ "action:form",
+ name: "Second Page",
+ configuration: {
+ "page_type" => "page",
+ "form_fields" => [
+ { "field_label" => "Email", "field_type" => "text", "required" => false },
+ {
+ "field_label" => "Tracking ID",
+ "field_name" => "tracking_id",
+ "field_type" => "hiddenField",
+ },
+ ],
+ }
+ g.node "form-completion-1",
+ "action:form",
+ name: "Completion",
+ configuration: {
+ "page_type" => "completion",
+ "on_submission" => "completion_screen",
+ "completion_title" => "={{ $json.email }}",
+ "completion_message" => "={{ $trigger.name }}",
+ }
+ end
+ workflow.update!(
+ nodes: workflow.nodes + extra[:nodes],
+ connections:
+ workflow_connections_for(
+ workflow.nodes + extra[:nodes],
+ %w[trigger-1 form-action-1],
+ %w[form-action-1 form-completion-1],
+ ),
+ )
+ publish_workflow!(workflow)
+ end
+
+ it "returns signed waiting URLs without exposing the raw waiting token" do
+ post form_path,
+ params: {
+ resume_token: initial_resume_token,
+ form_data: {
+ name: "Test User",
+ },
+ },
+ headers: origin_headers
+ expect(response).to have_http_status(:ok)
+
+ expect(response.parsed_body).not_to have_key("resume_token")
+ expect(response.parsed_body["form_waiting_url"]).to be_present
+ expect(response.parsed_body["form_submit_url"]).to be_present
+ expect(response.parsed_body["form_status_url"]).to be_present
+
+ execution = DiscourseWorkflows::Execution.last
+ expect(execution.status).to eq("waiting")
+ expect(execution.waiting_node_id).to eq("form-action-1")
+ expect(
+ response
+ .parsed_body
+ .values_at("form_waiting_url", "form_submit_url", "form_status_url")
+ .join,
+ ).not_to include(execution.resume_token)
+
+ post response.parsed_body["form_submit_url"],
+ params: {
+ form_data: {
+ email: "[email protected]",
+ },
+ },
+ headers: origin_headers
+ expect(response).to have_http_status(:ok)
+ expect(response.parsed_body).not_to have_key("resume_token")
+
+ execution.reload
+ expect(execution.status).to eq("success")
+ end
+
+ it "serves and resumes a waiting form through waiting execution endpoints" do
+ post form_path,
+ params: {
+ resume_token: initial_resume_token,
+ form_data: {
+ name: "Test User",
+ },
+ },
+ headers: origin_headers
+ expect(response).to have_http_status(:ok)
+
+ waiting_url = response.parsed_body["form_waiting_url"]
+ submit_url = response.parsed_body["form_submit_url"]
+ status_url = response.parsed_body["form_status_url"]
+
+ get status_url
+ expect(response).to have_http_status(:ok)
+ expect(response.parsed_body["status"]).to eq("form_waiting")
+
+ get waiting_url
+ expect(response).to have_http_status(:ok)
+ expect(response.parsed_body).not_to have_key("resume_token")
+ expect(response.parsed_body["fields"].first["name"]).to eq("email")
+
+ post submit_url,
+ params: {
+ form_data: {
+ email: "[email protected]",
+ },
+ },
+ headers: origin_headers
+ expect(response).to have_http_status(:ok)
+ expect(response.parsed_body["status"]).to eq("success")
+ expect(response.parsed_body["form_completion"]).to include(
+ "completion_title" => "[email protected]",
+ "completion_message" => "Test User",
+ )
+ expect(DiscourseWorkflows::Execution.last.execution_data.context_data).not_to have_key(
+ "__form_completion",
+ )
+ completion_step =
+ DiscourseWorkflows::Execution.last.execution_data.steps_array.find do |step|
+ step["node_id"] == "form-completion-1"
+ end
+ expect(completion_step.dig("metadata", "form_completion")).to include(
+ "completion_title" => "[email protected]",
+ "completion_message" => "Test User",
+ )
+ end
+
+ it "returns an error when a waiting form resumes into a failing workflow" do
+ extra =
+ build_workflow_graph do |g|
+ g.node "wait-1",
+ "flow:wait",
+ configuration: {
+ "resume" => "time_interval",
+ "wait_amount" => 0,
+ "wait_unit" => "seconds",
+ }
+ end
+ workflow.update!(
+ nodes: workflow.nodes + extra[:nodes],
+ connections:
+ workflow_connections_for(
+ workflow.nodes + extra[:nodes],
+ %w[trigger-1 form-action-1],
+ %w[form-action-1 wait-1],
+ ),
+ )
+ publish_workflow!(workflow)
+
+ post form_path,
+ params: {
+ resume_token: initial_resume_token,
+ form_data: {
+ name: "Test User",
+ },
+ },
+ headers: origin_headers
+ expect(response).to have_http_status(:ok)
+
+ post response.parsed_body["form_submit_url"],
+ params: {
+ form_data: {
+ email: "[email protected]",
+ },
+ },
+ headers: origin_headers
+ expect(response).to have_http_status(:internal_server_error)
+ expect(response.parsed_body).to include(
+ "status" => "error",
+ "errors" => [I18n.t("discourse_workflows.errors.workflow_failed")],
+ )
+ expect(response.parsed_body).not_to have_key("error")
+ end
+
+ it "returns no response body when a waiting form resumes into a non-form wait" do
+ update_workflow_node(workflow, "trigger-1") do |node|
+ node["parameters"]["response_mode"] = "workflow_finishes"
+ end
+ extra =
+ build_workflow_graph do |g|
+ g.node "wait-1",
+ "flow:wait",
+ configuration: {
+ "resume" => "time_interval",
+ "wait_amount" => 1,
+ "wait_unit" => "hours",
+ }
+ end
+ workflow.update!(
+ nodes: workflow.nodes + extra[:nodes],
+ connections:
+ workflow_connections_for(
+ workflow.nodes + extra[:nodes],
+ %w[trigger-1 form-action-1],
+ %w[form-action-1 wait-1],
+ ),
+ )
+ publish_workflow!(workflow)
+
+ post form_path,
+ params: {
+ resume_token: initial_resume_token,
+ form_data: {
+ name: "Test User",
+ },
+ },
+ headers: origin_headers
+ expect(response).to have_http_status(:ok)
+
+ post response.parsed_body["form_submit_url"],
+ params: {
+ form_data: {
+ email: "[email protected]",
+ },
+ },
+ headers: origin_headers
+ expect(response).to have_http_status(:ok)
+ expect(response.body).to be_blank
+ expect(DiscourseWorkflows::Execution.last).to have_attributes(status: "waiting")
+ end
+
+ it "carries query-backed hidden values through downstream form pages" do
+ get form_path, params: { tracking_id: "campaign-42" }
+ expect(response).to have_http_status(:ok)
+
+ post form_path,
+ params: {
+ resume_token: response.parsed_body["resume_token"],
+ form_data: {
+ name: "Test User",
+ },
+ },
+ headers: origin_headers
+ expect(response).to have_http_status(:ok)
+
+ get response.parsed_body["form_waiting_url"]
+ expect(response).to have_http_status(:ok)
+ expect(response.parsed_body).not_to have_key("form_fields")
+ expect(response.parsed_body["fields"].pluck("name")).not_to include("tracking_id")
+
+ post response.parsed_body["form_submit_url"],
+ params: {
+ form_data: {
+ email: "[email protected]",
+ tracking_id: "client-tamper",
+ },
+ },
+ headers: origin_headers
+ expect(response).to have_http_status(:ok)
+
+ form_step =
+ DiscourseWorkflows::Execution.last.execution_data.steps_array.find do |step|
+ step["node_id"] == "form-action-1" &&
+ step["status"] == DiscourseWorkflows::Executor::Step::SUCCESS
+ end
+ expect(form_step.dig("output", 0, "json")).to include(
+ "email" => "[email protected]",
+ "tracking_id" => "campaign-42",
+ "form_query_parameters" => {
+ "tracking_id" => "campaign-42",
+ },
+ )
+ end
+
+ it "keeps workflow_finishes submissions waiting on the next FormKit page" do
+ trigger_node = workflow.nodes.find { |node| node["id"] == "trigger-1" }
+ trigger_node["parameters"]["response_mode"] = "workflow_finishes"
+ workflow.update!(nodes: workflow.nodes)
+ publish_workflow!(workflow)
+
+ post form_path,
+ params: {
+ resume_token: initial_resume_token,
+ form_data: {
+ name: "Test User",
+ },
+ },
+ headers: origin_headers
+ expect(response).to have_http_status(:ok)
+ expect(response.parsed_body).to include(
+ "response_mode" => "workflow_finishes",
+ "status" => "waiting",
+ )
+ expect(response.parsed_body["form_waiting_url"]).to be_present
+
+ get response.parsed_body["form_waiting_url"]
+ expect(response).to have_http_status(:ok)
+ expect(response.parsed_body["fields"].pluck("name")).to include("email")
+ end
+
+ it "returns sanitized HTML completion text" do
+ completion_node = workflow.nodes.find { |node| node["id"] == "form-completion-1" }
+ completion_node["parameters"].merge!(
+ "on_submission" => "show_text",
+ "completion_text" =>
+ '<strong>Done</strong><script>alert("x")</script><iframe src="https://example.com"></iframe>',
+ )
+ workflow.update!(nodes: workflow.nodes)
+ publish_workflow!(workflow)
+
+ post form_path,
+ params: {
+ resume_token: initial_resume_token,
+ form_data: {
+ name: "Test User",
+ },
+ },
+ headers: origin_headers
+ expect(response).to have_http_status(:ok)
+
+ post response.parsed_body["form_submit_url"],
+ params: {
+ form_data: {
+ email: "[email protected]",
+ },
+ },
+ headers: origin_headers
+ expect(response).to have_http_status(:ok)
+ expect(response.parsed_body["form_completion"]).to include(
+ "on_submission" => "show_text",
+ "completion_text" => "<strong>Done</strong>",
+ )
+ expect(response.parsed_body["form_completion"]["completion_text"]).not_to include(
+ "script",
+ "iframe",
+ )
+ end
+
+ it "returns 404 when the waiting signature does not match" do
+ post form_path,
+ params: {
+ resume_token: initial_resume_token,
+ form_data: {
+ name: "Test User",
+ },
+ },
+ headers: origin_headers
+ expect(response).to have_http_status(:ok)
+
+ get response.parsed_body["form_status_url"].sub(/signature=[^&]+/, "signature=invalid")
+ expect(response).to have_http_status(:not_found)
+ expect(response.parsed_body).to eq("errors" => ["not_found"])
+ end
+
+ it "returns plural errors when a waiting form resume loses the claim race" do
+ post form_path,
+ params: {
+ resume_token: initial_resume_token,
+ form_data: {
+ name: "Test User",
+ },
+ },
+ headers: origin_headers
+ submit_url = response.parsed_body["form_submit_url"]
+
+ allow(DiscourseWorkflows::WaitingExecution).to receive(:claim).and_return(nil)
+
+ post submit_url,
+ params: {
+ form_data: {
+ email: "[email protected]",
+ },
+ },
+ headers: origin_headers
+ expect(response).to have_http_status(:conflict)
+ expect(response.parsed_body).to eq(
+ "errors" => [I18n.t("discourse_workflows.errors.already_resumed")],
+ )
+ end
+
+ it "returns 404 when execution has already been resumed" do
+ post form_path,
+ params: {
+ resume_token: initial_resume_token,
+ form_data: {
+ name: "Test User",
+ },
+ },
+ headers: origin_headers
+ submit_url = response.parsed_body["form_submit_url"]
+
+ post submit_url,
+ params: {
+ form_data: {
+ email: "[email protected]",
+ },
+ },
+ headers: origin_headers
+ expect(response).to have_http_status(:ok)
+
+ post submit_url,
+ params: {
+ form_data: {
+ email: "[email protected]",
+ },
+ },
+ headers: origin_headers
+ expect(response).to have_http_status(:not_found)
+ expect(response.parsed_body).to eq("errors" => ["not_found"])
+ end
+ end
+ end
+end
diff --git a/plugins/discourse-workflows/spec/requests/discourse_workflows/node_types_controller_spec.rb b/plugins/discourse-workflows/spec/requests/discourse_workflows/node_types_controller_spec.rb
new file mode 100644
index 00000000000..78baf66e671
--- /dev/null
+++ b/plugins/discourse-workflows/spec/requests/discourse_workflows/node_types_controller_spec.rb
@@ -0,0 +1,66 @@
+# frozen_string_literal: true
+
+RSpec.describe DiscourseWorkflows::NodeTypesController do
+ fab!(:admin)
+
+ before { sign_in(admin) }
+
+ context "when not logged in as admin" do
+ fab!(:user)
+
+ before { sign_in(user) }
+
+ it "returns 404" do
+ get "/admin/plugins/discourse-workflows/node-types.json"
+ expect(response).to have_http_status(:not_found)
+ end
+ end
+
+ describe "GET /admin/plugins/discourse-workflows/node-types" do
+ it "returns all registered node types" do
+ get "/admin/plugins/discourse-workflows/node-types.json"
+
+ expect(response).to have_http_status(:ok)
+ json = response.parsed_body
+ identifiers = json["node_types"].map { |nt| nt["identifier"] }
+
+ expect(identifiers).to include("trigger:topic_closed")
+ expect(identifiers).to include("action:topic_tags")
+ expect(identifiers).to include("action:create_post")
+ expect(identifiers).to include("action:topic")
+ expect(identifiers).to include("condition:if")
+ end
+
+ it "does not include metadata key in node type response" do
+ get "/admin/plugins/discourse-workflows/node-types.json"
+
+ badge_node =
+ response.parsed_body["node_types"].find { |nt| nt["identifier"] == "action:badge" }
+ expect(badge_node).not_to have_key("metadata")
+ end
+
+ it "returns descriptor fields used by the admin client" do
+ get "/admin/plugins/discourse-workflows/node-types.json"
+
+ condition =
+ response.parsed_body["node_types"].find do |node_type|
+ node_type["identifier"] == "condition:if"
+ end
+
+ expect(condition["ui"]["palette_group"]).to include("id" => "flow")
+ expect(condition["capabilities"]).to include(
+ "branching" => true,
+ "manually_triggerable" => false,
+ "result_mode" => "ports",
+ )
+ expect(condition["ports"]).to include(
+ a_hash_including(
+ "key" => "true",
+ "label_key" => "discourse_workflows.branch.true",
+ "primary" => true,
+ ),
+ )
+ expect(condition["inputs"]).to include(a_hash_including("key" => "main", "required" => true))
+ end
+ end
+end
diff --git a/plugins/discourse-workflows/spec/requests/discourse_workflows/stats_controller_spec.rb b/plugins/discourse-workflows/spec/requests/discourse_workflows/stats_controller_spec.rb
new file mode 100644
index 00000000000..b80fb27f6ef
--- /dev/null
+++ b/plugins/discourse-workflows/spec/requests/discourse_workflows/stats_controller_spec.rb
@@ -0,0 +1,57 @@
+# frozen_string_literal: true
+
+RSpec.describe DiscourseWorkflows::StatsController do
+ fab!(:admin)
+
+ before { sign_in(admin) }
+
+ context "when not logged in as admin" do
+ fab!(:user)
+
+ before { sign_in(user) }
+
+ it "returns 404" do
+ get "/admin/plugins/discourse-workflows/stats.json"
+ expect(response).to have_http_status(:not_found)
+ end
+ end
+
+ describe "GET /admin/plugins/discourse-workflows/stats" do
+ fab!(:workflow, :discourse_workflows_workflow)
+ fab!(:other_workflow, :discourse_workflows_workflow)
+
+ before do
+ Fabricate(:discourse_workflows_completed_execution, workflow: workflow)
+ Fabricate(:discourse_workflows_error_execution, workflow: workflow)
+ Fabricate(:discourse_workflows_completed_execution, workflow: other_workflow)
+ end
+
+ it "returns aggregate stats across all workflows" do
+ get "/admin/plugins/discourse-workflows/stats.json"
+
+ expect(response).to have_http_status(:ok)
+ json = response.parsed_body
+ expect(json).to include("total" => 3, "failed" => 1)
+ expect(json["failure_rate"]).to match(/\A[\d.]+%\z/)
+ expect(json["avg_duration"]).to match(/\A[\d.]+(ms|s)\z/)
+ end
+ end
+
+ describe "GET /admin/plugins/discourse-workflows/stats/:workflow_id" do
+ fab!(:workflow, :discourse_workflows_workflow)
+ fab!(:other_workflow, :discourse_workflows_workflow)
+
+ before do
+ Fabricate(:discourse_workflows_completed_execution, workflow: workflow)
+ Fabricate(:discourse_workflows_error_execution, workflow: workflow)
+ Fabricate(:discourse_workflows_completed_execution, workflow: other_workflow)
+ end
+
+ it "returns stats scoped to the workflow" do
+ get "/admin/plugins/discourse-workflows/stats/#{workflow.id}.json"
+
+ expect(response).to have_http_status(:ok)
+ expect(response.parsed_body).to include("total" => 2, "failed" => 1)
+ end
+ end
+end
diff --git a/plugins/discourse-workflows/spec/requests/discourse_workflows/templates_controller_spec.rb b/plugins/discourse-workflows/spec/requests/discourse_workflows/templates_controller_spec.rb
new file mode 100644
index 00000000000..f0514834d03
--- /dev/null
+++ b/plugins/discourse-workflows/spec/requests/discourse_workflows/templates_controller_spec.rb
@@ -0,0 +1,51 @@
+# frozen_string_literal: true
+
+RSpec.describe DiscourseWorkflows::TemplatesController do
+ fab!(:admin)
+
+ before do
+ DiscourseWorkflows::TemplateStore.reset_cache!
+ sign_in(admin)
+ end
+ after { DiscourseWorkflows::TemplateStore.reset_cache! }
+
+ context "when not logged in as admin" do
+ fab!(:user)
+
+ before { sign_in(user) }
+
+ it "returns 404" do
+ get "/admin/plugins/discourse-workflows/templates.json"
+ expect(response).to have_http_status(:not_found)
+ end
+ end
+
+ describe "GET /admin/plugins/discourse-workflows/templates" do
+ it "returns a list of templates with the expected attributes" do
+ get "/admin/plugins/discourse-workflows/templates.json"
+
+ expect(response).to have_http_status(:ok)
+ templates = response.parsed_body["templates"]
+ expect(templates).to be_an(Array).and(be_present)
+ expect(templates).to all(include("id", "name", "description", "node_types"))
+ expect(templates.first["node_types"]).to be_an(Array)
+ end
+ end
+
+ describe "GET /admin/plugins/discourse-workflows/templates/:id" do
+ it "returns the template" do
+ get "/admin/plugins/discourse-workflows/templates/auto-tag-topics.json"
+
+ expect(response).to have_http_status(:ok)
+ json = response.parsed_body
+ expect(json["template"]["name"]).to eq("Auto-tag new topics")
+ expect(json["template"]["nodes"]).to be_an(Array)
+ end
+
+ it "returns 404 when template does not exist" do
+ get "/admin/plugins/discourse-workflows/templates/nonexistent.json"
+
+ expect(response).to have_http_status(:not_found)
+ end
+ end
+end
diff --git a/plugins/discourse-workflows/spec/requests/discourse_workflows/topic_admin_button_controller_spec.rb b/plugins/discourse-workflows/spec/requests/discourse_workflows/topic_admin_button_controller_spec.rb
new file mode 100644
index 00000000000..54b7cb80948
--- /dev/null
+++ b/plugins/discourse-workflows/spec/requests/discourse_workflows/topic_admin_button_controller_spec.rb
@@ -0,0 +1,99 @@
+# frozen_string_literal: true
+
+RSpec.describe DiscourseWorkflows::TopicAdminButtonController do
+ fab!(:admin)
+ fab!(:user)
+ fab!(:topic)
+ fab!(:workflow) do
+ graph =
+ build_workflow_graph do |g|
+ g.node "trigger-1",
+ "trigger:topic_admin_button",
+ configuration: {
+ "label" => "Run workflow",
+ "icon" => "gear",
+ }
+ end
+ Fabricate(:discourse_workflows_workflow, created_by: admin, published: true, **graph)
+ end
+
+ describe "POST /discourse-workflows/trigger-topic-admin-button" do
+ it "requires authentication" do
+ post "/discourse-workflows/trigger-topic-admin-button.json",
+ params: {
+ trigger_node_id: "trigger-1",
+ topic_id: topic.id,
+ }
+
+ expect(response).to have_http_status(:forbidden)
+ end
+
+ it "returns 403 when user is not an admin" do
+ sign_in(user)
+
+ post "/discourse-workflows/trigger-topic-admin-button.json",
+ params: {
+ trigger_node_id: "trigger-1",
+ topic_id: topic.id,
+ }
+
+ expect(response).to have_http_status(:forbidden)
+ end
+
+ context "when signed in as admin" do
+ before { sign_in(admin) }
+
+ it "returns 204 on success" do
+ post "/discourse-workflows/trigger-topic-admin-button.json",
+ params: {
+ trigger_node_id: "trigger-1",
+ topic_id: topic.id,
+ }
+
+ expect(response).to have_http_status(:no_content)
+ end
+
+ it "enqueues an ExecuteWorkflow job" do
+ post "/discourse-workflows/trigger-topic-admin-button.json",
+ params: {
+ trigger_node_id: "trigger-1",
+ topic_id: topic.id,
+ }
+
+ job = Jobs::DiscourseWorkflows::ExecuteWorkflow.jobs.last
+ expect(job["args"].first).to include(
+ "trigger_node_id" => "trigger-1",
+ "workflow_version_id" => workflow.active_version_id,
+ )
+ end
+
+ it "returns 400 when contract is invalid" do
+ post "/discourse-workflows/trigger-topic-admin-button.json", params: {}
+
+ expect(response).to have_http_status(:bad_request)
+ end
+
+ it "returns 404 when trigger node does not exist" do
+ post "/discourse-workflows/trigger-topic-admin-button.json",
+ params: {
+ trigger_node_id: "nonexistent",
+ topic_id: topic.id,
+ }
+
+ expect(response).to have_http_status(:not_found)
+ end
+
+ it "returns 404 when workflow is unpublished" do
+ unpublish_workflow!(workflow)
+
+ post "/discourse-workflows/trigger-topic-admin-button.json",
+ params: {
+ trigger_node_id: "trigger-1",
+ topic_id: topic.id,
+ }
+
+ expect(response).to have_http_status(:not_found)
+ end
+ end
+ end
+end
diff --git a/plugins/discourse-workflows/spec/requests/discourse_workflows/variables_controller_spec.rb b/plugins/discourse-workflows/spec/requests/discourse_workflows/variables_controller_spec.rb
new file mode 100644
index 00000000000..adf00c883c9
--- /dev/null
+++ b/plugins/discourse-workflows/spec/requests/discourse_workflows/variables_controller_spec.rb
@@ -0,0 +1,126 @@
+# frozen_string_literal: true
+
+RSpec.describe DiscourseWorkflows::VariablesController do
+ fab!(:admin)
+
+ before { sign_in(admin) }
+
+ context "when not logged in as admin" do
+ fab!(:user)
+
+ before { sign_in(user) }
+
+ it "returns 404 for index" do
+ get "/admin/plugins/discourse-workflows/variables.json"
+ expect(response).to have_http_status(:not_found)
+ end
+
+ it "returns 404 for create" do
+ post "/admin/plugins/discourse-workflows/variables.json", params: { key: "X", value: "Y" }
+ expect(response).to have_http_status(:not_found)
+ end
+ end
+
+ describe "GET /admin/plugins/discourse-workflows/variables" do
+ it "returns variables" do
+ variable = Fabricate(:discourse_workflows_variable)
+
+ get "/admin/plugins/discourse-workflows/variables.json"
+
+ expect(response).to have_http_status(:ok)
+ json = response.parsed_body
+ expect(json["variables"].length).to eq(1)
+ expect(json["variables"][0]["key"]).to eq(variable.key)
+ expect(json["variables"][0]["created_by"]["username"]).to eq(variable.created_by.username)
+ end
+
+ it "returns shared pagination meta" do
+ Fabricate(:discourse_workflows_variable, key: "FIRST")
+ variable = Fabricate(:discourse_workflows_variable, key: "SECOND")
+
+ get "/admin/plugins/discourse-workflows/variables.json", params: { limit: 1 }
+
+ json = response.parsed_body
+ expect(json["meta"]).to include(
+ "total_rows" => 2,
+ "load_more_url" =>
+ "/admin/plugins/discourse-workflows/variables.json?cursor=#{variable.id}&limit=1",
+ )
+ end
+
+ it "paginates with cursor param" do
+ variable_1 = Fabricate(:discourse_workflows_variable, key: "FIRST")
+ variable_2 = Fabricate(:discourse_workflows_variable, key: "SECOND")
+
+ get "/admin/plugins/discourse-workflows/variables.json",
+ params: {
+ cursor: variable_2.id,
+ limit: 10,
+ }
+
+ json = response.parsed_body
+ expect(json["variables"].length).to eq(1)
+ expect(json["variables"][0]["id"]).to eq(variable_1.id)
+ end
+ end
+
+ describe "POST /admin/plugins/discourse-workflows/variables" do
+ it "creates a variable" do
+ post "/admin/plugins/discourse-workflows/variables.json",
+ params: {
+ key: "API_URL",
+ value: "https://example.com",
+ description: "API base",
+ }
+
+ expect(response).to have_http_status(:created)
+ json = response.parsed_body
+ expect(json["variable"]).to include(
+ "key" => "API_URL",
+ "value" => "https://example.com",
+ "created_by" => include("username" => admin.username),
+ )
+ end
+
+ it "returns 400 when key is missing" do
+ post "/admin/plugins/discourse-workflows/variables.json", params: { value: "test" }
+ expect(response).to have_http_status(:bad_request)
+ end
+ end
+
+ describe "PUT /admin/plugins/discourse-workflows/variables/:id" do
+ it "updates a variable" do
+ variable = Fabricate(:discourse_workflows_variable)
+
+ put "/admin/plugins/discourse-workflows/variables/#{variable.id}.json",
+ params: {
+ key: "UPDATED_KEY",
+ value: "updated",
+ }
+
+ expect(response).to have_http_status(:ok)
+ expect(response.parsed_body["variable"]["key"]).to eq("UPDATED_KEY")
+ end
+
+ it "returns 404 when variable does not exist" do
+ put "/admin/plugins/discourse-workflows/variables/-1.json", params: { key: "X", value: "Y" }
+ expect(response).to have_http_status(:not_found)
+ end
+ end
+
+ describe "DELETE /admin/plugins/discourse-workflows/variables/:id" do
+ it "deletes a variable" do
+ variable = Fabricate(:discourse_workflows_variable)
+
+ delete "/admin/plugins/discourse-workflows/variables/#{variable.id}.json"
+
+ expect(response).to have_http_status(:no_content)
+ expect(DiscourseWorkflows::Variable.exists?(variable.id)).to be(false)
+ end
+
+ it "returns 404 when variable does not exist" do
+ delete "/admin/plugins/discourse-workflows/variables/-1.json"
+ expect(response).to have_http_status(:not_found)
+ end
+ end
+end
diff --git a/plugins/discourse-workflows/spec/requests/discourse_workflows/webhook_test_listeners_controller_spec.rb b/plugins/discourse-workflows/spec/requests/discourse_workflows/webhook_test_listeners_controller_spec.rb
new file mode 100644
index 00000000000..a79563758c2
--- /dev/null
+++ b/plugins/discourse-workflows/spec/requests/discourse_workflows/webhook_test_listeners_controller_spec.rb
@@ -0,0 +1,63 @@
+# frozen_string_literal: true
+
+RSpec.describe DiscourseWorkflows::WebhookTestListenersController do
+ fab!(:admin)
+ fab!(:workflow) do
+ graph =
+ build_workflow_graph do |g|
+ g.node "webhook-1",
+ "trigger:webhook",
+ configuration: {
+ "path" => "test-hook",
+ "http_method" => "POST",
+ }
+ end
+ Fabricate(:discourse_workflows_workflow, created_by: admin, published: false, **graph)
+ end
+
+ describe "POST /admin/plugins/discourse-workflows/workflows/:id/webhook-test-listeners.json" do
+ it "requires an admin" do
+ sign_in(Fabricate(:user))
+
+ post "/admin/plugins/discourse-workflows/workflows/#{workflow.id}/webhook-test-listeners.json",
+ params: {
+ trigger_node_id: "webhook-1",
+ }
+
+ expect(response).to have_http_status(:not_found)
+ end
+
+ it "creates a short-lived webhook test listener" do
+ sign_in(admin)
+
+ post "/admin/plugins/discourse-workflows/workflows/#{workflow.id}/webhook-test-listeners.json",
+ params: {
+ trigger_node_id: "webhook-1",
+ }
+
+ expect(response).to have_http_status(:created)
+ expect(response.parsed_body).to include(
+ "listener_id" => match(/\A[0-9a-f-]{36}\z/),
+ "test_url" => match(%r{\A/workflows/webhook-test/[0-9a-f-]{36}/test-hook\z}),
+ "expires_at" => be_present,
+ )
+ end
+ end
+
+ describe "DELETE /admin/plugins/discourse-workflows/workflows/:id/webhook-test-listeners/:listener_id.json" do
+ it "cancels the listener" do
+ sign_in(admin)
+ listener =
+ DiscourseWorkflows::WebhookTestListener.create!(
+ workflow: workflow,
+ user: admin,
+ trigger_node: workflow.find_node("webhook-1"),
+ )
+
+ delete "/admin/plugins/discourse-workflows/workflows/#{workflow.id}/webhook-test-listeners/#{listener.listener_id}.json"
+
+ expect(response).to have_http_status(:no_content)
+ expect(DiscourseWorkflows::WebhookTestListener.find(listener.listener_id)).to be_nil
+ end
+ end
+end
diff --git a/plugins/discourse-workflows/spec/requests/discourse_workflows/webhooks_controller_spec.rb b/plugins/discourse-workflows/spec/requests/discourse_workflows/webhooks_controller_spec.rb
new file mode 100644
index 00000000000..d4f8b74af11
--- /dev/null
+++ b/plugins/discourse-workflows/spec/requests/discourse_workflows/webhooks_controller_spec.rb
@@ -0,0 +1,915 @@
+# frozen_string_literal: true
+
+RSpec.describe DiscourseWorkflows::WebhooksController do
+ fab!(:admin)
+
+ fab!(:workflow) do
+ graph =
+ build_workflow_graph do |g|
+ g.node "webhook-1",
+ "trigger:webhook",
+ configuration: {
+ "path" => "my-hook",
+ "http_method" => "POST",
+ }
+ end
+ Fabricate(:discourse_workflows_workflow, created_by: admin, published: true, **graph)
+ end
+
+ describe "POST /workflows/webhooks/:path" do
+ it "enqueues workflow execution for matching webhook" do
+ post "/workflows/webhooks/my-hook.json",
+ params: { foo: "bar" }.to_json,
+ headers: {
+ "CONTENT_TYPE" => "application/json",
+ }
+
+ expect(response).to have_http_status(:ok)
+ expect(response.parsed_body["success"]).to be(true)
+
+ job = Jobs::DiscourseWorkflows::ExecuteWorkflow.jobs.last
+ expect(job["args"][0]["trigger_node_id"]).to eq("webhook-1")
+
+ trigger_data = job["args"][0]["trigger_data"]
+ expect(trigger_data).to include(
+ "body" => {
+ "foo" => "bar",
+ },
+ "query" => be_a(Hash),
+ "headers" => include("content-type" => "application/json"),
+ )
+ end
+
+ it "returns 404 when no matching webhook exists" do
+ post "/workflows/webhooks/unknown-path.json"
+ expect(response).to have_http_status(:not_found)
+ end
+
+ it "returns 404 when HTTP method does not match" do
+ get "/workflows/webhooks/my-hook.json"
+ expect(response).to have_http_status(:not_found)
+ end
+
+ it "returns 404 when workflow is unpublished" do
+ unpublish_workflow!(workflow)
+ post "/workflows/webhooks/my-hook.json"
+ expect(response).to have_http_status(:not_found)
+ end
+
+ it "returns 404 when plugin is disabled" do
+ SiteSetting.discourse_workflows_enabled = false
+ post "/workflows/webhooks/my-hook.json"
+ expect(response).to have_http_status(:not_found)
+ end
+
+ it "works without authentication" do
+ post "/workflows/webhooks/my-hook.json",
+ params: { data: "test" }.to_json,
+ headers: {
+ "CONTENT_TYPE" => "application/json",
+ }
+
+ expect(response).to have_http_status(:ok)
+ end
+
+ it "passes query parameters in trigger data" do
+ post "/workflows/webhooks/my-hook.json?source=github&ref=main",
+ params: {}.to_json,
+ headers: {
+ "CONTENT_TYPE" => "application/json",
+ }
+
+ expect(response).to have_http_status(:ok)
+
+ trigger_data = Jobs::DiscourseWorkflows::ExecuteWorkflow.jobs.last["args"][0]["trigger_data"]
+ expect(trigger_data["query"]).to include("source" => "github", "ref" => "main")
+ end
+
+ it "handles different HTTP methods" do
+ update_workflow_node(workflow, "webhook-1") do |node|
+ node.merge("parameters" => { "path" => "my-hook", "http_method" => "PUT" })
+ end
+ publish_workflow!(workflow)
+
+ put "/workflows/webhooks/my-hook.json",
+ params: { updated: true }.to_json,
+ headers: {
+ "CONTENT_TYPE" => "application/json",
+ }
+
+ expect(response).to have_http_status(:ok)
+ end
+
+ it "matches dynamic paths and exposes captured params in trigger data" do
+ dynamic_graph =
+ build_workflow_graph do |g|
+ g.node "webhook-1",
+ "trigger:webhook",
+ webhook_id: "abcd-1234",
+ configuration: {
+ "path" => "users/:id/posts",
+ "http_method" => "POST",
+ }
+ end
+ dynamic_workflow =
+ Fabricate(
+ :discourse_workflows_workflow,
+ created_by: admin,
+ published: true,
+ **dynamic_graph,
+ )
+ publish_workflow!(dynamic_workflow)
+
+ post "/workflows/webhooks/abcd-1234/users/42/posts.json",
+ params: {}.to_json,
+ headers: {
+ "CONTENT_TYPE" => "application/json",
+ }
+
+ expect(response).to have_http_status(:ok)
+ trigger_data = Jobs::DiscourseWorkflows::ExecuteWorkflow.jobs.last["args"][0]["trigger_data"]
+ expect(trigger_data["params"]).to eq("id" => "42")
+ end
+
+ it "rate limits webhook requests" do
+ RateLimiter.enable
+
+ stub_const(DiscourseWorkflows::WebhooksController, "WEBHOOK_RATE_LIMIT", 1) do
+ post "/workflows/webhooks/my-hook.json",
+ params: {}.to_json,
+ headers: {
+ "CONTENT_TYPE" => "application/json",
+ }
+ expect(response).to have_http_status(:ok)
+
+ post "/workflows/webhooks/my-hook.json",
+ params: {}.to_json,
+ headers: {
+ "CONTENT_TYPE" => "application/json",
+ }
+ expect(response).to have_http_status(:too_many_requests)
+ end
+ ensure
+ RateLimiter.disable
+ end
+
+ it "returns 400 for malformed JSON body" do
+ post "/workflows/webhooks/my-hook.json",
+ headers: {
+ "RAW_POST_DATA" => "not valid json{",
+ "CONTENT_TYPE" => "application/json",
+ }
+
+ expect(response).to have_http_status(:bad_request)
+ end
+
+ it "handles non-JSON content type" do
+ post "/workflows/webhooks/my-hook.json", params: { data: "test" }
+
+ expect(response).to have_http_status(:ok)
+
+ trigger_data = Jobs::DiscourseWorkflows::ExecuteWorkflow.jobs.last["args"][0]["trigger_data"]
+ expect(trigger_data["body"]).to eq({ "data" => "test" })
+ end
+
+ context "when receiving test webhooks" do
+ def start_webhook_test_listener
+ DiscourseWorkflows::WebhookTestListener.create!(
+ workflow: workflow,
+ user: admin,
+ trigger_node: workflow.find_node("webhook-1"),
+ )
+ end
+
+ before { unpublish_workflow!(workflow) }
+
+ it "returns 404 when no listener exists" do
+ post "/workflows/webhook-test/my-hook.json",
+ params: { foo: "bar" }.to_json,
+ headers: {
+ "CONTENT_TYPE" => "application/json",
+ }
+
+ expect(response).to have_http_status(:not_found)
+ end
+
+ it "executes the draft workflow for the first matching request" do
+ listener = start_webhook_test_listener
+
+ expect do
+ post "#{listener.test_url}.json?source=test",
+ params: { foo: "bar" }.to_json,
+ headers: {
+ "CONTENT_TYPE" => "application/json",
+ }
+ end.to change { DiscourseWorkflows::Execution.count }.by(1)
+
+ expect(response).to have_http_status(:ok)
+ execution = DiscourseWorkflows::Execution.last
+ expect(execution).to have_attributes(
+ workflow_id: workflow.id,
+ trigger_node_id: "webhook-1",
+ execution_mode: "manual",
+ status: "success",
+ )
+ expect(execution.trigger_data).to include(
+ "body" => {
+ "foo" => "bar",
+ },
+ "query" => {
+ "source" => "test",
+ },
+ "method" => "POST",
+ "webhook_url" => "#{Discourse.base_url}#{listener.test_url}",
+ )
+ end
+
+ it "consumes the listener after the first matching request" do
+ listener = start_webhook_test_listener
+
+ 2.times do
+ post "#{listener.test_url}.json",
+ params: {}.to_json,
+ headers: {
+ "CONTENT_TYPE" => "application/json",
+ }
+ end
+
+ expect(response).to have_http_status(:not_found)
+ end
+
+ it "does not consume the listener when HTTP method does not match" do
+ listener = start_webhook_test_listener
+
+ get "#{listener.test_url}.json"
+ expect(response).to have_http_status(:not_found)
+
+ post "#{listener.test_url}.json",
+ params: {}.to_json,
+ headers: {
+ "CONTENT_TYPE" => "application/json",
+ }
+ expect(response).to have_http_status(:ok)
+ end
+
+ it "does not consume the listener without the listener id in the URL" do
+ listener = start_webhook_test_listener
+
+ post "/workflows/webhook-test/my-hook.json",
+ params: {}.to_json,
+ headers: {
+ "CONTENT_TYPE" => "application/json",
+ }
+ expect(response).to have_http_status(:not_found)
+
+ post "#{listener.test_url}.json",
+ params: {}.to_json,
+ headers: {
+ "CONTENT_TYPE" => "application/json",
+ }
+ expect(response).to have_http_status(:ok)
+ end
+
+ it "returns 404 after the listener is cancelled" do
+ listener = start_webhook_test_listener
+ DiscourseWorkflows::WebhookTestListener.cancel!(listener)
+
+ post "#{listener.test_url}.json",
+ params: {}.to_json,
+ headers: {
+ "CONTENT_TYPE" => "application/json",
+ }
+
+ expect(response).to have_http_status(:not_found)
+ end
+ end
+
+ context "when resuming a waiting webhook" do
+ let(:resume_token) { "resume-token" }
+ let(:signature) do
+ DiscourseWorkflows::WaitingExecution.resume_signature(
+ execution_id: waiting_execution.id,
+ resume_token: resume_token,
+ )
+ end
+
+ before do
+ extra =
+ build_workflow_graph do |g|
+ g.node "wait-1",
+ "flow:wait",
+ configuration: {
+ "http_method" => "POST",
+ "response_mode" => "on_received",
+ "webhook_suffix" => "after-approval",
+ }
+ g.chain "webhook-1", "wait-1"
+ end
+ nodes = workflow.nodes + extra[:nodes]
+ workflow.update!(
+ nodes: nodes,
+ connections: workflow_connections_for(nodes, %w[webhook-1 wait-1]),
+ )
+ end
+
+ fab!(:waiting_execution) do
+ Fabricate(
+ :discourse_workflows_execution,
+ workflow: workflow,
+ status: :waiting,
+ trigger_node_id: "webhook-1",
+ waiting_node_id: "wait-1",
+ resume_token: "resume-token",
+ )
+ end
+
+ before do
+ Fabricate(
+ :discourse_workflows_execution_data,
+ execution: waiting_execution,
+ workflow_data: DiscourseWorkflows::WorkflowSnapshot.from_workflow(workflow).to_h,
+ )
+ end
+
+ it "resumes when the suffix matches" do
+ post "/workflows/waiting/#{waiting_execution.id}/webhook/after-approval.json?signature=#{signature}",
+ params: { foo: "bar" }.to_json,
+ headers: {
+ "CONTENT_TYPE" => "application/json",
+ }
+
+ expect(response).to have_http_status(:ok)
+ expect(response.parsed_body["success"]).to eq(true)
+
+ job = Jobs::DiscourseWorkflows::ResumeWebhookWaiting.jobs.last
+ expect(job["args"].first).to include("execution_id" => waiting_execution.id)
+ expect(job["args"].first["response_items"].first["json"]["webhook_url"]).to eq(
+ DiscourseWorkflows::WaitingExecution.webhook_url(
+ execution_id: waiting_execution.id,
+ resume_token: resume_token,
+ suffix: "after-approval",
+ ),
+ )
+ end
+
+ it "returns 404 when the suffix does not match" do
+ post "/workflows/waiting/#{waiting_execution.id}/webhook/wrong-suffix.json?signature=#{signature}",
+ params: { foo: "bar" }.to_json,
+ headers: {
+ "CONTENT_TYPE" => "application/json",
+ }
+
+ expect(response).to have_http_status(:not_found)
+ end
+
+ it "does not accept token resume requests on the public webhook path" do
+ post "/workflows/webhooks/#{waiting_execution.id}/after-approval.json?token=#{resume_token}",
+ params: { foo: "bar" }.to_json,
+ headers: {
+ "CONTENT_TYPE" => "application/json",
+ }
+
+ expect(response).to have_http_status(:not_found)
+ end
+
+ it "does not accept token on the waiting resume route" do
+ expect do
+ post "/workflows/waiting/#{waiting_execution.id}/webhook/after-approval.json?token=#{resume_token}",
+ params: { foo: "bar" }.to_json,
+ headers: {
+ "CONTENT_TYPE" => "application/json",
+ }
+ end.not_to change { Jobs::DiscourseWorkflows::ResumeWebhookWaiting.jobs.size }
+
+ expect(response).to have_http_status(:not_found)
+ end
+
+ it "redirects when the resumed workflow responds to webhook with a redirect" do
+ extra =
+ build_workflow_graph do |g|
+ g.node "respond-1",
+ "action:respond_to_webhook",
+ configuration: {
+ "response_type" => "redirect",
+ "redirect_url" => "https://example.com/thanks",
+ "allowed_redirect_domains" => {
+ "values" => [{ "domain" => "example.com" }],
+ },
+ }
+ g.connect "wait-1", "respond-1"
+ end
+ updated_nodes =
+ (workflow.nodes + extra[:nodes]).map do |n|
+ if n["id"] == "wait-1"
+ n.merge(
+ "parameters" => (n["parameters"] || {}).merge("response_mode" => "response_node"),
+ )
+ else
+ n
+ end
+ end
+ workflow.update!(
+ nodes: updated_nodes,
+ connections: workflow_connections_for(updated_nodes, %w[wait-1 respond-1]),
+ )
+
+ waiting_execution.execution_data.update!(
+ workflow_data: DiscourseWorkflows::WorkflowSnapshot.from_workflow(workflow).to_h,
+ )
+
+ post "/workflows/waiting/#{waiting_execution.id}/webhook/after-approval.json?signature=#{signature}",
+ params: { foo: "bar" }.to_json,
+ headers: {
+ "CONTENT_TYPE" => "application/json",
+ }
+
+ expect(response).to have_http_status(:found)
+ expect(response.headers["Location"]).to eq("https://example.com/thanks")
+ end
+ end
+
+ describe "synchronous response modes" do
+ def setup_webhook_with_response(response_mode:, target_node_id:, extra:, webhook_config: {})
+ nodes =
+ workflow_nodes_with_update(workflow, "webhook-1") do |node|
+ node.merge(
+ "parameters" => {
+ "path" => "my-hook",
+ "http_method" => "POST",
+ "response_mode" => response_mode,
+ }.merge(webhook_config),
+ )
+ end + extra[:nodes]
+
+ workflow.update!(
+ nodes: nodes,
+ connections: workflow_connections_for(nodes, ["webhook-1", target_node_id]),
+ )
+ publish_workflow!(workflow)
+ end
+
+ it "redirects when respond_to_webhook node produces a redirect" do
+ extra =
+ build_workflow_graph do |g|
+ g.node "respond-1",
+ "action:respond_to_webhook",
+ configuration: {
+ "response_type" => "redirect",
+ "redirect_url" => "https://example.com/thanks",
+ "allowed_redirect_domains" => {
+ "values" => [{ "domain" => "example.com" }],
+ },
+ }
+ end
+ setup_webhook_with_response(
+ response_mode: "response_node",
+ target_node_id: "respond-1",
+ extra: extra,
+ )
+
+ post "/workflows/webhooks/my-hook.json",
+ params: {}.to_json,
+ headers: {
+ "CONTENT_TYPE" => "application/json",
+ }
+
+ expect(response).to have_http_status(:found)
+ expect(response.headers["Location"]).to eq("https://example.com/thanks")
+ end
+
+ it "rejects external redirect responses when the domain is not allowed" do
+ extra =
+ build_workflow_graph do |g|
+ g.node "respond-1",
+ "action:respond_to_webhook",
+ configuration: {
+ "response_type" => "redirect",
+ "redirect_url" => "https://example.com/thanks",
+ }
+ end
+ setup_webhook_with_response(
+ response_mode: "response_node",
+ target_node_id: "respond-1",
+ extra: extra,
+ )
+
+ post "/workflows/webhooks/my-hook.json",
+ params: {}.to_json,
+ headers: {
+ "CONTENT_TYPE" => "application/json",
+ }
+
+ expect(response).to have_http_status(:bad_request)
+ expect(response.parsed_body["error"]).to eq("invalid_redirect_url")
+ end
+
+ it "allows wildcard subdomain redirect responses" do
+ extra =
+ build_workflow_graph do |g|
+ g.node "respond-1",
+ "action:respond_to_webhook",
+ configuration: {
+ "response_type" => "redirect",
+ "redirect_url" => "https://docs.example.com/thanks",
+ "allowed_redirect_domains" => {
+ "values" => [{ "domain" => "*.example.com" }],
+ },
+ }
+ end
+ setup_webhook_with_response(
+ response_mode: "response_node",
+ target_node_id: "respond-1",
+ extra: extra,
+ )
+
+ post "/workflows/webhooks/my-hook.json",
+ params: {}.to_json,
+ headers: {
+ "CONTENT_TYPE" => "application/json",
+ }
+
+ expect(response).to have_http_status(:found)
+ expect(response.headers["Location"]).to eq("https://docs.example.com/thanks")
+ end
+
+ it "does not allow wildcard domains to match the root domain" do
+ extra =
+ build_workflow_graph do |g|
+ g.node "respond-1",
+ "action:respond_to_webhook",
+ configuration: {
+ "response_type" => "redirect",
+ "redirect_url" => "https://example.com/thanks",
+ "allowed_redirect_domains" => {
+ "values" => [{ "domain" => "*.example.com" }],
+ },
+ }
+ end
+ setup_webhook_with_response(
+ response_mode: "response_node",
+ target_node_id: "respond-1",
+ extra: extra,
+ )
+
+ post "/workflows/webhooks/my-hook.json",
+ params: {}.to_json,
+ headers: {
+ "CONTENT_TYPE" => "application/json",
+ }
+
+ expect(response).to have_http_status(:bad_request)
+ expect(response.parsed_body["error"]).to eq("invalid_redirect_url")
+ end
+
+ it "returns JSON when respond_to_webhook node produces JSON" do
+ extra =
+ build_workflow_graph do |g|
+ g.node "respond-1",
+ "action:respond_to_webhook",
+ configuration: {
+ "response_type" => "json",
+ "status_code" => "201",
+ "response_body" => '{"created": true}',
+ }
+ end
+ setup_webhook_with_response(
+ response_mode: "response_node",
+ target_node_id: "respond-1",
+ extra: extra,
+ )
+
+ post "/workflows/webhooks/my-hook.json",
+ params: {}.to_json,
+ headers: {
+ "CONTENT_TYPE" => "application/json",
+ }
+
+ expect(response).to have_http_status(:created)
+ expect(response.parsed_body).to eq("created" => true)
+ end
+
+ it "returns JSON null when respond_to_webhook node produces null" do
+ extra =
+ build_workflow_graph do |g|
+ g.node "respond-1",
+ "action:respond_to_webhook",
+ configuration: {
+ "response_type" => "json",
+ "status_code" => "200",
+ "response_body" => "null",
+ }
+ end
+ setup_webhook_with_response(
+ response_mode: "response_node",
+ target_node_id: "respond-1",
+ extra: extra,
+ )
+
+ post "/workflows/webhooks/my-hook.json",
+ params: {}.to_json,
+ headers: {
+ "CONTENT_TYPE" => "application/json",
+ }
+
+ expect(response).to have_http_status(:ok)
+ expect(response.body).to eq("null")
+ end
+
+ it "returns text when respond_to_webhook node produces text" do
+ extra =
+ build_workflow_graph do |g|
+ g.node "respond-1",
+ "action:respond_to_webhook",
+ configuration: {
+ "response_type" => "text",
+ "status_code" => "200",
+ "response_body" => "OK thanks",
+ }
+ end
+ setup_webhook_with_response(
+ response_mode: "response_node",
+ target_node_id: "respond-1",
+ extra: extra,
+ )
+
+ post "/workflows/webhooks/my-hook.json",
+ params: {}.to_json,
+ headers: {
+ "CONTENT_TYPE" => "application/json",
+ }
+
+ expect(response).to have_http_status(:ok)
+ expect(response.body).to eq("OK thanks")
+ end
+
+ it "returns no data response" do
+ extra =
+ build_workflow_graph do |g|
+ g.node "respond-1",
+ "action:respond_to_webhook",
+ configuration: {
+ "response_type" => "no_data",
+ "status_code" => "204",
+ }
+ end
+ setup_webhook_with_response(
+ response_mode: "response_node",
+ target_node_id: "respond-1",
+ extra: extra,
+ )
+
+ post "/workflows/webhooks/my-hook.json",
+ params: {}.to_json,
+ headers: {
+ "CONTENT_TYPE" => "application/json",
+ }
+
+ expect(response).to have_http_status(:no_content)
+ end
+
+ it "returns last node output as JSON when mode is last_node" do
+ extra =
+ build_workflow_graph do |g|
+ g.node "set-fields-1",
+ "action:set_fields",
+ configuration: {
+ "mode" => "raw",
+ "json_output" => '{"result": "done"}',
+ }
+ end
+ setup_webhook_with_response(
+ response_mode: "last_node",
+ target_node_id: "set-fields-1",
+ extra: extra,
+ webhook_config: {
+ "response_code" => "200",
+ },
+ )
+
+ post "/workflows/webhooks/my-hook.json",
+ params: {}.to_json,
+ headers: {
+ "CONTENT_TYPE" => "application/json",
+ }
+
+ expect(response).to have_http_status(:ok)
+ expect(response.parsed_body).to be_a(Hash)
+ end
+ end
+
+ context "with basic auth webhook" do
+ fab!(:credential) do
+ Fabricate(
+ :discourse_workflows_credential,
+ credential_type: "basic_auth",
+ data: {
+ "user" => "hook_user",
+ "password" => "hook_pass",
+ },
+ )
+ end
+
+ before do
+ update_workflow_node(workflow, "webhook-1") do |node|
+ node.merge(
+ "parameters" => {
+ "path" => "my-hook",
+ "http_method" => "POST",
+ "response_mode" => "on_received",
+ "authentication" => "basic_auth",
+ },
+ "credentials" => {
+ "auth" => {
+ "id" => credential.id.to_s,
+ "credential_type" => "basic_auth",
+ },
+ },
+ )
+ end
+ publish_workflow!(workflow)
+ end
+
+ it "returns 401 with WWW-Authenticate and plain text body when no auth header" do
+ post "/workflows/webhooks/my-hook.json",
+ params: { data: "test" }.to_json,
+ headers: {
+ "CONTENT_TYPE" => "application/json",
+ }
+
+ expect(response).to have_http_status(:unauthorized)
+ expect(response.headers["WWW-Authenticate"]).to eq('Basic realm="Webhook"')
+ expect(response.media_type).to eq("text/plain")
+ expect(response.body).to eq("Authorization is required!")
+ end
+
+ it "returns 403 with WWW-Authenticate when credentials are wrong" do
+ post "/workflows/webhooks/my-hook.json",
+ params: { data: "test" }.to_json,
+ headers: {
+ "CONTENT_TYPE" => "application/json",
+ "HTTP_AUTHORIZATION" => "Basic #{Base64.strict_encode64("wrong:creds")}",
+ }
+
+ expect(response).to have_http_status(:forbidden)
+ expect(response.headers["WWW-Authenticate"]).to eq('Basic realm="Webhook"')
+ expect(response.body).to eq("Authorization data is wrong!")
+ end
+
+ it "returns 500 without WWW-Authenticate when credential is missing" do
+ credential.destroy!
+
+ post "/workflows/webhooks/my-hook.json",
+ params: { data: "test" }.to_json,
+ headers: {
+ "CONTENT_TYPE" => "application/json",
+ }
+
+ expect(response).to have_http_status(:internal_server_error)
+ expect(response.headers["WWW-Authenticate"]).to be_nil
+ expect(response.body).to eq("No authentication data defined on node!")
+ end
+
+ it "returns 200 with valid credentials" do
+ post "/workflows/webhooks/my-hook.json",
+ params: { data: "test" }.to_json,
+ headers: {
+ "CONTENT_TYPE" => "application/json",
+ "HTTP_AUTHORIZATION" => "Basic #{Base64.strict_encode64("hook_user:hook_pass")}",
+ }
+
+ expect(response).to have_http_status(:ok)
+ end
+ end
+
+ context "with bearer auth webhook" do
+ fab!(:credential) do
+ Fabricate(
+ :discourse_workflows_credential,
+ credential_type: "bearer_token",
+ data: {
+ "token" => "secret-token",
+ },
+ )
+ end
+
+ before do
+ update_workflow_node(workflow, "webhook-1") do |node|
+ node.merge(
+ "parameters" => {
+ "path" => "my-hook",
+ "http_method" => "POST",
+ "response_mode" => "on_received",
+ "authentication" => "bearer_auth",
+ },
+ "credentials" => {
+ "auth" => {
+ "id" => credential.id.to_s,
+ "credential_type" => "bearer_token",
+ },
+ },
+ )
+ end
+ publish_workflow!(workflow)
+ end
+
+ it "returns 403 without WWW-Authenticate when no bearer token" do
+ post "/workflows/webhooks/my-hook.json",
+ params: {}.to_json,
+ headers: {
+ "CONTENT_TYPE" => "application/json",
+ }
+
+ expect(response).to have_http_status(:forbidden)
+ expect(response.headers["WWW-Authenticate"]).to be_nil
+ end
+
+ it "returns 403 when bearer token is wrong" do
+ post "/workflows/webhooks/my-hook.json",
+ params: {}.to_json,
+ headers: {
+ "CONTENT_TYPE" => "application/json",
+ "HTTP_AUTHORIZATION" => "Bearer wrong-token",
+ }
+
+ expect(response).to have_http_status(:forbidden)
+ end
+
+ it "returns 200 with valid bearer token" do
+ post "/workflows/webhooks/my-hook.json",
+ params: {}.to_json,
+ headers: {
+ "CONTENT_TYPE" => "application/json",
+ "HTTP_AUTHORIZATION" => "Bearer secret-token",
+ }
+
+ expect(response).to have_http_status(:ok)
+ end
+ end
+
+ context "with header auth webhook" do
+ fab!(:credential) do
+ Fabricate(
+ :discourse_workflows_credential,
+ credential_type: "header_auth",
+ data: {
+ "name" => "X-Api-Key",
+ "value" => "secret-value",
+ },
+ )
+ end
+
+ before do
+ update_workflow_node(workflow, "webhook-1") do |node|
+ node.merge(
+ "parameters" => {
+ "path" => "my-hook",
+ "http_method" => "POST",
+ "response_mode" => "on_received",
+ "authentication" => "header_auth",
+ },
+ "credentials" => {
+ "auth" => {
+ "id" => credential.id.to_s,
+ "credential_type" => "header_auth",
+ },
+ },
+ )
+ end
+ publish_workflow!(workflow)
+ end
+
+ it "returns 403 without WWW-Authenticate when header is missing" do
+ post "/workflows/webhooks/my-hook.json",
+ params: {}.to_json,
+ headers: {
+ "CONTENT_TYPE" => "application/json",
+ }
+
+ expect(response).to have_http_status(:forbidden)
+ expect(response.headers["WWW-Authenticate"]).to be_nil
+ end
+
+ it "returns 403 when header value is wrong" do
+ post "/workflows/webhooks/my-hook.json",
+ params: {}.to_json,
+ headers: {
+ "CONTENT_TYPE" => "application/json",
+ "HTTP_X_API_KEY" => "wrong-value",
+ }
+
+ expect(response).to have_http_status(:forbidden)
+ end
+
+ it "returns 200 with correct header value" do
+ post "/workflows/webhooks/my-hook.json",
+ params: {}.to_json,
+ headers: {
+ "CONTENT_TYPE" => "application/json",
+ "HTTP_X_API_KEY" => "secret-value",
+ }
+
+ expect(response).to have_http_status(:ok)
+ end
+ end
+ end
+end
diff --git a/plugins/discourse-workflows/spec/requests/discourse_workflows/workflows_controller_spec.rb b/plugins/discourse-workflows/spec/requests/discourse_workflows/workflows_controller_spec.rb
new file mode 100644
index 00000000000..d92af8ee945
--- /dev/null
+++ b/plugins/discourse-workflows/spec/requests/discourse_workflows/workflows_controller_spec.rb
@@ -0,0 +1,461 @@
+# frozen_string_literal: true
+
+RSpec.describe DiscourseWorkflows::WorkflowsController do
+ fab!(:admin)
+
+ before do
+ SiteSetting.tagging_enabled = true
+ sign_in(admin)
+ end
+
+ context "when not logged in as admin" do
+ fab!(:user)
+
+ before { sign_in(user) }
+
+ it "returns 404 for index" do
+ get "/admin/plugins/discourse-workflows/workflows.json"
+ expect(response).to have_http_status(:not_found)
+ end
+ end
+
+ describe "GET /admin/plugins/discourse-workflows/workflows" do
+ it "returns workflows for authenticated users with access" do
+ workflow = Fabricate(:discourse_workflows_workflow, created_by: admin)
+
+ get "/admin/plugins/discourse-workflows/workflows.json"
+
+ expect(response).to have_http_status(:ok)
+ json = response.parsed_body
+ expect(json["workflows"].length).to eq(1)
+ expect(json["workflows"][0]["name"]).to eq(workflow.name)
+ end
+
+ it "returns the latest execution status for each workflow" do
+ workflow = Fabricate(:discourse_workflows_workflow, created_by: admin)
+
+ Fabricate(:discourse_workflows_error_execution, workflow: workflow, created_at: 2.hours.ago)
+ Fabricate(
+ :discourse_workflows_completed_execution,
+ workflow: workflow,
+ created_at: 1.hour.ago,
+ )
+
+ get "/admin/plugins/discourse-workflows/workflows.json"
+
+ expect(response).to have_http_status(:ok)
+ json = response.parsed_body
+ expect(json["workflows"][0]["last_execution_status"]).to eq("success")
+ end
+
+ it "returns meta with total rows" do
+ Fabricate(:discourse_workflows_workflow, created_by: admin)
+
+ get "/admin/plugins/discourse-workflows/workflows.json"
+
+ json = response.parsed_body
+ expect(json["meta"]["total_rows_workflows"]).to eq(1)
+ end
+
+ it "returns load_more_workflows when there are more results" do
+ stub_const(DiscourseWorkflows::Pagination, "DEFAULT_LIMIT", 1) do
+ Fabricate(:discourse_workflows_workflow, created_by: admin, name: "First")
+ Fabricate(:discourse_workflows_workflow, created_by: admin, name: "Second")
+
+ get "/admin/plugins/discourse-workflows/workflows.json"
+
+ json = response.parsed_body
+ expect(json["workflows"].length).to eq(1)
+ expect(json["meta"]["load_more_workflows"]).to be_present
+ end
+ end
+
+ it "paginates with cursor param" do
+ workflow_1 = Fabricate(:discourse_workflows_workflow, created_by: admin, name: "First")
+ workflow_2 = Fabricate(:discourse_workflows_workflow, created_by: admin, name: "Second")
+
+ get "/admin/plugins/discourse-workflows/workflows.json",
+ params: {
+ cursor: workflow_2.id,
+ limit: 10,
+ }
+
+ json = response.parsed_body
+ expect(json["workflows"].length).to eq(1)
+ expect(json["workflows"][0]["id"]).to eq(workflow_1.id.to_s)
+ end
+ end
+
+ describe "POST /admin/plugins/discourse-workflows/workflows" do
+ fab!(:tag)
+
+ it "creates a workflow" do
+ post "/admin/plugins/discourse-workflows/workflows.json",
+ params: {
+ workflow: {
+ name: "My Workflow",
+ nodes: [
+ { id: "t1", type: "trigger:topic_closed", name: "Topic Closed" },
+ {
+ id: "a1",
+ type: "action:topic_tags",
+ name: "Topic Tags",
+ parameters: {
+ topic_id: "={{ $trigger.topic_id }}",
+ tag_names: tag.name,
+ },
+ },
+ ],
+ connections: {
+ "Topic Closed" => {
+ "main" => [[{ "node" => "Topic Tags", "type" => "main", "index" => 0 }]],
+ },
+ },
+ static_data: {
+ "node:Topic Closed" => {
+ "cursor" => "abc",
+ },
+ },
+ },
+ },
+ as: :json
+
+ expect(response).to have_http_status(:created)
+ json = response.parsed_body
+ expect(json["workflow"]["name"]).to eq("My Workflow")
+ expect(json["workflow"]["nodes"].length).to eq(2)
+ expect(json["workflow"]["connections"].keys).to contain_exactly("Topic Closed")
+ expect(json["workflow"]["static_data"]).to eq("node:Topic Closed" => { "cursor" => "abc" })
+ end
+
+ it "returns 400 when name is missing" do
+ post "/admin/plugins/discourse-workflows/workflows.json", params: { workflow: { nodes: [] } }
+ expect(response).to have_http_status(:bad_request)
+ end
+
+ it "returns 422 when node validation fails" do
+ post "/admin/plugins/discourse-workflows/workflows.json",
+ params: {
+ workflow: {
+ name: "Invalid Schedule",
+ nodes: [
+ {
+ id: "t1",
+ type: "trigger:schedule",
+ name: "Schedule",
+ parameters: {
+ rule: {
+ interval: [{ field: "cronExpression", expression: "invalid" }],
+ },
+ },
+ },
+ ],
+ connections: {
+ },
+ },
+ }
+
+ expect(response).to have_http_status(:unprocessable_entity)
+ end
+ end
+
+ describe "PUT /admin/plugins/discourse-workflows/workflows/:id" do
+ it "updates a workflow" do
+ workflow = Fabricate(:discourse_workflows_workflow, created_by: admin)
+
+ put "/admin/plugins/discourse-workflows/workflows/#{workflow.id}.json",
+ params: {
+ workflow: {
+ name: "Updated Name",
+ nodes: [{ id: "t1", type: "trigger:topic_closed", name: "Topic Closed" }],
+ connections: {
+ },
+ },
+ }
+
+ expect(response).to have_http_status(:ok)
+ expect(response.parsed_body["workflow"]).to include("name" => "Updated Name")
+ expect(response.parsed_body["workflow"]["active_version_id"]).to be_nil
+ end
+
+ it "publishes a workflow draft" do
+ workflow = Fabricate(:discourse_workflows_workflow, created_by: admin)
+
+ put "/admin/plugins/discourse-workflows/workflows/#{workflow.id}.json",
+ params: {
+ workflow: {
+ name: workflow.name,
+ published: true,
+ },
+ }
+
+ expect(response).to have_http_status(:ok)
+ expect(response.parsed_body["workflow"]["active_version_id"]).to eq(
+ workflow.reload.active_version_id,
+ )
+ end
+
+ it "unpublishes a workflow" do
+ workflow = Fabricate(:discourse_workflows_workflow, created_by: admin, published: true)
+
+ put "/admin/plugins/discourse-workflows/workflows/#{workflow.id}.json",
+ params: {
+ workflow: {
+ name: workflow.name,
+ published: false,
+ },
+ }
+
+ expect(response).to have_http_status(:ok)
+ expect(response.parsed_body["workflow"]["active_version_id"]).to be_nil
+ expect(workflow.reload.active_version_id).to be_nil
+ end
+
+ it "updates error_workflow_id" do
+ workflow = Fabricate(:discourse_workflows_workflow, created_by: admin)
+ error_wf = Fabricate(:discourse_workflows_workflow, created_by: admin)
+
+ put "/admin/plugins/discourse-workflows/workflows/#{workflow.id}.json",
+ params: {
+ workflow: {
+ name: workflow.name,
+ error_workflow_id: error_wf.id,
+ },
+ }
+
+ expect(response).to have_http_status(:ok)
+ expect(response.parsed_body["workflow"]["error_workflow_id"]).to eq(error_wf.id)
+ expect(workflow.reload.error_workflow_id).to eq(error_wf.id)
+ end
+
+ it "returns 422 when error_workflow_id points to the workflow itself" do
+ workflow = Fabricate(:discourse_workflows_workflow, created_by: admin)
+
+ put "/admin/plugins/discourse-workflows/workflows/#{workflow.id}.json",
+ params: {
+ workflow: {
+ name: workflow.name,
+ error_workflow_id: workflow.id,
+ },
+ }
+
+ expect(response).to have_http_status(:unprocessable_entity)
+ expect(workflow.reload.error_workflow_id).to be_nil
+ end
+
+ it "clears error_workflow_id" do
+ error_wf = Fabricate(:discourse_workflows_workflow, created_by: admin)
+ workflow =
+ Fabricate(:discourse_workflows_workflow, created_by: admin, error_workflow_id: error_wf.id)
+
+ put "/admin/plugins/discourse-workflows/workflows/#{workflow.id}.json",
+ params: {
+ workflow: {
+ name: workflow.name,
+ error_workflow_id: nil,
+ },
+ }
+
+ expect(response).to have_http_status(:ok)
+ expect(response.parsed_body["workflow"]["error_workflow_id"]).to be_nil
+ expect(workflow.reload.error_workflow_id).to be_nil
+ end
+
+ it "preserves error_workflow_id when omitted" do
+ error_wf = Fabricate(:discourse_workflows_workflow, created_by: admin)
+ graph =
+ build_workflow_graph { |graph_builder| graph_builder.node "trigger-1", "trigger:manual" }
+ workflow =
+ Fabricate(
+ :discourse_workflows_workflow,
+ created_by: admin,
+ error_workflow_id: error_wf.id,
+ **graph,
+ )
+
+ put "/admin/plugins/discourse-workflows/workflows/#{workflow.id}.json",
+ params: {
+ workflow: {
+ name: workflow.name,
+ nodes: workflow.nodes,
+ connections: workflow.connections,
+ },
+ }
+
+ expect(response).to have_http_status(:ok)
+ expect(response.parsed_body["workflow"]["error_workflow_id"]).to eq(error_wf.id)
+ expect(workflow.reload.error_workflow_id).to eq(error_wf.id)
+ end
+
+ it "returns 400 when name is missing" do
+ workflow = Fabricate(:discourse_workflows_workflow, created_by: admin)
+
+ put "/admin/plugins/discourse-workflows/workflows/#{workflow.id}.json",
+ params: {
+ workflow: {
+ nodes: [],
+ },
+ }
+
+ expect(response).to have_http_status(:bad_request)
+ end
+
+ it "returns 404 when workflow does not exist" do
+ put "/admin/plugins/discourse-workflows/workflows/-1.json",
+ params: {
+ workflow: {
+ name: "Test",
+ },
+ }
+
+ expect(response).to have_http_status(:not_found)
+ end
+
+ it "returns 422 when graph population fails" do
+ workflow = Fabricate(:discourse_workflows_workflow, created_by: admin)
+
+ put "/admin/plugins/discourse-workflows/workflows/#{workflow.id}.json",
+ params: {
+ workflow: {
+ name: "Updated",
+ nodes: [
+ {
+ id: "t1",
+ type: "trigger:schedule",
+ name: "Schedule",
+ parameters: {
+ rule: {
+ interval: [{ field: "cronExpression", expression: "invalid" }],
+ },
+ },
+ },
+ ],
+ connections: {
+ },
+ },
+ }
+
+ expect(response).to have_http_status(:unprocessable_entity)
+ end
+ end
+
+ describe "PUT /admin/plugins/discourse-workflows/workflows/:id/pin-data" do
+ fab!(:workflow) do
+ graph = build_workflow_graph { |g| g.node "trigger-1", "trigger:post_created" }
+ Fabricate(:discourse_workflows_workflow, created_by: admin, **graph)
+ end
+
+ it "persists pinned items unwrapped from ActionController::Parameters" do
+ put "/admin/plugins/discourse-workflows/workflows/#{workflow.id}/pin-data.json",
+ params: {
+ node_name: "Trigger-1",
+ items: [{ json: { post: { id: 42 } } }],
+ },
+ as: :json
+
+ expect(response).to have_http_status(:no_content)
+ expect(workflow.reload.pin_data["Trigger-1"].first["json"]).to eq("post" => { "id" => 42 })
+ end
+
+ it "unpins when no items are provided" do
+ workflow.update_node_pin_data!("Trigger-1", [{ "json" => { "x" => 1 } }])
+
+ put "/admin/plugins/discourse-workflows/workflows/#{workflow.id}/pin-data.json",
+ params: {
+ node_name: "Trigger-1",
+ },
+ as: :json
+
+ expect(response).to have_http_status(:no_content)
+ expect(workflow.reload.pin_data).not_to have_key("Trigger-1")
+ end
+ end
+
+ describe "POST /admin/plugins/discourse-workflows/workflows/:id/discard-draft" do
+ it "restores a workflow to its published version" do
+ published_graph =
+ build_workflow_graph { |builder| builder.node "published-1", "trigger:manual" }
+ workflow =
+ Fabricate(
+ :discourse_workflows_workflow,
+ created_by: admin,
+ published: true,
+ **published_graph,
+ )
+ published_version = workflow.active_version
+ draft_graph = build_workflow_graph { |builder| builder.node "draft-1", "trigger:schedule" }
+ workflow.update!(
+ name: "Draft workflow",
+ nodes: draft_graph[:nodes],
+ connections: draft_graph[:connections],
+ )
+ workflow.snapshot!(user: admin)
+
+ post "/admin/plugins/discourse-workflows/workflows/#{workflow.id}/discard-draft.json"
+
+ expect(response).to have_http_status(:ok)
+ expect(response.parsed_body["workflow"]).to include(
+ "name" => published_version.name,
+ "nodes" => published_version.nodes,
+ "connections" => published_version.connections,
+ "version_id" => published_version.version_id,
+ "active_version_id" => published_version.version_id,
+ "has_unpublished_changes" => false,
+ )
+ end
+ end
+
+ describe "DELETE /admin/plugins/discourse-workflows/workflows/:id" do
+ it "deletes a workflow" do
+ workflow = Fabricate(:discourse_workflows_workflow, created_by: admin)
+
+ delete "/admin/plugins/discourse-workflows/workflows/#{workflow.id}.json"
+
+ expect(response).to have_http_status(:no_content)
+ expect(DiscourseWorkflows::Workflow.exists?(workflow.id)).to be(false)
+ end
+
+ it "returns 404 when workflow does not exist" do
+ delete "/admin/plugins/discourse-workflows/workflows/-1.json"
+ expect(response).to have_http_status(:not_found)
+ end
+ end
+
+ describe "GET /admin/plugins/discourse-workflows/workflows/:id" do
+ it "returns the workflow with nodes and connections" do
+ graph = build_workflow_graph { |g| g.node "trigger-1", "trigger:topic_closed" }
+ workflow = Fabricate(:discourse_workflows_workflow, created_by: admin, **graph)
+
+ get "/admin/plugins/discourse-workflows/workflows/#{workflow.id}.json"
+
+ expect(response).to have_http_status(:ok)
+ json = response.parsed_body
+ expect(json["workflow"]["nodes"].length).to eq(1)
+ end
+
+ it "returns 404 when workflow does not exist" do
+ get "/admin/plugins/discourse-workflows/workflows/-1.json"
+ expect(response).to have_http_status(:not_found)
+ end
+
+ it "includes error_workflow_name when error workflow is set" do
+ error_wf = Fabricate(:discourse_workflows_workflow, created_by: admin, name: "Error handler")
+ workflow =
+ Fabricate(:discourse_workflows_workflow, created_by: admin, error_workflow_id: error_wf.id)
+
+ get "/admin/plugins/discourse-workflows/workflows/#{workflow.id}.json"
+
+ expect(response).to have_http_status(:ok)
+ expect(response.parsed_body["workflow"]["error_workflow_name"]).to eq("Error handler")
+ end
+
+ it "does not include error_workflow_name when no error workflow is set" do
+ workflow = Fabricate(:discourse_workflows_workflow, created_by: admin)
+
+ get "/admin/plugins/discourse-workflows/workflows/#{workflow.id}.json"
+
+ expect(response).to have_http_status(:ok)
+ expect(response.parsed_body["workflow"]).not_to have_key("error_workflow_name")
+ 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
new file mode 100644
index 00000000000..69626cc0935
--- /dev/null
+++ b/plugins/discourse-workflows/spec/serializers/site_serializer_spec.rb
@@ -0,0 +1,72 @@
+# frozen_string_literal: true
+
+RSpec.describe SiteSerializer do
+ fab!(:admin)
+ fab!(:moderator)
+ fab!(:user)
+ let(:guardian) { Guardian.new(admin) }
+
+ describe "#topic_admin_button_workflows" do
+ before { DiscourseWorkflows::WorkflowDependency.clear_cache! }
+
+ fab!(:workflow) do
+ graph =
+ build_workflow_graph do |g|
+ g.node "trigger-1",
+ "trigger:topic_admin_button",
+ configuration: {
+ "label" => "Run workflow",
+ "icon" => "bolt",
+ }
+ end
+ Fabricate(:discourse_workflows_workflow, created_by: admin, published: true, **graph)
+ end
+
+ it "includes published topic admin button workflows" do
+ data = described_class.new(Site.new(guardian), scope: guardian, root: false).as_json
+
+ expect(data[:topic_admin_button_workflows]).to contain_exactly(
+ {
+ trigger_node_id: "trigger-1",
+ workflow_id: workflow.id,
+ label: "Run workflow",
+ icon: "bolt",
+ },
+ )
+ end
+
+ it "is not included for moderators" do
+ mod_guardian = Guardian.new(moderator)
+ data = described_class.new(Site.new(mod_guardian), scope: mod_guardian, root: false).as_json
+
+ expect(data).not_to have_key(:topic_admin_button_workflows)
+ end
+
+ it "is not included for regular users" do
+ user_guardian = Guardian.new(user)
+ data = described_class.new(Site.new(user_guardian), scope: user_guardian, root: false).as_json
+
+ expect(data).not_to have_key(:topic_admin_button_workflows)
+ end
+
+ it "keeps the icon empty when none is configured" do
+ update_workflow_node(workflow, "trigger-1") do |node|
+ node.merge("parameters" => { "label" => "Run workflow" })
+ end
+ publish_workflow!(workflow)
+
+ data = described_class.new(Site.new(guardian), scope: guardian, root: false).as_json
+
+ expect(data[:topic_admin_button_workflows].first[:icon]).to be_nil
+ end
+
+ it "excludes unpublished workflows" do
+ unpublish_workflow!(workflow)
+ DiscourseWorkflows::WorkflowDependency.clear_cache!
+
+ data = described_class.new(Site.new(guardian), scope: guardian, root: false).as_json
+
+ expect(data[:topic_admin_button_workflows]).to be_empty
+ end
+ end
+end
diff --git a/plugins/discourse-workflows/spec/services/discourse_workflows/credential/create_spec.rb b/plugins/discourse-workflows/spec/services/discourse_workflows/credential/create_spec.rb
new file mode 100644
index 00000000000..cc0142cedc1
--- /dev/null
+++ b/plugins/discourse-workflows/spec/services/discourse_workflows/credential/create_spec.rb
@@ -0,0 +1,90 @@
+# frozen_string_literal: true
+
+RSpec.describe DiscourseWorkflows::Credential::Create do
+ describe described_class::Contract, type: :model do
+ it { is_expected.to validate_presence_of(:name) }
+ it { is_expected.to validate_length_of(:name).is_at_most(128) }
+ it { is_expected.to validate_presence_of(:credential_type) }
+ it { is_expected.to validate_length_of(:credential_type).is_at_most(64) }
+ end
+
+ describe ".call" do
+ subject(:result) { described_class.call(params:, **dependencies) }
+
+ fab!(:admin)
+
+ let(:params) do
+ {
+ name: "My webhook auth",
+ credential_type: "basic_auth",
+ data: {
+ user: "admin",
+ password: "secret123",
+ },
+ }
+ end
+ let(:dependencies) { { guardian: admin.guardian } }
+
+ context "when user cannot manage workflows" do
+ fab!(:user)
+
+ let(:dependencies) { { guardian: user.guardian } }
+
+ it { is_expected.to fail_a_policy(:can_manage_workflows) }
+ end
+
+ context "when contract is invalid" do
+ let(:params) { { name: nil, credential_type: nil } }
+
+ it { is_expected.to fail_a_contract }
+ end
+
+ context "when credential_type is not registered" do
+ let(:params) { super().merge(credential_type: "unknown_type") }
+
+ it { is_expected.to fail_a_policy(:valid_credential_type) }
+ end
+
+ context "when data is not a hash" do
+ ["not-a-hash", %w[foo bar]].each do |non_hash|
+ context "with #{non_hash.class}" do
+ let(:params) { super().merge(data: non_hash) }
+
+ it { is_expected.to fail_a_contract }
+ end
+ end
+ end
+
+ context "when data is missing a required field" do
+ let(:params) { super().merge(data: { user: "admin" }) }
+
+ it { is_expected.to fail_with_an_invalid_model(:credential) }
+ end
+
+ context "when a required field is empty" do
+ let(:params) { super().merge(data: { user: "admin", password: "" }) }
+
+ it { is_expected.to fail_with_an_invalid_model(:credential) }
+ end
+
+ context "when everything is valid" do
+ it { is_expected.to run_successfully }
+
+ it "creates a credential" do
+ expect { result }.to change { DiscourseWorkflows::Credential.count }.by(1)
+ credential = DiscourseWorkflows::Credential.last
+ expect(credential.name).to eq("My webhook auth")
+ expect(credential.credential_type).to eq("basic_auth")
+ expect(credential.data).to eq("user" => "admin", "password" => "secret123")
+ end
+
+ it "logs a staff action" do
+ expect { result }.to change { UserHistory.count }.by(1)
+ expect(UserHistory.last).to have_attributes(
+ custom_type: "discourse_workflows_credential_created",
+ subject: "My webhook auth",
+ )
+ end
+ end
+ end
+end
diff --git a/plugins/discourse-workflows/spec/services/discourse_workflows/credential/destroy_spec.rb b/plugins/discourse-workflows/spec/services/discourse_workflows/credential/destroy_spec.rb
new file mode 100644
index 00000000000..7d7b2e90b5d
--- /dev/null
+++ b/plugins/discourse-workflows/spec/services/discourse_workflows/credential/destroy_spec.rb
@@ -0,0 +1,83 @@
+# frozen_string_literal: true
+
+RSpec.describe DiscourseWorkflows::Credential::Destroy do
+ describe described_class::Contract, type: :model do
+ it { is_expected.to validate_presence_of(:credential_id) }
+ end
+
+ describe ".call" do
+ subject(:result) { described_class.call(params:, **dependencies) }
+
+ fab!(:admin)
+ fab!(:credential, :discourse_workflows_credential)
+
+ let(:params) { { credential_id: credential.id } }
+ let(:dependencies) { { guardian: admin.guardian } }
+
+ context "when contract is invalid" do
+ let(:params) { {} }
+
+ it { is_expected.to fail_a_contract }
+ end
+
+ context "when credential is not found" do
+ let(:params) { { credential_id: -1 } }
+
+ it { is_expected.to fail_to_find_a_model(:credential) }
+ end
+
+ context "when user cannot manage workflows" do
+ fab!(:user)
+
+ let(:dependencies) { { guardian: user.guardian } }
+
+ it { is_expected.to fail_a_policy(:can_manage_workflows) }
+ end
+
+ context "when credential is referenced by a workflow node" do
+ fab!(:workflow) do
+ graph =
+ build_workflow_graph do |g|
+ g.node "webhook-1",
+ "trigger:webhook",
+ parameters: {
+ "authentication" => "basic_auth",
+ },
+ credentials: {
+ "auth" => {
+ "id" => credential.id,
+ "credential_type" => "basic_auth",
+ },
+ }
+ end
+ Fabricate(:discourse_workflows_workflow, name: "My Workflow", created_by: admin, **graph)
+ end
+
+ before { DiscourseWorkflows::WorkflowDependencyIndexer.call(workflow) }
+
+ it { is_expected.to fail_a_policy(:credential_not_in_use) }
+
+ it "exposes referencing workflows" do
+ expect(result[:referencing_workflows]).to contain_exactly(
+ { id: workflow.id, name: "My Workflow" },
+ )
+ end
+ end
+
+ context "when everything is valid" do
+ it { is_expected.to run_successfully }
+
+ it "destroys the credential" do
+ expect { result }.to change { DiscourseWorkflows::Credential.count }.by(-1)
+ end
+
+ it "logs a staff action" do
+ expect { result }.to change { UserHistory.count }.by(1)
+ expect(UserHistory.last).to have_attributes(
+ custom_type: "discourse_workflows_credential_destroyed",
+ subject: credential.name,
+ )
+ end
+ end
+ end
+end
diff --git a/plugins/discourse-workflows/spec/services/discourse_workflows/credential/list_spec.rb b/plugins/discourse-workflows/spec/services/discourse_workflows/credential/list_spec.rb
new file mode 100644
index 00000000000..3d5d8ddda39
--- /dev/null
+++ b/plugins/discourse-workflows/spec/services/discourse_workflows/credential/list_spec.rb
@@ -0,0 +1,91 @@
+# frozen_string_literal: true
+
+RSpec.describe DiscourseWorkflows::Credential::List do
+ describe ".call" do
+ subject(:result) { described_class.call(params:, **dependencies) }
+
+ fab!(:admin)
+
+ let(:params) { {} }
+ let(:dependencies) { { guardian: admin.guardian } }
+
+ context "when user cannot manage workflows" do
+ fab!(:user)
+
+ let(:dependencies) { { guardian: user.guardian } }
+
+ it { is_expected.to fail_a_policy(:can_manage_workflows) }
+ end
+
+ context "when credentials exist" do
+ fab!(:credential_1) { Fabricate(:discourse_workflows_credential, name: "First") }
+ fab!(:credential_2) { Fabricate(:discourse_workflows_credential, name: "Second") }
+
+ it { is_expected.to run_successfully }
+
+ it "returns credentials ordered by id desc" do
+ expect(result[:credentials].map(&:name)).to eq(%w[Second First])
+ end
+
+ it "returns total_rows" do
+ expect(result[:total_rows]).to eq(2)
+ end
+
+ it "does not set load_more_url" do
+ expect(result[:load_more_url]).to be_nil
+ end
+ end
+
+ context "when paginating" do
+ fab!(:credential_1) { Fabricate(:discourse_workflows_credential, name: "First") }
+ fab!(:credential_2) { Fabricate(:discourse_workflows_credential, name: "Second") }
+ fab!(:credential_3) { Fabricate(:discourse_workflows_credential, name: "Third") }
+
+ let(:params) { { limit: 2 } }
+
+ it "returns load_more_url when more results exist" do
+ expect(result[:credentials].length).to eq(2)
+ expect(result[:load_more_url]).to include("cursor=")
+ end
+
+ context "with cursor" do
+ let(:params) { { cursor: credential_3.id, limit: 10 } }
+
+ it "returns credentials before cursor" do
+ expect(result[:credentials].map(&:name)).to eq(%w[Second First])
+ end
+ end
+ end
+
+ context "when filtering by type" do
+ fab!(:basic_credential) do
+ Fabricate(:discourse_workflows_credential, credential_type: "basic_auth")
+ end
+ fab!(:other_credential) do
+ Fabricate(:discourse_workflows_credential, credential_type: "api_key", name: "API Key")
+ end
+
+ let(:params) { { type: "basic_auth" } }
+
+ it "returns only matching credentials" do
+ expect(result[:credentials].map(&:id)).to eq([basic_credential.id])
+ end
+
+ it "returns total_rows scoped to type" do
+ expect(result[:total_rows]).to eq(1)
+ end
+
+ context "with pagination" do
+ fab!(:basic_credential_2) do
+ Fabricate(:discourse_workflows_credential, credential_type: "basic_auth", name: "Auth 2")
+ end
+
+ let(:params) { { type: "basic_auth", limit: 1 } }
+
+ it "includes type in load_more_url" do
+ expect(result[:load_more_url]).to include("type=basic_auth")
+ end
+ end
+ end
+ end
+end
diff --git a/plugins/discourse-workflows/spec/services/discourse_workflows/credential/update_spec.rb b/plugins/discourse-workflows/spec/services/discourse_workflows/credential/update_spec.rb
new file mode 100644
index 00000000000..039fa6a65e3
--- /dev/null
+++ b/plugins/discourse-workflows/spec/services/discourse_workflows/credential/update_spec.rb
@@ -0,0 +1,151 @@
+# frozen_string_literal: true
+
+RSpec.describe DiscourseWorkflows::Credential::Update do
+ describe described_class::Contract, type: :model do
+ it { is_expected.to validate_presence_of(:credential_id) }
+ it { is_expected.to validate_presence_of(:name) }
+ it { is_expected.to validate_length_of(:name).is_at_most(128) }
+ end
+
+ describe ".call" do
+ subject(:result) { described_class.call(params:, **dependencies) }
+
+ fab!(:admin)
+ fab!(:credential) { Fabricate(:discourse_workflows_credential, name: "Old name") }
+
+ let(:params) do
+ {
+ credential_id: credential.id,
+ name: "New name",
+ data: {
+ user: DiscourseWorkflows::Credential::REDACTED_VALUE,
+ password: "new_password",
+ },
+ }
+ end
+ let(:dependencies) { { guardian: admin.guardian } }
+
+ context "when contract is invalid" do
+ let(:params) { { credential_id: credential.id, name: nil } }
+
+ it { is_expected.to fail_a_contract }
+ end
+
+ context "when credential not found" do
+ let(:params) { super().merge(credential_id: -1) }
+
+ it { is_expected.to fail_to_find_a_model(:credential) }
+ end
+
+ context "when user cannot manage workflows" do
+ fab!(:user)
+
+ let(:dependencies) { { guardian: user.guardian } }
+
+ it { is_expected.to fail_a_policy(:can_manage_workflows) }
+ end
+
+ context "when name is too long" do
+ let(:params) { super().merge(name: "x" * 200) }
+
+ it { is_expected.to fail_a_contract }
+ end
+
+ context "when everything is valid" do
+ it { is_expected.to run_successfully }
+
+ it "updates the name" do
+ result
+ expect(credential.reload.name).to eq("New name")
+ end
+
+ it "preserves redacted values from original data" do
+ result
+ data = credential.reload.data
+ expect(data["user"]).to eq("admin")
+ expect(data["password"]).to eq("new_password")
+ end
+
+ it "logs a staff action" do
+ expect { result }.to change { UserHistory.count }.by(1)
+ expect(UserHistory.last).to have_attributes(
+ custom_type: "discourse_workflows_credential_updated",
+ subject: "New name",
+ )
+ end
+ end
+
+ context "when all values are redacted" do
+ let(:params) do
+ {
+ credential_id: credential.id,
+ name: "New name",
+ data: {
+ user: DiscourseWorkflows::Credential::REDACTED_VALUE,
+ password: DiscourseWorkflows::Credential::REDACTED_VALUE,
+ },
+ }
+ end
+
+ it "preserves all original values" do
+ result
+ data = credential.reload.data
+ expect(data["user"]).to eq("admin")
+ expect(data["password"]).to eq("secret")
+ end
+ end
+
+ context "when data is not provided" do
+ let(:params) { { credential_id: credential.id, name: "New name" } }
+
+ it { is_expected.to run_successfully }
+
+ it "updates only the name" do
+ result
+ credential.reload
+ expect(credential.name).to eq("New name")
+ expect(credential.data).to eq({ "user" => "admin", "password" => "secret" })
+ end
+ end
+
+ context "when data is a partial payload omitting original keys" do
+ let(:params) do
+ { credential_id: credential.id, name: "New name", data: { password: "new_password" } }
+ end
+
+ it "preserves keys that were not sent" do
+ result
+ expect(credential.reload.data).to eq("user" => "admin", "password" => "new_password")
+ end
+ end
+
+ context "when data contains a new key not in the original" do
+ let(:params) { { credential_id: credential.id, name: "New name", data: { extra: "value" } } }
+
+ it "adds the new key while preserving originals" do
+ result
+ expect(credential.reload.data).to eq(
+ "user" => "admin",
+ "password" => "secret",
+ "extra" => "value",
+ )
+ end
+ end
+
+ context "when data is not a hash" do
+ ["not-a-hash", %w[foo bar]].each do |non_hash|
+ context "with #{non_hash.class}" do
+ let(:params) { super().merge(data: non_hash) }
+
+ it { is_expected.to fail_a_contract }
+ end
+ end
+ end
+
+ context "when an explicit empty value would clear a required field" do
+ let(:params) { { credential_id: credential.id, name: "New name", data: { password: "" } } }
+
+ it { is_expected.to fail_with_an_invalid_model(:credential) }
+ end
+ end
+end
diff --git a/plugins/discourse-workflows/spec/services/discourse_workflows/data_table/create_spec.rb b/plugins/discourse-workflows/spec/services/discourse_workflows/data_table/create_spec.rb
new file mode 100644
index 00000000000..3021bc7cef7
--- /dev/null
+++ b/plugins/discourse-workflows/spec/services/discourse_workflows/data_table/create_spec.rb
@@ -0,0 +1,85 @@
+# frozen_string_literal: true
+
+RSpec.describe DiscourseWorkflows::DataTable::Create do
+ describe described_class::Contract, type: :model do
+ it { is_expected.to validate_presence_of(:name) }
+ it { is_expected.to validate_length_of(:name).is_at_most(100) }
+ it do
+ is_expected.to allow_values("valid_name", "Name 123", "_underscore", "Table A").for(:name)
+ end
+ it { is_expected.not_to allow_values("123start", "name!@#").for(:name) }
+ end
+
+ describe ".call" do
+ subject(:result) { described_class.call(params:, **dependencies) }
+
+ fab!(:admin)
+
+ let(:params) { { name: "my_table", columns: } }
+ let(:dependencies) { { guardian: } }
+ let(:guardian) { admin.guardian }
+ let(:columns) { [{ "name" => "value", "type" => "string" }] }
+
+ context "when contract is invalid" do
+ let(:params) { { name: nil } }
+
+ it { is_expected.to fail_a_contract }
+ end
+
+ context "when user cannot manage workflows" do
+ fab!(:user)
+
+ let(:guardian) { user.guardian }
+
+ it { is_expected.to fail_a_policy(:can_manage_workflows) }
+ end
+
+ context "when name has invalid format" do
+ let(:params) { { name: "123 invalid!", columns: [] } }
+
+ it { is_expected.to fail_a_contract }
+ end
+
+ context "when name is too long" do
+ let(:params) { { name: "a" * 101, columns: [] } }
+
+ it { is_expected.to fail_a_contract }
+ end
+
+ context "when everything's ok" do
+ it { is_expected.to run_successfully }
+
+ it "creates the data table with columns" do
+ expect { result }.to change(DiscourseWorkflows::DataTable, :count).by(1)
+
+ data_table = DiscourseWorkflows::DataTable.last
+ expect(data_table.name).to eq("my_table")
+ expect(data_table.columns).to include({ "name" => "value", "type" => "string" })
+ end
+
+ it "logs a staff action" do
+ result
+ log = UserHistory.last
+ expect(log.custom_type).to eq("discourse_workflows_data_table_created")
+ expect(log.subject).to eq("my_table")
+ end
+ end
+
+ context "when columns are omitted" do
+ let(:params) { { name: "empty_table" } }
+
+ it { is_expected.to run_successfully }
+
+ it "creates the data table without columns" do
+ result
+ data_table = DiscourseWorkflows::DataTable.last
+ expect(data_table.name).to eq("empty_table")
+ user_columns =
+ data_table.columns.reject do |c|
+ DiscourseWorkflows::DataTables::Types.system_column?(c["name"])
+ end
+ expect(user_columns).to be_empty
+ end
+ end
+ end
+end
diff --git a/plugins/discourse-workflows/spec/services/discourse_workflows/data_table/destroy_spec.rb b/plugins/discourse-workflows/spec/services/discourse_workflows/data_table/destroy_spec.rb
new file mode 100644
index 00000000000..438700509af
--- /dev/null
+++ b/plugins/discourse-workflows/spec/services/discourse_workflows/data_table/destroy_spec.rb
@@ -0,0 +1,88 @@
+# frozen_string_literal: true
+
+RSpec.describe DiscourseWorkflows::DataTable::Destroy do
+ describe described_class::Contract, type: :model do
+ it { is_expected.to validate_presence_of(:data_table_id) }
+ end
+
+ describe ".call" do
+ subject(:result) { described_class.call(params:, **dependencies) }
+
+ fab!(:admin)
+ fab!(:data_table, :discourse_workflows_data_table)
+
+ let(:params) { { data_table_id: data_table.id } }
+ let(:dependencies) { { guardian: admin.guardian } }
+
+ context "when contract is invalid" do
+ let(:params) { { data_table_id: nil } }
+
+ it { is_expected.to fail_a_contract }
+ end
+
+ context "when user cannot manage workflows" do
+ fab!(:user)
+
+ let(:dependencies) { { guardian: user.guardian } }
+
+ it { is_expected.to fail_a_policy(:can_manage_workflows) }
+ end
+
+ context "when data table does not exist" do
+ let(:params) { { data_table_id: -1 } }
+
+ it { is_expected.to fail_to_find_a_model(:data_table) }
+ end
+
+ context "when data table is referenced by a workflow node" do
+ fab!(:workflow) do
+ Fabricate(
+ :discourse_workflows_workflow,
+ name: "My Workflow",
+ created_by: admin,
+ nodes: [
+ {
+ "id" => "data-table-1",
+ "type" => "action:data_table",
+ "typeVersion" => "1.0",
+ "name" => "Data Table",
+ "position" => {
+ "x" => 0,
+ "y" => 0,
+ },
+ "parameters" => {
+ "data_table_id" => data_table.id,
+ },
+ "credentials" => {
+ },
+ },
+ ],
+ connections: {
+ },
+ )
+ end
+
+ before { DiscourseWorkflows::WorkflowDependencyIndexer.call(workflow) }
+
+ it { is_expected.to fail_a_policy(:data_table_not_in_use) }
+ end
+
+ context "when everything is ok" do
+ it { is_expected.to run_successfully }
+
+ it "destroys the data table" do
+ expect { result }.to change { DiscourseWorkflows::DataTable.exists?(data_table.id) }.from(
+ true,
+ ).to(false)
+ end
+
+ it "logs a staff action" do
+ expect { result }.to change { UserHistory.count }.by(1)
+
+ log = UserHistory.last
+ expect(log.custom_type).to eq("discourse_workflows_data_table_destroyed")
+ expect(log.subject).to eq(data_table.name)
+ end
+ end
+ end
+end
diff --git a/plugins/discourse-workflows/spec/services/discourse_workflows/data_table/list_spec.rb b/plugins/discourse-workflows/spec/services/discourse_workflows/data_table/list_spec.rb
new file mode 100644
index 00000000000..47e791c22ec
--- /dev/null
+++ b/plugins/discourse-workflows/spec/services/discourse_workflows/data_table/list_spec.rb
@@ -0,0 +1,102 @@
+# frozen_string_literal: true
+
+RSpec.describe DiscourseWorkflows::DataTable::List do
+ describe ".call" do
+ subject(:result) { described_class.call(params:, **dependencies) }
+
+ fab!(:admin)
+
+ let(:params) { {} }
+ let(:dependencies) { { guardian: admin.guardian } }
+
+ context "when user cannot manage workflows" do
+ fab!(:user)
+
+ let(:dependencies) { { guardian: user.guardian } }
+
+ it { is_expected.to fail_a_policy(:can_manage_workflows) }
+ end
+
+ context "when there are no data tables" do
+ it { is_expected.to run_successfully }
+
+ it "returns an empty collection" do
+ expect(result[:data_tables]).to be_empty
+ end
+
+ it "returns zero total rows" do
+ expect(result[:total_rows]).to eq(0)
+ end
+
+ it "does not return a load more url" do
+ expect(result[:load_more_url]).to be_nil
+ end
+
+ it "returns empty table sizes" do
+ expect(result[:table_sizes]).to eq({})
+ end
+ end
+
+ context "when there are data tables" do
+ fab!(:data_table_a) { Fabricate(:discourse_workflows_data_table, name: "Alpha") }
+ fab!(:data_table_b) { Fabricate(:discourse_workflows_data_table, name: "Bravo") }
+
+ it { is_expected.to run_successfully }
+
+ it "returns data tables ordered by id descending" do
+ expect(result[:data_tables].map(&:id)).to eq([data_table_b.id, data_table_a.id])
+ end
+
+ it "returns the total count" do
+ expect(result[:total_rows]).to eq(2)
+ end
+
+ it "does not return a load more url when all results fit" do
+ expect(result[:load_more_url]).to be_nil
+ end
+
+ it "returns table sizes keyed by data table id" do
+ expect(result[:table_sizes].keys).to contain_exactly(data_table_a.id, data_table_b.id)
+ end
+ end
+
+ context "with pagination" do
+ let(:params) { { limit: 2 } }
+
+ fab!(:data_table_1) { Fabricate(:discourse_workflows_data_table, name: "First") }
+ fab!(:data_table_2) { Fabricate(:discourse_workflows_data_table, name: "Second") }
+ fab!(:data_table_3) { Fabricate(:discourse_workflows_data_table, name: "Third") }
+
+ it "returns only the requested number of data tables" do
+ expect(result[:data_tables].size).to eq(2)
+ end
+
+ it "returns a load more url with cursor" do
+ last_id = result[:data_tables].last.id
+ expect(result[:load_more_url]).to eq(
+ "/admin/plugins/discourse-workflows/data-tables.json?cursor=#{last_id}&limit=2",
+ )
+ end
+
+ it "returns the total count of all data tables" do
+ expect(result[:total_rows]).to eq(3)
+ end
+
+ it "returns table sizes only for returned data tables" do
+ expect(result[:table_sizes].keys.size).to eq(2)
+ end
+
+ context "when using a cursor" do
+ let(:params) { { limit: 2, cursor: data_table_3.id } }
+
+ it "returns data tables after the cursor" do
+ expect(result[:data_tables].map(&:id)).to eq([data_table_2.id, data_table_1.id])
+ end
+
+ it "does not return a load more url when no more results" do
+ expect(result[:load_more_url]).to be_nil
+ end
+ end
+ end
+ end
+end
diff --git a/plugins/discourse-workflows/spec/services/discourse_workflows/data_table/show_spec.rb b/plugins/discourse-workflows/spec/services/discourse_workflows/data_table/show_spec.rb
new file mode 100644
index 00000000000..c5871f28852
--- /dev/null
+++ b/plugins/discourse-workflows/spec/services/discourse_workflows/data_table/show_spec.rb
@@ -0,0 +1,44 @@
+# frozen_string_literal: true
+
+RSpec.describe DiscourseWorkflows::DataTable::Show do
+ describe described_class::Contract, type: :model do
+ it { is_expected.to validate_presence_of(:data_table_id) }
+ end
+
+ describe ".call" do
+ subject(:result) { described_class.call(params:, **dependencies) }
+
+ fab!(:admin)
+ fab!(:data_table, :discourse_workflows_data_table)
+
+ let(:params) { { data_table_id: data_table.id } }
+ let(:dependencies) { { guardian: admin.guardian } }
+
+ context "when contract is invalid" do
+ let(:params) { { data_table_id: nil } }
+
+ it { is_expected.to fail_a_contract }
+ end
+
+ context "when user cannot manage workflows" do
+ fab!(:user)
+
+ let(:dependencies) { { guardian: user.guardian } }
+
+ it { is_expected.to fail_a_policy(:can_manage_workflows) }
+ end
+
+ context "when data table does not exist" do
+ let(:params) { { data_table_id: -1 } }
+
+ it { is_expected.to fail_to_find_a_model(:data_table) }
+ end
+
+ context "when data table exists" do
+ it "returns the data table" do
+ expect(result).to run_successfully
+ expect(result[:data_table]).to eq(data_table)
+ end
+ end
+ end
+end
diff --git a/plugins/discourse-workflows/spec/services/discourse_workflows/data_table/update_spec.rb b/plugins/discourse-workflows/spec/services/discourse_workflows/data_table/update_spec.rb
new file mode 100644
index 00000000000..dac5b1436ba
--- /dev/null
+++ b/plugins/discourse-workflows/spec/services/discourse_workflows/data_table/update_spec.rb
@@ -0,0 +1,81 @@
+# frozen_string_literal: true
+
+RSpec.describe DiscourseWorkflows::DataTable::Update do
+ describe described_class::Contract, type: :model do
+ it { is_expected.to validate_presence_of(:data_table_id) }
+ it { is_expected.to validate_presence_of(:name) }
+ it { is_expected.to validate_length_of(:name).is_at_most(100) }
+ it do
+ is_expected.to allow_values("valid_name", "Name 123", "_underscore", "Table A").for(:name)
+ end
+ it { is_expected.not_to allow_values("123start", "name!@#").for(:name) }
+ end
+
+ describe ".call" do
+ subject(:result) { described_class.call(params:, **dependencies) }
+
+ fab!(:admin)
+ fab!(:data_table) do
+ Fabricate(
+ :discourse_workflows_data_table,
+ name: "original",
+ columns: [{ "name" => "value", "type" => "string" }],
+ )
+ end
+
+ let(:params) { { data_table_id: data_table.id, name: "updated" } }
+ let(:dependencies) { { guardian: admin.guardian } }
+
+ context "when data table does not exist" do
+ let(:params) { { data_table_id: -1, name: "anything" } }
+
+ it { is_expected.to fail_to_find_a_model(:data_table) }
+ end
+
+ context "when contract is invalid" do
+ let(:params) { { data_table_id: data_table.id, name: "" } }
+
+ it { is_expected.to fail_a_contract }
+ end
+
+ context "when user cannot manage workflows" do
+ fab!(:user)
+
+ let(:dependencies) { { guardian: user.guardian } }
+
+ it { is_expected.to fail_a_policy(:can_manage_workflows) }
+ end
+
+ context "when name has invalid format" do
+ let(:params) { { data_table_id: data_table.id, name: "invalid-name!" } }
+
+ it { is_expected.to fail_a_contract }
+ end
+
+ context "when name is too long" do
+ let(:params) { { data_table_id: data_table.id, name: "a" * 101 } }
+
+ it { is_expected.to fail_a_contract }
+ end
+
+ context "when everything is ok" do
+ it { is_expected.to run_successfully }
+
+ it "updates the name" do
+ expect { result }.to change { data_table.reload.name }.from("original").to("updated")
+ end
+
+ it "preserves existing columns" do
+ expect { result }.not_to change { data_table.reload.columns.map { |c| c["name"] } }
+ end
+
+ it "logs a staff action" do
+ expect { result }.to change { UserHistory.count }.by(1)
+ expect(UserHistory.last).to have_attributes(
+ custom_type: "discourse_workflows_data_table_updated",
+ subject: "updated",
+ )
+ end
+ end
+ end
+end
diff --git a/plugins/discourse-workflows/spec/services/discourse_workflows/data_table_column/create_spec.rb b/plugins/discourse-workflows/spec/services/discourse_workflows/data_table_column/create_spec.rb
new file mode 100644
index 00000000000..ad1dbe63cb4
--- /dev/null
+++ b/plugins/discourse-workflows/spec/services/discourse_workflows/data_table_column/create_spec.rb
@@ -0,0 +1,112 @@
+# frozen_string_literal: true
+
+RSpec.describe DiscourseWorkflows::DataTableColumn::Create do
+ describe described_class::Contract, type: :model do
+ it { is_expected.to validate_presence_of(:data_table_id) }
+ it { is_expected.to validate_presence_of(:name) }
+ it do
+ is_expected.to validate_length_of(:name).is_at_most(
+ DiscourseWorkflows::DataTable::MAX_COLUMN_NAME_LENGTH,
+ )
+ end
+ it { is_expected.to allow_values("valid_col", "column_1", "_col").for(:name) }
+ it do
+ is_expected.not_to allow_values("123col", "col space", "col!@#", "id", "created_at").for(
+ :name,
+ )
+ end
+ it { is_expected.to validate_presence_of(:column_type) }
+ it do
+ is_expected.to allow_values(*DiscourseWorkflows::DataTable::VALID_COLUMN_TYPES).for(
+ :column_type,
+ )
+ end
+ it { is_expected.not_to allow_values("text", "unknown_type").for(:column_type) }
+ end
+
+ describe ".call" do
+ subject(:result) { described_class.call(params:, **dependencies) }
+
+ fab!(:admin)
+
+ fab!(:data_table) do
+ Fabricate(
+ :discourse_workflows_data_table,
+ columns: [{ "name" => "email", "type" => "string" }],
+ )
+ end
+
+ fab!(:row) { insert_data_table_row(data_table, "email" => "[email protected]") }
+
+ let(:params) { { data_table_id: data_table.id, name: "score", column_type: "number" } }
+ let(:dependencies) { { guardian: admin.guardian } }
+
+ context "when contract is invalid" do
+ let(:params) { { data_table_id: nil, name: nil, column_type: nil } }
+
+ it { is_expected.to fail_a_contract }
+ end
+
+ context "when user cannot manage workflows" do
+ fab!(:user)
+
+ let(:dependencies) { { guardian: user.guardian } }
+
+ it { is_expected.to fail_a_policy(:can_manage_workflows) }
+ end
+
+ context "when the data table does not exist" do
+ let(:params) { { data_table_id: -1, name: "score", column_type: "number" } }
+
+ it { is_expected.to fail_to_find_a_model(:data_table) }
+ end
+
+ context "when the column type is invalid" do
+ let(:params) { { data_table_id: data_table.id, name: "score", column_type: "invalid" } }
+
+ it { is_expected.to fail_a_contract }
+ end
+
+ context "when the name is reserved" do
+ let(:params) { { data_table_id: data_table.id, name: "id", column_type: "string" } }
+
+ it { is_expected.to fail_a_contract }
+ end
+
+ context "when column limit is reached" do
+ before do
+ facade = DiscourseWorkflows::DataTables::Facade.new(data_table)
+ 29.times { |i| facade.add_column!("col_#{i}", "string") }
+ end
+
+ it { is_expected.to fail_a_policy(:column_limit_not_reached) }
+ end
+
+ context "when everything is ok" do
+ it { is_expected.to run_successfully }
+
+ it "creates the column in the storage table" do
+ result
+ columns = data_table.columns.map { |c| c["name"] }
+ expect(columns).to include("email", "score")
+ end
+
+ it "logs a staff action" do
+ result
+ expect(UserHistory.last).to have_attributes(
+ custom_type: "discourse_workflows_data_table_column_created",
+ subject: data_table.name,
+ )
+ end
+
+ it "preserves existing row data" do
+ result
+
+ expect(find_data_table_row(data_table, row["id"])).to include(
+ "email" => "[email protected]",
+ "score" => nil,
+ )
+ end
+ end
+ end
+end
diff --git a/plugins/discourse-workflows/spec/services/discourse_workflows/data_table_column/destroy_spec.rb b/plugins/discourse-workflows/spec/services/discourse_workflows/data_table_column/destroy_spec.rb
new file mode 100644
index 00000000000..a7333052dfc
--- /dev/null
+++ b/plugins/discourse-workflows/spec/services/discourse_workflows/data_table_column/destroy_spec.rb
@@ -0,0 +1,89 @@
+# frozen_string_literal: true
+
+RSpec.describe DiscourseWorkflows::DataTableColumn::Destroy do
+ describe described_class::Contract, type: :model do
+ it { is_expected.to validate_presence_of(:data_table_id) }
+ it { is_expected.to validate_presence_of(:column_name) }
+ end
+
+ describe ".call" do
+ subject(:result) { described_class.call(params:, **dependencies) }
+
+ fab!(:admin)
+
+ let(:dependencies) { { guardian: admin.guardian } }
+
+ fab!(:data_table) do
+ Fabricate(
+ :discourse_workflows_data_table,
+ columns: [
+ { "name" => "email", "type" => "string" },
+ { "name" => "score", "type" => "number" },
+ ],
+ )
+ end
+
+ fab!(:row) { insert_data_table_row(data_table, "email" => "[email protected]", "score" => 5) }
+
+ let(:params) { { data_table_id: data_table.id, column_name: "email" } }
+
+ context "when contract is invalid" do
+ let(:params) { { data_table_id: nil, column_name: nil } }
+
+ it { is_expected.to fail_a_contract }
+ end
+
+ context "when user cannot manage workflows" do
+ fab!(:user)
+
+ let(:dependencies) { { guardian: user.guardian } }
+
+ it { is_expected.to fail_a_policy(:can_manage_workflows) }
+ end
+
+ context "when the data table does not exist" do
+ let(:params) { { data_table_id: -1, column_name: "email" } }
+
+ it { is_expected.to fail_to_find_a_model(:data_table) }
+ end
+
+ context "when the column does not exist" do
+ let(:params) { { data_table_id: data_table.id, column_name: "nonexistent" } }
+
+ it { is_expected.to fail_a_policy(:column_exists) }
+ end
+
+ context "when trying to delete a reserved column" do
+ let(:params) { { data_table_id: data_table.id, column_name: "id" } }
+
+ it { is_expected.to fail_a_policy(:not_reserved_column) }
+ end
+
+ context "when everything is ok" do
+ it { is_expected.to run_successfully }
+
+ it "removes the column from the storage table" do
+ result
+ column_names = data_table.columns.map { |c| c["name"] }
+ expect(column_names).not_to include("email")
+ expect(column_names).to include("score")
+ end
+
+ it "logs a staff action" do
+ result
+ expect(UserHistory.last).to have_attributes(
+ custom_type: "discourse_workflows_data_table_column_destroyed",
+ subject: data_table.name,
+ )
+ end
+
+ it "preserves the remaining row data" do
+ result
+
+ row_data = find_data_table_row(data_table, row["id"])
+ expect(row_data["score"]).to eq(5)
+ expect(row_data).not_to have_key("email")
+ end
+ end
+ end
+end
diff --git a/plugins/discourse-workflows/spec/services/discourse_workflows/data_table_column/rename_spec.rb b/plugins/discourse-workflows/spec/services/discourse_workflows/data_table_column/rename_spec.rb
new file mode 100644
index 00000000000..aa324ee4b22
--- /dev/null
+++ b/plugins/discourse-workflows/spec/services/discourse_workflows/data_table_column/rename_spec.rb
@@ -0,0 +1,108 @@
+# frozen_string_literal: true
+
+RSpec.describe DiscourseWorkflows::DataTableColumn::Rename do
+ describe described_class::Contract, type: :model do
+ it { is_expected.to validate_presence_of(:data_table_id) }
+ it { is_expected.to validate_presence_of(:column_name) }
+ it { is_expected.to validate_presence_of(:name) }
+ it do
+ is_expected.to validate_length_of(:name).is_at_most(
+ DiscourseWorkflows::DataTable::MAX_COLUMN_NAME_LENGTH,
+ )
+ end
+ it { is_expected.to allow_values("valid_col", "column_1", "_col").for(:name) }
+ it do
+ is_expected.not_to allow_values("123col", "col space", "col!@#", "id", "created_at").for(
+ :name,
+ )
+ end
+ end
+
+ describe ".call" do
+ subject(:result) { described_class.call(params:, **dependencies) }
+
+ fab!(:admin)
+
+ fab!(:data_table) do
+ Fabricate(
+ :discourse_workflows_data_table,
+ columns: [
+ { "name" => "email", "type" => "string" },
+ { "name" => "score", "type" => "number" },
+ ],
+ )
+ end
+
+ fab!(:row) { insert_data_table_row(data_table, "email" => "[email protected]") }
+
+ let(:params) { { data_table_id: data_table.id, column_name: "email", name: "contact_email" } }
+ let(:dependencies) { { guardian: admin.guardian } }
+
+ context "when contract is invalid" do
+ let(:params) { { data_table_id: data_table.id, column_name: "email", name: "123-invalid" } }
+
+ it { is_expected.to fail_a_contract }
+ end
+
+ context "when user cannot manage workflows" do
+ fab!(:user)
+
+ let(:dependencies) { { guardian: user.guardian } }
+
+ it { is_expected.to fail_a_policy(:can_manage_workflows) }
+ end
+
+ context "when the data table does not exist" do
+ let(:params) { { data_table_id: -1, column_name: "email", name: "contact_email" } }
+
+ it { is_expected.to fail_to_find_a_model(:data_table) }
+ end
+
+ context "when the column does not exist" do
+ let(:params) do
+ { data_table_id: data_table.id, column_name: "nonexistent", name: "contact_email" }
+ end
+
+ it { is_expected.to fail_a_policy(:column_exists) }
+ end
+
+ context "when trying to rename a reserved column" do
+ let(:params) { { data_table_id: data_table.id, column_name: "id", name: "contact_email" } }
+
+ it { is_expected.to fail_a_policy(:not_reserved_column) }
+ end
+
+ context "when the new name is the same as the old name" do
+ let(:params) { { data_table_id: data_table.id, column_name: "email", name: "email" } }
+
+ it { is_expected.to fail_a_policy(:name_differs) }
+ end
+
+ context "when the new name already exists" do
+ let(:params) { { data_table_id: data_table.id, column_name: "email", name: "score" } }
+
+ it { is_expected.to fail_a_policy(:name_available) }
+ end
+
+ context "when everything is ok" do
+ it { is_expected.to run_successfully }
+
+ it "preserves existing row data" do
+ result
+ row_data = find_data_table_row(data_table, row["id"])
+ expect(row_data["contact_email"]).to eq("[email protected]")
+ expect(row_data).not_to have_key("email")
+ end
+
+ it "logs a staff action" do
+ result
+ expect(UserHistory.last).to have_attributes(
+ custom_type: "discourse_workflows_data_table_column_renamed",
+ subject: data_table.name,
+ previous_value: "email",
+ new_value: "contact_email",
+ )
+ end
+ end
+ end
+end
diff --git a/plugins/discourse-workflows/spec/services/discourse_workflows/data_table_row/destroy_spec.rb b/plugins/discourse-workflows/spec/services/discourse_workflows/data_table_row/destroy_spec.rb
new file mode 100644
index 00000000000..9cf0380e717
--- /dev/null
+++ b/plugins/discourse-workflows/spec/services/discourse_workflows/data_table_row/destroy_spec.rb
@@ -0,0 +1,165 @@
+# frozen_string_literal: true
+
+RSpec.describe DiscourseWorkflows::DataTableRow::Destroy do
+ describe described_class::Contract, type: :model do
+ it { is_expected.to validate_presence_of(:data_table_id) }
+ end
+
+ describe ".call" do
+ subject(:result) { described_class.call(params:, **dependencies) }
+
+ fab!(:admin)
+
+ let(:dependencies) { { guardian: admin.guardian } }
+
+ context "when contract is invalid" do
+ let(:params) { { data_table_id: nil } }
+
+ it { is_expected.to fail_a_contract }
+ end
+
+ context "when user cannot manage workflows" do
+ fab!(:user)
+ fab!(:data_table, :discourse_workflows_data_table)
+ fab!(:row) { insert_data_table_row(data_table) }
+
+ let(:params) { { data_table_id: data_table.id, row_id: row["id"] } }
+ let(:dependencies) { { guardian: user.guardian } }
+
+ it { is_expected.to fail_a_policy(:can_manage_workflows) }
+ end
+
+ context "with row_id (single-row delete)" do
+ fab!(:data_table, :discourse_workflows_data_table)
+ fab!(:row) { insert_data_table_row(data_table) }
+
+ let(:params) { { data_table_id: data_table.id, row_id: row["id"] } }
+
+ context "when data table does not exist" do
+ let(:params) { { data_table_id: -1, row_id: row["id"] } }
+
+ it { is_expected.to fail_to_find_a_model(:data_table) }
+ end
+
+ context "when row does not exist" do
+ let(:params) { { data_table_id: data_table.id, row_id: -1 } }
+
+ it { is_expected.to fail_to_find_a_model(:row) }
+ end
+
+ context "when everything is ok" do
+ it { is_expected.to run_successfully }
+
+ it "destroys the row" do
+ result
+ expect(find_data_table_row(data_table, row["id"])).to be_nil
+ end
+ end
+ end
+
+ context "with row_ids (batch delete)" do
+ fab!(:data_table, :discourse_workflows_data_table)
+ fab!(:row_1) { insert_data_table_row(data_table) }
+ fab!(:row_2) { insert_data_table_row(data_table) }
+
+ let(:params) { { data_table_id: data_table.id, row_ids: [row_1["id"], row_2["id"]] } }
+
+ context "when data table does not exist" do
+ let(:params) { { data_table_id: -1, row_ids: [row_1["id"]] } }
+
+ it { is_expected.to fail_to_find_a_model(:data_table) }
+ end
+
+ context "when everything is ok" do
+ it { is_expected.to run_successfully }
+
+ it "destroys the rows" do
+ result
+ expect(find_data_table_row(data_table, row_1["id"])).to be_nil
+ expect(find_data_table_row(data_table, row_2["id"])).to be_nil
+ end
+
+ it "returns the deleted count" do
+ expect(result[:deleted_count]).to eq(2)
+ end
+
+ it "normalizes row_ids" do
+ params[:row_ids] = [row_1["id"].to_s, row_2["id"].to_s, row_1["id"].to_s]
+ expect(result[:deleted_count]).to eq(2)
+ end
+ end
+
+ context "when row_ids exceeds the maximum" do
+ let(:params) do
+ {
+ data_table_id: data_table.id,
+ row_ids: (1..(DiscourseWorkflows::DataTableRow::Destroy::MAX_BULK_DELETE + 1)).to_a,
+ }
+ end
+
+ it { is_expected.to fail_a_contract }
+ end
+ end
+
+ context "with filter (query-based delete)" do
+ fab!(:data_table) do
+ Fabricate(
+ :discourse_workflows_data_table,
+ columns: [{ "name" => "email", "type" => "string" }],
+ )
+ end
+
+ fab!(:row) { insert_data_table_row(data_table, "email" => "[email protected]") }
+
+ let(:filter) do
+ {
+ "type" => "and",
+ "filters" => [
+ { "columnName" => "email", "condition" => "eq", "value" => "[email protected]" },
+ ],
+ }
+ end
+ let(:params) { { data_table_id: data_table.id, filter: filter } }
+
+ context "when data table does not exist" do
+ let(:params) { { data_table_id: -1, filter: filter } }
+
+ it { is_expected.to fail_to_find_a_model(:data_table) }
+ end
+
+ context "when filter is missing" do
+ let(:params) { { data_table_id: data_table.id, filter: {} } }
+
+ it { is_expected.to fail_with_an_invalid_model(:query) }
+ end
+
+ context "when matching rows exist" do
+ it { is_expected.to run_successfully }
+
+ it "destroys the matching rows" do
+ row_id = row["id"]
+ result
+ expect(find_data_table_row(data_table, row_id)).to be_nil
+ end
+ end
+
+ context "when no rows match the filter" do
+ let(:filter) do
+ {
+ "type" => "and",
+ "filters" => [
+ { "columnName" => "email", "condition" => "eq", "value" => "[email protected]" },
+ ],
+ }
+ end
+
+ it { is_expected.to run_successfully }
+
+ it "leaves existing rows intact" do
+ row_id = row["id"]
+ expect { result }.not_to change { find_data_table_row(data_table, row_id) }
+ end
+ end
+ end
+ end
+end
diff --git a/plugins/discourse-workflows/spec/services/discourse_workflows/data_table_row/get_spec.rb b/plugins/discourse-workflows/spec/services/discourse_workflows/data_table_row/get_spec.rb
new file mode 100644
index 00000000000..71217d79c4c
--- /dev/null
+++ b/plugins/discourse-workflows/spec/services/discourse_workflows/data_table_row/get_spec.rb
@@ -0,0 +1,138 @@
+# frozen_string_literal: true
+
+RSpec.describe DiscourseWorkflows::DataTableRow::Get do
+ describe described_class::Contract, type: :model do
+ it { is_expected.to validate_presence_of(:data_table_id) }
+ end
+
+ describe ".call" do
+ subject(:result) { described_class.call(params:, **dependencies) }
+
+ fab!(:admin)
+ fab!(:data_table) do
+ Fabricate(
+ :discourse_workflows_data_table,
+ columns: [
+ { "name" => "email", "type" => "string" },
+ { "name" => "score", "type" => "number" },
+ ],
+ )
+ end
+
+ fab!(:row_1) { insert_data_table_row(data_table, "email" => "[email protected]", "score" => 10) }
+ fab!(:row_2) { insert_data_table_row(data_table, "email" => "[email protected]", "score" => 20) }
+
+ let(:params) { { data_table_id: data_table.id } }
+ let(:dependencies) { { guardian: admin.guardian } }
+
+ context "when contract is invalid" do
+ let(:params) { { data_table_id: nil } }
+
+ it { is_expected.to fail_a_contract }
+ end
+
+ context "when user cannot manage workflows" do
+ fab!(:user)
+
+ let(:dependencies) { { guardian: user.guardian } }
+
+ it { is_expected.to fail_a_policy(:can_manage_workflows) }
+ end
+
+ context "when data table does not exist" do
+ let(:params) { { data_table_id: -1 } }
+
+ it { is_expected.to fail_to_find_a_model(:data_table) }
+ end
+
+ context "when filter contains unknown columns" do
+ let(:params) do
+ {
+ data_table_id: data_table.id,
+ filter: {
+ "type" => "and",
+ "filters" => [{ "columnName" => "nonexistent", "condition" => "eq", "value" => "x" }],
+ },
+ }
+ end
+
+ it { is_expected.to fail_with_an_invalid_model(:query) }
+ end
+
+ context "when no filter is provided" do
+ it { is_expected.to run_successfully }
+
+ it "returns all rows" do
+ expect(result[:query_result][:rows].count).to eq(2)
+ expect(result[:query_result][:count]).to eq(2)
+ end
+ end
+
+ context "when filter matches a subset of rows" do
+ let(:params) do
+ {
+ data_table_id: data_table.id,
+ filter: {
+ "type" => "and",
+ "filters" => [
+ { "columnName" => "email", "condition" => "eq", "value" => "[email protected]" },
+ ],
+ },
+ }
+ end
+
+ it { is_expected.to run_successfully }
+
+ it "returns only matching rows" do
+ expect(result[:query_result][:rows].count).to eq(1)
+ expect(result[:query_result][:rows].first["email"]).to eq("[email protected]")
+ end
+ end
+
+ context "when filter matches no rows" do
+ let(:params) do
+ {
+ data_table_id: data_table.id,
+ filter: {
+ "type" => "and",
+ "filters" => [
+ { "columnName" => "email", "condition" => "eq", "value" => "[email protected]" },
+ ],
+ },
+ }
+ end
+
+ it { is_expected.to run_successfully }
+
+ it "returns an empty result" do
+ expect(result[:query_result][:rows].count).to eq(0)
+ expect(result[:query_result][:count]).to eq(0)
+ end
+ end
+
+ context "with sorting" do
+ let(:params) { { data_table_id: data_table.id, sort_by: "score", sort_direction: "desc" } }
+
+ it { is_expected.to run_successfully }
+
+ it "returns rows in the specified order" do
+ emails = result[:query_result][:rows].map { |r| r["email"] }
+ expect(emails).to eq(%w[[email protected] [email protected]])
+ end
+ end
+
+ context "with pagination" do
+ let(:params) { { data_table_id: data_table.id, limit: 1, offset: 0 } }
+
+ it { is_expected.to run_successfully }
+
+ it "limits the returned rows" do
+ expect(result[:query_result][:rows].count).to eq(1)
+ end
+
+ it "returns the total count" do
+ expect(result[:query_result][:count]).to eq(2)
+ end
+ end
+ end
+end
diff --git a/plugins/discourse-workflows/spec/services/discourse_workflows/data_table_row/insert_spec.rb b/plugins/discourse-workflows/spec/services/discourse_workflows/data_table_row/insert_spec.rb
new file mode 100644
index 00000000000..3ffff97b578
--- /dev/null
+++ b/plugins/discourse-workflows/spec/services/discourse_workflows/data_table_row/insert_spec.rb
@@ -0,0 +1,81 @@
+# frozen_string_literal: true
+
+RSpec.describe DiscourseWorkflows::DataTableRow::Insert do
+ describe described_class::Contract, type: :model do
+ it { is_expected.to validate_presence_of(:data_table_id) }
+ end
+
+ describe ".call" do
+ subject(:result) { described_class.call(params:, **dependencies) }
+
+ fab!(:admin)
+ fab!(:data_table) do
+ Fabricate(
+ :discourse_workflows_data_table,
+ columns: [
+ { "name" => "email", "type" => "string" },
+ { "name" => "score", "type" => "number" },
+ ],
+ )
+ end
+
+ let(:params) do
+ { data_table_id: data_table.id, data: { "email" => "[email protected]", "score" => "42" } }
+ end
+ let(:dependencies) { { guardian: admin.guardian } }
+
+ context "when contract is invalid" do
+ let(:params) { { data_table_id: nil } }
+
+ it { is_expected.to fail_a_contract }
+ end
+
+ context "when user cannot manage workflows" do
+ fab!(:user)
+
+ let(:dependencies) { { guardian: user.guardian } }
+
+ it { is_expected.to fail_a_policy(:can_manage_workflows) }
+ end
+
+ context "when data table does not exist" do
+ let(:params) { { data_table_id: -1, data: {} } }
+
+ it { is_expected.to fail_to_find_a_model(:data_table) }
+ end
+
+ context "when the storage limit is exceeded" do
+ before do
+ allow(DiscourseWorkflows::DataTables::Facade).to receive(:within_storage_limit?).and_return(
+ false,
+ )
+ end
+
+ it { is_expected.to fail_a_policy(:within_storage_limit) }
+ end
+
+ context "when row data contains unknown columns" do
+ let(:params) { { data_table_id: data_table.id, data: { "unknown_col" => "value" } } }
+
+ it { is_expected.to fail_with_an_invalid_model(:row_input) }
+ end
+
+ context "when everything is valid" do
+ it { is_expected.to run_successfully }
+
+ it "inserts a new row with cast data" do
+ expect { result }.to change { count_data_table_rows(data_table) }.by(1)
+
+ row = list_data_table_rows(data_table)[:rows].last
+ expect(row.slice("email", "score")).to eq("email" => "[email protected]", "score" => 42)
+ end
+
+ it "returns the created row" do
+ expect(result[:row].slice("email", "score")).to eq(
+ "email" => "[email protected]",
+ "score" => 42,
+ )
+ end
+ end
+ end
+end
diff --git a/plugins/discourse-workflows/spec/services/discourse_workflows/data_table_row/update_single_spec.rb b/plugins/discourse-workflows/spec/services/discourse_workflows/data_table_row/update_single_spec.rb
new file mode 100644
index 00000000000..6c695ebefad
--- /dev/null
+++ b/plugins/discourse-workflows/spec/services/discourse_workflows/data_table_row/update_single_spec.rb
@@ -0,0 +1,84 @@
+# frozen_string_literal: true
+
+RSpec.describe DiscourseWorkflows::DataTableRow::UpdateSingle do
+ describe described_class::Contract, type: :model do
+ it { is_expected.to validate_presence_of(:data_table_id) }
+ it { is_expected.to validate_presence_of(:row_id) }
+ end
+
+ describe ".call" do
+ subject(:result) { described_class.call(params:, **dependencies) }
+
+ fab!(:admin)
+ fab!(:data_table) do
+ Fabricate(
+ :discourse_workflows_data_table,
+ columns: [
+ { "name" => "email", "type" => "string" },
+ { "name" => "score", "type" => "number" },
+ ],
+ )
+ end
+
+ fab!(:row) { insert_data_table_row(data_table, "email" => "[email protected]", "score" => 1) }
+
+ let(:params) { { data_table_id: data_table.id, row_id: row["id"], data: { "score" => 99 } } }
+ let(:dependencies) { { guardian: admin.guardian } }
+
+ context "when contract is invalid" do
+ let(:params) { { data_table_id: nil, row_id: nil } }
+
+ it { is_expected.to fail_a_contract }
+ end
+
+ context "when user cannot manage workflows" do
+ fab!(:user)
+
+ let(:dependencies) { { guardian: user.guardian } }
+
+ it { is_expected.to fail_a_policy(:can_manage_workflows) }
+ end
+
+ context "when data table does not exist" do
+ let(:params) { { data_table_id: -1, row_id: row["id"], data: { "score" => 99 } } }
+
+ it { is_expected.to fail_to_find_a_model(:data_table) }
+ end
+
+ context "when the storage limit is exceeded" do
+ before do
+ allow(DiscourseWorkflows::DataTables::Facade).to receive(:within_storage_limit?).and_return(
+ false,
+ )
+ end
+
+ it { is_expected.to fail_a_policy(:within_storage_limit) }
+ end
+
+ context "when row does not exist" do
+ let(:params) { { data_table_id: data_table.id, row_id: -1, data: { "score" => 99 } } }
+
+ it { is_expected.to fail_to_find_a_model(:existing_row) }
+ end
+
+ context "when row data contains unknown columns" do
+ let(:params) do
+ { data_table_id: data_table.id, row_id: row["id"], data: { "unknown" => "x" } }
+ end
+
+ it { is_expected.to fail_with_an_invalid_model(:row_input) }
+ end
+
+ context "when everything's ok" do
+ it { is_expected.to run_successfully }
+
+ it "merges and casts the updated data" do
+ result
+ expect(find_data_table_row(data_table, row["id"]).slice("email", "score")).to eq(
+ "email" => "[email protected]",
+ "score" => 99,
+ )
+ end
+ end
+ end
+end
diff --git a/plugins/discourse-workflows/spec/services/discourse_workflows/data_table_row/update_spec.rb b/plugins/discourse-workflows/spec/services/discourse_workflows/data_table_row/update_spec.rb
new file mode 100644
index 00000000000..1f066df93fd
--- /dev/null
+++ b/plugins/discourse-workflows/spec/services/discourse_workflows/data_table_row/update_spec.rb
@@ -0,0 +1,104 @@
+# frozen_string_literal: true
+
+RSpec.describe DiscourseWorkflows::DataTableRow::Update do
+ describe described_class::Contract, type: :model do
+ it { is_expected.to validate_presence_of(:data_table_id) }
+ end
+
+ describe ".call" do
+ subject(:result) { described_class.call(params:, **dependencies) }
+
+ fab!(:admin)
+ fab!(:data_table) do
+ Fabricate(
+ :discourse_workflows_data_table,
+ columns: [
+ { "name" => "email", "type" => "string" },
+ { "name" => "score", "type" => "number" },
+ ],
+ )
+ end
+
+ fab!(:row) { insert_data_table_row(data_table, "email" => "[email protected]", "score" => 1) }
+
+ let(:filter) do
+ {
+ "type" => "and",
+ "filters" => [{ "columnName" => "email", "condition" => "eq", "value" => "[email protected]" }],
+ }
+ end
+ let(:params) { { data_table_id: data_table.id, filter: filter, data: { "score" => 42 } } }
+ let(:dependencies) { { guardian: admin.guardian } }
+
+ context "when contract is invalid" do
+ let(:params) { { data_table_id: nil } }
+
+ it { is_expected.to fail_a_contract }
+ end
+
+ context "when user cannot manage workflows" do
+ fab!(:user)
+
+ let(:dependencies) { { guardian: user.guardian } }
+
+ it { is_expected.to fail_a_policy(:can_manage_workflows) }
+ end
+
+ context "when data table does not exist" do
+ let(:params) { { data_table_id: -1, filter: filter, data: {} } }
+
+ it { is_expected.to fail_to_find_a_model(:data_table) }
+ end
+
+ context "when the storage limit is exceeded" do
+ before do
+ allow(DiscourseWorkflows::DataTables::Facade).to receive(:within_storage_limit?).and_return(
+ false,
+ )
+ end
+
+ it { is_expected.to fail_a_policy(:within_storage_limit) }
+ end
+
+ context "when filter is missing" do
+ let(:params) { { data_table_id: data_table.id, filter: {}, data: {} } }
+
+ it { is_expected.to fail_with_an_invalid_model(:query) }
+ end
+
+ context "when row data contains unknown columns" do
+ let(:params) { { data_table_id: data_table.id, filter: filter, data: { "unknown" => "x" } } }
+
+ it { is_expected.to fail_with_an_invalid_model(:row_input) }
+ end
+
+ context "when matching rows exist" do
+ it { is_expected.to run_successfully }
+
+ it "returns the updated count" do
+ expect(result[:updated_count]).to eq(1)
+ end
+
+ it "updates matching rows with merged data" do
+ result
+ expect(find_data_table_row(data_table, row["id"]).slice("email", "score")).to eq(
+ "email" => "[email protected]",
+ "score" => 42,
+ )
+ end
+ end
+
+ context "when no rows match the filter" do
+ let(:filter) do
+ {
+ "type" => "and",
+ "filters" => [
+ { "columnName" => "email", "condition" => "eq", "value" => "[email protected]" },
+ ],
+ }
+ end
+
+ it { is_expected.to fail_a_step(:ensure_rows_matched) }
+ end
+ end
+end
diff --git a/plugins/discourse-workflows/spec/services/discourse_workflows/execution/check_schedules_spec.rb b/plugins/discourse-workflows/spec/services/discourse_workflows/execution/check_schedules_spec.rb
new file mode 100644
index 00000000000..24312d23e06
--- /dev/null
+++ b/plugins/discourse-workflows/spec/services/discourse_workflows/execution/check_schedules_spec.rb
@@ -0,0 +1,203 @@
+# frozen_string_literal: true
+
+RSpec.describe DiscourseWorkflows::Execution::CheckSchedules do
+ describe ".call" do
+ subject(:result) { described_class.call }
+
+ fab!(:user)
+
+ def schedule_config(*rules)
+ { "rule" => { "interval" => rules } }
+ end
+
+ def create_schedule_workflow(configuration:, settings: {})
+ graph =
+ build_workflow_graph do |g|
+ g.node "trigger-1", "trigger:schedule", configuration: configuration
+ end
+ Fabricate(
+ :discourse_workflows_workflow,
+ published: true,
+ created_by: user,
+ settings: settings,
+ **graph,
+ )
+ end
+
+ context "when plugin is disabled" do
+ before { SiteSetting.discourse_workflows_enabled = false }
+
+ it { is_expected.to fail_a_policy(:workflows_enabled) }
+ end
+
+ it "enqueues matching minute rules through the trigger context" do
+ freeze_time Time.utc(2026, 3, 18, 9, 5)
+ workflow =
+ create_schedule_workflow(
+ configuration: schedule_config({ "field" => "minutes", "minutesInterval" => 5 }),
+ )
+
+ expect { result }.to change { Jobs::DiscourseWorkflows::ExecuteWorkflow.jobs.size }.by(1)
+
+ job = Jobs::DiscourseWorkflows::ExecuteWorkflow.jobs.last
+ expect(job["args"].first["workflow_id"]).to eq(workflow.id)
+ expect(job["args"].first["workflow_version_id"]).to eq(workflow.active_version_id)
+ end
+
+ it "normalizes scheduler ticks to the current minute" do
+ freeze_time Time.utc(2026, 3, 18, 9, 5, 12)
+ create_schedule_workflow(
+ configuration: schedule_config({ "field" => "minutes", "minutesInterval" => 5 }),
+ )
+
+ expect { result }.to change { Jobs::DiscourseWorkflows::ExecuteWorkflow.jobs.size }.by(1)
+
+ trigger_data =
+ Jobs::DiscourseWorkflows::ExecuteWorkflow.jobs.last["args"].first["trigger_data"]
+ expect(trigger_data).to include("hour" => "09", "minute" => "05", "second" => "00")
+ end
+
+ it "does not enqueue when a cron rule does not match" do
+ freeze_time Time.utc(2026, 3, 18, 10, 0)
+ create_schedule_workflow(
+ configuration:
+ schedule_config({ "field" => "cronExpression", "expression" => "0 9 * * *" }),
+ )
+
+ expect { result }.not_to change { Jobs::DiscourseWorkflows::ExecuteWorkflow.jobs.size }
+ end
+
+ it "evaluates rules in the workflow timezone" do
+ freeze_time Time.utc(2026, 3, 18, 8, 0)
+ create_schedule_workflow(
+ settings: {
+ "timezone" => "Europe/Paris",
+ },
+ configuration:
+ schedule_config(
+ {
+ "field" => "days",
+ "daysInterval" => 1,
+ "triggerAtHour" => 9,
+ "triggerAtMinute" => 0,
+ },
+ ),
+ )
+
+ expect { result }.to change { Jobs::DiscourseWorkflows::ExecuteWorkflow.jobs.size }.by(1)
+
+ trigger_data =
+ Jobs::DiscourseWorkflows::ExecuteWorkflow.jobs.last["args"].first["trigger_data"]
+ expect(trigger_data).to include(
+ "hour" => "09",
+ "minute" => "00",
+ "timezone" => "Europe/Paris (UTC+01:00)",
+ )
+ expect(trigger_data["timestamp"]).to end_with("+01:00")
+ end
+
+ it "supports multiple independent rules" do
+ freeze_time Time.utc(2026, 3, 18, 12, 0)
+ create_schedule_workflow(
+ configuration:
+ schedule_config(
+ {
+ "field" => "days",
+ "daysInterval" => 1,
+ "triggerAtHour" => 9,
+ "triggerAtMinute" => 0,
+ },
+ { "field" => "cronExpression", "expression" => "0 12 * * *" },
+ ),
+ )
+
+ expect { result }.to change { Jobs::DiscourseWorkflows::ExecuteWorkflow.jobs.size }.by(1)
+ end
+
+ it "fires overlapping rules on the same node independently" do
+ freeze_time Time.utc(2026, 3, 18, 9, 0)
+ create_schedule_workflow(
+ configuration:
+ schedule_config(
+ { "field" => "minutes", "minutesInterval" => 1 },
+ { "field" => "cronExpression", "expression" => "0 9 * * *" },
+ ),
+ )
+
+ expect { result }.to change { Jobs::DiscourseWorkflows::ExecuteWorkflow.jobs.size }.by(2)
+ end
+
+ it "deduplicates repeated ticks for the same scheduled time" do
+ freeze_time Time.utc(2026, 3, 18, 9, 0)
+ create_schedule_workflow(
+ configuration:
+ schedule_config({ "field" => "cronExpression", "expression" => "0 9 * * *" }),
+ )
+
+ described_class.call
+ expect(Jobs::DiscourseWorkflows::ExecuteWorkflow.jobs.size).to eq(1)
+
+ described_class.call
+ expect(Jobs::DiscourseWorkflows::ExecuteWorkflow.jobs.size).to eq(1)
+ end
+
+ it "fires again for a new matching minute" do
+ freeze_time Time.utc(2026, 3, 18, 9, 0)
+ create_schedule_workflow(
+ configuration:
+ schedule_config({ "field" => "cronExpression", "expression" => "0 * * * *" }),
+ )
+
+ described_class.call
+ expect(Jobs::DiscourseWorkflows::ExecuteWorkflow.jobs.size).to eq(1)
+
+ freeze_time Time.utc(2026, 3, 18, 10, 0)
+ described_class.call
+ expect(Jobs::DiscourseWorkflows::ExecuteWorkflow.jobs.size).to eq(2)
+ end
+
+ it "uses recurrence state for multi-day intervals" do
+ workflow =
+ create_schedule_workflow(
+ configuration:
+ schedule_config(
+ {
+ "field" => "days",
+ "daysInterval" => 3,
+ "triggerAtHour" => 9,
+ "triggerAtMinute" => 0,
+ },
+ ),
+ )
+
+ freeze_time Time.utc(2026, 3, 18, 9, 0)
+ described_class.call
+ expect(Jobs::DiscourseWorkflows::ExecuteWorkflow.jobs.size).to eq(1)
+
+ freeze_time Time.utc(2026, 3, 19, 9, 0)
+ described_class.call
+ expect(Jobs::DiscourseWorkflows::ExecuteWorkflow.jobs.size).to eq(1)
+
+ freeze_time Time.utc(2026, 3, 21, 9, 0)
+ described_class.call
+ expect(Jobs::DiscourseWorkflows::ExecuteWorkflow.jobs.size).to eq(2)
+ expect(workflow.reload.static_data).to include(
+ "node:Trigger-1" => {
+ "recurrenceRules" => be_present,
+ },
+ )
+ end
+
+ it "does not enqueue unpublished workflows" do
+ freeze_time Time.utc(2026, 3, 18, 9, 0)
+ workflow =
+ create_schedule_workflow(
+ configuration:
+ schedule_config({ "field" => "cronExpression", "expression" => "0 9 * * *" }),
+ )
+ unpublish_workflow!(workflow)
+
+ expect { result }.not_to change { Jobs::DiscourseWorkflows::ExecuteWorkflow.jobs.size }
+ end
+ end
+end
diff --git a/plugins/discourse-workflows/spec/services/discourse_workflows/execution/check_stale_topics_spec.rb b/plugins/discourse-workflows/spec/services/discourse_workflows/execution/check_stale_topics_spec.rb
new file mode 100644
index 00000000000..f5f3955a5ae
--- /dev/null
+++ b/plugins/discourse-workflows/spec/services/discourse_workflows/execution/check_stale_topics_spec.rb
@@ -0,0 +1,107 @@
+# frozen_string_literal: true
+
+RSpec.describe DiscourseWorkflows::Execution::CheckStaleTopics do
+ describe ".call" do
+ subject(:result) { described_class.call }
+
+ fab!(:admin)
+ fab!(:topic) { Fabricate(:topic, created_at: 48.hours.ago, last_posted_at: 48.hours.ago) }
+ fab!(:workflow) do
+ graph =
+ build_workflow_graph do |g|
+ g.node "trigger-1", "trigger:stale_topic", configuration: { "hours" => 24 }
+ end
+ Fabricate(:discourse_workflows_workflow, published: true, created_by: admin, **graph)
+ end
+
+ context "when plugin is disabled" do
+ before { SiteSetting.discourse_workflows_enabled = false }
+
+ it { is_expected.to fail_a_policy(:workflows_enabled) }
+ end
+
+ context "when no published stale topic trigger nodes exist" do
+ before { unpublish_workflow!(workflow) }
+
+ it { is_expected.to fail_to_find_a_model(:stale_trigger_nodes) }
+ end
+
+ context "when stale topics exist" do
+ it { is_expected.to run_successfully }
+
+ it "enqueues one execution carrying every stale topic as an item" do
+ result
+
+ expect(Jobs::DiscourseWorkflows::ExecuteWorkflow.jobs.size).to eq(1)
+ job_args = Jobs::DiscourseWorkflows::ExecuteWorkflow.jobs.first["args"].first
+ expect(job_args).to include(
+ "trigger_node_id" => "trigger-1",
+ "workflow_id" => workflow.id,
+ "workflow_version_id" => workflow.active_version_id,
+ )
+ expect(job_args["trigger_data"]).to match([include("topic" => include("id" => topic.id))])
+ end
+ end
+
+ context "when topic is newer than threshold" do
+ before { topic.update!(created_at: 12.hours.ago, last_posted_at: 12.hours.ago) }
+
+ it "does not enqueue" do
+ result
+ expect(Jobs::DiscourseWorkflows::ExecuteWorkflow.jobs.size).to eq(0)
+ end
+ end
+
+ context "when called repeatedly while the topic stays stale" do
+ it "re-fires each run" do
+ described_class.call
+ expect(Jobs::DiscourseWorkflows::ExecuteWorkflow.jobs.size).to eq(1)
+
+ Jobs::DiscourseWorkflows::ExecuteWorkflow.jobs.clear
+ described_class.call
+ expect(Jobs::DiscourseWorkflows::ExecuteWorkflow.jobs.size).to eq(1)
+ end
+ end
+
+ context "when topic is closed" do
+ before { topic.update!(closed: true) }
+
+ it "does not enqueue" do
+ result
+ expect(Jobs::DiscourseWorkflows::ExecuteWorkflow.jobs.size).to eq(0)
+ end
+ end
+
+ context "when topic is archived" do
+ before { topic.update!(archived: true) }
+
+ it "does not enqueue" do
+ result
+ expect(Jobs::DiscourseWorkflows::ExecuteWorkflow.jobs.size).to eq(0)
+ end
+ end
+
+ context "when topic has recent replies" do
+ before { topic.update!(created_at: 72.hours.ago, last_posted_at: 2.hours.ago) }
+
+ it "does not enqueue" do
+ result
+ expect(Jobs::DiscourseWorkflows::ExecuteWorkflow.jobs.size).to eq(0)
+ end
+ end
+
+ context "when there are multiple stale topics" do
+ fab!(:topic_2) { Fabricate(:topic, created_at: 48.hours.ago, last_posted_at: 48.hours.ago) }
+ fab!(:topic_3) { Fabricate(:topic, created_at: 48.hours.ago, last_posted_at: 48.hours.ago) }
+
+ it "enqueues one job carrying every topic as an item" do
+ result
+
+ expect(Jobs::DiscourseWorkflows::ExecuteWorkflow.jobs.size).to eq(1)
+ items = Jobs::DiscourseWorkflows::ExecuteWorkflow.jobs.first["args"].first["trigger_data"]
+ topic_ids = items.map { |item| item.dig("topic", "id") }
+ expect(topic_ids).to match_array([topic.id, topic_2.id, topic_3.id])
+ end
+ end
+ end
+end
diff --git a/plugins/discourse-workflows/spec/services/discourse_workflows/execution/destroy_spec.rb b/plugins/discourse-workflows/spec/services/discourse_workflows/execution/destroy_spec.rb
new file mode 100644
index 00000000000..5cacb97e7df
--- /dev/null
+++ b/plugins/discourse-workflows/spec/services/discourse_workflows/execution/destroy_spec.rb
@@ -0,0 +1,58 @@
+# frozen_string_literal: true
+
+RSpec.describe DiscourseWorkflows::Execution::Destroy do
+ describe described_class::Contract, type: :model do
+ it { is_expected.to validate_presence_of(:execution_ids) }
+ end
+
+ describe ".call" do
+ subject(:result) { described_class.call(params:, guardian:) }
+
+ fab!(:admin)
+ fab!(:workflow, :discourse_workflows_workflow)
+ fab!(:execution) { Fabricate(:discourse_workflows_execution, workflow: workflow) }
+
+ let(:params) { { execution_ids: [execution.id] } }
+ let(:guardian) { admin.guardian }
+
+ context "when contract is not valid" do
+ let(:params) { {} }
+
+ it { is_expected.to fail_a_contract }
+ end
+
+ context "when execution_ids exceeds the maximum" do
+ let(:params) do
+ { execution_ids: (1..(DiscourseWorkflows::Execution::Destroy::MAX_BULK_DELETE + 1)).to_a }
+ end
+
+ it { is_expected.to fail_a_contract }
+ end
+
+ context "when user is not admin" do
+ fab!(:user)
+
+ let(:guardian) { user.guardian }
+
+ it { is_expected.to fail_a_policy(:can_manage_workflows) }
+ end
+
+ context "when everything's ok" do
+ it { is_expected.to run_successfully }
+
+ it "deletes the executions" do
+ expect { result }.to change { DiscourseWorkflows::Execution.count }.by(-1)
+ end
+
+ it "deletes associated execution data" do
+ Fabricate(:discourse_workflows_execution_data, execution: execution)
+
+ expect { result }.to change { DiscourseWorkflows::ExecutionData.count }.by(-1)
+ end
+
+ it "returns the deleted count" do
+ expect(result[:deleted_count]).to eq(1)
+ end
+ end
+ end
+end
diff --git a/plugins/discourse-workflows/spec/services/discourse_workflows/execution/expire_waiting_spec.rb b/plugins/discourse-workflows/spec/services/discourse_workflows/execution/expire_waiting_spec.rb
new file mode 100644
index 00000000000..a46aa3c52ae
--- /dev/null
+++ b/plugins/discourse-workflows/spec/services/discourse_workflows/execution/expire_waiting_spec.rb
@@ -0,0 +1,108 @@
+# frozen_string_literal: true
+
+RSpec.describe DiscourseWorkflows::Execution::ExpireWaiting do
+ describe ".call" do
+ subject(:result) { described_class.call }
+
+ fab!(:user)
+
+ def create_waiting_execution(timeout_minutes: nil, timeout_action: nil, limit_wait_time: true)
+ configuration = { "resume" => "webhook", "limit_wait_time" => limit_wait_time }
+ if limit_wait_time
+ configuration["timeout_amount"] = timeout_minutes
+ configuration["timeout_unit"] = "minutes"
+ end
+
+ graph =
+ build_workflow_graph do |g|
+ g.node "trigger-1", "trigger:manual", name: "Manual"
+ g.node "wait-1", "flow:wait", name: "Wait", configuration: configuration
+ g.chain "trigger-1", "wait-1"
+ end
+ workflow =
+ Fabricate(:discourse_workflows_workflow, created_by: user, published: true, **graph)
+
+ execution = DiscourseWorkflows::Executor.new(workflow, "trigger-1", {}).run
+ execution.update!(timeout_action: timeout_action) if timeout_action
+ execution
+ end
+
+ context "when plugin is disabled" do
+ before { SiteSetting.discourse_workflows_enabled = false }
+
+ it { is_expected.to fail_a_policy(:workflows_enabled) }
+ end
+
+ context "when there are no expired executions" do
+ it { is_expected.to run_successfully }
+ end
+
+ context "when timeout_action is fail" do
+ it "fails the expired execution" do
+ freeze_time
+
+ execution = create_waiting_execution(timeout_minutes: 30, timeout_action: "fail")
+ expect(execution.status).to eq("waiting")
+
+ freeze_time(31.minutes.from_now)
+ result
+
+ execution.reload
+ expect(execution.status).to eq("error")
+ expect(execution.error).to eq("Approval timed out")
+ end
+ end
+
+ context "when the waiting node is no longer in the workflow" do
+ it "still fails the expired execution with the generic timeout logic" do
+ freeze_time
+
+ execution =
+ Fabricate(
+ :discourse_workflows_execution,
+ status: :waiting,
+ waiting_until: 1.minute.ago,
+ waiting_node_id: "wait-1",
+ timeout_action: "fail",
+ )
+
+ result
+
+ execution.reload
+ expect(execution.status).to eq("error")
+ end
+ end
+
+ context "when execution has not timed out" do
+ it "does not expire the execution" do
+ freeze_time
+
+ execution = create_waiting_execution(timeout_minutes: 60, timeout_action: "fail")
+
+ freeze_time(30.minutes.from_now)
+ result
+
+ expect(execution.reload.status).to eq("waiting")
+ end
+ end
+
+ context "when execution uses the default wait ceiling" do
+ it "expires after the executor timeout" do
+ freeze_time
+
+ execution = create_waiting_execution(limit_wait_time: false)
+
+ expect(execution.waiting_until).to eq_time(
+ DiscourseWorkflows::Executor::MAX_WAIT_DURATION_SECONDS.seconds.from_now,
+ )
+
+ freeze_time(
+ DiscourseWorkflows::Executor::MAX_WAIT_DURATION_SECONDS.seconds.from_now + 1.second,
+ )
+ result
+
+ expect(execution.reload.status).to eq("success")
+ end
+ end
+ end
+end
diff --git a/plugins/discourse-workflows/spec/services/discourse_workflows/execution/list_spec.rb b/plugins/discourse-workflows/spec/services/discourse_workflows/execution/list_spec.rb
new file mode 100644
index 00000000000..3b7fb67828e
--- /dev/null
+++ b/plugins/discourse-workflows/spec/services/discourse_workflows/execution/list_spec.rb
@@ -0,0 +1,162 @@
+# frozen_string_literal: true
+
+RSpec.describe DiscourseWorkflows::Execution::List do
+ describe described_class::Contract, type: :model do
+ subject(:contract) { described_class.new(limit: limit) }
+
+ context "when limit is within bounds" do
+ let(:limit) { 50 }
+
+ it "keeps the provided limit" do
+ contract.valid?
+ expect(contract.limit).to eq(50)
+ end
+ end
+
+ context "when limit exceeds maximum" do
+ let(:limit) { 200 }
+
+ it "clamps to MAX_LIMIT" do
+ contract.valid?
+ expect(contract.limit).to eq(DiscourseWorkflows::Pagination::MAX_LIMIT)
+ end
+ end
+
+ context "when limit is below minimum" do
+ let(:limit) { 0 }
+
+ it "clamps to 1" do
+ contract.valid?
+ expect(contract.limit).to eq(1)
+ end
+ end
+
+ context "when limit is not provided" do
+ let(:limit) { nil }
+
+ it "leaves limit as nil" do
+ contract.valid?
+ expect(contract.limit).to be_nil
+ end
+ end
+
+ describe "#effective_limit" do
+ context "when limit is set" do
+ let(:limit) { 10 }
+
+ it "returns the set limit" do
+ contract.valid?
+ expect(contract.effective_limit).to eq(10)
+ end
+ end
+
+ context "when limit is nil" do
+ let(:limit) { nil }
+
+ it "returns the default limit" do
+ expect(contract.effective_limit).to eq(DiscourseWorkflows::Pagination::DEFAULT_LIMIT)
+ end
+ end
+ end
+ end
+
+ describe ".call" do
+ subject(:result) { described_class.call(params:, **dependencies) }
+
+ fab!(:admin)
+ fab!(:workflow, :discourse_workflows_workflow)
+
+ let(:params) { {} }
+ let(:dependencies) { { guardian: admin.guardian } }
+
+ context "when user cannot manage workflows" do
+ fab!(:user)
+
+ let(:dependencies) { { guardian: user.guardian } }
+
+ it { is_expected.to fail_a_policy(:can_manage_workflows) }
+ end
+
+ context "when there are no executions" do
+ it { is_expected.to run_successfully }
+
+ it "returns an empty collection" do
+ expect(result[:executions]).to be_empty
+ end
+
+ it "does not return a load more url" do
+ expect(result[:load_more_url]).to be_nil
+ end
+ end
+
+ context "when there are executions" do
+ fab!(:execution_a) { Fabricate(:discourse_workflows_execution, workflow: workflow) }
+ fab!(:execution_b) { Fabricate(:discourse_workflows_execution, workflow: workflow) }
+
+ it { is_expected.to run_successfully }
+
+ it "returns executions ordered by id descending" do
+ expect(result[:executions].map(&:id)).to eq([execution_b.id, execution_a.id])
+ end
+ end
+
+ context "with pagination" do
+ fab!(:execution_1) { Fabricate(:discourse_workflows_execution, workflow: workflow) }
+ fab!(:execution_2) { Fabricate(:discourse_workflows_execution, workflow: workflow) }
+ fab!(:execution_3) { Fabricate(:discourse_workflows_execution, workflow: workflow) }
+
+ let(:params) { { limit: 2 } }
+
+ it "returns only the requested number of executions" do
+ expect(result[:executions].size).to eq(2)
+ end
+
+ it "returns a load more url with cursor" do
+ last_id = result[:executions].last.id
+ expect(result[:load_more_url]).to eq(
+ "/admin/plugins/discourse-workflows/executions.json?cursor=#{last_id}&limit=2",
+ )
+ end
+
+ context "when using a cursor" do
+ let(:params) { { limit: 2, cursor: execution_3.id } }
+
+ it "returns executions after the cursor" do
+ expect(result[:executions].map(&:id)).to eq([execution_2.id, execution_1.id])
+ end
+
+ it "does not return a load more url when no more results" do
+ expect(result[:load_more_url]).to be_nil
+ end
+ end
+ end
+
+ context "when scoped to a workflow" do
+ fab!(:workflow_a, :discourse_workflows_workflow)
+ fab!(:workflow_b, :discourse_workflows_workflow)
+ fab!(:execution_a) { Fabricate(:discourse_workflows_execution, workflow: workflow_a) }
+ fab!(:execution_b) { Fabricate(:discourse_workflows_execution, workflow: workflow_b) }
+
+ let(:params) { { workflow_id: workflow_a.id } }
+
+ it "returns only executions for the specified workflow" do
+ expect(result[:executions].map(&:id)).to eq([execution_a.id])
+ end
+
+ context "with pagination" do
+ fab!(:execution_c) { Fabricate(:discourse_workflows_execution, workflow: workflow_a) }
+ fab!(:execution_d) { Fabricate(:discourse_workflows_execution, workflow: workflow_a) }
+
+ let(:params) { { workflow_id: workflow_a.id, limit: 1 } }
+
+ it "returns a workflow-scoped load more url" do
+ last_id = result[:executions].last.id
+ expect(result[:load_more_url]).to include(
+ "/admin/plugins/discourse-workflows/workflows/#{workflow_a.id}/executions.json",
+ )
+ expect(result[:load_more_url]).to include("cursor=#{last_id}")
+ end
+ end
+ end
+ end
+end
diff --git a/plugins/discourse-workflows/spec/services/discourse_workflows/execution/show_spec.rb b/plugins/discourse-workflows/spec/services/discourse_workflows/execution/show_spec.rb
new file mode 100644
index 00000000000..16176510b9d
--- /dev/null
+++ b/plugins/discourse-workflows/spec/services/discourse_workflows/execution/show_spec.rb
@@ -0,0 +1,45 @@
+# frozen_string_literal: true
+
+RSpec.describe DiscourseWorkflows::Execution::Show do
+ describe described_class::Contract, type: :model do
+ it { is_expected.to validate_presence_of(:execution_id) }
+ end
+
+ describe ".call" do
+ subject(:result) { described_class.call(params:, **dependencies) }
+
+ fab!(:admin)
+ fab!(:workflow, :discourse_workflows_workflow)
+ fab!(:execution) { Fabricate(:discourse_workflows_execution, workflow: workflow) }
+
+ let(:params) { { execution_id: execution.id } }
+ let(:dependencies) { { guardian: admin.guardian } }
+
+ context "when contract is invalid" do
+ let(:params) { { execution_id: nil } }
+
+ it { is_expected.to fail_a_contract }
+ end
+
+ context "when user cannot manage workflows" do
+ fab!(:user)
+
+ let(:dependencies) { { guardian: user.guardian } }
+
+ it { is_expected.to fail_a_policy(:can_manage_workflows) }
+ end
+
+ context "when execution does not exist" do
+ let(:params) { { execution_id: -1 } }
+
+ it { is_expected.to fail_to_find_a_model(:execution) }
+ end
+
+ context "when everything's ok" do
+ it "returns the execution" do
+ expect(result).to run_successfully
+ expect(result[:execution]).to eq(execution)
+ end
+ end
+ end
+end
diff --git a/plugins/discourse-workflows/spec/services/discourse_workflows/expression/evaluate_spec.rb b/plugins/discourse-workflows/spec/services/discourse_workflows/expression/evaluate_spec.rb
new file mode 100644
index 00000000000..e316dafcb10
--- /dev/null
+++ b/plugins/discourse-workflows/spec/services/discourse_workflows/expression/evaluate_spec.rb
@@ -0,0 +1,107 @@
+# frozen_string_literal: true
+
+RSpec.describe DiscourseWorkflows::Expression::Evaluate do
+ describe described_class::Contract, type: :model do
+ it { is_expected.to validate_presence_of(:template) }
+ end
+
+ describe ".call" do
+ subject(:result) { described_class.call(params:, **dependencies) }
+
+ fab!(:admin)
+
+ let(:params) { { template: "Hello world" } }
+ let(:dependencies) { { guardian: admin.guardian } }
+
+ context "when contract is invalid" do
+ let(:params) { { template: nil } }
+
+ it { is_expected.to fail_a_contract }
+ end
+
+ context "when user cannot manage workflows" do
+ fab!(:user)
+
+ let(:dependencies) { { guardian: user.guardian } }
+
+ it { is_expected.to fail_a_policy(:can_manage_workflows) }
+ end
+
+ context "when workflow_id references a missing workflow" do
+ let(:params) { { template: "Hello", workflow_id: -1 } }
+
+ it "ignores the missing workflow and still resolves segments" do
+ expect(result).to run_successfully
+ expect(result[:workflow]).to be_nil
+ expect(result[:segments]).to eq([{ kind: "plaintext", text: "Hello" }])
+ end
+ end
+
+ context "when everything's ok" do
+ it { is_expected.to run_successfully }
+
+ it "builds the preview context" do
+ expect(result[:preview_context]).to include("$json" => {}, "$trigger" => {})
+ end
+
+ it "returns resolved segments" do
+ expect(result[:segments]).to eq([{ kind: "plaintext", text: "Hello world" }])
+ end
+ end
+
+ context "with a workflow_id" do
+ fab!(:workflow) do
+ graph =
+ build_workflow_graph do |g|
+ g.node "trigger-1", "trigger:topic_created", name: "Topic created"
+ end
+ Fabricate(:discourse_workflows_workflow, created_by: admin, **graph)
+ end
+
+ let(:params) { { template: "{{ $json.topic.title }}", workflow_id: workflow.id } }
+
+ fab!(:execution) do
+ Fabricate(:discourse_workflows_execution, workflow: workflow, status: :success)
+ end
+
+ fab!(:execution_data) do
+ Fabricate(
+ :discourse_workflows_execution_data,
+ execution: execution,
+ data: {
+ "entries" => {
+ },
+ "context" => {
+ },
+ "node_contexts" => {
+ },
+ "run_data" => {
+ "Topic created" => [
+ {
+ "node_id" => "trigger-1",
+ "node_name" => "Topic created",
+ "node_type" => "trigger:topic_created",
+ "status" => "success",
+ "run_index" => 0,
+ "inputs" => [],
+ "outputs" => [
+ {
+ "index" => 0,
+ "items" => [{ "json" => { "topic" => { "title" => "Preview topic" } } }],
+ "item_count" => 1,
+ },
+ ],
+ },
+ ],
+ },
+ },
+ )
+ end
+
+ it "resolves expressions against the preview context" do
+ expect(result).to run_successfully
+ expect(result[:segments].first[:state]).to eq("valid")
+ end
+ end
+ end
+end
diff --git a/plugins/discourse-workflows/spec/services/discourse_workflows/form/show_spec.rb b/plugins/discourse-workflows/spec/services/discourse_workflows/form/show_spec.rb
new file mode 100644
index 00000000000..3ead4aad2b0
--- /dev/null
+++ b/plugins/discourse-workflows/spec/services/discourse_workflows/form/show_spec.rb
@@ -0,0 +1,238 @@
+# frozen_string_literal: true
+
+RSpec.describe DiscourseWorkflows::Form::Show do
+ describe described_class::Contract, type: :model do
+ it "requires uuid for initial form requests" do
+ contract = described_class.new
+ expect(contract).not_to be_valid
+ expect(contract.errors[:uuid]).to be_present
+ end
+ end
+
+ describe ".call" do
+ subject(:result) { described_class.call(params:, **dependencies) }
+
+ fab!(:user)
+ fab!(:workflow) do
+ graph =
+ build_workflow_graph do |g|
+ g.node "trigger-1",
+ "trigger:form",
+ configuration: {
+ "uuid" => "a1b2c3d4-e5f6-7890-abcd-ef0123456789",
+ "form_title" => "Test Form",
+ "form_description" => "A test form",
+ "form_fields" => [
+ { "field_label" => "Name", "field_type" => "text", "required" => true },
+ ],
+ "response_mode" => "on_received",
+ }
+ end
+ Fabricate(:discourse_workflows_workflow, published: true, **graph)
+ end
+
+ let(:dependencies) { { guardian: Guardian.new(user) } }
+ let(:uuid) { "a1b2c3d4-e5f6-7890-abcd-ef0123456789" }
+ let(:params) { { uuid: uuid } }
+
+ before { DiscourseWorkflows::WorkflowDependencyIndexer.call(workflow) }
+
+ context "when contract is invalid" do
+ let(:uuid) { nil }
+
+ it { is_expected.to fail_a_contract }
+ end
+
+ context "when workflow is not found" do
+ let(:uuid) { "00000000-0000-0000-0000-000000000000" }
+
+ it { is_expected.to fail_to_find_a_model(:published_trigger) }
+ end
+
+ context "when workflow is unpublished" do
+ before { unpublish_workflow!(workflow) }
+
+ it { is_expected.to fail_to_find_a_model(:published_trigger) }
+ end
+
+ context "when the form requires a logged-in user" do
+ before do
+ trigger_node = workflow.nodes.find { |n| n["type"] == "trigger:form" }
+ trigger_node["parameters"]["authentication"] = "login_required"
+ workflow.update!(nodes: workflow.nodes)
+ publish_workflow!(workflow)
+ end
+
+ context "without a current user" do
+ let(:dependencies) { { guardian: Guardian.new } }
+
+ it { is_expected.to fail_a_policy(:authenticated_if_required) }
+ end
+
+ context "with a current user" do
+ it { is_expected.to run_successfully }
+ end
+ end
+
+ context "with an initial form request" do
+ it { is_expected.to run_successfully }
+
+ it "builds trigger form data" do
+ result
+ form_data = result[:form_data]
+ expect(form_data[:form_title]).to eq("Test Form")
+ expect(form_data[:form_description]).to eq("A test form")
+ expect(form_data[:response_mode]).to eq("on_received")
+ expect(form_data[:has_downstream_form]).to be(false)
+ expect(form_data[:form_submit_url]).to eq("/workflows/form/#{uuid}.json")
+ expect(form_data).not_to have_key(:form_fields)
+ expect(form_data).to include(
+ data: {
+ "name" => "",
+ },
+ fields: [
+ {
+ name: "name",
+ title: "Name",
+ type: "input",
+ validation: "required",
+ autofocus: false,
+ },
+ ],
+ )
+ end
+
+ it "returns a signed submission token without creating a waiting execution" do
+ expect { result }.not_to change { DiscourseWorkflows::Execution.waiting.count }
+
+ expect(result[:form_data][:resume_token]).to be_present
+ expect(
+ DiscourseWorkflows::FormTriggerToken.valid?(
+ result[:form_data][:resume_token],
+ workflow_id: workflow.id,
+ trigger_node_id: "trigger-1",
+ uuid: uuid,
+ ),
+ ).to be(true)
+ end
+
+ context "with URL query parameters" do
+ let(:params) do
+ { uuid: uuid, form_query_parameters: { "name" => "Query User", "source" => "email" } }
+ end
+
+ it "uses matching query parameters as field defaults" do
+ expect(result[:form_data][:data]["name"]).to eq("Query User")
+ end
+
+ it "persists query parameters in the signed submission token" do
+ token_payload =
+ DiscourseWorkflows::FormTriggerToken.payload(
+ result[:form_data][:resume_token],
+ workflow_id: workflow.id,
+ trigger_node_id: "trigger-1",
+ uuid: uuid,
+ )
+
+ expect(token_payload["form_query_parameters"]).to eq(
+ "name" => "Query User",
+ "source" => "email",
+ )
+ end
+ end
+
+ context "with hidden fields and URL query parameters" do
+ let(:params) do
+ { uuid: uuid, form_query_parameters: { "tracking_id" => "query-tracking" } }
+ end
+
+ before do
+ trigger_node = workflow.nodes.find { |node| node["id"] == "trigger-1" }
+ trigger_node["parameters"]["form_fields"] = [
+ {
+ "field_label" => "Tracking ID",
+ "field_name" => "tracking_id",
+ "field_type" => "hiddenField",
+ },
+ ]
+ workflow.update!(nodes: workflow.nodes)
+ publish_workflow!(workflow)
+ end
+
+ it "keeps hidden values server-side and out of public form data" do
+ expect(result[:form_data]).not_to have_key(:form_fields)
+ expect(result[:form_data][:data]).to be_empty
+ expect(result[:form_data][:fields]).to be_empty
+ end
+ end
+
+ context "when the draft workflow name changes after publishing" do
+ before do
+ trigger_node = workflow.nodes.find { |node| node["id"] == "trigger-1" }
+ trigger_node["parameters"]["form_title"] = "={{ $execution.workflow_name }}"
+ workflow.update!(nodes: workflow.nodes)
+ publish_workflow!(workflow)
+ workflow.update!(name: "Draft workflow name")
+ end
+
+ it "uses the published workflow name in execution expressions" do
+ expect(result[:form_data][:form_title]).to eq(workflow.active_version.name)
+ end
+ end
+ end
+
+ context "when form_description references $execution.resume_url" do
+ before do
+ trigger_node = workflow.nodes.find { |n| n["type"] == "trigger:form" }
+ trigger_node["parameters"]["form_description"] = "={{ $execution.resume_url }}"
+ workflow.update!(nodes: workflow.nodes)
+ publish_workflow!(workflow)
+ end
+
+ it "resolves $execution.resume_url without materializing an execution" do
+ expect(result).to run_successfully
+ expect(result[:form_data][:form_description]).to eq("")
+ end
+
+ it "returns resume_token in the response" do
+ expect(result).to run_successfully
+ expect(result[:form_data][:resume_token]).to be_present
+ end
+ end
+
+ context "when form_description references $execution.resumeFormUrl" do
+ before do
+ trigger_node = workflow.nodes.find { |n| n["type"] == "trigger:form" }
+ trigger_node["parameters"]["form_description"] = "={{ $execution.resumeFormUrl }}"
+ workflow.update!(nodes: workflow.nodes)
+ publish_workflow!(workflow)
+ end
+
+ it "resolves $execution.resumeFormUrl without materializing an execution" do
+ expect(result).to run_successfully
+ expect(result[:form_data][:form_description]).to eq("")
+ end
+ end
+
+ context "when a non-adjacent downstream form action exists" do
+ before do
+ extra =
+ build_workflow_graph do |g|
+ g.node "action-1", "action:send_message"
+ g.node "form-action-1", "action:form", configuration: { "form_fields" => [] }
+ end
+ nodes = workflow.nodes + extra[:nodes]
+ workflow.update!(
+ nodes: nodes,
+ connections:
+ workflow_connections_for(nodes, %w[trigger-1 action-1], %w[action-1 form-action-1]),
+ )
+ publish_workflow!(workflow)
+ end
+
+ it "detects the downstream form through intermediate nodes" do
+ expect(result[:form_data][:has_downstream_form]).to be(true)
+ end
+ end
+ end
+end
diff --git a/plugins/discourse-workflows/spec/services/discourse_workflows/form/submit_spec.rb b/plugins/discourse-workflows/spec/services/discourse_workflows/form/submit_spec.rb
new file mode 100644
index 00000000000..8adc36676a9
--- /dev/null
+++ b/plugins/discourse-workflows/spec/services/discourse_workflows/form/submit_spec.rb
@@ -0,0 +1,301 @@
+# frozen_string_literal: true
+
+RSpec.describe DiscourseWorkflows::Form::Submit do
+ describe described_class::Contract, type: :model do
+ it { is_expected.to validate_presence_of(:uuid) }
+ it { is_expected.to allow_value({}).for(:form_data) }
+ it { is_expected.not_to allow_value("string").for(:form_data) }
+ it { is_expected.not_to allow_value([]).for(:form_data) }
+ end
+
+ describe ".call" do
+ subject(:result) { described_class.call(params:, **dependencies) }
+
+ fab!(:user)
+ let(:dependencies) { { guardian: Guardian.new(user) } }
+
+ fab!(:workflow) do
+ graph =
+ build_workflow_graph do |g|
+ g.node "trigger-1",
+ "trigger:form",
+ configuration: {
+ "uuid" => "a1b2c3d4-e5f6-7890-abcd-ef0123456789",
+ "form_title" => "Test Form",
+ "form_fields" => [
+ { "field_label" => "Name", "field_type" => "text", "required" => true },
+ ],
+ "response_mode" => "on_received",
+ }
+ end
+ Fabricate(:discourse_workflows_workflow, published: true, **graph)
+ end
+
+ let(:uuid) { "a1b2c3d4-e5f6-7890-abcd-ef0123456789" }
+ let(:resume_token) do
+ DiscourseWorkflows::FormTriggerToken.generate(
+ workflow_id: workflow.id,
+ trigger_node_id: "trigger-1",
+ uuid: uuid,
+ )
+ end
+ let(:form_data) { { "name" => "Test User" } }
+ let(:params) { { uuid: uuid, resume_token: resume_token, form_data: form_data } }
+
+ before { DiscourseWorkflows::WorkflowDependencyIndexer.call(workflow) }
+
+ context "when the contract is invalid" do
+ let(:uuid) { nil }
+
+ it { is_expected.to fail_a_contract }
+ end
+
+ context "when the workflow is not found" do
+ let(:uuid) { "00000000-0000-0000-0000-000000000000" }
+
+ it { is_expected.to fail_to_find_a_model(:published_trigger) }
+ end
+
+ context "when the workflow is unpublished" do
+ before { unpublish_workflow!(workflow) }
+
+ it { is_expected.to fail_to_find_a_model(:published_trigger) }
+ end
+
+ context "when the form requires a logged-in user" do
+ before do
+ trigger_node = workflow.nodes.find { |n| n["type"] == "trigger:form" }
+ trigger_node["parameters"]["authentication"] = "login_required"
+ workflow.update!(nodes: workflow.nodes)
+ publish_workflow!(workflow)
+ end
+
+ context "without a current user" do
+ let(:dependencies) { { guardian: Guardian.new } }
+
+ it { is_expected.to fail_a_policy(:authenticated_if_required) }
+ end
+
+ context "with a current user" do
+ it { is_expected.to run_successfully }
+ end
+ end
+
+ context "when required form fields are missing" do
+ let(:form_data) { {} }
+
+ it { is_expected.to fail_a_step(:ensure_form_valid) }
+
+ it "sets the missing field error" do
+ expect(result[:form_validation].errors.map(&:to_h)).to contain_exactly(
+ { field_label: "Name", code: :missing },
+ )
+ end
+ end
+
+ context "when required form fields are blank" do
+ let(:form_data) { { "name" => "" } }
+
+ it { is_expected.to fail_a_step(:ensure_form_valid) }
+ end
+
+ context "when a number field receives a non-numeric value" do
+ let(:uuid) { "11111111-2222-3333-4444-555555555555" }
+
+ fab!(:workflow) do
+ graph =
+ build_workflow_graph do |g|
+ g.node "trigger-1",
+ "trigger:form",
+ configuration: {
+ "uuid" => "11111111-2222-3333-4444-555555555555",
+ "form_title" => "Test Form",
+ "form_fields" => [
+ { "field_label" => "Age", "field_type" => "number", "required" => true },
+ ],
+ "response_mode" => "on_received",
+ }
+ end
+ Fabricate(:discourse_workflows_workflow, published: true, **graph)
+ end
+
+ let(:form_data) { { "age" => "abc" } }
+
+ it { is_expected.to fail_a_step(:ensure_form_valid) }
+
+ it "reports the invalid value" do
+ expect(result[:form_validation].errors.map(&:to_h)).to contain_exactly(
+ { field_label: "Age", code: :invalid_value },
+ )
+ end
+ end
+
+ context "when the initial submission token is missing" do
+ let(:resume_token) { nil }
+
+ it { is_expected.to fail_a_policy(:valid_initial_submission_token) }
+ end
+
+ context "when the initial submission token is invalid" do
+ let(:resume_token) { "invalid-token" }
+
+ it { is_expected.to fail_a_policy(:valid_initial_submission_token) }
+ end
+
+ context "when everything's ok" do
+ it { is_expected.to run_successfully }
+
+ it "creates an execution" do
+ expect { result }.to change { DiscourseWorkflows::Execution.count }.by(1)
+ end
+
+ it "sets the execution in the context" do
+ result
+ expect(result[:execution]).to be_a(DiscourseWorkflows::Execution)
+ end
+
+ it "stores a compatible top-level trigger payload" do
+ freeze_time Time.utc(2026, 1, 1)
+
+ result
+
+ expect(result[:execution].trigger_data).to include(
+ "name" => "Test User",
+ "submitted_at" => "2026-01-01T00:00:00.000Z",
+ "form_mode" => "production",
+ )
+ expect(result[:execution].trigger_data).not_to have_key("form_data")
+ end
+
+ it "computes response metadata" do
+ result
+ expect(result[:response_metadata]).to include(
+ has_downstream_form: false,
+ response_mode: "on_received",
+ )
+ end
+
+ context "with a long form field value" do
+ let(:form_data) { { "name" => "a" * 10_001 } }
+
+ it "stores the truncated value in trigger data" do
+ result
+
+ stored_name = result[:execution].trigger_data["name"]
+ expect(stored_name.length).to eq(
+ DiscourseWorkflows::Schemas::FormFields::MAX_FIELD_VALUE_LENGTH,
+ )
+ end
+ end
+
+ context "with hidden form fields" do
+ before do
+ trigger_node = workflow.nodes.find { |node| node["id"] == "trigger-1" }
+ trigger_node["parameters"]["form_fields"] = [
+ { "field_label" => "Name", "field_type" => "text", "required" => true },
+ {
+ "field_label" => "Tracking ID",
+ "field_name" => "tracking_id",
+ "field_type" => "hiddenField",
+ "field_value" => "server-value",
+ },
+ ]
+ workflow.update!(nodes: workflow.nodes)
+ publish_workflow!(workflow)
+ end
+
+ let(:form_data) { { "name" => "Test User", "tracking_id" => "client-value" } }
+
+ it "stores the configured hidden value instead of the client-submitted value" do
+ result
+
+ expect(result[:execution].trigger_data).to include(
+ "name" => "Test User",
+ "tracking_id" => "server-value",
+ )
+ end
+ end
+
+ context "with query-backed hidden form fields" do
+ before do
+ trigger_node = workflow.nodes.find { |node| node["id"] == "trigger-1" }
+ trigger_node["parameters"]["form_fields"] = [
+ { "field_label" => "Name", "field_type" => "text", "required" => true },
+ {
+ "field_label" => "Tracking ID",
+ "field_name" => "tracking_id",
+ "field_type" => "hiddenField",
+ },
+ ]
+ workflow.update!(nodes: workflow.nodes)
+ publish_workflow!(workflow)
+ end
+
+ let(:resume_token) do
+ DiscourseWorkflows::FormTriggerToken.generate(
+ workflow_id: workflow.id,
+ trigger_node_id: "trigger-1",
+ uuid: uuid,
+ form_query_parameters: {
+ tracking_id: "query-value",
+ },
+ )
+ end
+ let(:form_data) { { "name" => "Test User", "tracking_id" => "client-value" } }
+
+ it "stores the signed query value instead of the client-submitted value" do
+ result
+
+ expect(result[:execution].trigger_data).to include(
+ "name" => "Test User",
+ "tracking_id" => "query-value",
+ )
+ end
+ end
+
+ context "when the initial form URL had query parameters" do
+ let(:resume_token) do
+ DiscourseWorkflows::FormTriggerToken.generate(
+ workflow_id: workflow.id,
+ trigger_node_id: "trigger-1",
+ uuid: uuid,
+ form_query_parameters: {
+ source: "email",
+ ref: "spring",
+ },
+ )
+ end
+
+ it "stores form_query_parameters on the trigger payload" do
+ result
+
+ expect(result[:execution].trigger_data["form_query_parameters"]).to eq(
+ "source" => "email",
+ "ref" => "spring",
+ )
+ end
+ end
+
+ context "when a non-adjacent downstream form action exists" do
+ before do
+ extra =
+ build_workflow_graph do |g|
+ g.node "action-1", "action:send_message"
+ g.node "form-action-1", "action:form", configuration: { "form_fields" => [] }
+ end
+ nodes = workflow.nodes + extra[:nodes]
+ workflow.update!(
+ nodes: nodes,
+ connections:
+ workflow_connections_for(nodes, %w[trigger-1 action-1], %w[action-1 form-action-1]),
+ )
+ publish_workflow!(workflow)
+ end
+
+ it "detects the downstream form through intermediate nodes" do
+ expect(result[:response_metadata]).to include(has_downstream_form: true)
+ end
+ end
+ end
+ end
+end
diff --git a/plugins/discourse-workflows/spec/services/discourse_workflows/form_test_session/create_spec.rb b/plugins/discourse-workflows/spec/services/discourse_workflows/form_test_session/create_spec.rb
new file mode 100644
index 00000000000..48163c6690c
--- /dev/null
+++ b/plugins/discourse-workflows/spec/services/discourse_workflows/form_test_session/create_spec.rb
@@ -0,0 +1,70 @@
+# frozen_string_literal: true
+
+RSpec.describe DiscourseWorkflows::FormTestSession::Create do
+ describe described_class::Contract, type: :model do
+ it { is_expected.to validate_presence_of(:workflow_id) }
+ it { is_expected.to validate_presence_of(:trigger_node_id) }
+ end
+
+ describe ".call" do
+ subject(:result) { described_class.call(params:, **dependencies) }
+
+ fab!(:admin)
+ fab!(:workflow) do
+ graph = build_workflow_graph { |g| g.node "trigger-1", "trigger:form" }
+ Fabricate(:discourse_workflows_workflow, created_by: admin, published: false, **graph)
+ end
+
+ let(:params) { { workflow_id: workflow.id, trigger_node_id: "trigger-1" } }
+ let(:dependencies) { { guardian: admin.guardian } }
+
+ context "when contract is invalid" do
+ let(:params) { { workflow_id: workflow.id, trigger_node_id: nil } }
+
+ it { is_expected.to fail_a_contract }
+ end
+
+ context "when user cannot manage workflows" do
+ fab!(:user)
+
+ let(:dependencies) { { guardian: user.guardian } }
+
+ it { is_expected.to fail_a_policy(:can_manage_workflows) }
+ end
+
+ context "when workflow does not exist" do
+ let(:params) { { workflow_id: -1, trigger_node_id: "trigger-1" } }
+
+ it { is_expected.to fail_to_find_a_model(:workflow) }
+ end
+
+ context "when trigger node does not exist" do
+ let(:params) { { workflow_id: workflow.id, trigger_node_id: "missing" } }
+
+ it { is_expected.to fail_to_find_a_model(:trigger_node) }
+ end
+
+ context "when the node is not a form trigger" do
+ fab!(:workflow) do
+ graph = build_workflow_graph { |g| g.node "trigger-1", "trigger:manual" }
+ Fabricate(:discourse_workflows_workflow, created_by: admin, published: false, **graph)
+ end
+
+ it { is_expected.to fail_a_policy(:form_trigger_node) }
+ end
+
+ context "when everything is valid" do
+ it { is_expected.to run_successfully }
+
+ it "stores a retrievable test session" do
+ session = DiscourseWorkflows::FormTestSession.find(result[:token])
+
+ expect(session).to have_attributes(
+ workflow_id: workflow.id,
+ user_id: admin.id,
+ trigger_node_id: "trigger-1",
+ )
+ end
+ end
+ end
+end
diff --git a/plugins/discourse-workflows/spec/services/discourse_workflows/node_type/list_spec.rb b/plugins/discourse-workflows/spec/services/discourse_workflows/node_type/list_spec.rb
new file mode 100644
index 00000000000..8e730dfe4fa
--- /dev/null
+++ b/plugins/discourse-workflows/spec/services/discourse_workflows/node_type/list_spec.rb
@@ -0,0 +1,300 @@
+# frozen_string_literal: true
+
+RSpec.describe DiscourseWorkflows::NodeType::List do
+ describe ".call" do
+ subject(:result) { described_class.call(**dependencies) }
+
+ fab!(:admin)
+
+ let(:dependencies) { { guardian: admin.guardian } }
+
+ context "when user cannot manage workflows" do
+ fab!(:user)
+
+ let(:dependencies) { { guardian: user.guardian } }
+
+ it { is_expected.to fail_a_policy(:can_manage_workflows) }
+ end
+
+ context "when everything's ok" do
+ fab!(:badge) { Fabricate(:badge, name: "Helpful") }
+
+ it { is_expected.to run_successfully }
+
+ it "returns all registered node types" do
+ identifiers = result[:node_types].map { |nt| nt[:identifier] }
+ expect(identifiers).to include(
+ "trigger:topic_closed",
+ "action:topic_tags",
+ "action:create_post",
+ "action:topic",
+ "condition:if",
+ )
+ end
+
+ it "includes expected schema fields for each node type" do
+ node_type = result[:node_types].find { |nt| nt[:identifier] == "action:create_post" }
+ expect(node_type).to include(
+ :displayName,
+ :name,
+ :version,
+ :defaults,
+ :inputs,
+ :outputs,
+ :properties,
+ :credentials,
+ :webhooks,
+ )
+ expect(node_type[:name]).to eq("action:create_post")
+ expect(node_type[:kind]).to eq("action")
+ expect(node_type[:properties].keys).to contain_exactly(
+ :topic_id,
+ :raw,
+ :reply_to_post_number,
+ :author_username,
+ )
+ end
+
+ it "returns UI hints for schema-driven configurators" do
+ node_type = result[:node_types].find { |nt| nt[:identifier] == "action:create_post" }
+
+ expect(node_type.dig(:properties, :raw, :ui)).to eq(control: :textarea)
+ end
+
+ it "includes specialized property-engine controls in node schemas" do
+ award_badge = result[:node_types].find { |nt| nt[:identifier] == "action:badge" }
+ code = result[:node_types].find { |nt| nt[:identifier] == "action:code" }
+ data_table = result[:node_types].find { |nt| nt[:identifier] == "action:data_table" }
+ condition = result[:node_types].find { |nt| nt[:identifier] == "condition:if" }
+ webhook = result[:node_types].find { |nt| nt[:identifier] == "trigger:webhook" }
+
+ expect(award_badge.dig(:properties, :badge_id, :ui, :control)).to eq(:combo_box)
+ expect(code.dig(:properties, :code, :ui, :control)).to eq(:code)
+ expect(data_table.dig(:properties, :columns, :ui, :control)).to eq(:data_table_columns)
+ expect(data_table.dig(:properties, :sort_column, :ui, :control)).to eq(
+ :data_table_column_select,
+ )
+ expect(condition.dig(:properties, :conditions, :ui, :control)).to eq(:condition_builder)
+ expect(webhook.dig(:properties, :url_preview, :ui, :control)).to eq(:url_preview)
+ end
+
+ it "declares load options methods for dynamic combo box fields" do
+ award_badge = result[:node_types].find { |nt| nt[:identifier] == "action:badge" }
+
+ expect(award_badge.dig(:properties, :badge_id, :type_options)).to include(
+ load_options_method: "badges",
+ )
+ expect(award_badge).not_to have_key(:metadata)
+ end
+
+ it "includes branching for condition nodes" do
+ condition = result[:node_types].find { |nt| nt[:identifier] == "condition:if" }
+ expect(condition[:branching]).to be(true)
+ end
+
+ it "serializes ui palette group for action nodes" do
+ create_post = result[:node_types].find { |nt| nt[:identifier] == "action:create_post" }
+ form = result[:node_types].find { |nt| nt[:identifier] == "action:form" }
+
+ expect(create_post.dig(:ui, :palette_group, :id)).to eq("discourse_actions")
+ expect(form.dig(:ui, :palette_group, :id)).to eq("human_review")
+ end
+
+ it "does not serialize internal waiting webhook handlers" do
+ form = result[:node_types].find { |nt| nt[:identifier] == "action:form" }
+
+ expect(form[:webhooks]).to include(
+ a_hash_including(name: "setup", restart_webhook: true, node_type: "form"),
+ a_hash_including(name: "default", restart_webhook: true, node_type: "form"),
+ a_hash_including(name: "status", restart_webhook: true, node_type: "form"),
+ )
+ expect(form[:webhooks]).to all(exclude(:handler))
+ expect(form.dig(:description, :webhooks)).to all(exclude(:handler))
+ end
+
+ it "serializes ui and operations for data_table node" do
+ data_table = result[:node_types].find { |nt| nt[:identifier] == "action:data_table" }
+
+ expect(data_table[:ui]).to include(
+ icon: "table",
+ color: "violet",
+ i18n_prefix: "discourse_workflows",
+ i18n_scope: "data_table_node",
+ palette_group: a_hash_including(id: "data"),
+ )
+ expect(data_table[:operations]).to include(
+ value: "insert",
+ label_key: "discourse_workflows.data_table_node.operations.insert",
+ )
+ end
+
+ it "serializes capabilities and ports for condition node" do
+ condition = result[:node_types].find { |nt| nt[:identifier] == "condition:if" }
+
+ expect(condition[:capabilities]).to include(
+ branching: true,
+ manually_triggerable: false,
+ result_mode: "ports",
+ )
+ expect(condition[:ports]).to eq(
+ [
+ {
+ key: "true",
+ type: "main",
+ index: 0,
+ primary: true,
+ label_key: "discourse_workflows.branch.true",
+ },
+ {
+ key: "false",
+ type: "main",
+ index: 1,
+ primary: false,
+ label_key: "discourse_workflows.branch.false",
+ },
+ ],
+ )
+ end
+
+ it "does not serialize hidden loop node" do
+ loop_node = result[:node_types].find { |nt| nt[:identifier] == "flow:loop_over_items" }
+
+ expect(loop_node).to be_nil
+ end
+
+ it "serializes ui palette group for trigger nodes" do
+ topic_closed = result[:node_types].find { |nt| nt[:identifier] == "trigger:topic_closed" }
+
+ expect(topic_closed.dig(:ui, :palette_group, :id)).to eq("discourse_triggers")
+ end
+
+ it "includes manually_triggerable for triggers that support it" do
+ manual = result[:node_types].find { |nt| nt[:identifier] == "trigger:manual" }
+ schedule = result[:node_types].find { |nt| nt[:identifier] == "trigger:schedule" }
+ form = result[:node_types].find { |nt| nt[:identifier] == "trigger:form" }
+ error = result[:node_types].find { |nt| nt[:identifier] == "trigger:error" }
+ topic_closed = result[:node_types].find { |nt| nt[:identifier] == "trigger:topic_closed" }
+
+ expect(manual[:manually_triggerable]).to be(true)
+ expect(schedule[:manually_triggerable]).to be(true)
+ expect(form[:manually_triggerable]).to be(true)
+ expect(error[:manually_triggerable]).to be(false)
+ expect(topic_closed[:manually_triggerable]).to be(false)
+ end
+
+ it "includes credential_types in the result" do
+ expect(result[:credential_types]).to include(
+ a_hash_including(
+ identifier: "basic_auth",
+ display_name: "Basic Auth",
+ property_schema: DiscourseWorkflows::CredentialTypes::BasicAuth.property_schema,
+ ),
+ )
+ end
+
+ it "exposes first-class credential slots on credential-consuming node types" do
+ http_request = result[:node_types].find { |nt| nt[:identifier] == "action:http_request" }
+
+ expect(http_request[:credentials]).to contain_exactly(
+ a_hash_including(
+ name: "auth",
+ credential_types: %w[basic_auth bearer_token],
+ required: false,
+ display_options: {
+ show: {
+ authentication: %w[basic_auth bearer_token],
+ },
+ },
+ ),
+ )
+ expect(http_request[:properties]).not_to have_key(:credential_id)
+ end
+ end
+ end
+
+ describe "#fetch_node_types" do
+ fab!(:admin)
+
+ it "includes unavailable node types with available: false" do
+ reason_key = "discourse_workflows.node_unavailable.test_reason"
+ unavailable_class =
+ Class.new(DiscourseWorkflows::NodeType) do
+ description(
+ name: "action:unavailable_palette_test",
+ available: false,
+ unavailable_reason_key: -> { reason_key },
+ )
+ end
+
+ DiscoursePluginRegistry.register_discourse_workflows_node(
+ unavailable_class,
+ Plugin::Instance.new,
+ )
+ DiscourseWorkflows::Registry.reset_indexes!
+
+ result = described_class.call(guardian: admin.guardian)
+ unavailable =
+ result[:node_types].find { |nt| nt[:identifier] == "action:unavailable_palette_test" }
+
+ expect(unavailable).to be_present
+ expect(unavailable[:available]).to eq(false)
+ expect(unavailable[:unavailable_reason_key]).to eq(reason_key)
+ ensure
+ DiscoursePluginRegistry.discourse_workflows_nodes.delete(unavailable_class)
+ DiscourseWorkflows::Registry.reset_indexes!
+ end
+
+ it "serializes full descriptions for each registered node version" do
+ v1 =
+ Class.new(DiscourseWorkflows::NodeType) do
+ description(
+ name: "action:versioned_palette_test",
+ version: "1.0",
+ properties: {
+ old_field: {
+ type: :string,
+ },
+ },
+ outputs: [{ key: "old", primary: true }],
+ )
+ end
+ v2 =
+ Class.new(DiscourseWorkflows::NodeType) do
+ description(
+ name: "action:versioned_palette_test",
+ version: "2.0",
+ properties: {
+ new_field: {
+ type: :string,
+ },
+ },
+ outputs: [{ key: "new", primary: true }],
+ )
+ end
+
+ DiscoursePluginRegistry.register_discourse_workflows_node(v1, Plugin::Instance.new)
+ DiscoursePluginRegistry.register_discourse_workflows_node(v2, Plugin::Instance.new)
+ DiscourseWorkflows::Registry.reset_indexes!
+
+ result = described_class.call(guardian: admin.guardian)
+ node_type =
+ result[:node_types].find { |nt| nt[:identifier] == "action:versioned_palette_test" }
+
+ expect(node_type.dig(:latest, :version)).to eq("2.0")
+ expect(node_type[:properties]).to have_key(:new_field)
+ expect(node_type.dig(:versions, "1.0", :properties)).to have_key(:old_field)
+ expect(node_type.dig(:versions, "1.0", :outputs)).to contain_exactly(include(key: "old"))
+ expect(node_type.dig(:versions, "2.0", :properties)).to have_key(:new_field)
+ expect(node_type).not_to have_key(:latest_version)
+ expect(node_type).not_to have_key(:available_versions)
+ expect(node_type).not_to have_key(:property_versions)
+ expect(node_type).not_to have_key(:property_schema_versions)
+ expect(node_type[:latest]).not_to have_key(:property_schema)
+ ensure
+ DiscoursePluginRegistry._raw_discourse_workflows_nodes.reject! do |entry|
+ [v1, v2].include?(entry[:value])
+ end
+ DiscourseWorkflows::Registry.reset_indexes!
+ end
+ end
+end
diff --git a/plugins/discourse-workflows/spec/services/discourse_workflows/stats/summary_spec.rb b/plugins/discourse-workflows/spec/services/discourse_workflows/stats/summary_spec.rb
new file mode 100644
index 00000000000..834a84d84fd
--- /dev/null
+++ b/plugins/discourse-workflows/spec/services/discourse_workflows/stats/summary_spec.rb
@@ -0,0 +1,114 @@
+# frozen_string_literal: true
+
+RSpec.describe DiscourseWorkflows::Stats::Summary do
+ describe ".call" do
+ subject(:result) { described_class.call(params:, **dependencies) }
+
+ fab!(:admin)
+ fab!(:workflow) { Fabricate(:discourse_workflows_workflow, created_by: admin) }
+
+ let(:params) { {} }
+ let(:dependencies) { { guardian: admin.guardian } }
+
+ context "when user cannot manage workflows" do
+ fab!(:user)
+
+ let(:dependencies) { { guardian: user.guardian } }
+
+ it { is_expected.to fail_a_policy(:can_manage_workflows) }
+ end
+
+ context "when there are no executions" do
+ it { is_expected.to run_successfully }
+
+ it "returns zeroed stats" do
+ expect(result[:stats]).to eq(total: 0, failed: 0, failure_rate: "0%", avg_duration: "0ms")
+ end
+ end
+
+ context "when there are recent executions" do
+ before do
+ Fabricate(
+ :discourse_workflows_execution,
+ workflow: workflow,
+ status: :success,
+ started_at: 2.hours.ago,
+ finished_at: 2.hours.ago + 10.seconds,
+ )
+ Fabricate(
+ :discourse_workflows_execution,
+ workflow: workflow,
+ status: :success,
+ started_at: 1.hour.ago,
+ finished_at: 1.hour.ago + 20.seconds,
+ )
+ Fabricate(
+ :discourse_workflows_execution,
+ workflow: workflow,
+ status: :error,
+ started_at: 30.minutes.ago,
+ finished_at: 30.minutes.ago + 30.seconds,
+ )
+ end
+
+ it { is_expected.to run_successfully }
+
+ it "computes correct stats" do
+ stats = result[:stats]
+ expect(stats[:total]).to eq(3)
+ expect(stats[:failed]).to eq(1)
+ expect(stats[:failure_rate]).to eq("33.3%")
+ expect(stats[:avg_duration]).to eq("20.0s")
+ end
+ end
+
+ context "when executions are older than 7 days" do
+ before do
+ execution =
+ Fabricate(
+ :discourse_workflows_execution,
+ workflow: workflow,
+ status: :success,
+ started_at: 10.days.ago,
+ finished_at: 10.days.ago + 5.seconds,
+ )
+ execution.update_column(:created_at, 10.days.ago)
+ end
+
+ it { is_expected.to run_successfully }
+
+ it "does not count old executions" do
+ expect(result[:stats]).to eq(total: 0, failed: 0, failure_rate: "0%", avg_duration: "0ms")
+ end
+ end
+
+ context "when filtering by workflow_id" do
+ fab!(:other_workflow) { Fabricate(:discourse_workflows_workflow, created_by: admin) }
+
+ before do
+ Fabricate(
+ :discourse_workflows_execution,
+ workflow: workflow,
+ status: :success,
+ started_at: 1.hour.ago,
+ finished_at: 1.hour.ago + 10.seconds,
+ )
+ Fabricate(
+ :discourse_workflows_execution,
+ workflow: other_workflow,
+ status: :success,
+ started_at: 1.hour.ago,
+ finished_at: 1.hour.ago + 20.seconds,
+ )
+ end
+
+ let(:params) { { workflow_id: workflow.id } }
+
+ it { is_expected.to run_successfully }
+
+ it "only counts executions for the specified workflow" do
+ expect(result[:stats][:total]).to eq(1)
+ end
+ end
+ end
+end
diff --git a/plugins/discourse-workflows/spec/services/discourse_workflows/template/list_spec.rb b/plugins/discourse-workflows/spec/services/discourse_workflows/template/list_spec.rb
new file mode 100644
index 00000000000..d03465fa8b7
--- /dev/null
+++ b/plugins/discourse-workflows/spec/services/discourse_workflows/template/list_spec.rb
@@ -0,0 +1,63 @@
+# frozen_string_literal: true
+
+RSpec.describe DiscourseWorkflows::Template::List do
+ describe ".call" do
+ subject(:result) { described_class.call(**dependencies) }
+
+ fab!(:admin)
+ let(:dependencies) { { guardian: admin.guardian } }
+
+ before { DiscourseWorkflows::TemplateStore.reset_cache! }
+ after { DiscourseWorkflows::TemplateStore.reset_cache! }
+
+ context "when user is not admin" do
+ fab!(:user)
+ let(:dependencies) { { guardian: user.guardian } }
+
+ it { is_expected.to fail_a_policy(:can_manage_workflows) }
+ end
+
+ context "when templates exist" do
+ it { is_expected.to run_successfully }
+
+ it "returns templates with the expected attributes" do
+ template = result[:templates].first
+ expect(template).to include(:id, :name, :description, :node_types)
+ end
+
+ it "includes known templates from config/templates" do
+ ids = result[:templates].map { |t| t[:id] }
+ expect(ids).to include("auto-tag-topics")
+ end
+ end
+
+ context "when a template file has invalid JSON" do
+ before do
+ FileUtils.mkdir_p(DiscourseWorkflows::TEMPLATES_PATH)
+ File.write(
+ File.join(DiscourseWorkflows::TEMPLATES_PATH, "broken.json"),
+ "not valid json{{{",
+ )
+ end
+
+ after { FileUtils.rm_f(File.join(DiscourseWorkflows::TEMPLATES_PATH, "broken.json")) }
+
+ it { is_expected.to run_successfully }
+
+ it "skips the malformed template" do
+ ids = result[:templates].map { |t| t[:id] }
+ expect(ids).not_to include("broken")
+ end
+ end
+
+ context "when no template files exist" do
+ before { DiscourseWorkflows::TemplateStore.stubs(:summaries).returns([]) }
+
+ it { is_expected.to run_successfully }
+
+ it "returns an empty array" do
+ expect(result[:templates]).to eq([])
+ end
+ end
+ end
+end
diff --git a/plugins/discourse-workflows/spec/services/discourse_workflows/template/show_spec.rb b/plugins/discourse-workflows/spec/services/discourse_workflows/template/show_spec.rb
new file mode 100644
index 00000000000..282601ad055
--- /dev/null
+++ b/plugins/discourse-workflows/spec/services/discourse_workflows/template/show_spec.rb
@@ -0,0 +1,57 @@
+# frozen_string_literal: true
+
+RSpec.describe DiscourseWorkflows::Template::Show do
+ describe described_class::Contract, type: :model do
+ it { is_expected.to validate_presence_of(:template_id) }
+ it do
+ is_expected.to allow_values("auto-tag-topics", "my_template", "test123").for(:template_id)
+ end
+ it do
+ is_expected.not_to allow_values("../etc/passwd", "UPPER", "with spaces", "with/slash").for(
+ :template_id,
+ )
+ end
+ end
+
+ describe ".call" do
+ subject(:result) { described_class.call(params:, **dependencies) }
+
+ fab!(:admin)
+
+ let(:params) { { template_id: } }
+ let(:template_id) { "auto-tag-topics" }
+ let(:dependencies) { { guardian: admin.guardian } }
+
+ before { DiscourseWorkflows::TemplateStore.reset_cache! }
+ after { DiscourseWorkflows::TemplateStore.reset_cache! }
+
+ context "when contract is invalid" do
+ let(:template_id) { nil }
+
+ it { is_expected.to fail_a_contract }
+ end
+
+ context "when user cannot manage workflows" do
+ fab!(:user)
+
+ let(:dependencies) { { guardian: user.guardian } }
+
+ it { is_expected.to fail_a_policy(:can_manage_workflows) }
+ end
+
+ context "when template is not found" do
+ let(:template_id) { "nonexistent-template" }
+
+ it { is_expected.to fail_to_find_a_model(:template) }
+ end
+
+ context "when template exists" do
+ it { is_expected.to run_successfully }
+
+ it "returns the parsed template data" do
+ expect(result[:template]).to be_a(Hash)
+ expect(result[:template]["name"]).to eq("Auto-tag new topics")
+ end
+ end
+ end
+end
diff --git a/plugins/discourse-workflows/spec/services/discourse_workflows/variable/create_spec.rb b/plugins/discourse-workflows/spec/services/discourse_workflows/variable/create_spec.rb
new file mode 100644
index 00000000000..3c299e01607
--- /dev/null
+++ b/plugins/discourse-workflows/spec/services/discourse_workflows/variable/create_spec.rb
@@ -0,0 +1,64 @@
+# frozen_string_literal: true
+
+RSpec.describe DiscourseWorkflows::Variable::Create do
+ describe described_class::Contract, type: :model do
+ it { is_expected.to validate_presence_of(:key) }
+ it { is_expected.to validate_presence_of(:value) }
+ it { is_expected.to validate_length_of(:key).is_at_most(100) }
+ it { is_expected.to validate_length_of(:value).is_at_most(1000) }
+ it { is_expected.to validate_length_of(:description).is_at_most(500) }
+ it { is_expected.to allow_values("valid_key", "Key_123", "_underscore").for(:key) }
+ it { is_expected.not_to allow_values("invalid key", "123start", "key!@#").for(:key) }
+ end
+
+ describe ".call" do
+ subject(:result) { described_class.call(params:, **dependencies) }
+
+ fab!(:admin)
+
+ let(:params) { { key: "API_BASE_URL", value: "https://example.com", description: "Base URL" } }
+ let(:dependencies) { { guardian: admin.guardian } }
+
+ context "when contract is invalid" do
+ let(:params) { { key: "invalid key!", value: nil } }
+
+ it { is_expected.to fail_a_contract }
+ end
+
+ context "when user cannot manage workflows" do
+ fab!(:user)
+
+ let(:dependencies) { { guardian: user.guardian } }
+
+ it { is_expected.to fail_a_policy(:can_manage_workflows) }
+ end
+
+ context "when variable key already exists" do
+ before { Fabricate(:discourse_workflows_variable, key: "API_BASE_URL") }
+
+ it { is_expected.to fail_with_an_invalid_model(:variable) }
+ end
+
+ context "when everything's ok" do
+ it { is_expected.to run_successfully }
+
+ it "creates the variable" do
+ expect { result }.to change { DiscourseWorkflows::Variable.count }.by(1)
+ expect(DiscourseWorkflows::Variable.last).to have_attributes(
+ key: "API_BASE_URL",
+ value: "https://example.com",
+ description: "Base URL",
+ created_by: admin,
+ )
+ end
+
+ it "logs a staff action" do
+ expect { result }.to change { UserHistory.count }.by(1)
+ expect(UserHistory.last).to have_attributes(
+ custom_type: "discourse_workflows_variable_created",
+ subject: "API_BASE_URL",
+ )
+ end
+ end
+ end
+end
diff --git a/plugins/discourse-workflows/spec/services/discourse_workflows/variable/destroy_spec.rb b/plugins/discourse-workflows/spec/services/discourse_workflows/variable/destroy_spec.rb
new file mode 100644
index 00000000000..cc69852584d
--- /dev/null
+++ b/plugins/discourse-workflows/spec/services/discourse_workflows/variable/destroy_spec.rb
@@ -0,0 +1,53 @@
+# frozen_string_literal: true
+
+RSpec.describe DiscourseWorkflows::Variable::Destroy do
+ describe described_class::Contract, type: :model do
+ it { is_expected.to validate_presence_of(:variable_id) }
+ end
+
+ describe ".call" do
+ subject(:result) { described_class.call(params:, **dependencies) }
+
+ fab!(:admin)
+ fab!(:variable, :discourse_workflows_variable)
+
+ let(:params) { { variable_id: variable.id } }
+ let(:dependencies) { { guardian: admin.guardian } }
+
+ context "when params are not valid" do
+ let(:params) { {} }
+
+ it { is_expected.to fail_a_contract }
+ end
+
+ context "when variable does not exist" do
+ let(:params) { { variable_id: -1 } }
+
+ it { is_expected.to fail_to_find_a_model(:variable) }
+ end
+
+ context "when user cannot manage workflows" do
+ fab!(:user)
+
+ let(:dependencies) { { guardian: user.guardian } }
+
+ it { is_expected.to fail_a_policy(:can_manage_workflows) }
+ end
+
+ context "when everything's ok" do
+ it { is_expected.to run_successfully }
+
+ it "deletes the variable" do
+ expect { result }.to change { DiscourseWorkflows::Variable.count }.by(-1)
+ end
+
+ it "logs a staff action" do
+ expect { result }.to change { UserHistory.count }.by(1)
+ expect(UserHistory.last).to have_attributes(
+ custom_type: "discourse_workflows_variable_destroyed",
+ subject: variable.key,
+ )
+ end
+ end
+ end
+end
diff --git a/plugins/discourse-workflows/spec/services/discourse_workflows/variable/list_spec.rb b/plugins/discourse-workflows/spec/services/discourse_workflows/variable/list_spec.rb
new file mode 100644
index 00000000000..239d15388e4
--- /dev/null
+++ b/plugins/discourse-workflows/spec/services/discourse_workflows/variable/list_spec.rb
@@ -0,0 +1,82 @@
+# frozen_string_literal: true
+
+RSpec.describe DiscourseWorkflows::Variable::List do
+ describe ".call" do
+ subject(:result) { described_class.call(params:, **dependencies) }
+
+ fab!(:admin)
+
+ let(:params) { {} }
+ let(:dependencies) { { guardian: admin.guardian } }
+
+ context "when user cannot manage workflows" do
+ fab!(:user)
+
+ let(:dependencies) { { guardian: user.guardian } }
+
+ it { is_expected.to fail_a_policy(:can_manage_workflows) }
+ end
+
+ context "when there are no variables" do
+ it { is_expected.to run_successfully }
+
+ it "returns an empty collection" do
+ expect(result[:variables]).to be_empty
+ end
+
+ it "returns zero total rows" do
+ expect(result[:total_rows]).to eq(0)
+ end
+
+ it "does not return a load more url" do
+ expect(result[:load_more_url]).to be_nil
+ end
+ end
+
+ context "when there are variables" do
+ fab!(:variable_a) { Fabricate(:discourse_workflows_variable, key: "ALPHA") }
+ fab!(:variable_b) { Fabricate(:discourse_workflows_variable, key: "BRAVO") }
+
+ it { is_expected.to run_successfully }
+
+ it "returns variables ordered by id descending" do
+ expect(result[:variables].map(&:id)).to eq([variable_b.id, variable_a.id])
+ end
+
+ it "returns the total count" do
+ expect(result[:total_rows]).to eq(2)
+ end
+ end
+
+ context "with pagination" do
+ let(:params) { { limit: 2 } }
+
+ fab!(:variable_1) { Fabricate(:discourse_workflows_variable, key: "FIRST") }
+ fab!(:variable_2) { Fabricate(:discourse_workflows_variable, key: "SECOND") }
+ fab!(:variable_3) { Fabricate(:discourse_workflows_variable, key: "THIRD") }
+
+ it "returns only the requested number of variables" do
+ expect(result[:variables].size).to eq(2)
+ end
+
+ it "returns a load more url with cursor" do
+ last_id = result[:variables].last.id
+ expect(result[:load_more_url]).to eq(
+ "/admin/plugins/discourse-workflows/variables.json?cursor=#{last_id}&limit=2",
+ )
+ end
+
+ context "when using a cursor" do
+ let(:params) { { limit: 2, cursor: variable_3.id } }
+
+ it "returns variables after the cursor" do
+ expect(result[:variables].map(&:id)).to eq([variable_2.id, variable_1.id])
+ end
+
+ it "does not return a load more url when no more results" do
+ expect(result[:load_more_url]).to be_nil
+ end
+ end
+ end
+ end
+end
diff --git a/plugins/discourse-workflows/spec/services/discourse_workflows/variable/update_spec.rb b/plugins/discourse-workflows/spec/services/discourse_workflows/variable/update_spec.rb
new file mode 100644
index 00000000000..9f39396d46b
--- /dev/null
+++ b/plugins/discourse-workflows/spec/services/discourse_workflows/variable/update_spec.rb
@@ -0,0 +1,66 @@
+# frozen_string_literal: true
+
+RSpec.describe DiscourseWorkflows::Variable::Update do
+ describe described_class::Contract, type: :model do
+ it { is_expected.to validate_presence_of(:variable_id) }
+ it { is_expected.to validate_presence_of(:key) }
+ it { is_expected.to validate_presence_of(:value) }
+ it { is_expected.to validate_length_of(:value).is_at_most(1000) }
+ it { is_expected.to validate_length_of(:description).is_at_most(500) }
+ end
+
+ describe ".call" do
+ subject(:result) { described_class.call(params:, **dependencies) }
+
+ fab!(:admin)
+ fab!(:variable, :discourse_workflows_variable)
+
+ let(:params) do
+ { variable_id: variable.id, key: "NEW_KEY", value: "new_value", description: "Updated" }
+ end
+ let(:dependencies) { { guardian: admin.guardian } }
+
+ context "when contract is invalid" do
+ let(:params) { { variable_id: variable.id, key: nil, value: nil } }
+
+ it { is_expected.to fail_a_contract }
+ end
+
+ context "when user cannot manage workflows" do
+ fab!(:user)
+
+ let(:dependencies) { { guardian: user.guardian } }
+
+ it { is_expected.to fail_a_policy(:can_manage_workflows) }
+ end
+
+ context "when variable does not exist" do
+ let(:params) { { variable_id: -1, key: "X", value: "Y" } }
+
+ it { is_expected.to fail_to_find_a_model(:variable) }
+ end
+
+ context "when variable has invalid attributes" do
+ fab!(:other_variable) { Fabricate(:discourse_workflows_variable, key: "NEW_KEY") }
+
+ it { is_expected.to fail_with_an_invalid_model(:variable) }
+ end
+
+ context "when everything's ok" do
+ it { is_expected.to run_successfully }
+
+ it "updates the variable" do
+ expect { result }.to change { variable.reload.key }.to("NEW_KEY")
+ expect(variable).to have_attributes(value: "new_value", description: "Updated")
+ end
+
+ it "logs a staff action" do
+ expect { result }.to change { UserHistory.count }.by(1)
+ expect(UserHistory.last).to have_attributes(
+ custom_type: "discourse_workflows_variable_updated",
+ subject: "NEW_KEY",
+ )
+ end
+ end
+ end
+end
diff --git a/plugins/discourse-workflows/spec/services/discourse_workflows/webhook/action/activate_webhooks_spec.rb b/plugins/discourse-workflows/spec/services/discourse_workflows/webhook/action/activate_webhooks_spec.rb
new file mode 100644
index 00000000000..65aca55ec79
--- /dev/null
+++ b/plugins/discourse-workflows/spec/services/discourse_workflows/webhook/action/activate_webhooks_spec.rb
@@ -0,0 +1,102 @@
+# frozen_string_literal: true
+
+RSpec.describe DiscourseWorkflows::Webhook::Action::ActivateWebhooks do
+ fab!(:admin)
+
+ def build_published_workflow(path:, http_method:, webhook_id: nil)
+ graph =
+ build_workflow_graph do |g|
+ g.node "webhook-1",
+ "trigger:webhook",
+ webhook_id: webhook_id,
+ configuration: {
+ "path" => path,
+ "http_method" => http_method,
+ }
+ end
+ Fabricate(:discourse_workflows_workflow, created_by: admin, published: true, **graph)
+ end
+
+ describe ".call" do
+ it "stores a row per webhook trigger in the active version" do
+ workflow = build_published_workflow(path: "hooks/inbound", http_method: "POST")
+ version = workflow.workflow_versions.find_by(version_id: workflow.version_id)
+
+ described_class.call(workflow: workflow, workflow_version: version)
+
+ row = DiscourseWorkflows::Webhook.production.find_by(workflow_id: workflow.id)
+ expect(row).to have_attributes(
+ webhook_path: "hooks/inbound",
+ http_method: "POST",
+ webhook_id: nil,
+ path_length: nil,
+ node_name: "Webhook-1",
+ test_webhook: false,
+ )
+ end
+
+ it "marks rows as dynamic when the path contains :placeholder segments" do
+ workflow =
+ build_published_workflow(
+ path: "users/:id/posts",
+ http_method: "GET",
+ webhook_id: "abcd-1234",
+ )
+ version = workflow.workflow_versions.find_by(version_id: workflow.version_id)
+
+ described_class.call(workflow: workflow, workflow_version: version)
+
+ row = DiscourseWorkflows::Webhook.production.find_by(workflow_id: workflow.id)
+ expect(row).to have_attributes(webhook_id: "abcd-1234", path_length: 3)
+ end
+
+ it "raises CollisionError when another workflow already owns the route" do
+ owner = build_published_workflow(path: "shared", http_method: "POST")
+ owner_version = owner.workflow_versions.find_by(version_id: owner.version_id)
+ described_class.call(workflow: owner, workflow_version: owner_version)
+
+ conflicting_graph =
+ build_workflow_graph do |g|
+ g.node "webhook-1",
+ "trigger:webhook",
+ configuration: {
+ "path" => "shared",
+ "http_method" => "POST",
+ }
+ end
+ other_workflow =
+ Fabricate(
+ :discourse_workflows_workflow,
+ created_by: admin,
+ published: false,
+ **conflicting_graph,
+ )
+ other_workflow.update_columns(active_version_id: other_workflow.version_id)
+ other_version =
+ other_workflow.workflow_versions.find_by(version_id: other_workflow.version_id)
+
+ expect do
+ described_class.call(workflow: other_workflow, workflow_version: other_version)
+ end.to raise_error(described_class::CollisionError) do |error|
+ expect(error.method).to eq("POST")
+ expect(error.path).to eq("shared")
+ end
+ end
+
+ it "replaces this workflow's prior rows on re-activation" do
+ workflow = build_published_workflow(path: "old", http_method: "POST")
+ version = workflow.workflow_versions.find_by(version_id: workflow.version_id)
+ described_class.call(workflow: workflow, workflow_version: version)
+
+ updated_nodes = version.nodes.deep_dup
+ updated_nodes.first["parameters"]["path"] = "new"
+ version.update!(nodes: updated_nodes)
+
+ described_class.call(workflow: workflow, workflow_version: version.reload)
+
+ expect(
+ DiscourseWorkflows::Webhook.production.where(workflow_id: workflow.id).pluck(:webhook_path),
+ ).to eq(["new"])
+ end
+ end
+end
diff --git a/plugins/discourse-workflows/spec/services/discourse_workflows/webhook/action/authenticate_node_spec.rb b/plugins/discourse-workflows/spec/services/discourse_workflows/webhook/action/authenticate_node_spec.rb
new file mode 100644
index 00000000000..ff5d8ac26cf
--- /dev/null
+++ b/plugins/discourse-workflows/spec/services/discourse_workflows/webhook/action/authenticate_node_spec.rb
@@ -0,0 +1,216 @@
+# frozen_string_literal: true
+
+RSpec.describe DiscourseWorkflows::Webhook::Action::AuthenticateNode do
+ fab!(:basic_credential) do
+ Fabricate(
+ :discourse_workflows_credential,
+ credential_type: "basic_auth",
+ data: {
+ "user" => "admin",
+ "password" => "secret",
+ },
+ )
+ end
+
+ fab!(:bearer_credential) do
+ Fabricate(
+ :discourse_workflows_credential,
+ credential_type: "bearer_token",
+ data: {
+ "token" => "secret-token",
+ },
+ )
+ end
+
+ fab!(:header_credential) do
+ Fabricate(
+ :discourse_workflows_credential,
+ credential_type: "header_auth",
+ data: {
+ "name" => "X-Api-Key",
+ "value" => "secret-value",
+ },
+ )
+ end
+
+ subject(:result) { described_class.call(node:, params:, credentials:) }
+
+ let(:credentials) do
+ {
+ basic_credential.id => basic_credential,
+ bearer_credential.id => bearer_credential,
+ header_credential.id => header_credential,
+ }
+ end
+ let(:credential_id) { basic_credential.id.to_s }
+ let(:credential_type) { "basic_auth" }
+
+ let(:node) do
+ {
+ "id" => "webhook-1",
+ "type" => "trigger:webhook",
+ "parameters" => {
+ "authentication" => auth_mode,
+ },
+ "credentials" => {
+ "auth" => {
+ "id" => credential_id,
+ "credential_type" => credential_type,
+ },
+ },
+ }
+ end
+
+ let(:auth_mode) { "none" }
+ let(:raw_authorization) { nil }
+ let(:headers) { {} }
+ let(:params) { OpenStruct.new(raw_authorization:, headers:) }
+
+ describe ".call" do
+ context "when authentication is none" do
+ it "returns :authenticated" do
+ expect(result).to eq(:authenticated)
+ end
+ end
+
+ context "when no configuration is present" do
+ let(:node) { { "id" => "webhook-1", "type" => "trigger:webhook" } }
+
+ it "returns :authenticated" do
+ expect(result).to eq(:authenticated)
+ end
+ end
+
+ context "when authentication mode is unsupported" do
+ let(:auth_mode) { "unsupported_mode" }
+
+ it "logs a warning and returns :misconfigured" do
+ Rails.logger.expects(:warn).with(regexp_matches(/Unsupported webhook auth mode/))
+ expect(result).to eq(:misconfigured)
+ end
+ end
+
+ context "when authentication is basic_auth" do
+ let(:auth_mode) { "basic_auth" }
+
+ context "when credential is not found" do
+ let(:credentials) { {} }
+
+ it "logs a warning and returns :misconfigured" do
+ Rails.logger.expects(:warn).with(regexp_matches(/credential not found/i))
+ expect(result).to eq(:misconfigured)
+ end
+ end
+
+ context "when no authorization header is present" do
+ it "returns :challenge" do
+ expect(result).to eq(:challenge)
+ end
+ end
+
+ context "when authorization header does not start with Basic" do
+ let(:raw_authorization) { "Bearer some-token" }
+
+ it "returns :challenge" do
+ expect(result).to eq(:challenge)
+ end
+ end
+
+ context "when credentials are wrong" do
+ let(:raw_authorization) { "Basic #{Base64.strict_encode64("wrong:creds")}" }
+
+ it "returns :denied" do
+ expect(result).to eq(:denied)
+ end
+ end
+
+ context "when credentials are correct" do
+ let(:raw_authorization) { "Basic #{Base64.strict_encode64("admin:secret")}" }
+
+ it "returns :authenticated" do
+ expect(result).to eq(:authenticated)
+ end
+ end
+
+ context "when credential data is missing required fields" do
+ before { basic_credential.update_column(:data, { "user" => "admin" }) }
+
+ it "returns :misconfigured" do
+ expect(result).to eq(:misconfigured)
+ end
+ end
+ end
+
+ context "when authentication is bearer_auth" do
+ let(:auth_mode) { "bearer_auth" }
+ let(:credential_id) { bearer_credential.id.to_s }
+ let(:credential_type) { "bearer_token" }
+
+ context "when authorization header is missing" do
+ it "returns :denied" do
+ expect(result).to eq(:denied)
+ end
+ end
+
+ context "when token is wrong" do
+ let(:raw_authorization) { "Bearer wrong-token" }
+
+ it "returns :denied" do
+ expect(result).to eq(:denied)
+ end
+ end
+
+ context "when token is correct" do
+ let(:raw_authorization) { "Bearer secret-token" }
+
+ it "returns :authenticated" do
+ expect(result).to eq(:authenticated)
+ end
+ end
+
+ context "when credential is missing the token field" do
+ before { bearer_credential.update_column(:data, {}) }
+
+ it "returns :misconfigured" do
+ expect(result).to eq(:misconfigured)
+ end
+ end
+ end
+
+ context "when authentication is header_auth" do
+ let(:auth_mode) { "header_auth" }
+ let(:credential_id) { header_credential.id.to_s }
+ let(:credential_type) { "header_auth" }
+
+ context "when header is missing" do
+ it "returns :denied" do
+ expect(result).to eq(:denied)
+ end
+ end
+
+ context "when header value is wrong" do
+ let(:headers) { { "x-api-key" => "wrong" } }
+
+ it "returns :denied" do
+ expect(result).to eq(:denied)
+ end
+ end
+
+ context "when header value matches" do
+ let(:headers) { { "x-api-key" => "secret-value" } }
+
+ it "returns :authenticated" do
+ expect(result).to eq(:authenticated)
+ end
+ end
+
+ context "when credential is missing name or value" do
+ before { header_credential.update_column(:data, { "name" => "X-Api-Key" }) }
+
+ it "returns :misconfigured" do
+ expect(result).to eq(:misconfigured)
+ end
+ end
+ end
+ end
+end
diff --git a/plugins/discourse-workflows/spec/services/discourse_workflows/webhook/receive_spec.rb b/plugins/discourse-workflows/spec/services/discourse_workflows/webhook/receive_spec.rb
new file mode 100644
index 00000000000..e26190cba2f
--- /dev/null
+++ b/plugins/discourse-workflows/spec/services/discourse_workflows/webhook/receive_spec.rb
@@ -0,0 +1,568 @@
+# frozen_string_literal: true
+
+RSpec.describe DiscourseWorkflows::Webhook::Receive do
+ describe described_class::Contract, type: :model do
+ it { is_expected.to validate_presence_of(:http_method) }
+ end
+
+ describe ".call" do
+ subject(:result) { described_class.call(params:) }
+
+ fab!(:admin)
+ fab!(:workflow) do
+ graph =
+ build_workflow_graph do |g|
+ g.node "webhook-1",
+ "trigger:webhook",
+ configuration: {
+ "path" => "my-hook",
+ "http_method" => "POST",
+ }
+ end
+ Fabricate(:discourse_workflows_workflow, created_by: admin, published: true, **graph)
+ end
+
+ let(:params) do
+ {
+ path: "my-hook",
+ http_method: "POST",
+ body: {
+ "foo" => "bar",
+ },
+ headers: {
+ "content-type" => "application/json",
+ },
+ query_params: {
+ "source" => "test",
+ },
+ }
+ end
+
+ context "when contract is invalid" do
+ let(:params) { { http_method: nil } }
+
+ it { is_expected.to fail_a_contract }
+ end
+
+ context "when resuming a waiting execution" do
+ let(:resume_token) { "my-hook" }
+ let(:webhook_suffix) { "" }
+ let(:response_mode) { "on_received" }
+ let(:response_code) { "200" }
+ let(:wait_http_method) { "POST" }
+
+ let(:waiting_workflow) do
+ graph =
+ build_workflow_graph do |g|
+ g.node "trigger-1", "trigger:manual"
+ g.node "wait-1",
+ "flow:wait",
+ configuration: {
+ "resume" => "webhook",
+ "http_method" => wait_http_method,
+ "response_mode" => response_mode,
+ "response_code" => response_code,
+ "webhook_suffix" => webhook_suffix,
+ }
+ g.chain "trigger-1", "wait-1"
+ end
+ Fabricate(:discourse_workflows_workflow, created_by: admin, published: true, **graph)
+ end
+
+ let(:waiting_execution) do
+ execution = DiscourseWorkflows::Executor.new(waiting_workflow, "trigger-1", {}).run
+ execution.update!(resume_token: resume_token)
+ execution
+ end
+
+ let(:signature) do
+ DiscourseWorkflows::WaitingExecution.resume_signature(
+ execution_id: waiting_execution.id,
+ resume_token: resume_token,
+ )
+ end
+
+ let(:params) do
+ {
+ execution_id: waiting_execution.id,
+ token: signature,
+ webhook_suffix: webhook_suffix,
+ http_method: "POST",
+ body: {
+ "foo" => "bar",
+ },
+ headers: {
+ "content-type" => "application/json",
+ },
+ query_params: {
+ "source" => "test",
+ },
+ }
+ end
+
+ context "when HTTP method does not match waiting execution" do
+ let(:params) { super().merge(http_method: "GET") }
+
+ it { is_expected.to fail_a_policy(:valid_http_method) }
+ end
+
+ context "when response mode is on_received" do
+ it { is_expected.to run_successfully }
+
+ it "enqueues a ResumeWebhookWaiting job" do
+ result
+ job = Jobs::DiscourseWorkflows::ResumeWebhookWaiting.jobs.last
+ expect(job["args"].first).to include("execution_id" => waiting_execution.id)
+ expect(job["args"].first["response_items"].first["json"]).to include(
+ "body" => {
+ "foo" => "bar",
+ },
+ "method" => "POST",
+ "webhook_url" =>
+ DiscourseWorkflows::WaitingExecution.webhook_url(
+ execution_id: waiting_execution.id,
+ resume_token: resume_token,
+ ),
+ )
+ end
+ end
+
+ context "when waiting execution expects a webhook suffix" do
+ let(:webhook_suffix) { "after-approval" }
+
+ it { is_expected.to run_successfully }
+ end
+
+ context "when webhook suffix does not match" do
+ let(:webhook_suffix) { "after-approval" }
+ let(:params) { super().merge(webhook_suffix: "wrong-suffix") }
+
+ it { is_expected.to fail_a_policy(:valid_resume_request) }
+ end
+
+ context "when token does not match" do
+ let(:params) { super().merge(token: "wrong-token") }
+
+ it { is_expected.to fail_a_policy(:valid_resume_request) }
+ end
+
+ context "when response mode is synchronous" do
+ let(:response_mode) { "last_node" }
+ let(:response_code) { "200" }
+
+ fab!(:resumed_execution) { Fabricate(:discourse_workflows_execution, workflow: workflow) }
+
+ before { DiscourseWorkflows::Executor.stubs(:resume).returns(resumed_execution) }
+
+ it { is_expected.to run_successfully }
+
+ it "sets sync_result on the context" do
+ expect(result[:sync_result][:execution]).to eq(resumed_execution)
+ expect(result[:sync_result][:response_mode]).to eq("last_node")
+ expect(result[:sync_result][:response_code]).to eq("200")
+ end
+
+ context "when the execution has already been claimed for resume" do
+ before do
+ allow(DiscourseWorkflows::Execution).to receive(:claim_for_resume).and_return(nil)
+ end
+
+ it { is_expected.to fail_to_find_a_model(:claimed_execution) }
+ end
+ end
+ end
+
+ context "when triggering new workflows" do
+ before { publish_workflow!(workflow) }
+
+ context "when path does not match any webhook node" do
+ let(:params) { super().merge(path: "unknown") }
+
+ it { is_expected.to fail_to_find_a_model(:webhook_nodes) }
+ end
+
+ context "when HTTP method does not match" do
+ let(:params) { super().merge(http_method: "GET") }
+
+ it { is_expected.to fail_to_find_a_model(:webhook_nodes) }
+ end
+
+ context "when workflow is unpublished" do
+ before { unpublish_workflow!(workflow) }
+
+ it { is_expected.to fail_to_find_a_model(:webhook_nodes) }
+ end
+
+ context "when everything is valid" do
+ it { is_expected.to run_successfully }
+
+ it "enqueues an ExecuteWorkflow job" do
+ result
+ job = Jobs::DiscourseWorkflows::ExecuteWorkflow.jobs.last
+ expect(job["args"].first).to include(
+ "trigger_node_id" => "webhook-1",
+ "workflow_id" => workflow.id,
+ "trigger_data" => {
+ "body" => {
+ "foo" => "bar",
+ },
+ "headers" => {
+ "content-type" => "application/json",
+ },
+ "params" => {
+ },
+ "query" => {
+ "source" => "test",
+ },
+ "method" => "POST",
+ "webhook_url" => "#{Discourse.base_url}/workflows/webhooks/my-hook",
+ },
+ )
+ end
+ end
+
+ context "with an IP allowlist" do
+ before do
+ update_workflow_node(workflow, "webhook-1") do |node|
+ node.merge(
+ "parameters" => node["parameters"].merge("ip_allowlist" => "not-an-ip, 127.0.0.1"),
+ )
+ end
+ publish_workflow!(workflow)
+ end
+
+ let(:params) { super().merge(remote_ip: "127.0.0.1") }
+
+ it "ignores invalid entries when another entry matches" do
+ result
+ job = Jobs::DiscourseWorkflows::ExecuteWorkflow.jobs.last
+ expect(job["args"].first["trigger_node_id"]).to eq("webhook-1")
+ end
+ end
+
+ context "with basic auth" do
+ fab!(:credential) do
+ Fabricate(
+ :discourse_workflows_credential,
+ credential_type: "basic_auth",
+ data: {
+ "user" => "webhook_user",
+ "password" => "webhook_pass",
+ },
+ )
+ end
+
+ before do
+ update_workflow_node(workflow, "webhook-1") do |node|
+ node.merge(
+ DiscourseWorkflows::NodeData.split(
+ parameters: {
+ "path" => "my-hook",
+ "http_method" => "POST",
+ "authentication" => "basic_auth",
+ },
+ credentials: {
+ "auth" => {
+ "id" => credential.id,
+ "credential_type" => "basic_auth",
+ },
+ },
+ node_type: node["type"],
+ ),
+ )
+ end
+ publish_workflow!(workflow)
+ end
+
+ context "when request has valid basic auth" do
+ let(:params) do
+ auth = "Basic #{Base64.strict_encode64("webhook_user:webhook_pass")}"
+ super().merge(headers: { "authorization" => auth }, raw_authorization: auth)
+ end
+
+ it { is_expected.to run_successfully }
+
+ it "executes the workflow" do
+ result
+ job = Jobs::DiscourseWorkflows::ExecuteWorkflow.jobs.last
+ expect(job["args"].first["trigger_node_id"]).to eq("webhook-1")
+ end
+ end
+
+ context "when request has wrong credentials" do
+ let(:params) do
+ auth = "Basic #{Base64.strict_encode64("wrong:creds")}"
+ super().merge(headers: { "authorization" => auth }, raw_authorization: auth)
+ end
+
+ it { is_expected.to fail_to_find_a_model(:authenticated_nodes) }
+
+ it "exposes :denied as the auth failure reason" do
+ expect(result[:auth_failure_reason]).to eq(:denied)
+ expect(result[:auth_failure_mode]).to eq("basic_auth")
+ end
+ end
+
+ context "when request has no authorization header" do
+ it { is_expected.to fail_to_find_a_model(:authenticated_nodes) }
+
+ it "exposes :challenge as the auth failure reason" do
+ expect(result[:auth_failure_reason]).to eq(:challenge)
+ expect(result[:auth_failure_mode]).to eq("basic_auth")
+ end
+ end
+
+ context "when credential record is missing" do
+ before { credential.destroy! }
+
+ it { is_expected.to fail_to_find_a_model(:authenticated_nodes) }
+
+ it "exposes :misconfigured as the auth failure reason" do
+ expect(result[:auth_failure_reason]).to eq(:misconfigured)
+ end
+ end
+
+ context "when auth mode is unsupported" do
+ before do
+ update_workflow_node(workflow, "webhook-1") do |node|
+ node.merge(
+ "parameters" => node["parameters"].merge("authentication" => "unknown_mode"),
+ )
+ end
+ publish_workflow!(workflow)
+ end
+
+ it { is_expected.to fail_to_find_a_model(:authenticated_nodes) }
+
+ it "exposes :misconfigured as the auth failure reason" do
+ expect(result[:auth_failure_reason]).to eq(:misconfigured)
+ end
+ end
+ end
+
+ context "with bearer auth" do
+ fab!(:credential) do
+ Fabricate(
+ :discourse_workflows_credential,
+ credential_type: "bearer_token",
+ data: {
+ "token" => "secret-token",
+ },
+ )
+ end
+
+ before do
+ update_workflow_node(workflow, "webhook-1") do |node|
+ node.merge(
+ DiscourseWorkflows::NodeData.split(
+ parameters: {
+ "path" => "my-hook",
+ "http_method" => "POST",
+ "authentication" => "bearer_auth",
+ },
+ credentials: {
+ "auth" => {
+ "id" => credential.id,
+ "credential_type" => "bearer_token",
+ },
+ },
+ node_type: node["type"],
+ ),
+ )
+ end
+ publish_workflow!(workflow)
+ end
+
+ context "when request has valid bearer token" do
+ let(:params) do
+ auth = "Bearer secret-token"
+ super().merge(headers: { "authorization" => auth }, raw_authorization: auth)
+ end
+
+ it { is_expected.to run_successfully }
+ end
+
+ context "when bearer token is missing" do
+ it "exposes :denied as the auth failure reason" do
+ expect(result[:auth_failure_reason]).to eq(:denied)
+ end
+ end
+ end
+
+ context "with header auth" do
+ fab!(:credential) do
+ Fabricate(
+ :discourse_workflows_credential,
+ credential_type: "header_auth",
+ data: {
+ "name" => "X-Api-Key",
+ "value" => "secret-value",
+ },
+ )
+ end
+
+ before do
+ update_workflow_node(workflow, "webhook-1") do |node|
+ node.merge(
+ DiscourseWorkflows::NodeData.split(
+ parameters: {
+ "path" => "my-hook",
+ "http_method" => "POST",
+ "authentication" => "header_auth",
+ },
+ credentials: {
+ "auth" => {
+ "id" => credential.id,
+ "credential_type" => "header_auth",
+ },
+ },
+ node_type: node["type"],
+ ),
+ )
+ end
+ publish_workflow!(workflow)
+ end
+
+ context "when request has matching header" do
+ let(:params) { super().merge(headers: { "x-api-key" => "secret-value" }) }
+
+ it { is_expected.to run_successfully }
+ end
+
+ context "when header is missing" do
+ it "exposes :denied as the auth failure reason" do
+ expect(result[:auth_failure_reason]).to eq(:denied)
+ end
+ end
+ end
+
+ context "when another workflow tries to claim the same path" do
+ fab!(:conflicting_workflow) do
+ graph =
+ build_workflow_graph do |g|
+ g.node "other-webhook-1",
+ "trigger:webhook",
+ configuration: {
+ "path" => "my-hook",
+ "http_method" => "POST",
+ "authentication" => "none",
+ }
+ end
+ Fabricate(:discourse_workflows_workflow, created_by: admin, published: false, **graph)
+ end
+
+ it "rejects activation of the second workflow with CollisionError" do
+ publish_workflow!(workflow)
+
+ expect { publish_workflow!(conflicting_workflow) }.to raise_error(
+ DiscourseWorkflows::Webhook::Action::ActivateWebhooks::CollisionError,
+ )
+ end
+ end
+
+ context "with synchronous response mode" do
+ before do
+ update_workflow_node(workflow, "webhook-1") do |node|
+ node.merge(
+ "parameters" =>
+ node["parameters"].merge("response_mode" => "last_node", "response_code" => "201"),
+ )
+ end
+ publish_workflow!(workflow)
+ end
+
+ it { is_expected.to run_successfully }
+
+ it "does not enqueue an async job" do
+ result
+ expect(Jobs::DiscourseWorkflows::ExecuteWorkflow.jobs).to be_empty
+ end
+
+ it "sets sync_result on the context" do
+ expect(result[:sync_result][:execution]).to be_a(DiscourseWorkflows::Execution)
+ expect(result[:sync_result][:response_mode]).to eq("last_node")
+ expect(result[:sync_result][:response_code]).to eq("201")
+ end
+ end
+ end
+
+ context "when triggering a test webhook" do
+ let(:test_listener_id) { nil }
+ let(:params) { super().merge(test_webhook: true, test_listener_id: test_listener_id) }
+
+ before { unpublish_workflow!(workflow) }
+
+ context "when no listener is active" do
+ it { is_expected.to fail_to_find_a_model(:webhook_test_listener) }
+ end
+
+ context "when everything is valid" do
+ let(:listener) do
+ DiscourseWorkflows::WebhookTestListener.create!(
+ workflow: workflow,
+ user: admin,
+ trigger_node: workflow.find_node("webhook-1"),
+ )
+ end
+ let(:test_listener_id) { listener.listener_id }
+
+ it { is_expected.to run_successfully }
+
+ it "runs the draft workflow synchronously" do
+ expect { result }.to change { DiscourseWorkflows::Execution.count }.by(1)
+
+ execution = DiscourseWorkflows::Execution.last
+ expect(execution).to have_attributes(
+ workflow_id: workflow.id,
+ trigger_node_id: "webhook-1",
+ execution_mode: "manual",
+ status: "success",
+ )
+ expect(execution.trigger_data["webhook_url"]).to eq(
+ "#{Discourse.base_url}/workflows/webhook-test/#{listener.listener_id}/my-hook",
+ )
+ end
+
+ it "does not enqueue an async job" do
+ result
+
+ expect(Jobs::DiscourseWorkflows::ExecuteWorkflow.jobs).to be_empty
+ end
+ end
+
+ context "when request filtering rejects the request" do
+ let(:listener) do
+ DiscourseWorkflows::WebhookTestListener.create!(
+ workflow: workflow,
+ user: admin,
+ trigger_node: workflow.find_node("webhook-1"),
+ )
+ end
+ let(:test_listener_id) { listener.listener_id }
+
+ before do
+ workflow.update!(
+ nodes:
+ workflow.nodes.map do |node|
+ next node unless node["id"] == "webhook-1"
+
+ node.merge("parameters" => node["parameters"].merge("ip_allowlist" => "127.0.0.1"))
+ end,
+ )
+ end
+
+ let(:params) { super().merge(remote_ip: "192.0.2.10") }
+
+ it { is_expected.to fail_to_find_a_model(:request_allowed_nodes) }
+
+ it "does not consume the listener" do
+ result
+
+ expect(
+ DiscourseWorkflows::WebhookTestListener.find_by_route(method: "POST", path: "my-hook"),
+ ).to be_present
+ end
+ end
+ end
+ end
+end
diff --git a/plugins/discourse-workflows/spec/services/discourse_workflows/webhook_test_listener/cancel_spec.rb b/plugins/discourse-workflows/spec/services/discourse_workflows/webhook_test_listener/cancel_spec.rb
new file mode 100644
index 00000000000..e20822ea1db
--- /dev/null
+++ b/plugins/discourse-workflows/spec/services/discourse_workflows/webhook_test_listener/cancel_spec.rb
@@ -0,0 +1,83 @@
+# frozen_string_literal: true
+
+RSpec.describe DiscourseWorkflows::WebhookTestListener::Cancel do
+ describe described_class::Contract, type: :model do
+ it { is_expected.to validate_presence_of(:workflow_id) }
+ it { is_expected.to validate_presence_of(:listener_id) }
+ end
+
+ describe ".call" do
+ subject(:result) { described_class.call(params:, **dependencies) }
+
+ fab!(:admin)
+ fab!(:other_admin, :admin)
+ fab!(:workflow) do
+ graph = build_workflow_graph { |g| g.node "webhook-1", "trigger:webhook" }
+ Fabricate(:discourse_workflows_workflow, created_by: admin, published: false, **graph)
+ end
+
+ let(:trigger_node) { workflow.find_node("webhook-1") }
+ let(:listener) do
+ DiscourseWorkflows::WebhookTestListener.create!(
+ workflow: workflow,
+ user: admin,
+ trigger_node: trigger_node,
+ )
+ end
+ let(:params) { { workflow_id: workflow.id, listener_id: listener.listener_id } }
+ let(:dependencies) { { guardian: admin.guardian } }
+
+ context "when contract is invalid" do
+ let(:params) { { workflow_id: workflow.id, listener_id: nil } }
+
+ it { is_expected.to fail_a_contract }
+ end
+
+ context "when user cannot manage workflows" do
+ fab!(:user)
+
+ let(:dependencies) { { guardian: user.guardian } }
+
+ it { is_expected.to fail_a_policy(:can_manage_workflows) }
+ end
+
+ context "when workflow does not exist" do
+ let(:params) { { workflow_id: -1, listener_id: listener.listener_id } }
+
+ it { is_expected.to fail_to_find_a_model(:workflow) }
+ end
+
+ context "when listener does not exist" do
+ let(:params) { { workflow_id: workflow.id, listener_id: SecureRandom.uuid } }
+
+ it { is_expected.to fail_to_find_a_model(:listener) }
+ end
+
+ context "when listener belongs to another workflow" do
+ fab!(:other_workflow) do
+ graph = build_workflow_graph { |g| g.node "webhook-2", "trigger:webhook" }
+ Fabricate(:discourse_workflows_workflow, created_by: admin, published: false, **graph)
+ end
+
+ let(:params) { { workflow_id: other_workflow.id, listener_id: listener.listener_id } }
+
+ it { is_expected.to fail_a_policy(:listener_belongs_to_workflow) }
+ end
+
+ context "when listener belongs to another admin" do
+ let(:dependencies) { { guardian: other_admin.guardian } }
+
+ it { is_expected.to fail_a_policy(:owns_webhook_test_listener) }
+ end
+
+ context "when everything is valid" do
+ it { is_expected.to run_successfully }
+
+ it "cancels the listener" do
+ result
+
+ expect(DiscourseWorkflows::WebhookTestListener.find(listener.listener_id)).to be_nil
+ end
+ end
+ end
+end
diff --git a/plugins/discourse-workflows/spec/services/discourse_workflows/webhook_test_listener/start_spec.rb b/plugins/discourse-workflows/spec/services/discourse_workflows/webhook_test_listener/start_spec.rb
new file mode 100644
index 00000000000..f1c2a78824a
--- /dev/null
+++ b/plugins/discourse-workflows/spec/services/discourse_workflows/webhook_test_listener/start_spec.rb
@@ -0,0 +1,86 @@
+# frozen_string_literal: true
+
+RSpec.describe DiscourseWorkflows::WebhookTestListener::Start do
+ describe described_class::Contract, type: :model do
+ it { is_expected.to validate_presence_of(:workflow_id) }
+ it { is_expected.to validate_presence_of(:trigger_node_id) }
+ end
+
+ describe ".call" do
+ subject(:result) { described_class.call(params:, **dependencies) }
+
+ fab!(:admin)
+ fab!(:workflow) do
+ graph = build_workflow_graph { |g| g.node "webhook-1", "trigger:webhook" }
+ Fabricate(:discourse_workflows_workflow, created_by: admin, published: false, **graph)
+ end
+
+ let(:params) { { workflow_id: workflow.id, trigger_node_id: "webhook-1" } }
+ let(:dependencies) { { guardian: admin.guardian } }
+
+ context "when contract is invalid" do
+ let(:params) { { workflow_id: workflow.id, trigger_node_id: nil } }
+
+ it { is_expected.to fail_a_contract }
+ end
+
+ context "when user cannot manage workflows" do
+ fab!(:user)
+
+ let(:dependencies) { { guardian: user.guardian } }
+
+ it { is_expected.to fail_a_policy(:can_manage_workflows) }
+ end
+
+ context "when workflow does not exist" do
+ let(:params) { { workflow_id: -1, trigger_node_id: "webhook-1" } }
+
+ it { is_expected.to fail_to_find_a_model(:workflow) }
+ end
+
+ context "when trigger node does not exist" do
+ let(:params) { { workflow_id: workflow.id, trigger_node_id: "missing" } }
+
+ it { is_expected.to fail_to_find_a_model(:trigger_node) }
+ end
+
+ context "when the node is not a webhook trigger" do
+ fab!(:workflow) do
+ graph = build_workflow_graph { |g| g.node "trigger-1", "trigger:manual" }
+ Fabricate(:discourse_workflows_workflow, created_by: admin, published: false, **graph)
+ end
+
+ let(:params) { { workflow_id: workflow.id, trigger_node_id: "trigger-1" } }
+
+ it { is_expected.to fail_a_policy(:webhook_trigger_node) }
+ end
+
+ context "when everything is valid" do
+ it { is_expected.to run_successfully }
+
+ it "stores a retrievable test listener" do
+ listener = DiscourseWorkflows::WebhookTestListener.find(result[:listener].listener_id)
+
+ expect(listener).to have_attributes(
+ workflow_id: workflow.id,
+ user_id: admin.id,
+ trigger_node_id: "webhook-1",
+ )
+ end
+ end
+
+ context "when another admin is already listening on the same URL" do
+ fab!(:other_admin, :admin)
+
+ before do
+ DiscourseWorkflows::WebhookTestListener.create!(
+ workflow: workflow,
+ user: other_admin,
+ trigger_node: workflow.find_node("webhook-1"),
+ )
+ end
+
+ it { is_expected.to fail_to_find_a_model(:listener) }
+ end
+ end
+end
diff --git a/plugins/discourse-workflows/spec/services/discourse_workflows/workflow/action/build_expression_preview_context_spec.rb b/plugins/discourse-workflows/spec/services/discourse_workflows/workflow/action/build_expression_preview_context_spec.rb
new file mode 100644
index 00000000000..ab9faae5b87
--- /dev/null
+++ b/plugins/discourse-workflows/spec/services/discourse_workflows/workflow/action/build_expression_preview_context_spec.rb
@@ -0,0 +1,321 @@
+# frozen_string_literal: true
+
+RSpec.describe DiscourseWorkflows::Workflow::Action::BuildExpressionPreviewContext do
+ subject(:context) { described_class.call(workflow: workflow, node_id: node_id) }
+
+ fab!(:admin)
+
+ let(:node_id) { nil }
+
+ def run_data_for(
+ node_id,
+ node_name:,
+ node_type:,
+ items:,
+ inputs: nil,
+ outputs: nil,
+ status: "success"
+ )
+ {
+ node_name => [
+ {
+ "node_id" => node_id.to_s,
+ "node_name" => node_name,
+ "node_type" => node_type,
+ "status" => status,
+ "run_index" => 0,
+ "inputs" => inputs || [],
+ "outputs" =>
+ outputs || [{ "index" => 0, "items" => items, "item_count" => items.length }],
+ },
+ ],
+ }
+ end
+
+ describe ".call" do
+ context "without a workflow" do
+ let(:workflow) { nil }
+
+ it "returns the default context" do
+ expect(context).to eq({ "$json" => {}, "$trigger" => {} })
+ end
+ end
+
+ context "with a workflow" do
+ fab!(:workflow) do
+ graph =
+ build_workflow_graph do |g|
+ g.node "trigger-1", "trigger:topic_created", name: "Topic created"
+ g.node "action-1", "action:topic_tags", name: "Tag topic"
+ g.chain "trigger-1", "action-1"
+ end
+ Fabricate(:discourse_workflows_workflow, created_by: admin, **graph)
+ end
+
+ it "includes initial execution metadata and node lookup data" do
+ expect(context["__execution"]).to include(
+ "id" => 0,
+ "workflow_id" => workflow.id,
+ "workflow_name" => workflow.name,
+ )
+ expect(context["__node_parameters_by_name"]).to include("Tag topic" => {})
+ end
+
+ it "does not create output exemplars without execution data" do
+ expect(context["$json"]).to eq({})
+ expect(context["$trigger"]).to eq({})
+ expect(context).not_to have_key("Topic created")
+ end
+
+ context "when node_id is provided" do
+ let(:node_id) { "action-1" }
+
+ it "sets the current node id for expression resolution" do
+ expect(context["__current_node_id"]).to eq("action-1")
+ end
+ end
+
+ context "with a last successful execution" do
+ fab!(:execution) do
+ Fabricate(:discourse_workflows_execution, workflow: workflow, status: :success)
+ end
+
+ context "without execution_data" do
+ it "sets the execution id on metadata" do
+ expect(context["__execution"]["id"]).to eq(execution.id)
+ end
+ end
+
+ context "with a successful trigger run" do
+ let(:items) { [{ "json" => { "title" => "From past run" } }] }
+
+ before do
+ Fabricate(
+ :discourse_workflows_execution_data,
+ execution: execution,
+ data: {
+ "entries" => {
+ },
+ "context" => {
+ },
+ "node_contexts" => {
+ },
+ "run_data" =>
+ run_data_for(
+ "trigger-1",
+ node_name: "Topic created",
+ node_type: "trigger:topic_created",
+ items: items,
+ ),
+ },
+ )
+ end
+
+ it "overlays the trigger json into trigger and $json" do
+ expect(context["$trigger"]).to eq({ "title" => "From past run" })
+ expect(context["$json"]).to eq({ "title" => "From past run" })
+ end
+
+ it "overlays the run items under the node name" do
+ expect(context["Topic created"]).to eq(items)
+ end
+
+ it "exposes node runs in the expression resolver shape" do
+ expect(context.dig("__node_runs", "Topic created", 0, "outputs", 0)).to eq(items)
+ end
+
+ context "when node_id matches the trigger's downstream" do
+ let(:node_id) { "action-1" }
+
+ it "uses the upstream execution output for $json" do
+ expect(context["$json"]).to eq({ "title" => "From past run" })
+ expect(context["__input_items"]).to eq(items)
+ end
+ end
+
+ context "when the current node has recorded input data" do
+ let(:node_id) { "action-1" }
+ let(:current_items) { [{ "json" => { "title" => "From current input" } }] }
+
+ before do
+ execution.execution_data.update!(
+ data: {
+ "entries" => {
+ },
+ "context" => {
+ },
+ "node_contexts" => {
+ },
+ "run_data" =>
+ run_data_for(
+ "trigger-1",
+ node_name: "Topic created",
+ node_type: "trigger:topic_created",
+ items: items,
+ ).deep_merge(
+ run_data_for(
+ "action-1",
+ node_name: "Tag topic",
+ node_type: "action:topic_tags",
+ items: [],
+ inputs: [
+ {
+ "index" => 0,
+ "items" => current_items,
+ "item_count" => current_items.length,
+ "source" => {
+ "node_name" => "Topic created",
+ "output_index" => 0,
+ },
+ },
+ ],
+ ),
+ ),
+ },
+ )
+ end
+
+ it "uses the current node input for $json" do
+ expect(context["$json"]).to eq({ "title" => "From current input" })
+ expect(context["__input_item"]).to eq(current_items.first)
+ expect(context["__input_items"]).to eq(current_items)
+ expect(context["__input_sources"]).to eq(
+ [{ "node_name" => "Topic created", "output_index" => 0 }],
+ )
+ end
+ end
+ end
+
+ context "when the current node is connected to a non-primary upstream output" do
+ subject(:context) do
+ described_class.call(workflow: branched_workflow, node_id: "action-1")
+ end
+
+ let(:primary_items) { [{ "json" => { "matched" => true } }] }
+ let(:rejected_items) { [{ "json" => { "matched" => false } }] }
+
+ fab!(:branched_workflow) do
+ graph =
+ build_workflow_graph do |g|
+ g.node "filter-1", "condition:filter", name: "Filter"
+ g.node "action-1", "action:log", name: "Log"
+ g.connect "filter-1", "action-1", output: "false"
+ end
+ Fabricate(:discourse_workflows_workflow, created_by: admin, **graph)
+ end
+
+ before do
+ Fabricate(
+ :discourse_workflows_execution_data,
+ execution:
+ Fabricate(
+ :discourse_workflows_execution,
+ workflow: branched_workflow,
+ status: :success,
+ ),
+ data: {
+ "entries" => {
+ },
+ "context" => {
+ },
+ "node_contexts" => {
+ },
+ "run_data" =>
+ run_data_for(
+ "filter-1",
+ node_name: "Filter",
+ node_type: "condition:filter",
+ items: primary_items,
+ outputs: [
+ {
+ "index" => 0,
+ "items" => primary_items,
+ "item_count" => primary_items.length,
+ },
+ {
+ "index" => 1,
+ "items" => rejected_items,
+ "item_count" => rejected_items.length,
+ },
+ ],
+ ),
+ },
+ )
+ end
+
+ it "uses the connected output for current-node input context" do
+ expect(context["$json"]).to eq({ "matched" => false })
+ expect(context["__input_item"]).to eq(rejected_items.first)
+ expect(context["__input_items"]).to eq(rejected_items)
+ expect(context["__input_sources"]).to eq(
+ [{ "node_name" => "Filter", "output_index" => 1 }],
+ )
+ expect(context.dig("__node_runs", "Filter", 0, "outputs", 1)).to eq(rejected_items)
+ end
+ end
+
+ context "with a successful non-trigger run" do
+ before do
+ Fabricate(
+ :discourse_workflows_execution_data,
+ execution: execution,
+ data: {
+ "entries" => {
+ },
+ "context" => {
+ },
+ "node_contexts" => {
+ },
+ "run_data" =>
+ run_data_for(
+ "action-1",
+ node_name: "Tag topic",
+ node_type: "action:topic_tags",
+ items: [{ "json" => { "tagged" => true } }],
+ ),
+ },
+ )
+ end
+
+ it "overlays the run items under the node name" do
+ expect(context["Tag topic"]).to eq([{ "json" => { "tagged" => true } }])
+ end
+
+ it "does not overwrite $json when there is no node_id" do
+ expect(context["$json"]).to eq({})
+ end
+ end
+
+ context "with no successful run" do
+ before do
+ Fabricate(
+ :discourse_workflows_execution_data,
+ execution: execution,
+ data: {
+ "entries" => {
+ },
+ "context" => {
+ },
+ "node_contexts" => {
+ },
+ "run_data" =>
+ run_data_for(
+ "trigger-1",
+ node_name: "Topic created",
+ node_type: "trigger:topic_created",
+ items: [{ "json" => { "title" => "Should not appear" } }],
+ status: "error",
+ ),
+ },
+ )
+ end
+
+ it "does not overlay failed run data" do
+ expect(context["Topic created"]).to be_nil
+ expect(context["$json"]).to eq({})
+ end
+ end
+ end
+ end
+ end
+end
diff --git a/plugins/discourse-workflows/spec/services/discourse_workflows/workflow/action/expire_caches_spec.rb b/plugins/discourse-workflows/spec/services/discourse_workflows/workflow/action/expire_caches_spec.rb
new file mode 100644
index 00000000000..d2ad975ba83
--- /dev/null
+++ b/plugins/discourse-workflows/spec/services/discourse_workflows/workflow/action/expire_caches_spec.rb
@@ -0,0 +1,20 @@
+# frozen_string_literal: true
+
+RSpec.describe DiscourseWorkflows::Workflow::Action::ExpireCaches do
+ describe ".call" do
+ subject(:result) { described_class.call }
+
+ it "clears workflow dependency caches" do
+ DiscourseWorkflows::WorkflowDependency.expects(:clear_cache!).once
+
+ result
+ end
+
+ it "does not clear the site cache" do
+ Site.expects(:clear_cache).never
+ DiscourseWorkflows::WorkflowDependency.stubs(:clear_cache!)
+
+ result
+ end
+ end
+end
diff --git a/plugins/discourse-workflows/spec/services/discourse_workflows/workflow/action/find_published_triggers_spec.rb b/plugins/discourse-workflows/spec/services/discourse_workflows/workflow/action/find_published_triggers_spec.rb
new file mode 100644
index 00000000000..5b0fd6ebb68
--- /dev/null
+++ b/plugins/discourse-workflows/spec/services/discourse_workflows/workflow/action/find_published_triggers_spec.rb
@@ -0,0 +1,49 @@
+# frozen_string_literal: true
+
+RSpec.describe DiscourseWorkflows::Workflow::Action::FindPublishedTriggers do
+ describe ".call" do
+ subject(:result) do
+ described_class.call(
+ trigger_type: "trigger:form",
+ filter:
+ lambda do |published_trigger|
+ published_trigger.trigger_node["webhookId"] == "published-uuid"
+ end,
+ )
+ end
+
+ fab!(:workflow) do
+ graph =
+ build_workflow_graph do |g|
+ g.node "trigger-1", "trigger:form", webhook_id: "published-uuid"
+ end
+ Fabricate(:discourse_workflows_workflow, published: true, **graph)
+ end
+
+ context "when the draft changes after publishing" do
+ before do
+ update_workflow_node(workflow, "trigger-1") { |node| node["webhookId"] = "draft-uuid" }
+ end
+
+ it "returns the published trigger node" do
+ expect(workflow.reload.nodes.first["webhookId"]).to eq("draft-uuid")
+
+ expect(result.size).to eq(1)
+ published_trigger = result.first
+ expect(published_trigger.workflow).to eq(workflow)
+ expect(published_trigger.workflow_version).to eq(workflow.active_version)
+ expect(published_trigger.trigger_node).to include(
+ "id" => "trigger-1",
+ "type" => "trigger:form",
+ "webhookId" => "published-uuid",
+ )
+ end
+ end
+
+ context "when the workflow is unpublished" do
+ before { unpublish_workflow!(workflow) }
+
+ it { is_expected.to be_empty }
+ end
+ end
+end
diff --git a/plugins/discourse-workflows/spec/services/discourse_workflows/workflow/action/populate_graph_spec.rb b/plugins/discourse-workflows/spec/services/discourse_workflows/workflow/action/populate_graph_spec.rb
new file mode 100644
index 00000000000..588169910ad
--- /dev/null
+++ b/plugins/discourse-workflows/spec/services/discourse_workflows/workflow/action/populate_graph_spec.rb
@@ -0,0 +1,647 @@
+# frozen_string_literal: true
+
+RSpec.describe DiscourseWorkflows::Workflow::Action::PopulateGraph do
+ fab!(:workflow, :discourse_workflows_workflow)
+
+ describe ".call" do
+ context "when node count exceeds the maximum" do
+ it "returns false and adds an error to the workflow" do
+ nodes_data =
+ (described_class::MAX_NODES + 1).times.map do |i|
+ { id: "node-#{i}", type: "trigger:topic_created", name: "Node #{i}" }
+ end
+
+ result =
+ described_class.call(workflow: workflow, nodes_data: nodes_data, connections_data: {})
+
+ expect(result).to eq(false)
+ expect(workflow.errors.full_messages).to include(
+ /cannot have more than #{described_class::MAX_NODES}/,
+ )
+ end
+
+ it "accepts exactly the maximum number of nodes" do
+ nodes_data =
+ described_class::MAX_NODES.times.map do |i|
+ { id: "node-#{i}", type: "trigger:topic_created", name: "Node #{i}" }
+ end
+
+ result =
+ described_class.call(workflow: workflow, nodes_data: nodes_data, connections_data: {})
+
+ expect(result).to eq(true)
+ expect(workflow.reload.nodes.size).to eq(described_class::MAX_NODES)
+ end
+ end
+
+ context "when a node type exceeds its per-workflow limit" do
+ it "returns false and adds an error to the workflow" do
+ result =
+ described_class.call(
+ workflow: workflow,
+ nodes_data: [
+ { id: "error-1", type: "trigger:error", name: "Error one" },
+ { id: "error-1", type: "trigger:error", name: "Error one" },
+ { id: "error-2", type: "trigger:error", name: "Error two" },
+ ],
+ connections_data: {
+ },
+ )
+
+ expect(result).to eq(false)
+ expect(workflow.errors.full_messages).to include(
+ I18n.t(
+ "discourse_workflows.errors.max_nodes_of_type_exceeded",
+ max: 1,
+ type: "trigger:error",
+ ),
+ )
+ end
+ end
+
+ context "when a connection targets a node without input ports" do
+ it "returns false and adds an error to the workflow" do
+ result =
+ described_class.call(
+ workflow: workflow,
+ nodes_data: [
+ { id: "manual-1", type: "trigger:manual", name: "Manual" },
+ { id: "error-1", type: "trigger:error", name: "Error trigger" },
+ ],
+ connections_data: {
+ "Manual" => {
+ "main" => [[{ "node" => "Error trigger", "type" => "main", "index" => 0 }]],
+ },
+ },
+ )
+
+ expect(result).to eq(false)
+ expect(workflow.errors.full_messages).to include(
+ I18n.t("discourse_workflows.errors.node_does_not_accept_inputs", node: "Error trigger"),
+ )
+ end
+ end
+
+ context "when nodes have invalid versions" do
+ it "returns false and adds errors to the workflow" do
+ result =
+ described_class.call(
+ workflow: workflow,
+ nodes_data: [
+ { id: "node-1", type: "trigger:topic_created", typeVersion: "99.0", name: "Bad" },
+ ],
+ connections_data: {
+ },
+ )
+
+ expect(result).to eq(false)
+ expect(workflow.errors.full_messages).to include(
+ I18n.t(
+ "discourse_workflows.errors.unsupported_node_version",
+ version: "99.0",
+ type: "trigger:topic_created",
+ ),
+ )
+ end
+ end
+
+ context "when a node type is registered by a disabled plugin" do
+ it "accepts existing unavailable nodes" do
+ plugin = Plugin::Instance.new
+ allow(plugin).to receive(:enabled?).and_return(false)
+ node_class =
+ Class.new(DiscourseWorkflows::NodeType) do
+ description(name: "action:populate_disabled_plugin_test", version: "1.0")
+ end
+
+ DiscoursePluginRegistry.register_discourse_workflows_node(node_class, plugin)
+
+ result =
+ described_class.call(
+ workflow: workflow,
+ nodes_data: [
+ {
+ id: "node-1",
+ type: "action:populate_disabled_plugin_test",
+ typeVersion: "1.0",
+ name: "Unavailable node",
+ },
+ ],
+ connections_data: {
+ },
+ )
+
+ expect(result).to eq(true)
+ expect(workflow.reload.nodes.first).to include(
+ "type" => "action:populate_disabled_plugin_test",
+ "typeVersion" => "1.0",
+ )
+ ensure
+ DiscoursePluginRegistry._raw_discourse_workflows_nodes.reject! do |entry|
+ entry[:value] == node_class
+ end
+ DiscourseWorkflows::Registry.reset_indexes!
+ end
+ end
+
+ context "when a node type has multiple versions" do
+ it "uses the latest version for new nodes without a submitted typeVersion" do
+ v1 =
+ Class.new(DiscourseWorkflows::NodeType) do
+ description(name: "action:populate_versioned_test", version: "1.0")
+ end
+ v2 =
+ Class.new(DiscourseWorkflows::NodeType) do
+ description(name: "action:populate_versioned_test", version: "2.0")
+ end
+
+ DiscoursePluginRegistry.register_discourse_workflows_node(v1, Plugin::Instance.new)
+ DiscoursePluginRegistry.register_discourse_workflows_node(v2, Plugin::Instance.new)
+ DiscourseWorkflows::Registry.reset_indexes!
+
+ result =
+ described_class.call(
+ workflow: workflow,
+ nodes_data: [
+ { id: "node-1", type: "action:populate_versioned_test", name: "Versioned" },
+ ],
+ connections_data: {
+ },
+ )
+
+ expect(result).to eq(true)
+ expect(workflow.reload.nodes.first["typeVersion"]).to eq("2.0")
+ ensure
+ DiscoursePluginRegistry._raw_discourse_workflows_nodes.reject! do |entry|
+ [v1, v2].include?(entry[:value])
+ end
+ DiscourseWorkflows::Registry.reset_indexes!
+ end
+ end
+
+ context "with nodes and connections" do
+ let(:nodes_data) do
+ [
+ { id: "node-1", type: "trigger:topic_created", name: "Topic Created" },
+ {
+ id: "node-2",
+ type: "action:topic_tags",
+ name: "Topic Tags",
+ parameters: {
+ "tag_names" => "processed",
+ },
+ },
+ { id: "node-3", type: "action:log", name: "Log" },
+ ]
+ end
+
+ let(:connections_data) do
+ {
+ "Topic Created" => {
+ "main" => [[{ "node" => "Topic Tags", "type" => "main", "index" => 0 }]],
+ },
+ "Topic Tags" => {
+ "main" => [[{ "node" => "Log", "type" => "main", "index" => 0 }]],
+ },
+ }
+ end
+
+ it "creates nodes with workflow document attributes" do
+ described_class.call(
+ workflow: workflow,
+ nodes_data: nodes_data,
+ connections_data: connections_data,
+ )
+
+ workflow.reload
+ nodes = workflow.nodes
+ expect(nodes.size).to eq(3)
+
+ expect(nodes[0]).to include(
+ "type" => "trigger:topic_created",
+ "name" => "Topic Created",
+ "parameters" => {
+ },
+ "credentials" => {
+ },
+ )
+ expect(nodes[1]).to include(
+ "type" => "action:topic_tags",
+ "name" => "Topic Tags",
+ "parameters" => {
+ "tag_names" => "processed",
+ },
+ "credentials" => {
+ },
+ )
+ expect(nodes[2]).to include(
+ "type" => "action:log",
+ "name" => "Log",
+ "parameters" => {
+ },
+ "credentials" => {
+ },
+ )
+ expect(nodes).not_to include(include("position_index"))
+ end
+
+ it "creates connections with correct attributes" do
+ described_class.call(
+ workflow: workflow,
+ nodes_data: nodes_data,
+ connections_data: connections_data,
+ )
+
+ workflow.reload
+ nodes = workflow.nodes
+ connections = workflow.connections
+ expect(connections).to eq(
+ "Topic Created" => {
+ "main" => [[{ "node" => "Topic Tags", "type" => "main", "index" => 0 }]],
+ },
+ "Topic Tags" => {
+ "main" => [[{ "node" => "Log", "type" => "main", "index" => 0 }]],
+ },
+ )
+ expect(nodes.map { |node| node["id"] }).to eq(%w[node-1 node-2 node-3])
+ end
+ end
+
+ context "with unsupported node JSON keys" do
+ let(:nodes_data) { [{ id: "node-1", type: "trigger:manual", settings: {}, name: "Manual" }] }
+
+ it "rejects the graph" do
+ result =
+ described_class.call(workflow: workflow, nodes_data: nodes_data, connections_data: {})
+
+ expect(result).to eq(false)
+ expect(workflow.errors.full_messages).to include(
+ I18n.t("discourse_workflows.errors.invalid_node_json_keys"),
+ )
+ end
+ end
+
+ context "with malformed node fields" do
+ it "rejects the graph before normalizing node data" do
+ result =
+ described_class.call(
+ workflow: workflow,
+ nodes_data: [
+ { id: "node-1", type: "trigger:manual", name: "Manual", parameters: "bad" },
+ ],
+ connections_data: {
+ },
+ )
+
+ expect(result).to eq(false)
+ expect(workflow.errors.full_messages).to include(
+ I18n.t("discourse_workflows.errors.invalid_node_fields"),
+ )
+ end
+ end
+
+ context "when an executable node is missing a name" do
+ it "rejects the graph" do
+ result =
+ described_class.call(
+ workflow: workflow,
+ nodes_data: [{ id: "node-1", type: "trigger:manual" }],
+ connections_data: {
+ },
+ )
+
+ expect(result).to eq(false)
+ expect(workflow.errors.full_messages).to include(
+ I18n.t("discourse_workflows.errors.node_names_required"),
+ )
+ end
+ end
+
+ context "when two executable nodes share the same name" do
+ it "rejects the graph" do
+ result =
+ described_class.call(
+ workflow: workflow,
+ nodes_data: [
+ { id: "node-1", type: "trigger:manual", name: "Step" },
+ { id: "node-2", type: "action:log", name: "Step" },
+ ],
+ connections_data: {
+ },
+ )
+
+ expect(result).to eq(false)
+ expect(workflow.errors.full_messages).to include(
+ I18n.t("discourse_workflows.errors.duplicate_node_names", names: "Step"),
+ )
+ end
+ end
+
+ context "when a sticky note shares its name with an executable node" do
+ it "rejects the graph" do
+ result =
+ described_class.call(
+ workflow: workflow,
+ nodes_data: [
+ { id: "node-1", type: "trigger:manual", name: "Sticky Note" },
+ { id: "note-1", type: "flow:sticky_note", name: "Sticky Note" },
+ ],
+ connections_data: {
+ },
+ )
+
+ expect(result).to eq(false)
+ expect(workflow.errors.full_messages).to include(
+ I18n.t("discourse_workflows.errors.duplicate_node_names", names: "Sticky Note"),
+ )
+ end
+ end
+
+ context "when two sticky notes share the same default name" do
+ it "accepts the graph" do
+ result =
+ described_class.call(
+ workflow: workflow,
+ nodes_data: [
+ { id: "note-1", type: "flow:sticky_note", name: "Sticky Note" },
+ { id: "note-2", type: "flow:sticky_note", name: "Sticky Note" },
+ ],
+ connections_data: {
+ },
+ )
+
+ expect(result).to eq(true)
+ expect(workflow.reload.nodes.map { |node| node["name"] }).to eq(
+ ["Sticky Note", "Sticky Note"],
+ )
+ end
+ end
+
+ context "with a sparse multi-output connection map" do
+ let(:nodes_data) do
+ [
+ { id: "node-1", type: "condition:if", name: "If" },
+ { id: "node-2", type: "action:log", name: "Log" },
+ ]
+ end
+ let(:connections_data) do
+ { "If" => { "main" => [nil, [{ "node" => "Log", "type" => "main", "index" => 0 }]] } }
+ end
+
+ it "stores empty arrays instead of null output slots" do
+ described_class.call(
+ workflow: workflow,
+ nodes_data: nodes_data,
+ connections_data: connections_data,
+ )
+
+ expect(workflow.reload.connections).to eq(
+ "If" => {
+ "main" => [[], [{ "node" => "Log", "type" => "main", "index" => 0 }]],
+ },
+ )
+ end
+ end
+
+ context "with split node data" do
+ it "stores parameters, credentials, and direct node settings separately" do
+ described_class.call(
+ workflow: workflow,
+ nodes_data: [
+ {
+ id: "http-1",
+ type: "action:http_request",
+ name: "HTTP request",
+ notes: "Fetches data",
+ alwaysOutputData: true,
+ parameters: {
+ "url" => "https://example.com",
+ "method" => "GET",
+ "authentication" => "basic_auth",
+ },
+ credentials: {
+ "auth" => {
+ "id" => 12,
+ "credential_type" => "basic_auth",
+ },
+ },
+ },
+ ],
+ connections_data: {
+ },
+ )
+
+ node = workflow.reload.nodes.first
+ expect(node["parameters"]).to eq(
+ "url" => "https://example.com",
+ "method" => "GET",
+ "authentication" => "basic_auth",
+ )
+ expect(node["credentials"]).to eq(
+ "auth" => {
+ "id" => "12",
+ "credential_type" => "basic_auth",
+ },
+ )
+ expect(node["notes"]).to eq("Fetches data")
+ expect(node["alwaysOutputData"]).to eq(true)
+ expect(node).not_to have_key("settings")
+ end
+
+ it "removes stale credentials when authentication no longer uses them" do
+ described_class.call(
+ workflow: workflow,
+ nodes_data: [
+ {
+ id: "http-1",
+ type: "action:http_request",
+ name: "HTTP request",
+ parameters: {
+ "url" => "https://example.com",
+ "method" => "GET",
+ "authentication" => "none",
+ },
+ credentials: {
+ "auth" => {
+ "id" => "12",
+ "credential_type" => "basic_auth",
+ },
+ },
+ },
+ ],
+ connections_data: {
+ },
+ )
+
+ expect(workflow.reload.nodes.first["credentials"]).to eq({})
+ end
+ end
+
+ context "when workflow has existing nodes and connections" do
+ before do
+ extra =
+ build_workflow_graph do |g|
+ g.node "existing-1", "action:topic_tags", name: "Existing Node 1"
+ g.node "existing-2", "action:topic_tags", name: "Existing Node 2"
+ g.chain "existing-1", "existing-2"
+ end
+ workflow.update!(nodes: extra[:nodes], connections: extra[:connections])
+ end
+
+ it "removes stale nodes and creates new ones" do
+ described_class.call(
+ workflow: workflow,
+ nodes_data: [{ id: "new-1", type: "trigger:topic_created", name: "New Node" }],
+ connections_data: {
+ },
+ )
+
+ workflow.reload
+ expect(workflow.nodes.map { |n| n["name"] }).to eq(["New Node"])
+ expect(workflow.connections).to be_empty
+ end
+
+ it "preserves the existing node's id and typeVersion" do
+ described_class.call(
+ workflow: workflow,
+ nodes_data: [
+ {
+ id: "existing-1",
+ type: "action:topic_tags",
+ name: "Updated Name",
+ parameters: {
+ "tag_names" => "new",
+ },
+ },
+ ],
+ connections_data: {
+ },
+ )
+
+ node = workflow.reload.nodes.first
+ expect(node["id"]).to eq("existing-1")
+ expect(node["typeVersion"]).to eq("1.0")
+ expect(node["name"]).to eq("Updated Name")
+ end
+
+ it "preserves static_data for removed nodes" do
+ workflow.update!(
+ static_data: {
+ "global" => {
+ "tenant_id" => "acme",
+ },
+ "node:Kept Node" => {
+ "key" => "value",
+ },
+ "node:Removed Node" => {
+ "key" => "stale",
+ },
+ },
+ )
+
+ described_class.call(
+ workflow: workflow,
+ nodes_data: [
+ { id: "existing-1", type: "action:topic_tags", name: "Kept Node", parameters: {} },
+ ],
+ connections_data: {
+ },
+ )
+
+ workflow.reload
+ expect(workflow.static_data["global"]).to eq("tenant_id" => "acme")
+ expect(workflow.static_data).to include(
+ "node:Kept Node" => {
+ "key" => "value",
+ },
+ "node:Removed Node" => {
+ "key" => "stale",
+ },
+ )
+ end
+ end
+
+ context "with connections referencing non-existent client IDs" do
+ let(:nodes_data) { [{ id: "node-1", type: "trigger:topic_created", name: "Topic Created" }] }
+
+ let(:connections_data) do
+ {
+ "Topic Created" => {
+ "main" => [[{ "node" => "Missing node", "type" => "main", "index" => 0 }]],
+ },
+ }
+ end
+
+ it "skips connections with invalid references" do
+ described_class.call(
+ workflow: workflow,
+ nodes_data: nodes_data,
+ connections_data: connections_data,
+ )
+
+ workflow.reload
+ expect(workflow.nodes.size).to eq(1)
+ expect(workflow.connections).to be_empty
+ end
+ end
+
+ context "when creating a form trigger without a uuid" do
+ it "assigns a generated uuid" do
+ described_class.call(
+ workflow: workflow,
+ nodes_data: [{ id: "form-1", type: "trigger:form", name: "Form" }],
+ connections_data: {
+ },
+ )
+
+ workflow.reload
+ expect(workflow.nodes.first["webhookId"]).to be_present
+ end
+ end
+
+ context "when a form trigger already has a webhookId" do
+ it "preserves the existing webhookId" do
+ described_class.call(
+ workflow: workflow,
+ nodes_data: [
+ { id: "form-1", type: "trigger:form", name: "Form", webhookId: "existing-uuid" },
+ ],
+ connections_data: {
+ },
+ )
+
+ expect(workflow.reload.nodes.first["webhookId"]).to eq("existing-uuid")
+ end
+ end
+
+ context "when an existing form trigger is updated" do
+ before do
+ extra =
+ build_workflow_graph { |g| g.node "form-1", "trigger:form", webhook_id: "original-uuid" }
+ workflow.update!(nodes: extra[:nodes])
+ end
+
+ it "preserves the original webhookId" do
+ described_class.call(
+ workflow: workflow,
+ nodes_data: [
+ {
+ id: "form-1",
+ type: "trigger:form",
+ name: "Updated Form",
+ parameters: {
+ "some_field" => "value",
+ },
+ },
+ ],
+ connections_data: {
+ },
+ )
+
+ node = workflow.reload.nodes.first
+ expect(node["webhookId"]).to eq("original-uuid")
+ expect(node.dig("parameters", "some_field")).to eq("value")
+ end
+ end
+ end
+end
diff --git a/plugins/discourse-workflows/spec/services/discourse_workflows/workflow/create_spec.rb b/plugins/discourse-workflows/spec/services/discourse_workflows/workflow/create_spec.rb
new file mode 100644
index 00000000000..3ff709daa61
--- /dev/null
+++ b/plugins/discourse-workflows/spec/services/discourse_workflows/workflow/create_spec.rb
@@ -0,0 +1,174 @@
+# frozen_string_literal: true
+
+RSpec.describe DiscourseWorkflows::Workflow::Create do
+ describe described_class::Contract, type: :model do
+ it { is_expected.to validate_presence_of(:name) }
+ it { is_expected.to validate_length_of(:name).is_at_most(100) }
+ end
+
+ describe ".call" do
+ subject(:result) { described_class.call(params:, **dependencies) }
+
+ fab!(:user, :admin)
+
+ let(:params) { { name:, nodes:, connections:, static_data: } }
+ let(:dependencies) { { guardian: user.guardian } }
+ let(:name) { "My Workflow" }
+ let(:nodes) { [] }
+ let(:connections) { {} }
+ let(:static_data) { {} }
+
+ context "when contract is invalid" do
+ let(:name) { nil }
+
+ it { is_expected.to fail_a_contract }
+ end
+
+ context "when name is too long" do
+ let(:name) { "a" * 101 }
+
+ it { is_expected.to fail_a_contract }
+ end
+
+ context "when connections use an unsupported array shape" do
+ let(:connections) { [{ source_index: 0, target_index: 1 }] }
+
+ it { is_expected.to fail_a_step(:populate_graph) }
+ end
+
+ context "when nodes use unsupported snake_case workflow JSON keys" do
+ let(:nodes) { [{ type: "trigger:manual", type_version: "1.0", name: "Manual" }] }
+
+ it { is_expected.to fail_a_step(:populate_graph) }
+ end
+
+ context "when static_data uses a nested node bucket" do
+ let(:static_data) { { "node" => { "Manual" => {} } } }
+
+ it { is_expected.to fail_a_contract }
+ end
+
+ context "when static_data has a non-object slot" do
+ let(:static_data) { { "global" => "bad" } }
+
+ it { is_expected.to fail_a_contract }
+ end
+
+ context "when two nodes share the same name" do
+ let(:nodes) do
+ [
+ { id: "a", type: "trigger:manual", name: "Step" },
+ { id: "b", type: "action:log", name: "Step" },
+ ]
+ end
+
+ it { is_expected.to fail_a_step(:populate_graph) }
+ end
+
+ context "when two sticky notes share the same default name" do
+ let(:nodes) do
+ [
+ { id: "note-1", type: "flow:sticky_note", name: "Sticky Note" },
+ { id: "note-2", type: "flow:sticky_note", name: "Sticky Note" },
+ ]
+ end
+
+ it { is_expected.to run_successfully }
+ end
+
+ context "when user cannot manage workflows" do
+ fab!(:user)
+
+ it { is_expected.to fail_a_policy(:can_manage_workflows) }
+ end
+
+ context "when graph population fails" do
+ before { DiscourseWorkflows::Workflow::Action::PopulateGraph.stubs(:call).returns(false) }
+
+ it { is_expected.to fail_a_step(:populate_graph) }
+ end
+
+ context "when everything's ok" do
+ let(:nodes) do
+ [
+ {
+ id: "node_1",
+ type: "trigger:topic_created",
+ name: "Topic Created",
+ parameters: {
+ category_id: 1,
+ },
+ },
+ {
+ id: "node_2",
+ type: "action:topic_tags",
+ name: "Topic Tags",
+ parameters: {
+ tag_names: "test",
+ },
+ },
+ ]
+ end
+ let(:connections) do
+ {
+ "Topic Created" => {
+ "main" => [[{ "node" => "Topic Tags", "type" => "main", "index" => 0 }]],
+ },
+ }
+ end
+ let(:static_data) do
+ { "global" => { "tenant_id" => "acme" }, "node:Topic Created" => { "cursor" => "abc" } }
+ end
+
+ it { is_expected.to run_successfully }
+
+ it "creates a workflow with correct attributes" do
+ result
+ expect(result[:workflow]).to have_attributes(
+ name: "My Workflow",
+ created_by: user,
+ updated_by: user,
+ )
+ expect(result[:workflow]).not_to be_published
+ end
+
+ it "stores static data without reshaping it" do
+ result
+
+ expect(result[:workflow].static_data).to eq(JSON.parse(static_data.to_json))
+ end
+
+ it "populates the workflow graph" do
+ result
+ workflow = result[:workflow].reload
+ expect(workflow.nodes.size).to eq(2)
+ expect(workflow.connections).to eq(
+ "Topic Created" => {
+ "main" => [[{ "node" => "Topic Tags", "type" => "main", "index" => 0 }]],
+ },
+ )
+ end
+
+ it "creates the initial snapshot tagged with the workflow's versionId" do
+ result
+ workflow = result[:workflow].reload
+ snapshot = workflow.workflow_versions.find_by(version_id: workflow.version_id)
+ expect(snapshot).to have_attributes(
+ name: "My Workflow",
+ nodes: workflow.nodes,
+ connections: workflow.connections,
+ )
+ expect(workflow.active_version_id).to be_nil
+ end
+
+ it "logs a staff action" do
+ result
+ log = UserHistory.last
+ expect(log.custom_type).to eq("discourse_workflows_workflow_created")
+ expect(log.subject).to eq("My Workflow")
+ end
+
+ it_behaves_like "expires workflow caches"
+ end
+ end
+end
diff --git a/plugins/discourse-workflows/spec/services/discourse_workflows/workflow/destroy_spec.rb b/plugins/discourse-workflows/spec/services/discourse_workflows/workflow/destroy_spec.rb
new file mode 100644
index 00000000000..9b9e6a8c675
--- /dev/null
+++ b/plugins/discourse-workflows/spec/services/discourse_workflows/workflow/destroy_spec.rb
@@ -0,0 +1,52 @@
+# frozen_string_literal: true
+
+RSpec.describe DiscourseWorkflows::Workflow::Destroy do
+ describe described_class::Contract, type: :model do
+ it { is_expected.to validate_presence_of(:workflow_id) }
+ end
+
+ describe ".call" do
+ subject(:result) { described_class.call(params:, **dependencies) }
+
+ fab!(:admin)
+ fab!(:workflow) { Fabricate(:discourse_workflows_workflow, created_by: admin) }
+
+ let(:params) { { workflow_id: workflow.id } }
+ let(:dependencies) { { guardian: admin.guardian } }
+
+ context "when contract is invalid" do
+ let(:params) { { workflow_id: nil } }
+
+ it { is_expected.to fail_a_contract }
+ end
+
+ context "when workflow does not exist" do
+ let(:params) { { workflow_id: -1 } }
+
+ it { is_expected.to fail_to_find_a_model(:workflow) }
+ end
+
+ context "when user cannot manage workflows" do
+ fab!(:user)
+ let(:dependencies) { { guardian: user.guardian } }
+
+ it { is_expected.to fail_a_policy(:can_manage_workflows) }
+ end
+
+ context "when everything's ok" do
+ it { is_expected.to run_successfully }
+
+ it "destroys the workflow" do
+ expect { result }.to change { DiscourseWorkflows::Workflow.exists?(workflow.id) }.to(false)
+ end
+
+ it "logs a staff action" do
+ expect { result }.to change {
+ UserHistory.where(custom_type: "discourse_workflows_workflow_destroyed").count
+ }.by(1)
+ end
+
+ it_behaves_like "expires workflow caches"
+ end
+ end
+end
diff --git a/plugins/discourse-workflows/spec/services/discourse_workflows/workflow/discard_draft_spec.rb b/plugins/discourse-workflows/spec/services/discourse_workflows/workflow/discard_draft_spec.rb
new file mode 100644
index 00000000000..03bacf267f2
--- /dev/null
+++ b/plugins/discourse-workflows/spec/services/discourse_workflows/workflow/discard_draft_spec.rb
@@ -0,0 +1,81 @@
+# frozen_string_literal: true
+
+RSpec.describe DiscourseWorkflows::Workflow::DiscardDraft do
+ describe described_class::Contract, type: :model do
+ it { is_expected.to validate_presence_of(:workflow_id) }
+ end
+
+ describe ".call" do
+ subject(:result) { described_class.call(params:, **dependencies) }
+
+ fab!(:user, :admin)
+ fab!(:workflow) do
+ graph = build_workflow_graph { |builder| builder.node "published-1", "trigger:manual" }
+ Fabricate(:discourse_workflows_workflow, created_by: user, published: true, **graph)
+ end
+
+ let(:params) { { workflow_id: workflow.id } }
+ let(:dependencies) { { guardian: user.guardian } }
+
+ before do
+ graph = build_workflow_graph { |builder| builder.node "draft-1", "trigger:schedule" }
+ workflow.update!(
+ name: "Draft workflow",
+ nodes: graph[:nodes],
+ connections: graph[:connections],
+ settings: {
+ "timezone" => "Europe/Paris",
+ },
+ )
+ workflow.snapshot!(user: user)
+ end
+
+ context "when the contract is invalid" do
+ let(:params) { { workflow_id: nil } }
+
+ it { is_expected.to fail_a_contract }
+ end
+
+ context "when workflow is not found" do
+ let(:params) { { workflow_id: -1 } }
+
+ it { is_expected.to fail_to_find_a_model(:workflow) }
+ end
+
+ context "when the workflow has no active version" do
+ fab!(:workflow) { Fabricate(:discourse_workflows_workflow, created_by: user) }
+
+ it { is_expected.to fail_to_find_a_model(:active_version) }
+ end
+
+ context "when user cannot manage workflows" do
+ fab!(:non_admin, :user)
+
+ let(:dependencies) { { guardian: non_admin.guardian } }
+
+ it { is_expected.to fail_a_policy(:can_manage_workflows) }
+ end
+
+ context "when everything's ok" do
+ it { is_expected.to run_successfully }
+
+ it "restores the published workflow version" do
+ published_version = workflow.active_version
+
+ result
+
+ expect(workflow.reload).to have_attributes(
+ name: published_version.name,
+ nodes: published_version.nodes,
+ connections: published_version.connections,
+ settings: published_version.settings,
+ version_id: published_version.version_id,
+ active_version_id: published_version.version_id,
+ )
+ expect(workflow).not_to have_unpublished_changes
+ end
+
+ it_behaves_like "expires workflow caches"
+ end
+ end
+end
diff --git a/plugins/discourse-workflows/spec/services/discourse_workflows/workflow/execute_spec.rb b/plugins/discourse-workflows/spec/services/discourse_workflows/workflow/execute_spec.rb
new file mode 100644
index 00000000000..9e74e2a1a51
--- /dev/null
+++ b/plugins/discourse-workflows/spec/services/discourse_workflows/workflow/execute_spec.rb
@@ -0,0 +1,105 @@
+# frozen_string_literal: true
+
+RSpec.describe DiscourseWorkflows::Workflow::Execute do
+ describe described_class::Contract, type: :model do
+ it { is_expected.to validate_presence_of(:trigger_node_id) }
+ end
+
+ describe ".call" do
+ subject(:result) { described_class.call(params:) }
+
+ fab!(:user)
+ fab!(:workflow) do
+ graph = build_workflow_graph { |g| g.node "trigger-1", "trigger:manual" }
+ Fabricate(:discourse_workflows_workflow, created_by: user, published: true, **graph)
+ end
+
+ let(:params) { { workflow_id: workflow.id, trigger_node_id: "trigger-1" } }
+
+ context "when contract is invalid" do
+ let(:params) { { workflow_id: workflow.id, trigger_node_id: nil } }
+
+ it { is_expected.to fail_a_contract }
+ end
+
+ context "when workflows are not enabled" do
+ before { SiteSetting.discourse_workflows_enabled = false }
+
+ it { is_expected.to fail_a_policy(:can_execute) }
+ end
+
+ context "when workflow does not exist" do
+ let(:params) { { workflow_id: -1, trigger_node_id: "trigger-1" } }
+
+ it { is_expected.to fail_to_find_a_model(:workflow) }
+ end
+
+ context "when trigger node does not exist" do
+ let(:params) { { workflow_id: workflow.id, trigger_node_id: "nonexistent" } }
+
+ it { is_expected.to fail_to_find_a_model(:trigger_node) }
+ end
+
+ context "when workflow_id is not provided" do
+ let(:params) { { trigger_node_id: "trigger-1" } }
+
+ before do
+ DiscourseWorkflows::WorkflowDependencyIndexer.call(
+ workflow,
+ version: workflow.active_version,
+ )
+ end
+
+ it { is_expected.to run_successfully }
+
+ it "finds the workflow via dependency index" do
+ expect { result }.to change { DiscourseWorkflows::Execution.count }.by(1)
+ end
+ end
+
+ context "when a matched workflow version is provided" do
+ let!(:matched_version) { workflow.active_version }
+ let(:params) do
+ {
+ workflow_id: workflow.id,
+ workflow_version_id: matched_version.version_id,
+ trigger_node_id: "trigger-1",
+ }
+ end
+
+ before do
+ update_workflow_node(workflow, "trigger-1") { |node| node["id"] = "trigger-2" }
+ publish_workflow!(workflow)
+ end
+
+ it { is_expected.to run_successfully }
+
+ it "executes the matched version instead of the current active version" do
+ expect(result[:workflow_version]).to eq(matched_version)
+ workflow_data = result[:execution].execution_data.workflow_data
+ expect(workflow_data["nodes"]).to contain_exactly(include("id" => "trigger-1"))
+ end
+ end
+
+ context "when everything's ok" do
+ it { is_expected.to run_successfully }
+
+ it "creates an execution record" do
+ expect { result }.to change { DiscourseWorkflows::Execution.count }.by(1)
+ end
+ end
+
+ context "when user_id is provided" do
+ fab!(:execution_user, :user)
+ let(:params) do
+ { workflow_id: workflow.id, trigger_node_id: "trigger-1", user_id: execution_user.id }
+ end
+
+ it { is_expected.to run_successfully }
+
+ it "fetches the correct user" do
+ expect(result[:user]).to eq(execution_user)
+ end
+ end
+ end
+end
diff --git a/plugins/discourse-workflows/spec/services/discourse_workflows/workflow/list_spec.rb b/plugins/discourse-workflows/spec/services/discourse_workflows/workflow/list_spec.rb
new file mode 100644
index 00000000000..2bc75ca11fa
--- /dev/null
+++ b/plugins/discourse-workflows/spec/services/discourse_workflows/workflow/list_spec.rb
@@ -0,0 +1,180 @@
+# frozen_string_literal: true
+
+RSpec.describe DiscourseWorkflows::Workflow::List do
+ describe ".call" do
+ subject(:result) { described_class.call(params:, **dependencies) }
+
+ fab!(:admin)
+ fab!(:user)
+
+ let(:params) { {} }
+ let(:dependencies) { { guardian: admin.guardian } }
+
+ context "when user cannot manage workflows" do
+ let(:dependencies) { { guardian: user.guardian } }
+
+ it { is_expected.to fail_a_policy(:can_manage_workflows) }
+ end
+
+ context "when there are no workflows" do
+ it { is_expected.to run_successfully }
+
+ it "returns an empty collection" do
+ expect(result[:workflows]).to be_empty
+ end
+
+ it "returns zero total rows" do
+ expect(result[:total_rows]).to eq(0)
+ end
+
+ it "does not return a load more url" do
+ expect(result[:load_more_url]).to be_nil
+ end
+ end
+
+ context "when there are workflows" do
+ fab!(:workflow_a) do
+ Fabricate(:discourse_workflows_workflow, name: "Alpha", created_by: user)
+ end
+ fab!(:workflow_b) do
+ Fabricate(:discourse_workflows_workflow, name: "Bravo", created_by: user)
+ end
+
+ it { is_expected.to run_successfully }
+
+ it "returns workflows ordered by id descending" do
+ expect(result[:workflows].map(&:id)).to eq([workflow_b.id, workflow_a.id])
+ end
+
+ it "returns the total count" do
+ expect(result[:total_rows]).to eq(2)
+ end
+
+ it "does not return a load more url when all results fit" do
+ expect(result[:load_more_url]).to be_nil
+ end
+ end
+
+ context "with pagination" do
+ let(:params) { { limit: 2 } }
+
+ fab!(:workflow_1) do
+ Fabricate(:discourse_workflows_workflow, name: "First", created_by: user)
+ end
+ fab!(:workflow_2) do
+ Fabricate(:discourse_workflows_workflow, name: "Second", created_by: user)
+ end
+ fab!(:workflow_3) do
+ Fabricate(:discourse_workflows_workflow, name: "Third", created_by: user)
+ end
+
+ it "returns only the requested number of workflows" do
+ expect(result[:workflows].size).to eq(2)
+ end
+
+ it "returns a load more url with cursor" do
+ last_id = result[:workflows].last.id
+ expect(result[:load_more_url]).to eq(
+ "/admin/plugins/discourse-workflows/workflows.json?cursor=#{last_id}&limit=2",
+ )
+ end
+
+ it "returns the total count of all workflows" do
+ expect(result[:total_rows]).to eq(3)
+ end
+
+ context "when using a cursor" do
+ let(:params) { { limit: 2, cursor: workflow_3.id } }
+
+ it "returns workflows after the cursor" do
+ expect(result[:workflows].map(&:id)).to eq([workflow_2.id, workflow_1.id])
+ end
+
+ it "does not return a load more url when no more results" do
+ expect(result[:load_more_url]).to be_nil
+ end
+ end
+ end
+
+ context "with name filter" do
+ fab!(:workflow_a) do
+ Fabricate(:discourse_workflows_workflow, name: "Deploy to production", created_by: user)
+ end
+ fab!(:workflow_b) do
+ Fabricate(:discourse_workflows_workflow, name: "Send notification", created_by: user)
+ end
+
+ let(:params) { { filter: "deploy" } }
+
+ it { is_expected.to run_successfully }
+
+ it "returns only matching workflows" do
+ expect(result[:workflows].map(&:name)).to eq(["Deploy to production"])
+ end
+
+ it "returns filtered total rows" do
+ expect(result[:total_rows]).to eq(1)
+ end
+ end
+
+ context "with trigger_type filter" do
+ fab!(:error_workflow) do
+ graph = build_workflow_graph { |g| g.node "trigger-1", "trigger:error" }
+ Fabricate(:discourse_workflows_workflow, name: "Error handler", created_by: user, **graph)
+ end
+ fab!(:other_workflow) do
+ Fabricate(:discourse_workflows_workflow, name: "Other", created_by: user)
+ end
+
+ let(:params) { { trigger_type: "error" } }
+
+ it "returns only workflows with the specified trigger type" do
+ expect(result[:workflows].map(&:name)).to eq(["Error handler"])
+ end
+
+ it "returns filtered total rows" do
+ expect(result[:total_rows]).to eq(1)
+ end
+ end
+
+ context "with pagination and filters" do
+ let(:params) { { limit: 1, filter: "deploy" } }
+
+ fab!(:workflow_1) do
+ Fabricate(:discourse_workflows_workflow, name: "Deploy alpha", created_by: user)
+ end
+ fab!(:workflow_2) do
+ Fabricate(:discourse_workflows_workflow, name: "Deploy beta", created_by: user)
+ end
+ fab!(:workflow_3) do
+ Fabricate(:discourse_workflows_workflow, name: "Other workflow", created_by: user)
+ end
+
+ it "returns filtered total rows" do
+ expect(result[:total_rows]).to eq(2)
+ end
+
+ it "includes filter params in load more url" do
+ url = result[:load_more_url]
+ expect(url).to include("filter=deploy")
+ expect(url).to include("limit=1")
+ expect(url).to include("cursor=")
+ end
+ end
+
+ context "with exclude_id" do
+ fab!(:workflow_a) do
+ Fabricate(:discourse_workflows_workflow, name: "Alpha", created_by: user)
+ end
+ fab!(:workflow_b) do
+ Fabricate(:discourse_workflows_workflow, name: "Bravo", created_by: user)
+ end
+
+ let(:params) { { exclude_id: workflow_a.id } }
+
+ it "excludes the specified workflow" do
+ expect(result[:workflows].map(&:name)).to eq(["Bravo"])
+ end
+ end
+ end
+end
diff --git a/plugins/discourse-workflows/spec/services/discourse_workflows/workflow/manual_execute_spec.rb b/plugins/discourse-workflows/spec/services/discourse_workflows/workflow/manual_execute_spec.rb
new file mode 100644
index 00000000000..44727acf6d5
--- /dev/null
+++ b/plugins/discourse-workflows/spec/services/discourse_workflows/workflow/manual_execute_spec.rb
@@ -0,0 +1,153 @@
+# frozen_string_literal: true
+
+RSpec.describe DiscourseWorkflows::Workflow::ManualExecute do
+ describe described_class::Contract, type: :model do
+ it { is_expected.to validate_presence_of(:trigger_node_id) }
+ end
+
+ describe ".call" do
+ subject(:result) { described_class.call(params:, **dependencies) }
+
+ fab!(:admin)
+ fab!(:workflow) do
+ graph = build_workflow_graph { |g| g.node "trigger-1", "trigger:manual" }
+ Fabricate(:discourse_workflows_workflow, created_by: admin, published: true, **graph)
+ end
+
+ let(:params) { { workflow_id: workflow.id, trigger_node_id: "trigger-1" } }
+ let(:dependencies) { { guardian: admin.guardian } }
+
+ context "when contract is invalid" do
+ let(:params) { super().merge(trigger_node_id: nil) }
+
+ it { is_expected.to fail_a_contract }
+ end
+
+ context "when user cannot manage workflows" do
+ fab!(:user)
+
+ let(:dependencies) { { guardian: user.guardian } }
+
+ it { is_expected.to fail_a_policy(:can_manage_workflows) }
+ end
+
+ context "when workflow does not exist" do
+ let(:params) { super().merge(workflow_id: -1) }
+
+ it { is_expected.to fail_to_find_a_model(:workflow) }
+ end
+
+ context "when trigger node does not exist" do
+ let(:params) { super().merge(trigger_node_id: "nonexistent") }
+
+ it { is_expected.to fail_to_find_a_model(:trigger_node) }
+ end
+
+ context "when everything is valid" do
+ it { is_expected.to run_successfully }
+
+ it "creates a new execution record" do
+ expect { result }.to change { DiscourseWorkflows::Execution.count }.by(1)
+ end
+
+ it "records a manual execution mode" do
+ result
+ expect(result[:execution]).to be_manual
+ end
+
+ context "when the trigger has pinned data" do
+ fab!(:workflow) do
+ graph = build_workflow_graph { |g| g.node "trigger-1", "trigger:post_created" }
+ Fabricate(:discourse_workflows_workflow, created_by: admin, published: true, **graph)
+ end
+
+ before do
+ workflow.update_node_pin_data!(
+ "Trigger-1",
+ [{ "json" => { "post" => { "id" => 42, "raw" => "pinned body" } } }],
+ )
+ end
+
+ it { is_expected.to run_successfully }
+
+ it "uses pinned items as the trigger output" do
+ execution = result[:execution]
+ trigger_run = execution.execution_data.run_data["Trigger-1"].first
+ expect(trigger_run["outputs"].first["items"]).to include(
+ hash_including("json" => hash_including("post" => hash_including("id" => 42))),
+ )
+ end
+ end
+
+ context "when the trigger is event-based without pinned data" do
+ fab!(:workflow) do
+ graph = build_workflow_graph { |g| g.node "trigger-1", "trigger:post_created" }
+ Fabricate(:discourse_workflows_workflow, created_by: admin, published: true, **graph)
+ end
+
+ it { is_expected.to run_successfully }
+
+ it "runs with empty trigger data" do
+ expect(result[:execution].trigger_data).to eq({})
+ end
+ end
+
+ context "when manually testing a Stale Topic trigger" do
+ fab!(:workflow) do
+ graph =
+ build_workflow_graph do |g|
+ g.node "trigger-1", "trigger:stale_topic", configuration: { "hours" => 24 }
+ end
+ Fabricate(:discourse_workflows_workflow, created_by: admin, published: true, **graph)
+ end
+
+ fab!(:stale_topic_1) do
+ Fabricate(:topic, created_at: 48.hours.ago, last_posted_at: 48.hours.ago)
+ end
+ fab!(:stale_topic_2) do
+ Fabricate(:topic, created_at: 48.hours.ago, last_posted_at: 48.hours.ago)
+ end
+
+ it { is_expected.to run_successfully }
+
+ it "creates one execution carrying every stale topic as an item" do
+ expect { result }.to change { DiscourseWorkflows::Execution.count }.by(1)
+
+ execution = result[:execution]
+ trigger_run = execution.execution_data.run_data["Trigger-1"].first
+ topic_ids =
+ trigger_run["outputs"].first["items"].map { |item| item.dig("json", "topic", "id") }
+ expect(topic_ids).to match_array([stale_topic_1.id, stale_topic_2.id])
+ end
+ end
+
+ context "when manually testing a Schedule trigger" do
+ fab!(:workflow) do
+ graph =
+ build_workflow_graph do |g|
+ g.node "trigger-1",
+ "trigger:schedule",
+ configuration: {
+ rule: {
+ interval: [{ field: "minutes", minutesInterval: 5 }],
+ },
+ }
+ end
+ Fabricate(:discourse_workflows_workflow, created_by: admin, published: true, **graph)
+ end
+
+ it "uses the schedule trigger's manual output" do
+ freeze_time Time.utc(2026, 3, 18, 9, 0)
+
+ result
+
+ expect(result[:execution].trigger_data).to include(
+ "timestamp" => "2026-03-18T09:00:00.000Z",
+ "hour" => "09",
+ "minute" => "00",
+ )
+ end
+ end
+ end
+ end
+end
diff --git a/plugins/discourse-workflows/spec/services/discourse_workflows/workflow/publish_spec.rb b/plugins/discourse-workflows/spec/services/discourse_workflows/workflow/publish_spec.rb
new file mode 100644
index 00000000000..f45ac2fe895
--- /dev/null
+++ b/plugins/discourse-workflows/spec/services/discourse_workflows/workflow/publish_spec.rb
@@ -0,0 +1,153 @@
+# frozen_string_literal: true
+
+RSpec.describe DiscourseWorkflows::Workflow::Publish do
+ describe described_class::Contract, type: :model do
+ it { is_expected.to validate_presence_of(:workflow_id) }
+ end
+
+ describe ".call" do
+ subject(:result) { described_class.call(params:, **dependencies) }
+
+ fab!(:user, :admin)
+ fab!(:workflow) { Fabricate(:discourse_workflows_workflow, created_by: user) }
+
+ let(:params) { { workflow_id: workflow.id } }
+ let(:dependencies) { { guardian: user.guardian } }
+
+ context "when workflow is not found" do
+ let(:params) { { workflow_id: -1 } }
+
+ it { is_expected.to fail_to_find_a_model(:workflow) }
+ end
+
+ context "when user cannot manage workflows" do
+ fab!(:non_admin, :user)
+
+ let(:dependencies) { { guardian: non_admin.guardian } }
+
+ it { is_expected.to fail_a_policy(:can_manage_workflows) }
+ end
+
+ context "when workflow has no matching snapshot for its current versionId" do
+ before { workflow.workflow_versions.delete_all }
+
+ it { is_expected.to fail_to_find_a_model(:workflow_version) }
+ end
+
+ context "when everything's ok" do
+ it { is_expected.to run_successfully }
+
+ it "publishes the workflow's current version" do
+ result
+ expect(workflow.reload.active_version_id).to eq(workflow.version_id)
+ end
+
+ it_behaves_like "expires workflow caches"
+
+ context "when another active workflow already owns the same webhook route" do
+ fab!(:owner) do
+ graph =
+ build_workflow_graph do |g|
+ g.node "webhook-1",
+ "trigger:webhook",
+ configuration: {
+ "path" => "shared-hook",
+ "http_method" => "POST",
+ }
+ end
+ Fabricate(:discourse_workflows_workflow, created_by: user, published: true, **graph)
+ end
+
+ before do
+ version = owner.workflow_versions.find_by(version_id: owner.version_id)
+ DiscourseWorkflows::Webhook::Action::ActivateWebhooks.call(
+ workflow: owner,
+ workflow_version: version,
+ )
+
+ conflicting_graph =
+ build_workflow_graph do |g|
+ g.node "webhook-1",
+ "trigger:webhook",
+ configuration: {
+ "path" => "shared-hook",
+ "http_method" => "POST",
+ }
+ end
+ workflow.update!(
+ nodes: conflicting_graph[:nodes],
+ connections: conflicting_graph[:connections],
+ )
+ workflow.snapshot!(user: user)
+ end
+
+ it { is_expected.to fail_a_step(:activate_triggers) }
+
+ it "rolls back the publish so active_version_id stays nil" do
+ result
+ expect(workflow.reload.active_version_id).to be_nil
+ end
+ end
+
+ it "prunes trigger_state for nodes removed from the published draft" do
+ last_triggered_at = 1.minute.ago.iso8601
+ graph = build_workflow_graph { |g| g.node "kept-trigger", "trigger:schedule" }
+ workflow.update!(
+ nodes: graph[:nodes],
+ connections: graph[:connections],
+ trigger_state: {
+ "kept-trigger" => {
+ "last_triggered_at" => last_triggered_at,
+ },
+ "removed-trigger" => {
+ "triggered_occurrences" => ["removed-key"],
+ },
+ },
+ )
+ workflow.snapshot!(user: user)
+
+ result
+
+ expect(workflow.reload.trigger_state).to eq(
+ "kept-trigger" => {
+ "last_triggered_at" => last_triggered_at,
+ },
+ )
+ end
+
+ it "leaves user-facing static_data untouched on publish" do
+ graph = build_workflow_graph { |g| g.node "kept-trigger", "trigger:schedule" }
+ workflow.update!(
+ nodes: graph[:nodes],
+ connections: graph[:connections],
+ static_data: {
+ "global" => {
+ "tenant_id" => "acme",
+ },
+ "node:Kept trigger" => {
+ "cursor" => "k-1",
+ },
+ "node:Removed Node" => {
+ "cursor" => "r-1",
+ },
+ },
+ )
+ workflow.snapshot!(user: user)
+
+ result
+
+ expect(workflow.reload.static_data).to eq(
+ "global" => {
+ "tenant_id" => "acme",
+ },
+ "node:Kept trigger" => {
+ "cursor" => "k-1",
+ },
+ "node:Removed Node" => {
+ "cursor" => "r-1",
+ },
+ )
+ end
+ end
+ end
+end
diff --git a/plugins/discourse-workflows/spec/services/discourse_workflows/workflow/show_spec.rb b/plugins/discourse-workflows/spec/services/discourse_workflows/workflow/show_spec.rb
new file mode 100644
index 00000000000..599f290dc82
--- /dev/null
+++ b/plugins/discourse-workflows/spec/services/discourse_workflows/workflow/show_spec.rb
@@ -0,0 +1,44 @@
+# frozen_string_literal: true
+
+RSpec.describe DiscourseWorkflows::Workflow::Show do
+ describe described_class::Contract, type: :model do
+ it { is_expected.to validate_presence_of(:workflow_id) }
+ end
+
+ describe ".call" do
+ subject(:result) { described_class.call(params:, **dependencies) }
+
+ fab!(:admin)
+ fab!(:workflow) { Fabricate(:discourse_workflows_workflow, created_by: admin) }
+
+ let(:params) { { workflow_id: workflow.id } }
+ let(:dependencies) { { guardian: admin.guardian } }
+
+ context "when params are not valid" do
+ let(:params) { { workflow_id: nil } }
+
+ it { is_expected.to fail_a_contract }
+ end
+
+ context "when workflow does not exist" do
+ let(:params) { { workflow_id: -1 } }
+
+ it { is_expected.to fail_to_find_a_model(:workflow) }
+ end
+
+ context "when user cannot manage workflows" do
+ fab!(:user)
+
+ let(:dependencies) { { guardian: user.guardian } }
+
+ it { is_expected.to fail_a_policy(:can_manage_workflows) }
+ end
+
+ context "when everything is valid" do
+ it "returns the workflow" do
+ expect(result).to run_successfully
+ expect(result[:workflow]).to eq(workflow)
+ end
+ end
+ end
+end
diff --git a/plugins/discourse-workflows/spec/services/discourse_workflows/workflow/trigger_topic_admin_button_spec.rb b/plugins/discourse-workflows/spec/services/discourse_workflows/workflow/trigger_topic_admin_button_spec.rb
new file mode 100644
index 00000000000..c4d983f8454
--- /dev/null
+++ b/plugins/discourse-workflows/spec/services/discourse_workflows/workflow/trigger_topic_admin_button_spec.rb
@@ -0,0 +1,85 @@
+# frozen_string_literal: true
+
+RSpec.describe DiscourseWorkflows::Workflow::TriggerTopicAdminButton do
+ describe described_class::Contract, type: :model do
+ it { is_expected.to validate_presence_of(:trigger_node_id) }
+ it { is_expected.to validate_presence_of(:topic_id) }
+ end
+
+ describe ".call" do
+ subject(:result) { described_class.call(params:, **dependencies) }
+
+ fab!(:admin)
+ fab!(:topic)
+ fab!(:workflow) do
+ graph =
+ build_workflow_graph do |g|
+ g.node "trigger-1",
+ "trigger:topic_admin_button",
+ configuration: {
+ "label" => "Run workflow",
+ "icon" => "gear",
+ }
+ end
+ Fabricate(:discourse_workflows_workflow, created_by: admin, published: true, **graph)
+ end
+
+ let(:params) { { trigger_node_id: "trigger-1", topic_id: topic.id } }
+ let(:dependencies) { { guardian: Guardian.new(admin) } }
+
+ before { DiscourseWorkflows::WorkflowDependencyIndexer.call(workflow) }
+
+ context "when contract is invalid" do
+ let(:params) { { trigger_node_id: nil, topic_id: nil } }
+
+ it { is_expected.to fail_a_contract }
+ end
+
+ context "when user is not an admin" do
+ fab!(:acting_user, :user)
+ let(:dependencies) { { guardian: Guardian.new(acting_user) } }
+
+ it { is_expected.to fail_a_policy(:can_manage_workflows) }
+ end
+
+ context "when workflow is not found" do
+ let(:params) { { trigger_node_id: "nonexistent", topic_id: topic.id } }
+
+ it { is_expected.to fail_to_find_a_model(:published_trigger) }
+ end
+
+ context "when workflow is unpublished" do
+ before { unpublish_workflow!(workflow) }
+
+ it { is_expected.to fail_to_find_a_model(:published_trigger) }
+ end
+
+ context "when topic does not exist" do
+ let(:params) { { trigger_node_id: "trigger-1", topic_id: -1 } }
+
+ it { is_expected.to fail_to_find_a_model(:topic) }
+ end
+
+ context "when everything is valid" do
+ it { is_expected.to run_successfully }
+
+ it "enqueues an ExecuteWorkflow job" do
+ result
+ job = Jobs::DiscourseWorkflows::ExecuteWorkflow.jobs.last
+ expect(job["args"].first).to include(
+ "trigger_node_id" => "trigger-1",
+ "workflow_id" => workflow.id,
+ "workflow_version_id" => workflow.active_version_id,
+ "user_id" => admin.id,
+ )
+ expect(job["args"].first["trigger_data"]["topic"]).to include(
+ "id" => topic.id,
+ "title" => topic.title,
+ )
+ expect(
+ job["args"].first["trigger_data"]["topic"]["posters"].map { |poster| poster["user_id"] },
+ ).to include(topic.user_id)
+ end
+ end
+ end
+end
diff --git a/plugins/discourse-workflows/spec/services/discourse_workflows/workflow/unpublish_spec.rb b/plugins/discourse-workflows/spec/services/discourse_workflows/workflow/unpublish_spec.rb
new file mode 100644
index 00000000000..be993ae396c
--- /dev/null
+++ b/plugins/discourse-workflows/spec/services/discourse_workflows/workflow/unpublish_spec.rb
@@ -0,0 +1,42 @@
+# frozen_string_literal: true
+
+RSpec.describe DiscourseWorkflows::Workflow::Unpublish do
+ describe described_class::Contract, type: :model do
+ it { is_expected.to validate_presence_of(:workflow_id) }
+ end
+
+ describe ".call" do
+ subject(:result) { described_class.call(params:, **dependencies) }
+
+ fab!(:user, :admin)
+ fab!(:workflow) { Fabricate(:discourse_workflows_workflow, created_by: user, published: true) }
+
+ let(:params) { { workflow_id: workflow.id } }
+ let(:dependencies) { { guardian: user.guardian } }
+
+ context "when workflow is not found" do
+ let(:params) { { workflow_id: -1 } }
+
+ it { is_expected.to fail_to_find_a_model(:workflow) }
+ end
+
+ context "when user cannot manage workflows" do
+ fab!(:non_admin, :user)
+
+ let(:dependencies) { { guardian: non_admin.guardian } }
+
+ it { is_expected.to fail_a_policy(:can_manage_workflows) }
+ end
+
+ context "when everything's ok" do
+ it { is_expected.to run_successfully }
+
+ it "clears the active version" do
+ result
+ expect(workflow.reload.active_version_id).to be_nil
+ end
+
+ it_behaves_like "expires workflow caches"
+ end
+ end
+end
diff --git a/plugins/discourse-workflows/spec/services/discourse_workflows/workflow/update_pin_data_spec.rb b/plugins/discourse-workflows/spec/services/discourse_workflows/workflow/update_pin_data_spec.rb
new file mode 100644
index 00000000000..548ef5d56b8
--- /dev/null
+++ b/plugins/discourse-workflows/spec/services/discourse_workflows/workflow/update_pin_data_spec.rb
@@ -0,0 +1,100 @@
+# frozen_string_literal: true
+
+RSpec.describe DiscourseWorkflows::Workflow::UpdatePinData do
+ describe described_class::Contract, type: :model do
+ it { is_expected.to validate_presence_of(:workflow_id) }
+ it { is_expected.to validate_presence_of(:node_name) }
+ end
+
+ describe ".call" do
+ subject(:result) { described_class.call(params:, **dependencies) }
+
+ fab!(:admin)
+ fab!(:workflow) do
+ graph =
+ build_workflow_graph do |g|
+ g.node "trigger-1", "trigger:post_created"
+ g.node "filter-1", "action:filter"
+ end
+ Fabricate(:discourse_workflows_workflow, created_by: admin, **graph)
+ end
+
+ let(:items) { [{ "json" => { "post" => { "id" => 7 } } }] }
+ let(:params) { { workflow_id: workflow.id, node_name: "Trigger-1", items: items } }
+ let(:dependencies) { { guardian: admin.guardian } }
+
+ context "when user cannot manage workflows" do
+ fab!(:user)
+
+ let(:dependencies) { { guardian: user.guardian } }
+
+ it { is_expected.to fail_a_policy(:can_manage_workflows) }
+ end
+
+ context "when the workflow does not exist" do
+ let(:params) { super().merge(workflow_id: -1) }
+
+ it { is_expected.to fail_to_find_a_model(:workflow) }
+ end
+
+ context "when the node does not exist" do
+ let(:params) { super().merge(node_name: "missing") }
+
+ it { is_expected.to fail_to_find_a_model(:node) }
+ end
+
+ context "when the node has more than one primary output" do
+ fab!(:workflow) do
+ graph =
+ build_workflow_graph do |g|
+ g.node "trigger-1", "trigger:manual"
+ g.node "if-1", "action:if"
+ end
+ Fabricate(:discourse_workflows_workflow, created_by: admin, **graph)
+ end
+
+ let(:params) { { workflow_id: workflow.id, node_name: "If-1", items: items } }
+
+ it { is_expected.to fail_a_policy(:node_supports_pinning) }
+ end
+
+ context "when the pinned items exceed the size cap" do
+ before { SiteSetting.discourse_workflows_max_pin_data_bytes = 32 }
+
+ let(:items) { [{ "json" => { "blob" => "x" * 5000 } }] }
+
+ it { is_expected.to fail_a_policy(:within_size_cap) }
+ end
+
+ context "when pinning valid items" do
+ it { is_expected.to run_successfully }
+
+ it "persists the pinned data on the workflow" do
+ result
+ expect(workflow.reload.pin_data).to include(
+ "Trigger-1" => [hash_including("json" => hash_including("post"))],
+ )
+ end
+
+ it "strips unsupported top-level item payloads" do
+ items.first["binary"] = { "file" => { "fileName" => "x.png" } }
+ result
+ pinned = workflow.reload.pin_data["Trigger-1"].first
+ expect(pinned).not_to have_key("binary")
+ end
+ end
+
+ context "when unpinning" do
+ before { workflow.update_node_pin_data!("Trigger-1", [{ "json" => { "x" => 1 } }]) }
+
+ let(:params) { { workflow_id: workflow.id, node_name: "Trigger-1" } }
+
+ it { is_expected.to run_successfully }
+
+ it "removes the entry for that node from pin data" do
+ result
+ expect(workflow.reload.pin_data).not_to have_key("Trigger-1")
+ end
+ end
+ end
+end
diff --git a/plugins/discourse-workflows/spec/services/discourse_workflows/workflow/update_spec.rb b/plugins/discourse-workflows/spec/services/discourse_workflows/workflow/update_spec.rb
new file mode 100644
index 00000000000..5dd890a0333
--- /dev/null
+++ b/plugins/discourse-workflows/spec/services/discourse_workflows/workflow/update_spec.rb
@@ -0,0 +1,385 @@
+# frozen_string_literal: true
+
+RSpec.describe DiscourseWorkflows::Workflow::Update do
+ describe described_class::Contract, type: :model do
+ it { is_expected.to validate_presence_of(:workflow_id) }
+ it { is_expected.to validate_presence_of(:name) }
+ it { is_expected.to validate_length_of(:name).is_at_most(100) }
+ end
+
+ describe ".call" do
+ subject(:result) { described_class.call(params:, **dependencies) }
+
+ fab!(:user, :admin)
+ fab!(:workflow) { Fabricate(:discourse_workflows_workflow, created_by: user) }
+
+ let(:params) do
+ attrs = { workflow_id: workflow.id, name:, error_workflow_id:, nodes:, connections: }
+ attrs[:timezone] = timezone unless timezone == :not_provided
+ attrs[:static_data] = static_data unless static_data == :not_provided
+ attrs
+ end
+ let(:dependencies) { { guardian: user.guardian } }
+ let(:name) { "Updated Workflow" }
+ let(:error_workflow_id) { nil }
+ let(:timezone) { :not_provided }
+ let(:static_data) { :not_provided }
+ let(:nodes) { [] }
+ let(:connections) { {} }
+
+ context "when contract is invalid" do
+ let(:name) { nil }
+
+ it { is_expected.to fail_a_contract }
+ end
+
+ context "when name is too long" do
+ let(:name) { "a" * 101 }
+
+ it { is_expected.to fail_a_contract }
+ end
+
+ context "when connections use an unsupported array shape" do
+ let(:connections) { [{ source_index: 0, target_index: 1 }] }
+
+ it { is_expected.to fail_a_step(:populate_graph) }
+ end
+
+ context "when nodes use unsupported JSON keys" do
+ let(:nodes) { [{ type: "trigger:manual", settings: {}, name: "Manual" }] }
+
+ it { is_expected.to fail_a_step(:populate_graph) }
+ end
+
+ context "when static_data uses a nested node bucket" do
+ let(:static_data) { { "node" => { "Manual" => {} } } }
+
+ it { is_expected.to fail_a_contract }
+ end
+
+ context "when static_data has a non-object slot" do
+ let(:static_data) { { "node:Manual" => "bad" } }
+
+ it { is_expected.to fail_a_contract }
+ end
+
+ context "when two nodes share the same name" do
+ let(:nodes) do
+ [
+ { id: "a", type: "trigger:manual", name: "Step" },
+ { id: "b", type: "action:log", name: "Step" },
+ ]
+ end
+
+ it { is_expected.to fail_a_step(:populate_graph) }
+ end
+
+ context "when two sticky notes share the same default name" do
+ let(:nodes) do
+ [
+ { id: "note-1", type: "flow:sticky_note", name: "Sticky Note" },
+ { id: "note-2", type: "flow:sticky_note", name: "Sticky Note" },
+ ]
+ end
+
+ it { is_expected.to run_successfully }
+ end
+
+ context "when workflow is not found" do
+ let(:params) { { workflow_id: -1, name: "Updated Workflow" } }
+
+ it { is_expected.to fail_to_find_a_model(:workflow) }
+ end
+
+ context "when user cannot manage workflows" do
+ fab!(:non_admin, :user)
+
+ let(:dependencies) { { guardian: non_admin.guardian } }
+
+ it { is_expected.to fail_a_policy(:can_manage_workflows) }
+ end
+
+ context "when error workflow is invalid" do
+ let(:error_workflow_id) { -1 }
+
+ it { is_expected.to fail_with_an_invalid_model(:workflow) }
+ end
+
+ context "when errorWorkflowId points to the workflow itself" do
+ let(:error_workflow_id) { workflow.id }
+
+ it { is_expected.to fail_with_an_invalid_model(:workflow) }
+ end
+
+ context "when error workflow is not provided" do
+ fab!(:error_workflow) { Fabricate(:discourse_workflows_workflow, created_by: user) }
+
+ let(:params) { { workflow_id: workflow.id, name:, nodes:, connections: } }
+
+ before { workflow.update!(error_workflow_id: error_workflow.id) }
+
+ it "preserves the existing error workflow" do
+ result
+
+ expect(workflow.reload.error_workflow_id).to eq(error_workflow.id)
+ end
+ end
+
+ context "when timezone is invalid" do
+ let(:timezone) { "Mars/Olympus" }
+
+ it { is_expected.to fail_a_contract }
+ end
+
+ context "when graph population fails" do
+ let(:nodes) { [{ id: "node_1", type: "trigger:manual", name: "Manual" }] }
+
+ before { DiscourseWorkflows::Workflow::Action::PopulateGraph.stubs(:call).returns(false) }
+
+ it { is_expected.to fail_a_step(:populate_graph) }
+ end
+
+ context "when no graph data is provided" do
+ let(:nodes) { nil }
+ let(:connections) { nil }
+
+ before do
+ extra = build_workflow_graph { |g| g.node "existing-1", "trigger:manual", name: "Existing" }
+ workflow.update!(nodes: extra[:nodes])
+ end
+
+ it { is_expected.to run_successfully }
+
+ it "preserves existing nodes" do
+ result
+ expect(workflow.reload.nodes.size).to eq(1)
+ end
+
+ context "when the workflow is already published" do
+ before { publish_workflow!(workflow) }
+
+ it "updates row-level metadata without creating a new snapshot" do
+ active_version_id = workflow.active_version_id
+ version_id = workflow.version_id
+
+ result
+ workflow.reload
+
+ expect(workflow.version_id).to eq(version_id)
+ expect(workflow.active_version_id).to eq(active_version_id)
+ expect(workflow.name).to eq("Updated Workflow")
+ end
+
+ it "does not mutate the active version metadata" do
+ active_version_id = workflow.active_version_id
+ active_version_name = workflow.active_version.name
+
+ result
+
+ expect(
+ DiscourseWorkflows::WorkflowVersion.find_by(version_id: active_version_id).name,
+ ).to eq(active_version_name)
+ end
+ end
+ end
+
+ context "when only static data is provided" do
+ let(:nodes) { nil }
+ let(:connections) { nil }
+ let(:static_data) do
+ { "global" => { "tenant_id" => "acme" }, "node:Existing" => { "cursor" => "abc" } }
+ end
+
+ before do
+ extra = build_workflow_graph { |g| g.node "existing-1", "trigger:manual", name: "Existing" }
+ workflow.update!(nodes: extra[:nodes])
+ end
+
+ it "updates static data without snapshotting graph state" do
+ version_id = workflow.version_id
+
+ result
+
+ expect(workflow.reload).to have_attributes(
+ static_data: JSON.parse(static_data.to_json),
+ version_id: version_id,
+ )
+ end
+ end
+
+ context "when graph data matches the current versioned payload" do
+ let(:name) { workflow.name }
+ let(:nodes) do
+ [
+ {
+ id: "node_1",
+ type: "trigger:manual",
+ typeVersion: "1.0",
+ name: "Manual",
+ position: {
+ x: 100,
+ y: 100,
+ },
+ parameters: {
+ },
+ credentials: {
+ },
+ webhookId: nil,
+ },
+ ]
+ end
+ let(:connections) { {} }
+
+ before do
+ workflow.update!(
+ nodes: [
+ {
+ "id" => "node_1",
+ "type" => "trigger:manual",
+ "typeVersion" => "1.0",
+ "name" => "Manual",
+ "position" => {
+ "x" => 100,
+ "y" => 100,
+ },
+ "parameters" => {
+ },
+ "credentials" => {
+ },
+ "webhookId" => nil,
+ },
+ ],
+ connections: {
+ },
+ )
+ publish_workflow!(workflow)
+ end
+
+ it { is_expected.to run_successfully }
+
+ it "does not create a draft version" do
+ active_version_id = workflow.active_version_id
+ version_id = workflow.version_id
+
+ expect { result }.not_to change {
+ DiscourseWorkflows::WorkflowVersion.where(workflow: workflow).count
+ }
+
+ workflow.reload
+ expect(workflow.version_id).to eq(version_id)
+ expect(workflow.active_version_id).to eq(active_version_id)
+ expect(workflow).not_to have_unpublished_changes
+ end
+ end
+
+ context "when everything's ok" do
+ before { publish_workflow!(workflow) }
+
+ let(:nodes) do
+ [
+ {
+ id: "node_1",
+ type: "trigger:topic_created",
+ name: "Topic Created",
+ parameters: {
+ category_id: 1,
+ },
+ },
+ {
+ id: "node_2",
+ type: "action:topic_tags",
+ name: "Topic Tags",
+ parameters: {
+ tag_names: "test",
+ },
+ },
+ ]
+ end
+ let(:connections) do
+ {
+ "Topic Created" => {
+ "main" => [[{ "node" => "Topic Tags", "type" => "main", "index" => 0 }]],
+ },
+ }
+ end
+
+ it { is_expected.to run_successfully }
+
+ it "updates the workflow attributes" do
+ result
+ workflow.reload
+ expect(workflow).to have_attributes(name: "Updated Workflow")
+ expect(workflow).to be_published
+ end
+
+ context "with a workflow timezone" do
+ let(:timezone) { "Europe/Paris" }
+
+ it "stores the timezone in workflow settings and the new snapshot" do
+ result
+
+ workflow.reload
+ expect(workflow.settings).to include("timezone" => "Europe/Paris")
+ snapshot = workflow.workflow_versions.find_by(version_id: workflow.version_id)
+ expect(snapshot.settings).to include("timezone" => "Europe/Paris")
+ end
+ end
+
+ it "populates the workflow graph" do
+ result
+ workflow.reload
+ expect(workflow.nodes.size).to eq(2)
+ expect(workflow.connections).to eq(
+ "Topic Created" => {
+ "main" => [[{ "node" => "Topic Tags", "type" => "main", "index" => 0 }]],
+ },
+ )
+ end
+
+ it "stamps a new version_id and snapshot, leaving active_version_id pinned" do
+ active_version_id = workflow.active_version_id
+ previous_version_id = workflow.version_id
+ result
+ workflow.reload
+ expect(workflow.version_id).not_to eq(previous_version_id)
+ expect(workflow.active_version_id).to eq(active_version_id)
+ expect(workflow).to have_unpublished_changes
+ expect(workflow.workflow_versions.where(version_id: workflow.version_id)).to exist
+ end
+
+ it "locks version creation for the workflow" do
+ DistributedMutex
+ .expects(:synchronize)
+ .with("discourse_workflows/workflow/update:workflow_id:#{workflow.id}")
+ .yields
+
+ result
+ end
+
+ it_behaves_like "expires workflow caches"
+
+ context "when graph data includes schedule triggers" do
+ let(:nodes) do
+ [
+ {
+ id: "node_1",
+ type: "trigger:schedule",
+ name: "Schedule",
+ parameters: {
+ rule: {
+ interval: [{ field: "minutes", minutesInterval: 5 }],
+ },
+ },
+ },
+ ]
+ end
+ let(:connections) { {} }
+
+ it "does not activate triggers before publishing" do
+ DiscourseWorkflows::TriggerRuntime.expects(:activate_workflow!).never
+ result
+ end
+ end
+ end
+ end
+end
diff --git a/plugins/discourse-workflows/spec/support/discourse_workflows_data_table_helpers.rb b/plugins/discourse-workflows/spec/support/discourse_workflows_data_table_helpers.rb
new file mode 100644
index 00000000000..61d79b1b7e1
--- /dev/null
+++ b/plugins/discourse-workflows/spec/support/discourse_workflows_data_table_helpers.rb
@@ -0,0 +1,40 @@
+# frozen_string_literal: true
+
+module DataTableHelpers
+ def data_table_facade(data_table)
+ DiscourseWorkflows::DataTables::Facade.new(data_table.reload)
+ end
+
+ def insert_data_table_row(data_table, data = {})
+ dt = data_table.reload
+ facade = DiscourseWorkflows::DataTables::Facade.new(dt)
+ facade.insert(facade.build_row_input(data: data, fill_missing: true))
+ end
+
+ def list_data_table_rows(data_table, **options)
+ facade = data_table_facade(data_table)
+ query =
+ facade.build_query(
+ filter: options[:normalized_filter],
+ limit: options[:limit],
+ offset: options[:offset],
+ sort_by: options[:sort_by],
+ sort_direction: options[:sort_direction],
+ optional_filter: true,
+ )
+
+ facade.query(query)
+ end
+
+ def count_data_table_rows(data_table, normalized_filter: nil)
+ facade = data_table_facade(data_table)
+ query = facade.build_query(filter: normalized_filter, optional_filter: true)
+ facade.count(query)
+ end
+
+ def find_data_table_row(data_table, row_id)
+ data_table_facade(data_table).find_row(row_id)
+ end
+end
+
+RSpec.configure { |config| config.include(DataTableHelpers) }
diff --git a/plugins/discourse-workflows/spec/support/node_execution_helpers.rb b/plugins/discourse-workflows/spec/support/node_execution_helpers.rb
new file mode 100644
index 00000000000..3958632d8be
--- /dev/null
+++ b/plugins/discourse-workflows/spec/support/node_execution_helpers.rb
@@ -0,0 +1,53 @@
+# frozen_string_literal: true
+
+module NodeExecutionHelpers
+ def execute_node_output(
+ configuration:,
+ item: nil,
+ input_items: nil,
+ input_groups: nil,
+ node_context: nil,
+ &block
+ )
+ item = { "json" => {} } if item.nil? && input_items.nil?
+ input_items = input_items || [item]
+ node_credentials = configuration.fetch("credentials") { {} }
+ node_parameters = configuration.except("credentials")
+ action = described_class.new(parameters: node_parameters, credentials: node_credentials)
+ resolver_context = { "$json" => input_items.first&.dig("json") || {} }
+ sandbox = DiscourseWorkflows::JsSandbox.new(resolver_context)
+ resolver = DiscourseWorkflows::ExpressionResolver.new(resolver_context, sandbox: sandbox)
+ kwargs = {
+ input_items: input_items,
+ input_groups: input_groups,
+ resolver: resolver,
+ parameters: node_parameters,
+ credentials: node_credentials,
+ property_schema: described_class.property_schema,
+ credential_schema: described_class.credentials,
+ node_identifier: described_class.identifier,
+ resolver_context: resolver_context,
+ }
+ kwargs[:node_context] = node_context if node_context
+
+ ctx = DiscourseWorkflows::Executor::NodeExecutionContext.new(**kwargs)
+ output_arrays = action.execute(ctx)
+ DiscourseWorkflows::ItemContract.validate_output_arrays!(
+ output_arrays,
+ source: described_class.name,
+ ports: described_class.ports(node_parameters),
+ )
+ block&.call(ctx)
+ output_arrays
+ ensure
+ resolver&.dispose
+ sandbox&.dispose
+ end
+
+ def execute_node(configuration:, item: { "json" => {} })
+ result = execute_node_output(configuration: configuration, item: item)
+ result.first.first["json"]
+ end
+end
+
+RSpec.configure { |config| config.include NodeExecutionHelpers }
diff --git a/plugins/discourse-workflows/spec/support/shared_examples/expires_workflow_caches.rb b/plugins/discourse-workflows/spec/support/shared_examples/expires_workflow_caches.rb
new file mode 100644
index 00000000000..a4f3604c456
--- /dev/null
+++ b/plugins/discourse-workflows/spec/support/shared_examples/expires_workflow_caches.rb
@@ -0,0 +1,8 @@
+# frozen_string_literal: true
+
+RSpec.shared_examples "expires workflow caches" do
+ it "expires workflow caches" do
+ DiscourseWorkflows::Workflow::Action::ExpireCaches.expects(:call).once
+ result
+ end
+end
diff --git a/plugins/discourse-workflows/spec/support/wait_handler_helpers.rb b/plugins/discourse-workflows/spec/support/wait_handler_helpers.rb
new file mode 100644
index 00000000000..82b3b1338d0
--- /dev/null
+++ b/plugins/discourse-workflows/spec/support/wait_handler_helpers.rb
@@ -0,0 +1,53 @@
+# frozen_string_literal: true
+
+module WaitHandlerHelpers
+ def build_wait_dependencies(execution, node_type:, configuration: {}, context: {})
+ waiting_step =
+ DiscourseWorkflows::Executor::Step.new(
+ node_id: "wait-1",
+ node_name: "Wait",
+ node_type: node_type,
+ position: 0,
+ input: [],
+ )
+ waiting_node =
+ DiscourseWorkflows::WorkflowSnapshot::SnapshotNode.new(
+ id: "wait-1",
+ type: node_type,
+ typeVersion: "1.0",
+ name: "Wait",
+ position: {
+ "x" => 0,
+ "y" => 0,
+ },
+ configuration: configuration,
+ )
+ persistence =
+ instance_double(DiscourseWorkflows::Executor::ExecutionStore, execution: execution)
+ allow(persistence).to receive(
+ :pause_waiting_execution!,
+ ) do |node:, waiting_until: nil, steps: []|
+ execution.update!(
+ status: :waiting,
+ waiting_node_id: node.id,
+ waiting_until: waiting_until,
+ resume_token: context["__resume_token"],
+ )
+ execution
+ end
+
+ {
+ persistence: persistence,
+ context:
+ instance_double(
+ DiscourseWorkflows::Executor::ExecutionContext,
+ resume_token: context["__resume_token"],
+ ),
+ node: waiting_node,
+ step: waiting_step,
+ steps: [],
+ }
+ end
+end
+
+RSpec.configure { |config| config.include WaitHandlerHelpers }
diff --git a/plugins/discourse-workflows/spec/support/workflow_graph_builder.rb b/plugins/discourse-workflows/spec/support/workflow_graph_builder.rb
new file mode 100644
index 00000000000..7f291e4a68f
--- /dev/null
+++ b/plugins/discourse-workflows/spec/support/workflow_graph_builder.rb
@@ -0,0 +1,157 @@
+# frozen_string_literal: true
+
+module DiscourseWorkflows
+ class WorkflowGraphBuilder
+ def initialize
+ @nodes = []
+ @connections = {}
+ @position_counter = 0
+ end
+
+ def node(
+ id,
+ type,
+ name: nil,
+ parameters: nil,
+ credentials: {},
+ webhook_id: nil,
+ position: nil,
+ configuration: {}
+ )
+ configuration = configuration.deep_stringify_keys
+ webhook_id ||=
+ configuration.delete("uuid") if DiscourseWorkflows::NodeDataShape.form_trigger?(type)
+ node_level_settings = DiscourseWorkflows::NodeData.direct_settings(configuration)
+ direct_setting_keys = DiscourseWorkflows::NodeData::NODE_DIRECT_SETTING_KEYS.keys
+ parameters ||= configuration.except(*direct_setting_keys)
+ split =
+ DiscourseWorkflows::NodeData.split(
+ parameters: parameters,
+ credentials: credentials,
+ webhook_id: webhook_id,
+ node_type: registered_node_type(type) || type,
+ )
+
+ node = {
+ "id" => id,
+ "type" => type,
+ "typeVersion" => "1.0",
+ "name" => name || id.to_s.humanize,
+ "position" => position || { "x" => @position_counter * 220, "y" => 0 },
+ "parameters" => split["parameters"],
+ "credentials" => split["credentials"],
+ "webhookId" => split["webhookId"],
+ }
+
+ @nodes << node.merge(node_level_settings)
+ @position_counter += 1
+ self
+ end
+
+ def connect(source, target, output: "main", input: "main")
+ source_node = @nodes.find { |node| node["id"] == source }
+ target_node = @nodes.find { |node| node["id"] == target }
+ return self if source_node.blank? || target_node.blank?
+
+ source_name = source_node["name"]
+ @connections[source_name] ||= {}
+ @connections[source_name]["main"] ||= []
+ source_output_index = connection_index(output)
+ while @connections[source_name]["main"].length <= source_output_index
+ @connections[source_name]["main"] << []
+ end
+ @connections[source_name]["main"][source_output_index] << {
+ "node" => target_node["name"],
+ "type" => "main",
+ "index" => connection_index(input),
+ }
+ self
+ end
+
+ def chain(*node_ids, output: "main")
+ node_ids.each_cons(2) { |source, target| connect(source, target, output: output) }
+ self
+ end
+
+ def to_h
+ { nodes: @nodes, connections: @connections }
+ end
+
+ private
+
+ def registered_node_type(type)
+ DiscourseWorkflows::NodeType.registered_nodes.find { _1.description[:name] == type }
+ end
+
+ def connection_index(value)
+ value = value.to_s
+ return 0 if value.blank? || value == "main" || value == "true" || value == "done"
+
+ match = value.match(/\Ainput_(\d+)\z/)
+ return match[1].to_i - 1 if match
+
+ return 1 if %w[false loop].include?(value)
+
+ value.to_i
+ end
+ end
+end
+
+def build_workflow_graph
+ builder = DiscourseWorkflows::WorkflowGraphBuilder.new
+ yield builder
+ builder.to_h
+end
+
+def workflow_connections_for(nodes, *edges)
+ nodes_by_id = nodes.index_by { |node| node["id"].to_s }
+
+ edges.each_with_object({}) do |edge, connections|
+ source_id, target_id, source_output_index, target_input_index = edge
+ source_node = nodes_by_id[source_id.to_s]
+ target_node = nodes_by_id[target_id.to_s]
+ next if source_node.blank? || target_node.blank?
+
+ connections[source_node["name"]] ||= {}
+ connections[source_node["name"]]["main"] ||= []
+ source_output_index = source_output_index.to_i
+ while connections[source_node["name"]]["main"].length <= source_output_index
+ connections[source_node["name"]]["main"] << []
+ end
+ connections[source_node["name"]]["main"][source_output_index] << {
+ "node" => target_node["name"],
+ "type" => "main",
+ "index" => target_input_index.to_i,
+ }
+ end
+end
+
+def workflow_nodes_with_update(workflow, node_id)
+ workflow.nodes.map do |workflow_node|
+ node = workflow_node.deep_dup
+ next node unless node["id"] == node_id
+
+ updated_node = yield node
+ updated_node.is_a?(Hash) ? updated_node : node
+ end
+end
+
+def update_workflow_node(workflow, node_id, &block)
+ workflow.update!(nodes: workflow_nodes_with_update(workflow, node_id, &block))
+end
+
+def publish_workflow!(workflow)
+ version = workflow.snapshot!(user: workflow.created_by)
+ workflow.update!(active_version_id: workflow.version_id)
+ DiscourseWorkflows::WorkflowDependencyIndexer.call(workflow, version:)
+ DiscourseWorkflows::Webhook::Action::ActivateWebhooks.call(
+ workflow: workflow,
+ workflow_version: version,
+ )
+ workflow.reload
+end
+
+def unpublish_workflow!(workflow)
+ workflow.update!(active_version_id: nil)
+ DiscourseWorkflows::Webhook::Action::DeactivateWebhooks.call(workflow: workflow)
+end
diff --git a/plugins/discourse-workflows/spec/system/credentials_spec.rb b/plugins/discourse-workflows/spec/system/credentials_spec.rb
new file mode 100644
index 00000000000..f57435bbc99
--- /dev/null
+++ b/plugins/discourse-workflows/spec/system/credentials_spec.rb
@@ -0,0 +1,21 @@
+# frozen_string_literal: true
+
+RSpec.describe "Discourse Workflows - Credentials" do
+ fab!(:admin)
+
+ let(:credentials_page) { PageObjects::Pages::DiscourseWorkflows::Credentials.new }
+
+ before { sign_in(admin) }
+
+ it "creates a new credential" do
+ credentials_page.visit_index
+ credentials_page.click_add_credential
+ credentials_page.fill_credential_name("production_auth")
+ credentials_page.select_credential_type("Basic Auth")
+ credentials_page.fill_credential_field("user", "alice")
+ credentials_page.fill_credential_field("password", "secret123")
+ credentials_page.submit_credential_modal
+
+ expect(credentials_page).to have_credential("production_auth")
+ end
+end
diff --git a/plugins/discourse-workflows/spec/system/data_tables_spec.rb b/plugins/discourse-workflows/spec/system/data_tables_spec.rb
new file mode 100644
index 00000000000..96afff071d4
--- /dev/null
+++ b/plugins/discourse-workflows/spec/system/data_tables_spec.rb
@@ -0,0 +1,35 @@
+# frozen_string_literal: true
+
+RSpec.describe "Discourse Workflows - Data Tables" do
+ fab!(:admin)
+
+ let(:data_tables_page) { PageObjects::Pages::DiscourseWorkflows::DataTables.new }
+
+ before { sign_in(admin) }
+
+ it "shows existing data tables" do
+ data_table = Fabricate(:discourse_workflows_data_table, name: "users_cache")
+
+ data_tables_page.visit_index
+
+ expect(data_tables_page).to have_data_table("users_cache")
+ end
+
+ it "creates a new data table and navigates to its viewer" do
+ data_tables_page.visit_index
+ data_tables_page.click_add_data_table
+ data_tables_page.fill_data_table_name("my_table")
+ data_tables_page.submit_data_table_modal
+
+ expect(data_tables_page).to have_viewer
+ end
+
+ it "adds a row to the data table" do
+ data_table = Fabricate(:discourse_workflows_data_table, name: "events")
+
+ data_tables_page.visit_show(data_table.id)
+ data_tables_page.click_add_row
+
+ expect(data_tables_page).to have_row(count: 1)
+ end
+end
diff --git a/plugins/discourse-workflows/spec/system/executions_spec.rb b/plugins/discourse-workflows/spec/system/executions_spec.rb
new file mode 100644
index 00000000000..d7da4512c18
--- /dev/null
+++ b/plugins/discourse-workflows/spec/system/executions_spec.rb
@@ -0,0 +1,34 @@
+# frozen_string_literal: true
+
+RSpec.describe "Discourse Workflows - Executions" do
+ fab!(:admin)
+ fab!(:workflow) { Fabricate(:discourse_workflows_workflow, created_by: admin) }
+
+ let(:executions_page) { PageObjects::Pages::DiscourseWorkflows::Executions.new }
+
+ before { sign_in(admin) }
+
+ it "lists executions with their status" do
+ Fabricate(:discourse_workflows_completed_execution, workflow: workflow)
+
+ executions_page.visit_index
+
+ expect(executions_page).to have_execution_with_status("success")
+ end
+
+ it "shows the execution detail view with steps" do
+ execution = Fabricate(:discourse_workflows_completed_execution, workflow: workflow)
+ Fabricate(
+ :discourse_workflows_execution_data_with_steps,
+ execution: execution,
+ node_name: "Manual Trigger",
+ node_type: "trigger:manual",
+ step_status: "success",
+ )
+
+ executions_page.visit_detail(workflow.id, execution.id)
+
+ expect(executions_page).to have_detail
+ expect(executions_page).to have_step("Manual Trigger")
+ end
+end
diff --git a/plugins/discourse-workflows/spec/system/expression_editor_spec.rb b/plugins/discourse-workflows/spec/system/expression_editor_spec.rb
new file mode 100644
index 00000000000..f13c6b63c87
--- /dev/null
+++ b/plugins/discourse-workflows/spec/system/expression_editor_spec.rb
@@ -0,0 +1,183 @@
+# frozen_string_literal: true
+
+RSpec.describe "Workflow Expression Editor" do
+ fab!(:admin)
+
+ let(:editor_page) { PageObjects::Pages::DiscourseWorkflows::WorkflowEditor.new }
+ let(:expression_editor) { PageObjects::Pages::DiscourseWorkflows::ExpressionEditor.new }
+
+ before { sign_in(admin) }
+
+ def open_create_post_configurator
+ editor_page.visit_new
+ editor_page.click_empty_state_add_node
+ editor_page.select_node_type("trigger:topic_created")
+ editor_page.click_add_node
+ editor_page.select_node_type("action:create_post")
+ editor_page.double_click_node(1)
+ end
+
+ def open_expression_editor
+ open_create_post_configurator
+ expression_editor.switch_to_expression_mode
+ end
+
+ context "when editing a node with expression fields" do
+ before { open_expression_editor }
+
+ it "shows the CodeMirror editor in expression mode" do
+ expect(expression_editor).to have_expression_editor
+ end
+
+ it "shows dollar variable completions on Ctrl+Space" do
+ expression_editor.type_in_editor("{{ ")
+ expression_editor.trigger_autocomplete
+
+ expect(expression_editor).to have_autocomplete_dropdown
+ expect(expression_editor).to have_autocomplete_option("$json")
+ expect(expression_editor).to have_autocomplete_option("$execution")
+ expect(expression_editor).to have_autocomplete_option("$vars")
+ end
+
+ it "shows completions when typing $ inside expression braces" do
+ expression_editor.type_in_editor("{{ $")
+
+ expect(expression_editor).to have_autocomplete_dropdown
+ expect(expression_editor).to have_autocomplete_option("$json")
+ expect(expression_editor).to have_autocomplete_option("$vars")
+ end
+
+ it "auto-closes {{ }} and triggers completions" do
+ expression_editor.type_in_editor("{{")
+
+ expect(expression_editor).to have_autocomplete_dropdown
+ end
+
+ it "shows global completions for Math, JSON, etc." do
+ expression_editor.type_in_editor("{{ Ma")
+
+ expect(expression_editor).to have_autocomplete_dropdown
+ expect(expression_editor).to have_autocomplete_option("Math")
+ end
+
+ it "marks unclosed expressions with error decoration" do
+ expression_editor.type_in_editor("{{ $json.title")
+ expression_editor.move_cursor_and_delete(3, 2)
+
+ expect(expression_editor).to have_syntax_error
+ end
+
+ it "removes error decoration when expression is closed" do
+ expression_editor.type_in_editor("{{ $json.title")
+
+ expect(expression_editor).to have_no_syntax_error
+ end
+
+ it "applies syntax highlighting to expression braces" do
+ expression_editor.type_in_editor("{{ $json.title")
+
+ expect(expression_editor).to have_syntax_highlight("cm-wf-brace")
+ end
+ end
+
+ context "when typing in expression mode" do
+ before { open_expression_editor }
+
+ it "updates the field value as the user types" do
+ expression_editor.type_in_editor("hello world")
+
+ text = expression_editor.editor_text
+ expect(text).to include("hello world")
+ end
+ end
+
+ context "with workflow variables" do
+ fab!(:variable) { Fabricate(:discourse_workflows_variable, key: "API_KEY", value: "secret123") }
+
+ before { open_expression_editor }
+
+ it "shows $vars in completions" do
+ expression_editor.type_in_editor("{{ $v")
+
+ expect(expression_editor).to have_autocomplete_dropdown
+ expect(expression_editor).to have_autocomplete_option("$vars")
+ end
+ end
+
+ context "with hover tooltips" do
+ before { open_expression_editor }
+
+ it "shows a tooltip when hovering over a dollar variable" do
+ expression_editor.type_in_editor("{{ $json }}")
+
+ expression_editor.hover_variable("$json")
+
+ expect(expression_editor).to have_hover_tooltip
+ expect(expression_editor.hover_tooltip_text).to include("current input item")
+ end
+ end
+
+ context "with expression preview" do
+ before { open_expression_editor }
+
+ it "shows a resolved preview below the editor" do
+ expression_editor.type_in_editor("{{ $current_user.username }}")
+
+ expect(expression_editor).to have_expression_preview
+ expect(expression_editor).to have_expression_preview_result("valid", text: admin.username)
+ end
+
+ it "shows invalid JavaScript for bad expressions" do
+ expression_editor.type_in_editor("{{ $vars. }}")
+
+ expect(expression_editor).to have_expression_preview
+ expect(expression_editor).to have_expression_preview_result(
+ "invalid",
+ text: "Invalid JavaScript",
+ )
+ end
+
+ it "shows plain text result for non-expression content" do
+ expression_editor.type_in_editor("Hello world")
+
+ expect(expression_editor).to have_expression_preview
+ expect(expression_editor).to have_expression_preview_plaintext("Hello world")
+ end
+
+ it "shows function warning when a method is referenced without calling it" do
+ expression_editor.type_in_editor("{{ $current_user.username.includes }}")
+
+ expect(expression_editor).to have_expression_preview
+ expect(expression_editor).to have_expression_preview_result(
+ "warning",
+ text: "Missing function call",
+ )
+ end
+
+ it "highlights invalid expressions in the editor with red background" do
+ expression_editor.type_in_editor("{{ $vars. }}")
+
+ expect(page).to have_css(".cm-wf-invalid-expression", wait: 10)
+ end
+ end
+
+ context "with property access completions" do
+ before { open_expression_editor }
+
+ it "shows field completions after $execution." do
+ expression_editor.type_in_editor("{{ $execution.")
+
+ expect(expression_editor).to have_autocomplete_dropdown
+ expect(expression_editor).to have_autocomplete_option("id")
+ expect(expression_editor).to have_autocomplete_option("workflow_id")
+ end
+
+ it "shows static method completions for global objects" do
+ expression_editor.type_in_editor("{{ Object.")
+
+ expect(expression_editor).to have_autocomplete_dropdown
+ expect(expression_editor).to have_autocomplete_option("keys")
+ expect(expression_editor).to have_autocomplete_option("values")
+ end
+ end
+end
diff --git a/plugins/discourse-workflows/spec/system/form_trigger_spec.rb b/plugins/discourse-workflows/spec/system/form_trigger_spec.rb
new file mode 100644
index 00000000000..f7b9102d289
--- /dev/null
+++ b/plugins/discourse-workflows/spec/system/form_trigger_spec.rb
@@ -0,0 +1,57 @@
+# frozen_string_literal: true
+
+RSpec.describe "Discourse Workflows - Form Trigger" do
+ FORM_UUID = "a1b2c3d4-e5f6-7890-abcd-ef0123456789"
+
+ let(:form_trigger_page) { PageObjects::Pages::DiscourseWorkflows::FormTrigger.new }
+
+ fab!(:workflow) do
+ Fabricate(
+ :discourse_workflows_workflow,
+ published: true,
+ nodes: [
+ {
+ "id" => "trigger-1",
+ "type" => "trigger:form",
+ "typeVersion" => "1.0",
+ "name" => "Form Trigger",
+ "position" => {
+ "x" => 0,
+ "y" => 0,
+ },
+ "parameters" => {
+ "form_title" => "Contact Us",
+ "form_fields" => [
+ { "field_label" => "Your name", "field_type" => "text", "required" => true },
+ ],
+ "response_mode" => "on_received",
+ "authentication" => "none",
+ },
+ "credentials" => {
+ },
+ "webhookId" => FORM_UUID,
+ },
+ ],
+ connections: {
+ },
+ )
+ end
+
+ before { DiscourseWorkflows::WorkflowDependencyIndexer.call(workflow) }
+
+ it "renders the public form" do
+ form_trigger_page.visit(FORM_UUID)
+
+ expect(form_trigger_page).to have_workflows_form
+ expect(form_trigger_page).to have_form_title("Contact Us")
+ expect(form_trigger_page).to have_form_field("your_name")
+ end
+
+ it "submits the form and shows completion" do
+ form_trigger_page.visit(FORM_UUID)
+
+ form_trigger_page.fill_field("your_name", "Alice").submit
+
+ expect(form_trigger_page).to have_completion
+ end
+end
diff --git a/plugins/discourse-workflows/spec/system/page_objects/pages/credentials.rb b/plugins/discourse-workflows/spec/system/page_objects/pages/credentials.rb
new file mode 100644
index 00000000000..71d5d225d55
--- /dev/null
+++ b/plugins/discourse-workflows/spec/system/page_objects/pages/credentials.rb
@@ -0,0 +1,51 @@
+# frozen_string_literal: true
+
+module PageObjects
+ module Pages
+ module DiscourseWorkflows
+ class Credentials < PageObjects::Pages::Base
+ def visit_index
+ page.visit("/admin/plugins/discourse-workflows/credentials")
+ self
+ end
+
+ def has_credential?(name)
+ page.has_css?("td", text: name)
+ end
+
+ def has_no_credentials?
+ page.has_css?(".workflows-empty-state")
+ end
+
+ def click_add_credential
+ if page.has_css?(".workflows-empty-state", wait: 5)
+ find(".workflows-empty-state .btn-primary").click
+ else
+ find(".workflows-admin-table__toolbar .btn-primary").click
+ end
+ self
+ end
+
+ def fill_credential_name(name)
+ find(".d-modal input[name='name']").fill_in(with: name)
+ self
+ end
+
+ def select_credential_type(type)
+ find(".d-modal select[name='credential_type']").select(type)
+ self
+ end
+
+ def fill_credential_field(name, value)
+ find(".d-modal input[name='#{name}']").fill_in(with: value)
+ self
+ end
+
+ def submit_credential_modal
+ find(".d-modal .btn-primary[type='submit']").click
+ self
+ end
+ end
+ end
+ end
+end
diff --git a/plugins/discourse-workflows/spec/system/page_objects/pages/data_tables.rb b/plugins/discourse-workflows/spec/system/page_objects/pages/data_tables.rb
new file mode 100644
index 00000000000..65f1d899ce2
--- /dev/null
+++ b/plugins/discourse-workflows/spec/system/page_objects/pages/data_tables.rb
@@ -0,0 +1,67 @@
+# frozen_string_literal: true
+
+module PageObjects
+ module Pages
+ module DiscourseWorkflows
+ class DataTables < PageObjects::Pages::Base
+ def visit_index
+ page.visit("/admin/plugins/discourse-workflows/data-tables")
+ self
+ end
+
+ def visit_show(id)
+ page.visit("/admin/plugins/discourse-workflows/data-tables/#{id}")
+ self
+ end
+
+ def has_data_table?(name)
+ page.has_css?(".d-table__overview-name", text: name)
+ end
+
+ def has_no_data_table?(name)
+ page.has_no_css?(".d-table__overview-name", text: name)
+ end
+
+ def click_add_data_table
+ if page.has_css?(".workflows-empty-state", wait: 5)
+ find(".workflows-empty-state .btn-primary").click
+ else
+ find(".workflows-admin-table__toolbar .btn-primary").click
+ end
+ self
+ end
+
+ def fill_data_table_name(name)
+ find(".data-table-modal input[name='name']").fill_in(with: name)
+ self
+ end
+
+ def submit_data_table_modal
+ find(".data-table-modal .btn-primary[type='submit']").click
+ self
+ end
+
+ def has_viewer?
+ page.has_css?(".workflows-data-table-viewer")
+ end
+
+ def has_add_row_button?
+ page.has_css?(".workflows-data-table-viewer__add-row")
+ end
+
+ def has_row?(count: nil)
+ if count
+ page.has_css?(".workflows-data-table-viewer__row", count: count)
+ else
+ page.has_css?(".workflows-data-table-viewer__row")
+ end
+ end
+
+ def click_add_row
+ find(".workflows-data-table-viewer__add-row .btn-transparent").click
+ self
+ end
+ end
+ end
+ end
+end
diff --git a/plugins/discourse-workflows/spec/system/page_objects/pages/executions.rb b/plugins/discourse-workflows/spec/system/page_objects/pages/executions.rb
new file mode 100644
index 00000000000..6521fb8b18e
--- /dev/null
+++ b/plugins/discourse-workflows/spec/system/page_objects/pages/executions.rb
@@ -0,0 +1,37 @@
+# frozen_string_literal: true
+
+module PageObjects
+ module Pages
+ module DiscourseWorkflows
+ class Executions < PageObjects::Pages::Base
+ def visit_index
+ page.visit("/admin/plugins/discourse-workflows/executions")
+ self
+ end
+
+ def visit_detail(workflow_id, execution_id)
+ page.visit(
+ "/admin/plugins/discourse-workflows/workflows/#{workflow_id}/executions/#{execution_id}",
+ )
+ self
+ end
+
+ def has_execution_with_status?(status)
+ page.has_css?(".workflows-executions-manager__status.--#{status}")
+ end
+
+ def has_no_executions?
+ page.has_css?(".workflows-empty-state")
+ end
+
+ def has_detail?
+ page.has_css?(".workflows-execution-detail")
+ end
+
+ def has_step?(name)
+ page.has_css?(".workflows-execution-detail__step-name", text: name)
+ end
+ end
+ end
+ end
+end
diff --git a/plugins/discourse-workflows/spec/system/page_objects/pages/expression_editor.rb b/plugins/discourse-workflows/spec/system/page_objects/pages/expression_editor.rb
new file mode 100644
index 00000000000..afa5460939a
--- /dev/null
+++ b/plugins/discourse-workflows/spec/system/page_objects/pages/expression_editor.rb
@@ -0,0 +1,132 @@
+# frozen_string_literal: true
+
+module PageObjects
+ module Pages
+ module DiscourseWorkflows
+ class ExpressionEditor < PageObjects::Pages::Base
+ VARIABLE_INPUT_SELECTOR = ".workflows-variable-input"
+ CM_EDITOR_SELECTOR = ".cm-editor"
+ CM_CONTENT_SELECTOR = ".cm-content"
+ AUTOCOMPLETE_SELECTOR = ".cm-tooltip-autocomplete"
+ HOVER_TOOLTIP_SELECTOR = ".cm-wf-hover-tooltip"
+ MODE_CONTROL_SELECTOR = ".workflows-property-engine__mode-control"
+ PREVIEW_SELECTOR = ".expression-preview"
+
+ def switch_to_expression_mode
+ label =
+ find(
+ "#{MODE_CONTROL_SELECTOR} input.d-segmented-control__input[value='dynamic']",
+ match: :first,
+ ).ancestor(".d-segmented-control__label")
+ label.click
+ self
+ end
+
+ def has_expression_editor?
+ page.has_css?(CM_EDITOR_SELECTOR)
+ end
+
+ def has_no_expression_editor?
+ page.has_no_css?(CM_EDITOR_SELECTOR)
+ end
+
+ def type_in_editor(text)
+ cm_content.click
+ cm_content.send_keys(text)
+ self
+ end
+
+ def editor_text
+ cm_content.text
+ end
+
+ def trigger_autocomplete
+ cm_content.send_keys([:control, " "])
+ self
+ end
+
+ def move_cursor_and_delete(right_count, backspace_count)
+ keys = Array.new(right_count, :right) + Array.new(backspace_count, :backspace)
+ cm_content.send_keys(*keys)
+ self
+ end
+
+ def has_autocomplete_dropdown?
+ page.has_css?(AUTOCOMPLETE_SELECTOR, wait: 5)
+ end
+
+ def has_no_autocomplete_dropdown?
+ page.has_no_css?(AUTOCOMPLETE_SELECTOR)
+ end
+
+ def autocomplete_options
+ all("#{AUTOCOMPLETE_SELECTOR} li[role='option']").map(&:text)
+ end
+
+ def has_autocomplete_option?(label)
+ page.has_css?("#{AUTOCOMPLETE_SELECTOR} li[role='option']", text: label, wait: 5)
+ end
+
+ def has_no_autocomplete_option?(label)
+ page.has_no_css?("#{AUTOCOMPLETE_SELECTOR} li[role='option']", text: label)
+ end
+
+ def select_autocomplete_option(label)
+ find("#{AUTOCOMPLETE_SELECTOR} li[role='option']", text: label).click
+ self
+ end
+
+ def has_syntax_error?
+ page.has_css?(".cm-wf-error")
+ end
+
+ def has_no_syntax_error?
+ page.has_no_css?(".cm-wf-error")
+ end
+
+ def has_syntax_highlight?(css_class)
+ page.has_css?(".cm-editor .#{css_class}")
+ end
+
+ def has_no_syntax_highlight?(css_class)
+ page.has_no_css?(".cm-editor .#{css_class}")
+ end
+
+ def has_hover_tooltip?
+ page.has_css?(HOVER_TOOLTIP_SELECTOR, wait: 5)
+ end
+
+ def hover_variable(name)
+ find(".cm-wf-variable", text: name, wait: 5).hover
+ self
+ end
+
+ def has_no_hover_tooltip?
+ page.has_no_css?(HOVER_TOOLTIP_SELECTOR)
+ end
+
+ def hover_tooltip_text
+ find(HOVER_TOOLTIP_SELECTOR).text
+ end
+
+ def has_expression_preview?
+ page.has_css?(PREVIEW_SELECTOR, wait: 10)
+ end
+
+ def has_expression_preview_result?(state, text:)
+ page.has_css?("#{PREVIEW_SELECTOR}__resolved.--#{state}", text: text)
+ end
+
+ def has_expression_preview_plaintext?(text)
+ page.has_css?("#{PREVIEW_SELECTOR}__plaintext", text: text)
+ end
+
+ private
+
+ def cm_content
+ find(CM_CONTENT_SELECTOR)
+ end
+ end
+ end
+ end
+end
diff --git a/plugins/discourse-workflows/spec/system/page_objects/pages/form_trigger.rb b/plugins/discourse-workflows/spec/system/page_objects/pages/form_trigger.rb
new file mode 100644
index 00000000000..20533391a53
--- /dev/null
+++ b/plugins/discourse-workflows/spec/system/page_objects/pages/form_trigger.rb
@@ -0,0 +1,40 @@
+# frozen_string_literal: true
+
+module PageObjects
+ module Pages
+ module DiscourseWorkflows
+ class FormTrigger < PageObjects::Pages::Base
+ def visit(uuid)
+ page.visit("/workflows/form/#{uuid}")
+ self
+ end
+
+ def has_workflows_form?
+ page.has_css?(".workflows-form")
+ end
+
+ def has_form_title?(title)
+ page.has_css?(".workflows-form__title", text: title)
+ end
+
+ def has_form_field?(name)
+ page.has_css?("input[name='#{name}']")
+ end
+
+ def fill_field(name, value)
+ find("input[name='#{name}']").fill_in(with: value)
+ self
+ end
+
+ def submit
+ find(".workflows-form .btn-primary[type='submit']").click
+ self
+ end
+
+ def has_completion?
+ page.has_css?(".workflows-form__complete")
+ end
+ end
+ end
+ end
+end
diff --git a/plugins/discourse-workflows/spec/system/page_objects/pages/variables.rb b/plugins/discourse-workflows/spec/system/page_objects/pages/variables.rb
new file mode 100644
index 00000000000..8fede8351a3
--- /dev/null
+++ b/plugins/discourse-workflows/spec/system/page_objects/pages/variables.rb
@@ -0,0 +1,50 @@
+# frozen_string_literal: true
+
+module PageObjects
+ module Pages
+ module DiscourseWorkflows
+ class Variables < PageObjects::Pages::Base
+ def visit_index
+ page.visit("/admin/plugins/discourse-workflows/variables")
+ self
+ end
+
+ def has_variable?(key)
+ page.has_css?("td", text: key)
+ end
+
+ def has_variable_creator?(username)
+ page.has_css?(".workflows-variables__creator[href$='/u/#{username}']", text: username)
+ end
+
+ def has_no_variables?
+ page.has_css?(".workflows-empty-state")
+ end
+
+ def click_add_variable
+ if page.has_css?(".workflows-empty-state", wait: 5)
+ find(".workflows-empty-state .btn-primary").click
+ else
+ find(".workflows-admin-table__toolbar .btn-primary").click
+ end
+ self
+ end
+
+ def fill_variable_key(key)
+ find(".d-modal input[name='key']").fill_in(with: key)
+ self
+ end
+
+ def fill_variable_value(value)
+ find(".d-modal input[name='value']").fill_in(with: value)
+ self
+ end
+
+ def submit_variable_modal
+ find(".d-modal .btn-primary[type='submit']").click
+ self
+ end
+ end
+ end
+ end
+end
diff --git a/plugins/discourse-workflows/spec/system/page_objects/pages/workflow_editor.rb b/plugins/discourse-workflows/spec/system/page_objects/pages/workflow_editor.rb
new file mode 100644
index 00000000000..5a1ca5411bf
--- /dev/null
+++ b/plugins/discourse-workflows/spec/system/page_objects/pages/workflow_editor.rb
@@ -0,0 +1,139 @@
+# frozen_string_literal: true
+
+module PageObjects
+ module Pages
+ module DiscourseWorkflows
+ class WorkflowEditor < PageObjects::Pages::Base
+ def visit_new
+ page.visit("/admin/plugins/discourse-workflows/workflows/new")
+ self
+ end
+
+ def visit(workflow_id)
+ page.visit("/admin/plugins/discourse-workflows/workflows/#{workflow_id}")
+ self
+ end
+
+ def close_node_configurator
+ find(".workflows-configurator-modal__close").click
+ self
+ end
+
+ def has_node_configurator?
+ page.has_css?(".workflows-configurator-modal")
+ end
+
+ def has_no_node_configurator?
+ page.has_no_css?(".workflows-configurator-modal")
+ end
+
+ def edit_name(name)
+ find(".workflows-editable-title__text").click
+ find(".workflows-editable-title__input").fill_in(with: name)
+ find(".workflows-editable-title__input").send_keys(:return)
+ self
+ end
+
+ def has_node_count?(count)
+ page.has_css?(".workflow-rete-node", count: count)
+ end
+
+ def has_no_node_count?(count)
+ page.has_no_css?(".workflow-rete-node", count: count)
+ end
+
+ def has_node?(label)
+ page.has_css?(".workflow-rete-node__label", text: label)
+ end
+
+ def click_add_node
+ find(".workflows-canvas__add-node-btn").click
+ self
+ end
+
+ def click_empty_state_add_node
+ first(".workflows-canvas__empty-state-trigger").click
+ self
+ end
+
+ def has_empty_state_add_node?
+ page.has_css?(".workflows-canvas__empty-state-trigger")
+ end
+
+ NODE_TYPE_LABELS = {
+ "trigger:topic_closed" => "Topic closed",
+ "trigger:post_created" => "Post created",
+ "trigger:topic_created" => "Topic created",
+ "trigger:webhook" => "Webhook",
+ "trigger:manual" => "Manual trigger",
+ "trigger:stale_topic" => "Stale topic",
+ "trigger:schedule" => "Schedule",
+ "condition:if" => "If",
+ "condition:filter" => "Filter",
+ "action:topic_tags" => "Topic tags",
+ "action:code" => "Code",
+ "action:topic" => "Topic",
+ "action:create_post" => "Create post",
+ "action:set_fields" => "Set fields",
+ "action:split_out" => "Split Out",
+ "action:http_request" => "HTTP Request",
+ "action:data_table" => "Data Table",
+ "flow:loop_over_items" => "Loop Over Items",
+ }.freeze
+
+ NODE_TYPE_OPERATION_LABELS = {
+ "action:badge" => {
+ "grant" => "Grant badge",
+ "revoke" => "Revoke badge",
+ },
+ "action:topic_tags" => {
+ "add" => "Add",
+ "remove" => "Remove",
+ },
+ "action:group" => {
+ "add" => "Add to group",
+ "remove" => "Remove from group",
+ "get" => "Get group",
+ },
+ "action:data_table" => {
+ "insert" => "Insert",
+ "get" => "Get",
+ "update" => "Update",
+ "delete" => "Delete",
+ "upsert" => "Upsert",
+ },
+ "action:topic" => {
+ "create" => "Create topic",
+ "get" => "Get topic",
+ "list" => "List topics",
+ },
+ }.freeze
+
+ def select_node_type(identifier, operation: nil)
+ label = NODE_TYPE_LABELS.fetch(identifier, identifier)
+ find(".workflows-node-panel__search-input").fill_in(with: label)
+ find(".workflows-node-panel__item-name", exact_text: label).click
+ if operation
+ operation_label = NODE_TYPE_OPERATION_LABELS.dig(identifier, operation) || operation
+ find(".workflows-node-panel__item-name", text: operation_label).click
+ end
+ self
+ end
+
+ def double_click_node(index)
+ all(".workflow-rete-node")[index].double_click
+ self
+ end
+
+ def has_connection_count?(count)
+ page.has_css?(".workflow-connection", count: count)
+ end
+
+ def has_condition_port_labels?
+ page.has_css?(".workflow-rete-node__port-pill", text: "true", wait: 10) &&
+ page.has_css?(".workflow-rete-node__port-pill", text: "false", wait: 10)
+ end
+ end
+ end
+ end
+end
diff --git a/plugins/discourse-workflows/spec/system/page_objects/pages/workflows.rb b/plugins/discourse-workflows/spec/system/page_objects/pages/workflows.rb
new file mode 100644
index 00000000000..ac595da7ea4
--- /dev/null
+++ b/plugins/discourse-workflows/spec/system/page_objects/pages/workflows.rb
@@ -0,0 +1,44 @@
+# frozen_string_literal: true
+
+module PageObjects
+ module Pages
+ module DiscourseWorkflows
+ class Workflows < PageObjects::Pages::Base
+ def visit_index
+ page.visit("/admin/plugins/discourse-workflows")
+ self
+ end
+
+ def has_workflow?(name)
+ page.has_css?(".workflows-index__name", text: name)
+ end
+
+ def has_failed_workflow?(workflow)
+ page.has_css?(
+ ".workflows-index__row[data-item-id='#{workflow.id}'] .workflows-index__warning",
+ )
+ end
+
+ def has_no_failed_workflow?(workflow)
+ page.has_no_css?(
+ ".workflows-index__row[data-item-id='#{workflow.id}'] .workflows-index__warning",
+ )
+ end
+
+ def has_no_workflows?
+ page.has_css?(".workflows-empty-state")
+ end
+
+ def click_new_workflow
+ find(".workflows-index__new-btn").click
+ self
+ end
+
+ def click_workflow(name)
+ find(".workflows-index__name", text: name).find("a").click
+ self
+ end
+ end
+ end
+ end
+end
diff --git a/plugins/discourse-workflows/spec/system/variables_spec.rb b/plugins/discourse-workflows/spec/system/variables_spec.rb
new file mode 100644
index 00000000000..1ad396dc59f
--- /dev/null
+++ b/plugins/discourse-workflows/spec/system/variables_spec.rb
@@ -0,0 +1,33 @@
+# frozen_string_literal: true
+
+RSpec.describe "Discourse Workflows - Variables" do
+ fab!(:admin)
+
+ let(:variables_page) { PageObjects::Pages::DiscourseWorkflows::Variables.new }
+
+ before { sign_in(admin) }
+
+ it "shows existing variables" do
+ Fabricate(
+ :discourse_workflows_variable,
+ key: "API_BASE_URL",
+ value: "https://example.com",
+ created_by: admin,
+ )
+
+ variables_page.visit_index
+
+ expect(variables_page).to have_variable("API_BASE_URL")
+ expect(variables_page).to have_variable_creator(admin.username)
+ end
+
+ it "creates a new variable" do
+ variables_page.visit_index
+ variables_page.click_add_variable
+ variables_page.fill_variable_key("MY_SECRET_KEY")
+ variables_page.fill_variable_value("secret_value")
+ variables_page.submit_variable_modal
+
+ expect(variables_page).to have_variable("MY_SECRET_KEY")
+ end
+end
diff --git a/plugins/discourse-workflows/spec/system/workflows_spec.rb b/plugins/discourse-workflows/spec/system/workflows_spec.rb
new file mode 100644
index 00000000000..c5cc98ddf9d
--- /dev/null
+++ b/plugins/discourse-workflows/spec/system/workflows_spec.rb
@@ -0,0 +1,119 @@
+# frozen_string_literal: true
+
+RSpec.describe "Discourse Workflows" do
+ fab!(:admin)
+
+ let(:workflows_page) { PageObjects::Pages::DiscourseWorkflows::Workflows.new }
+ let(:editor_page) { PageObjects::Pages::DiscourseWorkflows::WorkflowEditor.new }
+
+ before do
+ SiteSetting.tagging_enabled = true
+ sign_in(admin)
+ end
+
+ it "creates a workflow with trigger and action" do
+ editor_page.visit_new
+ editor_page.click_empty_state_add_node
+ editor_page.select_node_type("trigger:topic_closed")
+ editor_page.click_add_node
+ editor_page.select_node_type("action:topic_tags", operation: "add")
+
+ workflows_page.visit_index
+ expect(workflows_page).to have_workflow("My workflow")
+ end
+
+ it "creates a workflow with condition node" do
+ editor_page.visit_new
+ editor_page.click_empty_state_add_node
+ editor_page.select_node_type("trigger:topic_closed")
+ editor_page.click_add_node
+ editor_page.select_node_type("condition:if")
+
+ workflows_page.visit_index
+ expect(workflows_page).to have_workflow("My workflow")
+ end
+
+ it "renders the failed-run warning icon based on the most recent execution" do
+ failed_workflow = Fabricate(:discourse_workflows_workflow, created_by: admin)
+ recovered_workflow = Fabricate(:discourse_workflows_workflow, created_by: admin)
+
+ Fabricate(
+ :discourse_workflows_error_execution,
+ workflow: failed_workflow,
+ created_at: 1.hour.ago,
+ )
+ Fabricate(
+ :discourse_workflows_error_execution,
+ workflow: recovered_workflow,
+ created_at: 2.hours.ago,
+ )
+ Fabricate(
+ :discourse_workflows_completed_execution,
+ workflow: recovered_workflow,
+ created_at: 1.hour.ago,
+ )
+
+ workflows_page.visit_index
+
+ expect(workflows_page).to have_failed_workflow(failed_workflow)
+ expect(workflows_page).to have_no_failed_workflow(recovered_workflow)
+ end
+
+ context "when closing the node configurator" do
+ fab!(:workflow) { Fabricate(:discourse_workflows_workflow, created_by: admin) }
+
+ before do
+ workflow.update!(
+ nodes: [
+ {
+ "id" => "trigger-1",
+ "type" => "trigger:manual",
+ "typeVersion" => "1.0",
+ "name" => "Manual trigger",
+ "position" => {
+ "x" => 100,
+ "y" => 100,
+ },
+ "parameters" => {
+ },
+ "credentials" => {
+ },
+ },
+ ],
+ connections: {
+ },
+ )
+ end
+
+ def count_workflow_updates
+ count = 0
+ subscriber =
+ ActiveSupport::Notifications.subscribe("process_action.action_controller") do |*, payload|
+ if payload[:controller] == "DiscourseWorkflows::WorkflowsController" &&
+ payload[:action] == "update"
+ count += 1
+ end
+ end
+ begin
+ yield
+ ensure
+ ActiveSupport::Notifications.unsubscribe(subscriber)
+ end
+ count
+ end
+
+ it "does not save the workflow when nothing changed" do
+ updates =
+ count_workflow_updates do
+ editor_page.visit(workflow.id)
+ expect(editor_page).to have_node_count(1)
+ editor_page.double_click_node(0)
+ expect(editor_page).to have_node_configurator
+ editor_page.close_node_configurator
+ expect(editor_page).to have_no_node_configurator
+ end
+
+ expect(updates).to eq(0)
+ end
+ end
+end
diff --git a/plugins/discourse-workflows/test/javascripts/integration/components/workflows-form-test.gjs b/plugins/discourse-workflows/test/javascripts/integration/components/workflows-form-test.gjs
new file mode 100644
index 00000000000..4853f66f572
--- /dev/null
+++ b/plugins/discourse-workflows/test/javascripts/integration/components/workflows-form-test.gjs
@@ -0,0 +1,280 @@
+import { render, settled } from "@ember/test-helpers";
+import { module, test } from "qunit";
+import { setupRenderingTest } from "discourse/tests/helpers/component-test";
+import pretender, { response } from "discourse/tests/helpers/create-pretender";
+import formKit from "discourse/tests/helpers/form-kit-helper";
+import { i18n } from "discourse-i18n";
+import WorkflowsForm from "discourse/plugins/discourse-workflows/discourse/components/workflows-form";
+
+module("Integration | Component | workflows-form", function (hooks) {
+ setupRenderingTest(hooks);
+
+ test("renders backend form schema with FormKit controls", async function (assert) {
+ this.set("model", {
+ form_title: "Intake",
+ data: {
+ name: "",
+ age: "",
+ bio: "",
+ email: "",
+ password: "",
+ starts_on: "",
+ plan: "basic",
+ contact_method: "",
+ },
+ fields: [
+ {
+ name: "name",
+ title: "Name",
+ type: "input",
+ validation: "required",
+ placeholder: "Your name",
+ },
+ {
+ name: "age",
+ title: "Age",
+ type: "input-number",
+ },
+ {
+ name: "bio",
+ title: "Bio",
+ type: "textarea",
+ placeholder: "Tell us more",
+ },
+ {
+ name: "email",
+ title: "Email",
+ type: "input-email",
+ },
+ {
+ name: "password",
+ title: "Password",
+ type: "password",
+ },
+ {
+ name: "starts_on",
+ title: "Starts on",
+ type: "input-date",
+ },
+ {
+ name: "plan",
+ title: "Plan",
+ type: "select",
+ options: [
+ { value: "basic", label: "Basic" },
+ { value: "pro", label: "Pro" },
+ ],
+ },
+ {
+ name: "contact_method",
+ title: "Contact method",
+ type: "radio-group",
+ options: [
+ { value: "email", label: "Email" },
+ { value: "phone", label: "Phone" },
+ ],
+ },
+ {
+ name: "intro",
+ title: "Intro",
+ type: "html",
+ html: "<strong>Escaped intro</strong>",
+ },
+ ],
+ });
+
+ await render(<template><WorkflowsForm @model={{this.model}} /></template>);
+
+ assert.dom(".workflows-form__title").hasText("Intake");
+ assert.dom('[data-name="name"]').hasClass("form-kit__field-input");
+ assert.dom('input[name="name"]').hasAttribute("placeholder", "Your name");
+ assert.dom('[data-name="age"]').hasClass("form-kit__field-input-number");
+ assert.dom('input[name="age"]').hasAttribute("type", "number");
+ assert
+ .dom('textarea[name="bio"]')
+ .hasAttribute("placeholder", "Tell us more");
+ assert.dom('input[name="email"]').hasAttribute("type", "email");
+ assert.dom('input[name="password"]').hasAttribute("type", "password");
+ assert.dom('input[name="starts_on"]').hasAttribute("type", "date");
+ assert.dom('select[name="plan"]').exists();
+ assert.dom('option[value="basic"]').hasText("Basic");
+ assert.dom('option[value="pro"]').hasText("Pro");
+ assert.dom('input[name="contact_method"][value="email"]').exists();
+ assert.dom('input[name="contact_method"][value="phone"]').exists();
+ assert.dom(".workflows-form__html strong").hasText("Escaped intro");
+ assert.dom(".workflows-form__html").doesNotIncludeText("<strong>");
+ assert.dom('input[name="tracking_id"]').doesNotExist();
+ });
+
+ test("renders the test mode banner", async function (assert) {
+ this.set("model", {
+ form_mode: "test",
+ data: {},
+ fields: [],
+ });
+
+ await render(<template><WorkflowsForm @model={{this.model}} /></template>);
+
+ assert
+ .dom(".workflows-form__test-banner")
+ .hasText(i18n("discourse_workflows.form.test_mode_banner"));
+ });
+
+ test("renders completion text HTML returned by the workflow", async function (assert) {
+ pretender.post(
+ "/workflows/form/a1b2c3d4-e5f6-7890-abcd-ef0123456789.json",
+ () =>
+ response(200, {
+ status: "success",
+ form_completion: {
+ on_submission: "show_text",
+ completion_text: "<strong>Saved</strong>",
+ },
+ })
+ );
+
+ this.set("model", {
+ form_title: "Intake",
+ form_submit_url:
+ "/workflows/form/a1b2c3d4-e5f6-7890-abcd-ef0123456789.json",
+ data: {},
+ fields: [],
+ });
+
+ await render(<template><WorkflowsForm @model={{this.model}} /></template>);
+ await formKit().submit();
+
+ assert.dom(".workflows-form__completion-text strong").hasText("Saved");
+ assert
+ .dom(".workflows-form__completion-text")
+ .doesNotIncludeText("<strong>");
+ });
+
+ test("renders workflow errors returned by submit", async function (assert) {
+ pretender.post(
+ "/workflows/form/a1b2c3d4-e5f6-7890-abcd-ef0123456789.json",
+ () =>
+ response(500, {
+ status: "error",
+ errors: ["Error in workflow"],
+ })
+ );
+
+ this.set("model", {
+ form_title: "Intake",
+ form_submit_url:
+ "/workflows/form/a1b2c3d4-e5f6-7890-abcd-ef0123456789.json",
+ data: {},
+ fields: [],
+ });
+
+ await render(<template><WorkflowsForm @model={{this.model}} /></template>);
+ await formKit().submit();
+
+ assert.dom(".workflows-form__error").hasText("Error in workflow");
+ });
+
+ test("renders structured validation errors returned by submit", async function (assert) {
+ pretender.post(
+ "/workflows/form/a1b2c3d4-e5f6-7890-abcd-ef0123456789.json",
+ () =>
+ response(422, {
+ errors: [
+ { field_label: "Name", code: "missing" },
+ { field_label: "Email", code: "invalid_value" },
+ ],
+ })
+ );
+
+ this.set("model", {
+ form_title: "Intake",
+ form_submit_url:
+ "/workflows/form/a1b2c3d4-e5f6-7890-abcd-ef0123456789.json",
+ data: {},
+ fields: [],
+ });
+
+ await render(<template><WorkflowsForm @model={{this.model}} /></template>);
+ await formKit().submit();
+
+ assert
+ .dom(".workflows-form__error")
+ .hasText("Name is required, Email is invalid");
+ });
+
+ test("renders generic error when submit returns no errors", async function (assert) {
+ pretender.post(
+ "/workflows/form/a1b2c3d4-e5f6-7890-abcd-ef0123456789.json",
+ () =>
+ response(500, {
+ status: "error",
+ })
+ );
+
+ this.set("model", {
+ form_title: "Intake",
+ form_submit_url:
+ "/workflows/form/a1b2c3d4-e5f6-7890-abcd-ef0123456789.json",
+ data: {},
+ fields: [],
+ });
+
+ await render(<template><WorkflowsForm @model={{this.model}} /></template>);
+ await formKit().submit();
+
+ assert
+ .dom(".workflows-form__error")
+ .hasText(i18n("discourse_workflows.form.error_message"));
+ });
+
+ test("renders waiting form load errors returned from errors", async function (assert) {
+ pretender.post(
+ "/workflows/form/a1b2c3d4-e5f6-7890-abcd-ef0123456789.json",
+ () =>
+ response(200, {
+ form_waiting_url: "/workflows/forms/waiting/1.json",
+ })
+ );
+ pretender.get("/workflows/forms/waiting/1.json", () =>
+ response(404, {
+ errors: ["Waiting form not found"],
+ })
+ );
+
+ this.set("model", {
+ form_title: "Intake",
+ form_submit_url:
+ "/workflows/form/a1b2c3d4-e5f6-7890-abcd-ef0123456789.json",
+ data: {},
+ fields: [],
+ });
+
+ await render(<template><WorkflowsForm @model={{this.model}} /></template>);
+ await formKit().submit();
+ await settled();
+
+ assert.dom(".workflows-form__error").hasText("Waiting form not found");
+ });
+
+ test("completes empty successful workflow_finishes submissions", async function (assert) {
+ pretender.post(
+ "/workflows/form/a1b2c3d4-e5f6-7890-abcd-ef0123456789.json",
+ () => [200, {}, ""]
+ );
+
+ this.set("model", {
+ form_title: "Intake",
+ form_submit_url:
+ "/workflows/form/a1b2c3d4-e5f6-7890-abcd-ef0123456789.json",
+ data: {},
+ fields: [],
+ });
+
+ await render(<template><WorkflowsForm @model={{this.model}} /></template>);
+ await formKit().submit();
+
+ assert
+ .dom(".workflows-form__complete")
+ .hasText(i18n("discourse_workflows.form.thank_you"));
+ });
+});
diff --git a/plugins/discourse-workflows/test/javascripts/integration/components/workflows/boolean-control-test.gjs b/plugins/discourse-workflows/test/javascripts/integration/components/workflows/boolean-control-test.gjs
new file mode 100644
index 00000000000..e28b6768d7d
--- /dev/null
+++ b/plugins/discourse-workflows/test/javascripts/integration/components/workflows/boolean-control-test.gjs
@@ -0,0 +1,130 @@
+import { click, render } from "@ember/test-helpers";
+import { module, test } from "qunit";
+import Form from "discourse/components/form";
+import { setupRenderingTest } from "discourse/tests/helpers/component-test";
+import pretender, { response } from "discourse/tests/helpers/create-pretender";
+import BooleanControl from "discourse/plugins/discourse-workflows/admin/components/workflows/configurators/boolean-control";
+
+module("Integration | Component | workflows boolean control", function (hooks) {
+ setupRenderingTest(hooks);
+
+ hooks.beforeEach(function () {
+ pretender.get("/admin/plugins/discourse-workflows/variables.json", () =>
+ response(200, { variables: [] })
+ );
+ });
+
+ test("renders toggle in plain mode", async function (assert) {
+ this.setProperties({
+ configuration: { enabled: false },
+ formApi: null,
+ schema: { type: "boolean", ui: { expression: true } },
+ registerApi: (api) => this.set("formApi", api),
+ });
+
+ await render(
+ <template>
+ <Form
+ @data={{this.configuration}}
+ @onRegisterApi={{this.registerApi}}
+ as |form transientData|
+ >
+ <BooleanControl
+ @form={{form}}
+ @formApi={{this.formApi}}
+ @configuration={{transientData}}
+ @fieldName="enabled"
+ @label="Enabled"
+ @schema={{this.schema}}
+ />
+ </Form>
+ </template>
+ );
+
+ assert.dom(".form-kit__control-toggle").exists();
+ assert.dom(".workflows-property-engine__mode-control").exists();
+ });
+
+ test("switches to expression mode", async function (assert) {
+ this.setProperties({
+ configuration: { enabled: false },
+ formApi: null,
+ schema: { type: "boolean", ui: { expression: true } },
+ registerApi: (api) => this.set("formApi", api),
+ });
+
+ await render(
+ <template>
+ <Form
+ @data={{this.configuration}}
+ @onRegisterApi={{this.registerApi}}
+ as |form transientData|
+ >
+ <BooleanControl
+ @form={{form}}
+ @formApi={{this.formApi}}
+ @configuration={{transientData}}
+ @fieldName="enabled"
+ @label="Enabled"
+ @schema={{this.schema}}
+ />
+ </Form>
+ </template>
+ );
+
+ await click(
+ '.workflows-property-engine__mode-control input[value="dynamic"]'
+ );
+
+ assert.dom(".form-kit__control-toggle").doesNotExist();
+ assert.dom(".workflows-variable-input").exists();
+ });
+
+ test("renders in expression mode when value starts with =", async function (assert) {
+ this.setProperties({
+ configuration: { enabled: "=true" },
+ schema: { type: "boolean", ui: { expression: true } },
+ });
+
+ await render(
+ <template>
+ <Form @data={{this.configuration}} as |form transientData|>
+ <BooleanControl
+ @form={{form}}
+ @configuration={{transientData}}
+ @fieldName="enabled"
+ @label="Enabled"
+ @schema={{this.schema}}
+ />
+ </Form>
+ </template>
+ );
+
+ assert.dom(".form-kit__control-toggle").doesNotExist();
+ assert.dom(".workflows-variable-input").exists();
+ });
+
+ test("renders plain toggle without mode control when expressions disabled", async function (assert) {
+ this.setProperties({
+ configuration: { enabled: false },
+ schema: { type: "boolean", no_data_expression: true },
+ });
+
+ await render(
+ <template>
+ <Form @data={{this.configuration}} as |form transientData|>
+ <BooleanControl
+ @form={{form}}
+ @configuration={{transientData}}
+ @fieldName="enabled"
+ @label="Enabled"
+ @schema={{this.schema}}
+ />
+ </Form>
+ </template>
+ );
+
+ assert.dom(".form-kit__control-toggle").exists();
+ assert.dom(".workflows-property-engine__mode-control").doesNotExist();
+ });
+});
diff --git a/plugins/discourse-workflows/test/javascripts/integration/components/workflows/context-input-test.gjs b/plugins/discourse-workflows/test/javascripts/integration/components/workflows/context-input-test.gjs
new file mode 100644
index 00000000000..a6dcdeb9647
--- /dev/null
+++ b/plugins/discourse-workflows/test/javascripts/integration/components/workflows/context-input-test.gjs
@@ -0,0 +1,699 @@
+import { click, render, triggerEvent } from "@ember/test-helpers";
+import { module, test } from "qunit";
+import { setupRenderingTest } from "discourse/tests/helpers/component-test";
+import InputContext from "discourse/plugins/discourse-workflows/admin/components/workflows/context/input";
+import WorkflowEditorSession from "discourse/plugins/discourse-workflows/admin/lib/workflows/editor-session";
+import { WORKFLOW_VARIABLE_MIME } from "discourse/plugins/discourse-workflows/admin/lib/workflows/expression-context";
+
+const EXPRESSION_CONTEXT = {
+ environment: {
+ $site_settings: { type: "object" },
+ $vars: { type: "object" },
+ $current_user: {
+ type: "object",
+ fields: { id: { type: "integer" }, username: { type: "string" } },
+ },
+ $execution: {
+ type: "object",
+ fields: {
+ id: { type: "integer" },
+ workflow_id: { type: "integer" },
+ workflow_name: { type: "string" },
+ resume_url: {
+ type: "string",
+ display_options: {
+ show: {
+ node_present: [
+ {
+ type: "flow:wait",
+ parameters: { resume: "webhook" },
+ },
+ ],
+ },
+ },
+ },
+ resumeFormUrl: {
+ type: "string",
+ display_options: {
+ show: {
+ node_present: [
+ {
+ type: "action:form",
+ parameters: { page_type: "page" },
+ },
+ ],
+ },
+ },
+ },
+ },
+ },
+ },
+ node_reference_shape: { item: { json: "object" }, context: "object" },
+ item_prefix: "$json",
+};
+
+function makeNodes(...nodes) {
+ return nodes;
+}
+
+module("Integration | Component | workflows/context/input", function (hooks) {
+ setupRenderingTest(hooks);
+
+ hooks.beforeEach(function () {
+ const service = this.owner.lookup("service:workflows-node-types");
+ service.nodeTypes = [];
+ service.credentialTypes = [];
+ service.expressionContext = EXPRESSION_CONTEXT;
+ this.session = new WorkflowEditorSession({ lastExecutionRunData: {} });
+ });
+
+ hooks.afterEach(function () {
+ this.owner.lookup("service:workflows-node-types").clear();
+ });
+
+ test("renders environment fields", async function (assert) {
+ const node = {
+ clientId: "n1",
+ type: "action:http_request",
+ name: "HTTP",
+ };
+ const nodes = makeNodes(node);
+
+ await render(
+ <template>
+ <InputContext
+ @node={{node}}
+ @nodes={{nodes}}
+ @connections={{(Array)}}
+ @nodeTypes={{(Array)}}
+ @session={{this.session}}
+ />
+ </template>
+ );
+
+ const sections = this.element.querySelectorAll(
+ ".workflows-context-panel__section"
+ );
+ const envSection = sections[0];
+ const fieldKeys = [
+ ...envSection.querySelectorAll(".workflows-schema-field__key"),
+ ].map((el) => el.textContent.trim());
+
+ assert.true(fieldKeys.includes("site_settings"));
+ assert.true(fieldKeys.includes("vars"));
+ assert.true(fieldKeys.includes("current_user"));
+ assert.true(fieldKeys.includes("execution"));
+ });
+
+ test("execution fields include resume_url when webhook wait node exists", async function (assert) {
+ const waitNode = {
+ clientId: "w1",
+ type: "flow:wait",
+ name: "Wait",
+ configuration: { resume: "webhook" },
+ };
+ const actionNode = {
+ clientId: "a1",
+ type: "action:http_request",
+ name: "HTTP",
+ };
+ const nodes = makeNodes(waitNode, actionNode);
+
+ await render(
+ <template>
+ <InputContext
+ @node={{actionNode}}
+ @nodes={{nodes}}
+ @connections={{(Array)}}
+ @nodeTypes={{(Array)}}
+ @session={{this.session}}
+ />
+ </template>
+ );
+
+ const executionFields = this.element.querySelectorAll(
+ ".workflows-schema-field"
+ );
+ const executionField = [...executionFields].find(
+ (el) =>
+ el.querySelector(".workflows-schema-field__key")?.textContent.trim() ===
+ "execution"
+ );
+
+ await click(executionField.querySelector(".workflows-schema-field__row"));
+
+ const allKeys = [
+ ...this.element.querySelectorAll(".workflows-schema-field__key"),
+ ].map((el) => el.textContent.trim());
+
+ assert.true(allKeys.includes("resume_url"));
+ });
+
+ test("execution fields exclude resume_url when no webhook wait node", async function (assert) {
+ const node = {
+ clientId: "n1",
+ type: "action:http_request",
+ name: "HTTP",
+ };
+ const nodes = makeNodes(node);
+
+ await render(
+ <template>
+ <InputContext
+ @node={{node}}
+ @nodes={{nodes}}
+ @connections={{(Array)}}
+ @nodeTypes={{(Array)}}
+ @session={{this.session}}
+ />
+ </template>
+ );
+
+ const executionFields = this.element.querySelectorAll(
+ ".workflows-schema-field"
+ );
+ const executionField = [...executionFields].find(
+ (el) =>
+ el.querySelector(".workflows-schema-field__key")?.textContent.trim() ===
+ "execution"
+ );
+
+ await click(executionField.querySelector(".workflows-schema-field__row"));
+
+ const allKeys = [
+ ...this.element.querySelectorAll(".workflows-schema-field__key"),
+ ].map((el) => el.textContent.trim());
+
+ assert.false(allKeys.includes("resume_url"));
+ });
+
+ test("execution fields include resumeFormUrl when a form page node exists", async function (assert) {
+ const formNode = {
+ clientId: "f1",
+ type: "action:form",
+ name: "Form",
+ configuration: { page_type: "page" },
+ };
+ const actionNode = {
+ clientId: "a1",
+ type: "action:http_request",
+ name: "HTTP",
+ };
+ const nodes = makeNodes(formNode, actionNode);
+
+ await render(
+ <template>
+ <InputContext
+ @node={{actionNode}}
+ @nodes={{nodes}}
+ @connections={{(Array)}}
+ @nodeTypes={{(Array)}}
+ @session={{this.session}}
+ />
+ </template>
+ );
+
+ const executionFields = this.element.querySelectorAll(
+ ".workflows-schema-field"
+ );
+ const executionField = [...executionFields].find(
+ (el) =>
+ el.querySelector(".workflows-schema-field__key")?.textContent.trim() ===
+ "execution"
+ );
+
+ await click(executionField.querySelector(".workflows-schema-field__row"));
+
+ const allKeys = [
+ ...this.element.querySelectorAll(".workflows-schema-field__key"),
+ ].map((el) => el.textContent.trim());
+
+ assert.true(allKeys.includes("resumeFormUrl"));
+ });
+
+ test("uses previous node name as the input heading", async function (assert) {
+ const triggerNode = {
+ clientId: "t1",
+ type: "trigger:webhook",
+ name: "Webhook",
+ };
+ const step1 = {
+ clientId: "s1",
+ type: "action:http_request",
+ name: "First Step",
+ };
+ const currentNode = {
+ clientId: "c1",
+ type: "action:http_request",
+ name: "Current",
+ };
+ const nodes = makeNodes(triggerNode, step1, currentNode);
+ const connections = [
+ { sourceClientId: "t1", targetClientId: "s1" },
+ { sourceClientId: "s1", targetClientId: "c1" },
+ ];
+ this.session.lastExecutionRunData = {
+ "First Step": [
+ {
+ status: "success",
+ outputs: [
+ {
+ index: 0,
+ items: [{ json: { result: "ok" } }],
+ item_count: 1,
+ },
+ ],
+ },
+ ],
+ };
+
+ await render(
+ <template>
+ <InputContext
+ @node={{currentNode}}
+ @nodes={{nodes}}
+ @connections={{connections}}
+ @nodeTypes={{(Array)}}
+ @session={{this.session}}
+ />
+ </template>
+ );
+
+ const firstTitle = this.element
+ .querySelector(
+ ".workflows-context-panel__section .workflows-context-panel__title"
+ )
+ .textContent.trim();
+ const keys = [
+ ...this.element.querySelectorAll(".workflows-schema-field__key-title"),
+ ].map((el) => el.textContent.trim());
+
+ assert.true(firstTitle.includes("First Step"));
+ assert.true(firstTitle.includes("1 item"));
+ assert.dom(".workflows-context-panel__item-title").doesNotExist();
+ assert.true(keys.includes("result"));
+ });
+
+ test("shows an empty input state when the input has no JSON fields", async function (assert) {
+ const previousNode = {
+ clientId: "previous-1",
+ type: "action:http_request",
+ name: "Previous",
+ };
+ const currentNode = {
+ clientId: "current-1",
+ type: "action:http_request",
+ name: "Current",
+ };
+ const nodes = makeNodes(previousNode, currentNode);
+ const connections = [
+ { sourceClientId: "previous-1", targetClientId: "current-1" },
+ ];
+ this.session.lastExecutionRunData = {
+ Previous: [
+ {
+ status: "success",
+ outputs: [
+ {
+ index: 0,
+ items: [{ json: {} }],
+ item_count: 1,
+ },
+ ],
+ },
+ ],
+ };
+
+ await render(
+ <template>
+ <InputContext
+ @node={{currentNode}}
+ @nodes={{nodes}}
+ @connections={{connections}}
+ @nodeTypes={{(Array)}}
+ @session={{this.session}}
+ />
+ </template>
+ );
+
+ assert.dom(".workflows-context-panel__item-title").doesNotExist();
+ assert.dom(".workflows-context-panel__title-meta").hasText("1 item");
+ assert.dom(".workflows-context-panel__empty").hasText("No input fields");
+ });
+
+ test("shows an empty input state before the input has run", async function (assert) {
+ const previousNode = {
+ clientId: "previous-1",
+ type: "action:http_request",
+ name: "Previous",
+ };
+ const currentNode = {
+ clientId: "current-1",
+ type: "action:http_request",
+ name: "Current",
+ };
+ const nodes = makeNodes(previousNode, currentNode);
+ const connections = [
+ { sourceClientId: "previous-1", targetClientId: "current-1" },
+ ];
+
+ await render(
+ <template>
+ <InputContext
+ @node={{currentNode}}
+ @nodes={{nodes}}
+ @connections={{connections}}
+ @nodeTypes={{(Array)}}
+ @session={{this.session}}
+ />
+ </template>
+ );
+
+ assert
+ .dom(".workflows-context-panel__empty")
+ .hasText("No input data yet. It will appear after the first run.");
+ });
+
+ test("renders each direct input source for multi-input nodes", async function (assert) {
+ const leftNode = {
+ clientId: "left-1",
+ type: "action:http_request",
+ name: "Left",
+ };
+ const rightNode = {
+ clientId: "right-1",
+ type: "action:http_request",
+ name: "Right",
+ };
+ const currentNode = {
+ clientId: "merge-1",
+ type: "action:merge",
+ name: "Merge",
+ };
+ const nodes = makeNodes(leftNode, rightNode, currentNode);
+ const connections = [
+ {
+ sourceClientId: "right-1",
+ targetClientId: "merge-1",
+ targetInputIndex: 1,
+ },
+ {
+ sourceClientId: "left-1",
+ targetClientId: "merge-1",
+ targetInputIndex: 0,
+ },
+ ];
+ this.session.lastExecutionRunData = {
+ Left: [
+ {
+ status: "success",
+ outputs: [
+ { index: 0, items: [{ json: { left: true } }], item_count: 1 },
+ ],
+ },
+ ],
+ Right: [
+ {
+ status: "success",
+ outputs: [
+ { index: 0, items: [{ json: { right: true } }], item_count: 1 },
+ ],
+ },
+ ],
+ };
+
+ await render(
+ <template>
+ <InputContext
+ @node={{currentNode}}
+ @nodes={{nodes}}
+ @connections={{connections}}
+ @nodeTypes={{(Array)}}
+ @session={{this.session}}
+ />
+ </template>
+ );
+
+ const sectionTitles = [
+ ...this.element.querySelectorAll(".workflows-context-panel__title"),
+ ].map((el) => el.textContent.trim());
+ const keys = [
+ ...this.element.querySelectorAll(".workflows-schema-field__key-title"),
+ ].map((el) => el.textContent.trim());
+
+ assert.true(sectionTitles[0].includes("Left"));
+ assert.true(sectionTitles[0].includes("Input 1"));
+ assert.true(sectionTitles[0].includes("1 item"));
+ assert.true(sectionTitles[1].includes("Right"));
+ assert.true(sectionTitles[1].includes("Input 2"));
+ assert.true(sectionTitles[1].includes("1 item"));
+ assert.true(keys.includes("left"));
+ assert.true(keys.includes("right"));
+
+ const fieldRows = [
+ ...this.element.querySelectorAll(".workflows-schema-field__key"),
+ ];
+ const leftField = fieldRows.find((el) => el.textContent.trim() === "left");
+ const rightField = fieldRows.find(
+ (el) => el.textContent.trim() === "right"
+ );
+ const dragged = {};
+ const dataTransfer = {
+ setData(type, value) {
+ dragged[type] = value;
+ },
+ };
+
+ await triggerEvent(leftField, "dragstart", { dataTransfer });
+ assert.strictEqual(
+ JSON.parse(dragged[WORKFLOW_VARIABLE_MIME]).id,
+ "$json.left"
+ );
+
+ await triggerEvent(rightField, "dragstart", { dataTransfer });
+ assert.strictEqual(
+ JSON.parse(dragged[WORKFLOW_VARIABLE_MIME]).id,
+ '$("Right").all(0)[$itemIndex].json.right'
+ );
+ });
+
+ test("prefers the current node recorded input over the previous node output", async function (assert) {
+ const logNode = {
+ clientId: "log-1",
+ type: "action:log",
+ name: "Log",
+ };
+ const currentNode = {
+ clientId: "current-1",
+ type: "action:http_request",
+ name: "Current",
+ };
+ const nodes = makeNodes(logNode, currentNode);
+ const connections = [
+ { sourceClientId: "log-1", targetClientId: "current-1" },
+ ];
+ this.session.lastExecutionRunData = {
+ Log: [
+ {
+ status: "success",
+ outputs: [{ index: 0, items: [], item_count: 0 }],
+ },
+ ],
+ Current: [
+ {
+ status: "success",
+ inputs: [
+ {
+ index: 0,
+ items: [{ json: { topic: { id: 1, title: "Runtime topic" } } }],
+ item_count: 1,
+ source: { node_name: "Log", output_index: 0 },
+ },
+ ],
+ },
+ ],
+ };
+
+ await render(
+ <template>
+ <InputContext
+ @node={{currentNode}}
+ @nodes={{nodes}}
+ @connections={{connections}}
+ @nodeTypes={{(Array)}}
+ @session={{this.session}}
+ />
+ </template>
+ );
+
+ const firstTitle = this.element
+ .querySelector(
+ ".workflows-context-panel__section .workflows-context-panel__title"
+ )
+ .textContent.trim();
+ const keys = [
+ ...this.element.querySelectorAll(".workflows-schema-field__key-title"),
+ ].map((el) => el.textContent.trim());
+
+ assert.true(firstTitle.includes("Log"));
+ assert.true(firstTitle.includes("1 item"));
+ assert.dom(".workflows-context-panel__item-title").doesNotExist();
+ assert.true(keys.includes("topic"));
+ });
+
+ test("hides the input section when there is no previous node", async function (assert) {
+ const node = {
+ clientId: "n1",
+ type: "action:http_request",
+ name: "HTTP",
+ };
+ const nodes = makeNodes(node);
+
+ await render(
+ <template>
+ <InputContext
+ @node={{node}}
+ @nodes={{nodes}}
+ @connections={{(Array)}}
+ @nodeTypes={{(Array)}}
+ @session={{this.session}}
+ />
+ </template>
+ );
+
+ const firstTitle = this.element
+ .querySelector(
+ ".workflows-context-panel__section .workflows-context-panel__title"
+ )
+ .textContent.trim();
+
+ assert.strictEqual(
+ firstTitle,
+ "Environment",
+ "first section is Environment, input section is hidden"
+ );
+ });
+
+ test("renders ancestor nodes with $() expression format", async function (assert) {
+ const triggerNode = {
+ clientId: "t1",
+ type: "trigger:webhook",
+ name: "Webhook",
+ };
+ const step1 = {
+ clientId: "s1",
+ type: "action:http_request",
+ name: "First Step",
+ };
+ const step2 = {
+ clientId: "s2",
+ type: "action:http_request",
+ name: "Second Step",
+ };
+ const currentNode = {
+ clientId: "c1",
+ type: "action:http_request",
+ name: "Current",
+ };
+ const nodes = makeNodes(triggerNode, step1, step2, currentNode);
+ const connections = [
+ { sourceClientId: "t1", targetClientId: "s1" },
+ { sourceClientId: "s1", targetClientId: "s2" },
+ { sourceClientId: "s2", targetClientId: "c1" },
+ ];
+
+ const nodeTypes = [];
+ this.session.lastExecutionRunData = {
+ "First Step": [
+ {
+ status: "success",
+ outputs: [
+ {
+ index: 0,
+ items: [{ json: { result: "ok" } }],
+ item_count: 1,
+ },
+ ],
+ },
+ ],
+ "Second Step": [
+ {
+ status: "success",
+ outputs: [
+ {
+ index: 0,
+ items: [{ json: { data: { id: 1 } } }],
+ item_count: 1,
+ },
+ ],
+ },
+ ],
+ };
+
+ await render(
+ <template>
+ <InputContext
+ @node={{currentNode}}
+ @nodes={{nodes}}
+ @connections={{connections}}
+ @nodeTypes={{nodeTypes}}
+ @session={{this.session}}
+ />
+ </template>
+ );
+
+ const sectionTitles = [
+ ...this.element.querySelectorAll(".workflows-context-panel__title"),
+ ].map((el) => el.textContent.trim());
+
+ assert.true(
+ sectionTitles.some((t) => t.includes("First Step")),
+ "shows ancestor node as section"
+ );
+ });
+
+ test("environment fields match schema symbols", async function (assert) {
+ const node = {
+ clientId: "n1",
+ type: "action:http_request",
+ name: "HTTP",
+ };
+
+ await render(
+ <template>
+ <InputContext
+ @node={{node}}
+ @nodes={{Array node}}
+ @connections={{(Array)}}
+ @nodeTypes={{(Array)}}
+ @session={{this.session}}
+ />
+ </template>
+ );
+
+ const service = this.owner.lookup("service:workflows-node-types");
+ const expectedSymbols = Object.keys(
+ service.expressionContext.environment || {}
+ );
+
+ const sections = this.element.querySelectorAll(
+ ".workflows-context-panel__section"
+ );
+ const envSection = sections[0];
+ const fieldKeys = [
+ ...envSection.querySelectorAll(
+ ":scope > .workflows-schema-field-list > .workflows-schema-field"
+ ),
+ ].map((el) =>
+ el.querySelector(".workflows-schema-field__key")?.textContent.trim()
+ );
+
+ expectedSymbols.forEach((symbol) => {
+ const displayKey = symbol.replace(/^\$/, "");
+ assert.true(
+ fieldKeys.includes(displayKey),
+ `expected environment field "${displayKey}" (from schema symbol "${symbol}") to be rendered`
+ );
+ });
+ });
+});
diff --git a/plugins/discourse-workflows/test/javascripts/integration/components/workflows/context-output-test.gjs b/plugins/discourse-workflows/test/javascripts/integration/components/workflows/context-output-test.gjs
new file mode 100644
index 00000000000..a991e544e0d
--- /dev/null
+++ b/plugins/discourse-workflows/test/javascripts/integration/components/workflows/context-output-test.gjs
@@ -0,0 +1,352 @@
+import { render } from "@ember/test-helpers";
+import { module, test } from "qunit";
+import { setupRenderingTest } from "discourse/tests/helpers/component-test";
+import OutputContext from "discourse/plugins/discourse-workflows/admin/components/workflows/context/output";
+import WorkflowEditorSession from "discourse/plugins/discourse-workflows/admin/lib/workflows/editor-session";
+
+module("Integration | Component | workflows/context/output", function (hooks) {
+ setupRenderingTest(hooks);
+
+ hooks.beforeEach(function () {
+ this.session = new WorkflowEditorSession({ lastExecutionRunData: {} });
+ });
+
+ hooks.afterEach(function () {
+ this.owner.lookup("service:workflows-node-types").clear();
+ });
+
+ test("renders output fields from execution run data", async function (assert) {
+ const node = {
+ clientId: "n1",
+ name: "Sample",
+ type: "action:http_request",
+ typeVersion: "1.0",
+ configuration: {},
+ };
+ const nodes = [node];
+ this.session.lastExecutionRunData = {
+ Sample: [
+ {
+ status: "success",
+ outputs: [
+ {
+ index: 0,
+ items: [
+ { json: { body: { ok: true }, status: 200 } },
+ { json: { body: { ok: false }, status: 500 } },
+ ],
+ item_count: 2,
+ },
+ ],
+ },
+ ],
+ };
+
+ await render(
+ <template>
+ <OutputContext
+ @node={{node}}
+ @nodes={{nodes}}
+ @connections={{(Array)}}
+ @nodeTypes={{(Array)}}
+ @session={{this.session}}
+ />
+ </template>
+ );
+
+ assert.dom(".workflows-context-panel__title-meta").hasText("2 items");
+ assert
+ .dom(".workflows-context-panel__hint")
+ .hasText(
+ "Tip Now that you have output data for this node, you can pin it and use it when executing this trigger manually with the green play button."
+ );
+ assert.dom(".workflows-context-panel__item-title").doesNotExist();
+ const keys = [
+ ...this.element.querySelectorAll(".workflows-schema-field__key-title"),
+ ].map((el) => el.textContent.trim());
+ assert.deepEqual(keys, ["body", "status"]);
+ });
+
+ test("asks the user to run the workflow when no execution output is available", async function (assert) {
+ const node = {
+ clientId: "n1",
+ name: "Sample",
+ type: "action:http_request",
+ typeVersion: "1.0",
+ configuration: {},
+ };
+
+ await render(
+ <template>
+ <OutputContext
+ @node={{node}}
+ @nodes={{Array node}}
+ @connections={{(Array)}}
+ @nodeTypes={{(Array)}}
+ @session={{this.session}}
+ />
+ </template>
+ );
+
+ assert
+ .dom(".workflows-context-panel__empty-state-title")
+ .hasText("No output yet");
+ assert.dom(".workflows-context-panel__hint").doesNotExist();
+ assert
+ .dom(".workflows-context-panel__empty-state-btn")
+ .hasText(/Add sample data/);
+ });
+
+ test("does not show the pin tip when output data is already pinned", async function (assert) {
+ const node = {
+ clientId: "n1",
+ name: "Sample",
+ type: "action:http_request",
+ typeVersion: "1.0",
+ configuration: {},
+ };
+ const session = new WorkflowEditorSession({
+ lastExecutionRunData: {
+ Sample: [
+ {
+ status: "success",
+ outputs: [
+ {
+ index: 0,
+ items: [{ json: { body: { ok: true }, status: 200 } }],
+ item_count: 1,
+ },
+ ],
+ },
+ ],
+ },
+ pinData: {
+ Sample: [{ json: { body: { pinned: true }, status: 200 } }],
+ },
+ });
+
+ await render(
+ <template>
+ <OutputContext
+ @node={{node}}
+ @nodes={{Array node}}
+ @connections={{(Array)}}
+ @nodeTypes={{(Array)}}
+ @session={{session}}
+ />
+ </template>
+ );
+
+ assert.dom(".workflows-context-panel__pin-banner").exists();
+ assert.dom(".workflows-context-panel__hint").doesNotExist();
+ });
+
+ test("shows an empty output state when the node executed with zero items", async function (assert) {
+ const node = {
+ clientId: "n1",
+ name: "Sample",
+ type: "action:log",
+ typeVersion: "1.0",
+ configuration: {},
+ };
+ this.session.lastExecutionRunData = {
+ Sample: [
+ {
+ status: "success",
+ outputs: [{ index: 0, items: [], item_count: 0 }],
+ },
+ ],
+ };
+
+ await render(
+ <template>
+ <OutputContext
+ @node={{node}}
+ @nodes={{Array node}}
+ @connections={{(Array)}}
+ @nodeTypes={{(Array)}}
+ @session={{this.session}}
+ />
+ </template>
+ );
+
+ assert.dom(".workflows-context-panel__title-meta").doesNotExist();
+ assert.dom(".workflows-context-panel__empty").hasText("No output data");
+ });
+
+ test("shows item count and field-empty state for real empty output items", async function (assert) {
+ const node = {
+ clientId: "n1",
+ name: "Sample",
+ type: "action:http_request",
+ typeVersion: "1.0",
+ configuration: {},
+ };
+ this.session.lastExecutionRunData = {
+ Sample: [
+ {
+ status: "success",
+ outputs: [{ index: 0, items: [{ json: {} }], item_count: 1 }],
+ },
+ ],
+ };
+
+ await render(
+ <template>
+ <OutputContext
+ @node={{node}}
+ @nodes={{Array node}}
+ @connections={{(Array)}}
+ @nodeTypes={{(Array)}}
+ @session={{this.session}}
+ />
+ </template>
+ );
+
+ assert.dom(".workflows-context-panel__title-meta").hasText("1 item");
+ assert.dom(".workflows-context-panel__empty").hasText("No output fields");
+ });
+
+ test("does not show stale fields after a later zero-item output", async function (assert) {
+ const node = {
+ clientId: "n1",
+ name: "Sample",
+ type: "action:log",
+ typeVersion: "1.0",
+ configuration: {},
+ };
+ this.session.lastExecutionRunData = {
+ Sample: [
+ {
+ status: "success",
+ outputs: [
+ { index: 0, items: [{ json: { stale: true } }], item_count: 1 },
+ ],
+ },
+ {
+ status: "success",
+ outputs: [{ index: 0, items: [], item_count: 0 }],
+ },
+ ],
+ };
+
+ await render(
+ <template>
+ <OutputContext
+ @node={{node}}
+ @nodes={{Array node}}
+ @connections={{(Array)}}
+ @nodeTypes={{(Array)}}
+ @session={{this.session}}
+ />
+ </template>
+ );
+
+ assert.dom(".workflows-schema-field__key-title").doesNotExist();
+ assert.dom(".workflows-context-panel__empty").hasText("No output data");
+ });
+
+ test("merges fields across output items without rendering item rows", async function (assert) {
+ const node = {
+ clientId: "n1",
+ name: "Sample",
+ type: "action:http_request",
+ typeVersion: "1.0",
+ configuration: {},
+ };
+ this.session.lastExecutionRunData = {
+ Sample: [
+ {
+ status: "success",
+ outputs: [
+ {
+ index: 0,
+ items: [{ json: {} }, { json: { result: "ok" } }],
+ item_count: 2,
+ },
+ ],
+ },
+ ],
+ };
+
+ await render(
+ <template>
+ <OutputContext
+ @node={{node}}
+ @nodes={{Array node}}
+ @connections={{(Array)}}
+ @nodeTypes={{(Array)}}
+ @session={{this.session}}
+ />
+ </template>
+ );
+
+ const itemTitles = [
+ ...this.element.querySelectorAll(".workflows-context-panel__item-title"),
+ ].map((el) => el.textContent.trim());
+ const keys = [
+ ...this.element.querySelectorAll(".workflows-schema-field__key-title"),
+ ].map((el) => el.textContent.trim());
+
+ assert.deepEqual(itemTitles, []);
+ assert.dom(".workflows-context-panel__title-meta").hasText("2 items");
+ assert.deepEqual(keys, ["result"]);
+ });
+
+ test("combines output indexes into one output schema", async function (assert) {
+ const node = {
+ clientId: "n1",
+ name: "Sample",
+ type: "condition:if",
+ typeVersion: "1.0",
+ configuration: {},
+ };
+ this.session.lastExecutionRunData = {
+ Sample: [
+ {
+ status: "success",
+ outputs: [
+ {
+ index: 0,
+ items: [{ json: { topic: { id: 1 } } }],
+ item_count: 1,
+ },
+ {
+ index: 1,
+ items: [],
+ item_count: 0,
+ },
+ ],
+ },
+ ],
+ };
+
+ await render(
+ <template>
+ <OutputContext
+ @node={{node}}
+ @nodes={{Array node}}
+ @connections={{(Array)}}
+ @nodeTypes={{(Array)}}
+ @session={{this.session}}
+ />
+ </template>
+ );
+
+ const subtitles = [
+ ...this.element.querySelectorAll(".workflows-context-panel__subtitle"),
+ ].map((el) => el.textContent.replace(/\s+/g, " ").trim());
+ const keys = [
+ ...this.element.querySelectorAll(".workflows-schema-field__key-title"),
+ ].map((el) => el.textContent.trim());
+
+ assert.deepEqual(subtitles, []);
+ assert
+ .dom(
+ ".workflows-context-panel__header .workflows-context-panel__title-meta"
+ )
+ .hasText("1 item");
+ assert.dom(".workflows-context-panel__empty").doesNotExist();
+ assert.deepEqual(keys, ["topic"]);
+ });
+});
diff --git a/plugins/discourse-workflows/test/javascripts/integration/components/workflows/pin-data-editor-test.gjs b/plugins/discourse-workflows/test/javascripts/integration/components/workflows/pin-data-editor-test.gjs
new file mode 100644
index 00000000000..25c69dca16c
--- /dev/null
+++ b/plugins/discourse-workflows/test/javascripts/integration/components/workflows/pin-data-editor-test.gjs
@@ -0,0 +1,285 @@
+import { click, render, settled, waitFor } from "@ember/test-helpers";
+import { module, test } from "qunit";
+import { setupRenderingTest } from "discourse/tests/helpers/component-test";
+import pretender, { response } from "discourse/tests/helpers/create-pretender";
+import PinDataEditor from "discourse/plugins/discourse-workflows/admin/components/workflows/context/pin-data-editor";
+import WorkflowEditorSession from "discourse/plugins/discourse-workflows/admin/lib/workflows/editor-session";
+
+async function setBuffer(element, value) {
+ const editorContent = element.querySelector(
+ ".workflows-context-panel__editor .cm-content"
+ );
+ if (!editorContent) {
+ throw new Error("CodeMirror content not found");
+ }
+ const view = editorContent.cmTile?.root?.view;
+ if (!view) {
+ throw new Error("CodeMirror view not found");
+ }
+ view.dispatch({
+ changes: { from: 0, to: view.state.doc.length, insert: value },
+ });
+ await settled();
+}
+
+module(
+ "Integration | Component | workflows/context/pin-data-editor",
+ function (hooks) {
+ setupRenderingTest(hooks);
+
+ hooks.beforeEach(function () {
+ this.session = new WorkflowEditorSession({ workflowId: 7, pinData: {} });
+ });
+
+ hooks.afterEach(function () {
+ this.owner.lookup("service:workflows-node-types").clear();
+ });
+
+ test("renders the empty-state CTA when there are no items", async function (assert) {
+ await render(
+ <template>
+ <PinDataEditor
+ @nodeName="n1"
+ @initialItems={{undefined}}
+ @canEdit={{true}}
+ @session={{this.session}}
+ />
+ </template>
+ );
+
+ assert.dom(".workflows-context-panel__empty-state").exists();
+ assert
+ .dom(".workflows-context-panel__empty-state-btn")
+ .hasText(/Add sample data/);
+ });
+
+ test("clicking Add sample data enters edit mode with the empty seed", async function (assert) {
+ await render(
+ <template>
+ <PinDataEditor
+ @nodeName="n1"
+ @initialItems={{undefined}}
+ @canEdit={{true}}
+ @session={{this.session}}
+ />
+ </template>
+ );
+
+ await click(".workflows-context-panel__empty-state-btn");
+ await waitFor(".cm-editor");
+
+ const text = this.element
+ .querySelector(".cm-content")
+ ?.textContent.replace(/\s+/g, "");
+ assert.strictEqual(
+ text,
+ "[{}]",
+ `expected seed to be the unwrapped '[{}]', got ${text}`
+ );
+ });
+
+ test("disables Save when JSON is invalid", async function (assert) {
+ await render(
+ <template>
+ <PinDataEditor
+ @nodeName="n1"
+ @initialItems={{undefined}}
+ @canEdit={{true}}
+ @session={{this.session}}
+ />
+ </template>
+ );
+
+ await click(".workflows-context-panel__empty-state-btn");
+ await waitFor(".cm-editor");
+
+ await setBuffer(this.element, "{ not json");
+ await waitFor(".workflows-context-panel__editor-error");
+
+ assert
+ .dom(".workflows-context-panel__editor-save")
+ .hasAttribute("disabled");
+ assert
+ .dom(".workflows-context-panel__editor-error")
+ .containsText("Invalid JSON");
+ });
+
+ test("disables Save when shape is invalid", async function (assert) {
+ await render(
+ <template>
+ <PinDataEditor
+ @nodeName="n1"
+ @initialItems={{undefined}}
+ @canEdit={{true}}
+ @session={{this.session}}
+ />
+ </template>
+ );
+
+ await click(".workflows-context-panel__empty-state-btn");
+ await waitFor(".cm-editor");
+
+ await setBuffer(this.element, '"not an array"');
+ await waitFor(".workflows-context-panel__editor-error");
+
+ assert
+ .dom(".workflows-context-panel__editor-save")
+ .hasAttribute("disabled");
+ assert
+ .dom(".workflows-context-panel__editor-error")
+ .containsText("Pinned data must be an array of items");
+ });
+
+ test("Save calls pinNodeData and exits edit mode", async function (assert) {
+ let requestBody = null;
+ pretender.put(
+ "/admin/plugins/discourse-workflows/workflows/7/pin-data.json",
+ (request) => {
+ requestBody = JSON.parse(request.requestBody);
+ return response(200, {});
+ }
+ );
+
+ await render(
+ <template>
+ <PinDataEditor
+ @nodeName="n1"
+ @initialItems={{undefined}}
+ @canEdit={{true}}
+ @session={{this.session}}
+ />
+ </template>
+ );
+
+ await click(".workflows-context-panel__empty-state-btn");
+ await waitFor(".cm-editor");
+
+ // Unwrapped form — the editor wraps it as `{json: ...}` on save.
+ await setBuffer(this.element, '[{"id": 42}]');
+ await waitFor(".workflows-context-panel__editor-save:not([disabled])");
+
+ await click(".workflows-context-panel__editor-save");
+
+ assert.deepEqual(
+ requestBody,
+ { node_name: "n1", items: [{ json: { id: 42 } }] },
+ "PUT payload wraps the unwrapped buffer back into storage shape"
+ );
+
+ assert.deepEqual(
+ this.session.pinData,
+ { n1: [{ json: { id: 42 } }] },
+ "session pinData is updated optimistically with wrapped items"
+ );
+
+ assert
+ .dom(".workflows-context-panel__editor-toolbar")
+ .doesNotExist("Save/Cancel toolbar hides after a successful save");
+ });
+
+ test("Save also accepts the wrapped {json: ...} storage form", async function (assert) {
+ let requestBody = null;
+ pretender.put(
+ "/admin/plugins/discourse-workflows/workflows/7/pin-data.json",
+ (request) => {
+ requestBody = JSON.parse(request.requestBody);
+ return response(200, {});
+ }
+ );
+
+ await render(
+ <template>
+ <PinDataEditor
+ @nodeName="n1"
+ @initialItems={{undefined}}
+ @canEdit={{true}}
+ @session={{this.session}}
+ />
+ </template>
+ );
+
+ await click(".workflows-context-panel__empty-state-btn");
+ await waitFor(".cm-editor");
+
+ await setBuffer(this.element, '[{"json": {"id": 1}}]');
+ await waitFor(".workflows-context-panel__editor-save:not([disabled])");
+ await click(".workflows-context-panel__editor-save");
+
+ assert.deepEqual(requestBody, {
+ node_name: "n1",
+ items: [{ json: { id: 1 } }],
+ });
+ });
+
+ test("renders the editor pre-populated with unwrapped items and no Save toolbar", async function (assert) {
+ const items = [{ json: { hello: "world" } }];
+
+ await render(
+ <template>
+ <PinDataEditor
+ @nodeName="n1"
+ @initialItems={{items}}
+ @canEdit={{true}}
+ @session={{this.session}}
+ />
+ </template>
+ );
+
+ await waitFor(".cm-editor");
+
+ assert
+ .dom(".workflows-context-panel__editor-toolbar")
+ .doesNotExist("Save/Cancel toolbar only appears when buffer is dirty");
+ assert.dom(".workflows-context-panel__empty-state").doesNotExist();
+ const text = this.element
+ .querySelector(".cm-content")
+ ?.textContent.replace(/\s+/g, "");
+ assert.true(
+ text.includes('"hello":"world"'),
+ `expected unwrapped JSON to contain '"hello":"world"', got ${text}`
+ );
+ assert.false(
+ text.includes('"json":'),
+ "the JSON envelope must not be shown to the user"
+ );
+ });
+
+ test("Save/Cancel toolbar appears once the buffer is edited", async function (assert) {
+ const items = [{ json: { hello: "world" } }];
+
+ await render(
+ <template>
+ <PinDataEditor
+ @nodeName="n1"
+ @initialItems={{items}}
+ @canEdit={{true}}
+ @session={{this.session}}
+ />
+ </template>
+ );
+
+ await waitFor(".cm-editor");
+ await setBuffer(this.element, '[{"hello": "edited"}]');
+
+ assert.dom(".workflows-context-panel__editor-toolbar").exists();
+ assert.dom(".workflows-context-panel__editor-save").exists();
+ assert.dom(".workflows-context-panel__editor-cancel").exists();
+ });
+
+ test("read-only empty state when canEdit is false", async function (assert) {
+ await render(
+ <template>
+ <PinDataEditor
+ @nodeName="n1"
+ @initialItems={{undefined}}
+ @canEdit={{false}}
+ @session={{this.session}}
+ />
+ </template>
+ );
+
+ assert.dom(".workflows-context-panel__empty-state-btn").doesNotExist();
+ assert.dom(".workflows-context-panel__empty-state-title").exists();
+ });
+ }
+);
diff --git a/plugins/discourse-workflows/test/javascripts/integration/components/workflows/property-engine-test.gjs b/plugins/discourse-workflows/test/javascripts/integration/components/workflows/property-engine-test.gjs
new file mode 100644
index 00000000000..60b50983625
--- /dev/null
+++ b/plugins/discourse-workflows/test/javascripts/integration/components/workflows/property-engine-test.gjs
@@ -0,0 +1,700 @@
+import {
+ click,
+ fillIn,
+ findAll,
+ render,
+ select,
+ waitFor,
+} from "@ember/test-helpers";
+import { module, test } from "qunit";
+import sinon from "sinon";
+import Form from "discourse/components/form";
+import { setupRenderingTest } from "discourse/tests/helpers/component-test";
+import pretender, { response } from "discourse/tests/helpers/create-pretender";
+import selectKit from "discourse/tests/helpers/select-kit-helper";
+import PropertyEngineConfigurator from "discourse/plugins/discourse-workflows/admin/components/workflows/configurators/property-engine";
+import WorkflowEditorSession from "discourse/plugins/discourse-workflows/admin/lib/workflows/editor-session";
+
+module("Integration | Component | workflows property engine", function (hooks) {
+ setupRenderingTest(hooks);
+
+ hooks.beforeEach(function () {
+ pretender.get("/svg-sprite/picker-search", () =>
+ response(200, [
+ { id: "gear", symbol: '<symbol id="gear"></symbol>' },
+ { id: "bolt", symbol: '<symbol id="bolt"></symbol>' },
+ ])
+ );
+ pretender.get("/admin/plugins/discourse-workflows/variables.json", () =>
+ response(200, { variables: [] })
+ );
+ this.session = new WorkflowEditorSession({
+ workflowId: 7,
+ lastExecutionRunData: {},
+ });
+ });
+
+ hooks.afterEach(function () {
+ sinon.restore();
+ });
+
+ test("preserves focus for scalar fields while typing", async function (assert) {
+ this.setProperties({
+ configuration: { title: "" },
+ nodeType: "action:topic",
+ schema: {
+ title: {
+ type: "string",
+ required: true,
+ },
+ },
+ });
+
+ await render(
+ <template>
+ <Form @data={{this.configuration}} as |form transientData|>
+ <PropertyEngineConfigurator
+ @form={{form}}
+ @configuration={{transientData}}
+ @nodeType={{this.nodeType}}
+ @schema={{this.schema}}
+ @session={{this.session}}
+ />
+ </Form>
+ </template>
+ );
+
+ await fillIn("input", "Hello");
+
+ assert.dom("input").hasValue("Hello");
+ assert.dom("input").isFocused();
+ });
+
+ test("preserves focus for collection fields while typing", async function (assert) {
+ this.setProperties({
+ configuration: {
+ headers: { values: [{ key: "", value: "" }] },
+ },
+ nodeType: "action:http_request",
+ schema: {
+ headers: {
+ type: "fixed_collection",
+ options: [
+ {
+ name: "values",
+ values: {
+ key: {
+ type: "string",
+ required: true,
+ },
+ value: {
+ type: "string",
+ required: true,
+ },
+ },
+ },
+ ],
+ },
+ },
+ });
+
+ await render(
+ <template>
+ <Form @data={{this.configuration}} as |form transientData|>
+ <PropertyEngineConfigurator
+ @form={{form}}
+ @configuration={{transientData}}
+ @nodeType={{this.nodeType}}
+ @schema={{this.schema}}
+ @session={{this.session}}
+ />
+ </Form>
+ </template>
+ );
+
+ let [keyInput] = findAll(
+ ".workflows-property-engine__collection-row input"
+ );
+
+ await fillIn(keyInput, "Authorization");
+
+ [keyInput] = findAll(".workflows-property-engine__collection-row input");
+
+ assert.strictEqual(keyInput.value, "Authorization");
+ assert.strictEqual(document.activeElement, keyInput);
+ });
+
+ test("renders fixed collections with missing group data", async function (assert) {
+ this.setProperties({
+ configuration: { entries: {} },
+ formApi: null,
+ nodeType: "action:log",
+ schema: {
+ entries: {
+ type: "fixed_collection",
+ type_options: {
+ multiple_values: true,
+ },
+ options: [
+ {
+ name: "values",
+ values: {
+ key: {
+ type: "string",
+ required: true,
+ no_data_expression: true,
+ },
+ value: {
+ type: "string",
+ required: true,
+ },
+ },
+ },
+ ],
+ },
+ },
+ registerApi: (api) => {
+ this.set("formApi", api);
+ },
+ });
+
+ await render(
+ <template>
+ <Form
+ @data={{this.configuration}}
+ @onRegisterApi={{this.registerApi}}
+ as |form transientData|
+ >
+ <PropertyEngineConfigurator
+ @form={{form}}
+ @formApi={{this.formApi}}
+ @configuration={{transientData}}
+ @nodeType={{this.nodeType}}
+ @schema={{this.schema}}
+ @session={{this.session}}
+ />
+ </Form>
+ </template>
+ );
+
+ assert.dom(".workflows-property-engine__collection-row").doesNotExist();
+
+ await click(".btn-default");
+
+ assert.dom(".workflows-property-engine__collection-row").exists();
+ assert.strictEqual(this.formApi.get("entries.values").length, 1);
+ });
+
+ test("renders condition builder controls inside the property engine", async function (assert) {
+ this.setProperties({
+ configuration: {
+ conditions: [],
+ },
+ formApi: null,
+ node: {
+ clientId: "branch",
+ type: "condition:if",
+ },
+ nodes: [
+ {
+ clientId: "trigger",
+ type: "trigger:manual",
+ name: "Trigger",
+ },
+ {
+ clientId: "secondary",
+ type: "action:http_request",
+ name: "Secondary",
+ },
+ {
+ clientId: "branch",
+ type: "condition:if",
+ name: "Branch",
+ },
+ ],
+ connections: [
+ {
+ sourceClientId: "trigger",
+ targetClientId: "branch",
+ },
+ {
+ sourceClientId: "secondary",
+ targetClientId: "branch",
+ targetInputIndex: 1,
+ },
+ ],
+ nodeTypes: [],
+ nodeType: "condition:if",
+ schema: {
+ conditions: {
+ type: "array",
+ ui: {
+ control: "condition_builder",
+ },
+ },
+ },
+ registerApi: (api) => {
+ this.set("formApi", api);
+ },
+ });
+ this.session.lastExecutionRunData = {
+ Trigger: [
+ {
+ status: "success",
+ outputs: [
+ {
+ index: 0,
+ items: [
+ { json: { status: "ok", "topic title": { "post-count": 2 } } },
+ ],
+ item_count: 1,
+ },
+ ],
+ },
+ ],
+ Secondary: [
+ {
+ status: "success",
+ outputs: [
+ {
+ index: 0,
+ items: [{ json: { secondary_status: "ok" } }],
+ item_count: 1,
+ },
+ ],
+ },
+ ],
+ };
+
+ await render(
+ <template>
+ <Form
+ @data={{this.configuration}}
+ @onRegisterApi={{this.registerApi}}
+ as |form transientData|
+ >
+ <PropertyEngineConfigurator
+ @form={{form}}
+ @formApi={{this.formApi}}
+ @configuration={{transientData}}
+ @connections={{this.connections}}
+ @node={{this.node}}
+ @nodes={{this.nodes}}
+ @nodeType={{this.nodeType}}
+ @nodeTypes={{this.nodeTypes}}
+ @schema={{this.schema}}
+ @session={{this.session}}
+ />
+ </Form>
+ </template>
+ );
+
+ await click(".workflows-empty-state .btn-primary");
+
+ const conditions = this.formApi.get("conditions");
+ assert.strictEqual(conditions.length, 1);
+ assert.dom(".workflows-property-engine__collection-row").exists();
+ assert
+ .dom(
+ ".workflows-property-engine__collection-row option[value='$json.status']"
+ )
+ .exists();
+ assert
+ .dom(
+ '.workflows-property-engine__collection-row option[value=\'$json["topic title"]["post-count"]\']'
+ )
+ .exists();
+ assert
+ .dom(
+ ".workflows-property-engine__collection-row option[value='$(\"Secondary\").all(0)[$itemIndex].json.secondary_status']"
+ )
+ .hasText("Secondary.secondary_status");
+
+ await select(
+ ".workflows-property-engine__collection-row select",
+ '$json["topic title"]["post-count"]'
+ );
+
+ assert.strictEqual(
+ this.formApi.get("conditions.0.leftValue"),
+ '={{ $json["topic title"]["post-count"] }}'
+ );
+ });
+
+ test("renders webhook URL previews from schema controls", async function (assert) {
+ this.setProperties({
+ configuration: { path: "my-hook" },
+ nodeType: "trigger:webhook",
+ schema: {
+ path: {
+ type: "string",
+ },
+ url_preview: {
+ type: "custom",
+ ui: {
+ control: "url_preview",
+ },
+ },
+ },
+ });
+
+ await render(
+ <template>
+ <Form @data={{this.configuration}} as |form transientData|>
+ <PropertyEngineConfigurator
+ @form={{form}}
+ @configuration={{transientData}}
+ @nodeType={{this.nodeType}}
+ @schema={{this.schema}}
+ @session={{this.session}}
+ />
+ </Form>
+ </template>
+ );
+
+ assert
+ .dom(".workflows-url-preview code")
+ .includesText("/workflows/webhooks/my-hook");
+ });
+
+ test("renders form trigger test and production URL controls", async function (assert) {
+ sinon.stub(window, "open");
+ pretender.post(
+ "/admin/plugins/discourse-workflows/workflows/7/form-test-sessions.json",
+ (request) => {
+ assert.strictEqual(
+ request.requestBody,
+ "trigger_node_id=trigger-1",
+ "posts the selected form trigger node id"
+ );
+ return response(201, {
+ test_url: "/workflows/form-test/test-token",
+ });
+ }
+ );
+
+ this.setProperties({
+ configuration: {},
+ node: {
+ clientId: "trigger-1",
+ type: "trigger:form",
+ webhookId: "a1b2c3d4-e5f6-7890-abcd-ef0123456789",
+ },
+ nodeType: "trigger:form",
+ schema: {
+ url_preview: {
+ type: "custom",
+ ui: {
+ control: "url_preview",
+ },
+ },
+ },
+ });
+
+ await render(
+ <template>
+ <Form @data={{this.configuration}} as |form transientData|>
+ <PropertyEngineConfigurator
+ @form={{form}}
+ @configuration={{transientData}}
+ @node={{this.node}}
+ @nodeType={{this.nodeType}}
+ @schema={{this.schema}}
+ @session={{this.session}}
+ />
+ </Form>
+ </template>
+ );
+
+ assert.dom(".workflows-url-preview-mode__button").exists({ count: 2 });
+ assert
+ .dom(".workflows-url-preview code")
+ .includesText("/workflows/form/a1b2c3d4-e5f6-7890-abcd-ef0123456789");
+
+ await click(".workflows-url-preview-mode__button:first-child");
+ assert
+ .dom(".workflows-url-preview code")
+ .includesText("Listen for test event");
+
+ await click(".workflows-url-preview");
+
+ assert.true(window.open.calledOnce);
+ assert
+ .dom(".workflows-url-preview code")
+ .includesText("/workflows/form-test/test-token");
+ });
+
+ test("renders webhook trigger test and production URL controls", async function (assert) {
+ pretender.post(
+ "/admin/plugins/discourse-workflows/workflows/7/webhook-test-listeners.json",
+ (request) => {
+ assert.strictEqual(
+ request.requestBody,
+ "trigger_node_id=webhook-1",
+ "posts the selected webhook trigger node id"
+ );
+ return response(201, {
+ listener_id: "listener-1",
+ test_url: "/workflows/webhook-test/listener-1/my-hook",
+ expires_at: new Date(Date.now() + 120_000).toISOString(),
+ });
+ }
+ );
+
+ this.setProperties({
+ configuration: { path: "my-hook" },
+ node: { clientId: "webhook-1", type: "trigger:webhook" },
+ nodeType: "trigger:webhook",
+ schema: {
+ path: {
+ type: "string",
+ },
+ url_preview: {
+ type: "custom",
+ ui: {
+ control: "url_preview",
+ },
+ },
+ },
+ });
+
+ await render(
+ <template>
+ <Form @data={{this.configuration}} as |form transientData|>
+ <PropertyEngineConfigurator
+ @form={{form}}
+ @configuration={{transientData}}
+ @node={{this.node}}
+ @nodeType={{this.nodeType}}
+ @schema={{this.schema}}
+ @session={{this.session}}
+ />
+ </Form>
+ </template>
+ );
+
+ assert.dom(".workflows-url-preview-mode__button").exists({ count: 2 });
+ assert
+ .dom(".workflows-url-preview code")
+ .includesText("/workflows/webhooks/my-hook");
+
+ await click(".workflows-url-preview-mode__button:first-child");
+ assert
+ .dom(".workflows-url-preview code")
+ .includesText("Listen for test event");
+
+ await click(".workflows-url-preview");
+
+ assert
+ .dom(".workflows-url-preview code")
+ .includesText("/workflows/webhook-test/listener-1/my-hook");
+ assert
+ .dom(".workflows-url-preview__status")
+ .includesText("Listening for test event");
+ });
+
+ test("renders icon fields with the form-kit icon control", async function (assert) {
+ this.setProperties({
+ configuration: { icon: "gear" },
+ formApi: null,
+ nodeType: "trigger:topic_admin_button",
+ schema: {
+ icon: {
+ type: "icon",
+ },
+ },
+ registerApi: (api) => {
+ this.set("formApi", api);
+ },
+ });
+
+ await render(
+ <template>
+ <Form
+ @data={{this.configuration}}
+ @onRegisterApi={{this.registerApi}}
+ as |form transientData|
+ >
+ <PropertyEngineConfigurator
+ @form={{form}}
+ @formApi={{this.formApi}}
+ @configuration={{transientData}}
+ @nodeType={{this.nodeType}}
+ @schema={{this.schema}}
+ @session={{this.session}}
+ />
+ </Form>
+ </template>
+ );
+
+ assert.dom(".form-kit__control-icon").exists();
+ assert.dom(".form-kit__control-icon").hasAttribute("data-value", "gear");
+
+ await click(".form-kit__control-icon .d-icon-grid-picker-trigger");
+ await waitFor(".d-icon-grid-picker__icon");
+ await click('[data-icon-id="bolt"]');
+
+ assert.dom(".form-kit__control-icon").hasAttribute("data-value", "bolt");
+
+ await click(
+ '.workflows-property-engine__mode-control input[value="dynamic"]'
+ );
+
+ assert.strictEqual(this.formApi.get("icon"), "=bolt");
+ assert.dom(".workflows-variable-input").exists();
+ });
+
+ test("shows expected value hints in dynamic mode", async function (assert) {
+ this.setProperties({
+ configuration: { channel_id: "2" },
+ formApi: null,
+ nodeType: "action:send_chat_message",
+ schema: {
+ channel_id: {
+ type: "integer",
+ ui: {
+ dynamic_value: "chat_channel_id",
+ },
+ },
+ },
+ registerApi: (api) => {
+ this.set("formApi", api);
+ },
+ });
+
+ await render(
+ <template>
+ <Form
+ @data={{this.configuration}}
+ @onRegisterApi={{this.registerApi}}
+ as |form transientData|
+ >
+ <PropertyEngineConfigurator
+ @form={{form}}
+ @formApi={{this.formApi}}
+ @configuration={{transientData}}
+ @nodeType={{this.nodeType}}
+ @schema={{this.schema}}
+ @session={{this.session}}
+ />
+ </Form>
+ </template>
+ );
+
+ assert.dom(".workflows-property-engine__dynamic-hint").doesNotExist();
+
+ await click(
+ '.workflows-property-engine__mode-control input[value="dynamic"]'
+ );
+
+ assert
+ .dom(".workflows-property-engine__dynamic-hint")
+ .hasText("Must resolve to a chat channel ID.");
+ });
+
+ test("select fields render with correct initial value", async function (assert) {
+ this.setProperties({
+ configuration: { combinator: "or" },
+ nodeType: "condition:if",
+ schema: {
+ combinator: {
+ type: "options",
+ options: ["and", "or"],
+ default: "and",
+ no_data_expression: true,
+ },
+ },
+ });
+
+ await render(
+ <template>
+ <Form @data={{this.configuration}} as |form transientData|>
+ <PropertyEngineConfigurator
+ @form={{form}}
+ @configuration={{transientData}}
+ @nodeType={{this.nodeType}}
+ @schema={{this.schema}}
+ @session={{this.session}}
+ />
+ </Form>
+ </template>
+ );
+
+ assert.dom("select").hasValue("or");
+ });
+
+ test("renders combo boxes from metadata and applies option patches", async function (assert) {
+ this.setProperties({
+ configuration: { agent_id: 2, agent_name: "" },
+ formApi: null,
+ nodeType: "action:ai_agent",
+ nodeTypes: [
+ {
+ identifier: "action:ai_agent",
+ metadata: {
+ agents: [
+ { id: 1, name: "Support Bot" },
+ { id: 2, name: "Helper Bot" },
+ ],
+ i18n_prefix: "discourse_ai.discourse_workflows",
+ },
+ },
+ ],
+ schema: {
+ agent_id: {
+ type: "integer",
+ required: true,
+ type_options: {
+ load_options_method: "agents",
+ },
+ no_data_expression: true,
+ ui: {
+ control: "combo_box",
+ },
+ control_options: {
+ filterable: true,
+ name_property: "name",
+ none: "discourse_ai.discourse_workflows.ai_agent.select_agent",
+ set_from_option: {
+ agent_name: "name",
+ },
+ value_property: "id",
+ },
+ },
+ },
+ registerApi: (api) => {
+ this.set("formApi", api);
+ },
+ });
+
+ await render(
+ <template>
+ <Form
+ @data={{this.configuration}}
+ @onRegisterApi={{this.registerApi}}
+ as |form transientData|
+ >
+ <PropertyEngineConfigurator
+ @form={{form}}
+ @formApi={{this.formApi}}
+ @configuration={{transientData}}
+ @nodeType={{this.nodeType}}
+ @nodeTypes={{this.nodeTypes}}
+ @schema={{this.schema}}
+ @session={{this.session}}
+ />
+ </Form>
+ </template>
+ );
+
+ const selector = selectKit(".combo-box");
+ assert.strictEqual(selector.header().value(), "2");
+ assert.strictEqual(selector.header().label(), "Helper Bot");
+
+ await selector.expand();
+ await selector.selectRowByValue("1");
+
+ assert.strictEqual(String(this.formApi.get("agent_id")), "1");
+ assert.strictEqual(this.formApi.get("agent_name"), "Support Bot");
+ });
+});
diff --git a/plugins/discourse-workflows/test/javascripts/integration/components/workflows/variable-input-test.gjs b/plugins/discourse-workflows/test/javascripts/integration/components/workflows/variable-input-test.gjs
new file mode 100644
index 00000000000..a8653acbde2
--- /dev/null
+++ b/plugins/discourse-workflows/test/javascripts/integration/components/workflows/variable-input-test.gjs
@@ -0,0 +1,82 @@
+import { render, waitFor } from "@ember/test-helpers";
+import { module, test } from "qunit";
+import { setupRenderingTest } from "discourse/tests/helpers/component-test";
+import pretender, { response } from "discourse/tests/helpers/create-pretender";
+import VariableInput from "discourse/plugins/discourse-workflows/admin/components/workflows/variable/input";
+
+function editorText(element) {
+ return element.querySelector(".cm-content")?.textContent ?? "";
+}
+
+module("Integration | Component | workflows/variable/input", function (hooks) {
+ setupRenderingTest(hooks);
+
+ hooks.beforeEach(function () {
+ pretender.get("/admin/plugins/discourse-workflows/variables.json", () =>
+ response(200, { variables: [] })
+ );
+ });
+
+ test("renders CodeMirror editor", async function (assert) {
+ await render(<template><VariableInput @value="" /></template>);
+ await waitFor(".cm-editor");
+
+ assert.dom(".workflows-variable-input").exists();
+ assert.dom(".cm-editor").exists();
+ assert.dom(".cm-content").exists();
+ });
+
+ test("displays expression value as text", async function (assert) {
+ const value = "Hello {{ $current_user.username }}!";
+
+ await render(<template><VariableInput @value={{value}} /></template>);
+ await waitFor(".cm-editor");
+
+ const text = editorText(this.element);
+ assert.true(
+ text.includes("$current_user.username"),
+ "editor displays the expression variable"
+ );
+ });
+
+ test("displays multiple expressions", async function (assert) {
+ const value = "{{ $execution.id }} - {{ $json.title }}";
+
+ await render(<template><VariableInput @value={{value}} /></template>);
+ await waitFor(".cm-editor");
+
+ const text = editorText(this.element);
+ assert.true(text.includes("$execution.id"), "contains first expression");
+ assert.true(text.includes("$json.title"), "contains second expression");
+ });
+
+ test("preserves value through render cycle", async function (assert) {
+ const value = "prefix {{ $vars.API_URL }} suffix";
+
+ await render(<template><VariableInput @value={{value}} /></template>);
+ await waitFor(".cm-editor");
+
+ const text = editorText(this.element);
+ assert.true(text.includes("$vars.API_URL"), "expression is preserved");
+ assert.true(text.includes("prefix"), "prefix text is preserved");
+ assert.true(text.includes("suffix"), "suffix text is preserved");
+ });
+
+ test("fires onChange when user types", async function (assert) {
+ let captured = null;
+ let editorView = null;
+ const onChange = (val) => (captured = val);
+ const onSetup = (view) => (editorView = view);
+
+ await render(
+ <template>
+ <VariableInput @value="" @onChange={{onChange}} @onSetup={{onSetup}} />
+ </template>
+ );
+ await waitFor(".cm-editor");
+
+ editorView.dispatch({ changes: { from: 0, insert: "hello" } });
+
+ assert.strictEqual(captured, "hello", "onChange was called with the value");
+ });
+});
diff --git a/plugins/discourse-workflows/test/javascripts/unit/components/workflows/canvas-test.js b/plugins/discourse-workflows/test/javascripts/unit/components/workflows/canvas-test.js
new file mode 100644
index 00000000000..a73fb3c7801
--- /dev/null
+++ b/plugins/discourse-workflows/test/javascripts/unit/components/workflows/canvas-test.js
@@ -0,0 +1,293 @@
+import { setupTest } from "ember-qunit";
+import { module, test } from "qunit";
+import pretender, { response } from "discourse/tests/helpers/create-pretender";
+import { i18n } from "discourse-i18n";
+import WorkflowCanvas from "discourse/plugins/discourse-workflows/admin/components/workflows/canvas";
+
+module("Unit | Component | workflows canvas", function (hooks) {
+ setupTest(hooks);
+
+ test("autoLayout is defined on the prototype", function (assert) {
+ assert.true(
+ "autoLayout" in WorkflowCanvas.prototype,
+ "autoLayout action exists"
+ );
+ });
+
+ test("sync lifecycle entrypoints are defined on the prototype", function (assert) {
+ assert.true(
+ "registerCanvas" in WorkflowCanvas.prototype,
+ "registerCanvas action exists"
+ );
+ assert.true(
+ "registerContainer" in WorkflowCanvas.prototype,
+ "registerContainer action exists"
+ );
+ assert.true(
+ "syncToRete" in WorkflowCanvas.prototype,
+ "syncToRete action exists"
+ );
+ });
+
+ test("browseTemplates delegates to the editor", function (assert) {
+ const canvas = Object.create(WorkflowCanvas.prototype);
+
+ Object.defineProperty(canvas, "args", {
+ value: {
+ onBrowseTemplates() {
+ assert.step("browse");
+ },
+ },
+ });
+
+ canvas.browseTemplates();
+
+ assert.verifySteps(["browse"]);
+ });
+
+ test("publish success clears optimistic unpublished changes override", async function (assert) {
+ pretender.put("/admin/plugins/discourse-workflows/workflows/1.json", () =>
+ response({})
+ );
+
+ const workflow = {
+ versionId: "draft-uuid",
+ activeVersionId: "published-uuid",
+ hasUnpublishedChanges: true,
+ };
+
+ const canvas = Object.create(WorkflowCanvas.prototype);
+ Object.defineProperty(canvas, "args", {
+ value: {
+ workflow,
+ workflowId: 1,
+ workflowName: "Workflow",
+ nodes: [{ clientId: "node-1", type: "trigger:manual" }],
+ get workflowPublished() {
+ return workflow.activeVersionId;
+ },
+ get hasUnpublishedChanges() {
+ return workflow.hasUnpublishedChanges;
+ },
+ },
+ });
+
+ await canvas.publishWorkflow();
+
+ assert.true(canvas.publishDisabled, "publish is disabled after publish");
+ assert.false(
+ canvas.showPublishButton,
+ "publish is hidden after publish with no draft changes"
+ );
+ assert.false(
+ canvas.showToolbarPublishButton,
+ "toolbar publish is hidden after publish with no draft changes"
+ );
+ assert.false(
+ canvas.showUnpublishedChangesMessage,
+ "unpublished changes message is hidden after publish with no draft changes"
+ );
+ assert.false(
+ canvas.showDiscardChangesButton,
+ "discard changes is hidden after publish with no draft changes"
+ );
+
+ workflow.hasUnpublishedChanges = true;
+
+ assert.false(
+ canvas.publishDisabled,
+ "later draft edits can re-enable publish"
+ );
+ assert.true(
+ canvas.showPublishButton,
+ "later draft edits show publish again"
+ );
+ assert.false(
+ canvas.showToolbarPublishButton,
+ "later draft edits move publish into the unpublished changes panel"
+ );
+ assert.true(
+ canvas.showUnpublishedChangesMessage,
+ "later draft edits show the unpublished changes message"
+ );
+ assert.true(
+ canvas.showDiscardChangesButton,
+ "later draft edits show discard changes"
+ );
+ });
+
+ test("unpublish closes the menu", async function (assert) {
+ pretender.put("/admin/plugins/discourse-workflows/workflows/1.json", () =>
+ response({})
+ );
+
+ const workflow = {
+ activeVersionId: "published-uuid",
+ hasUnpublishedChanges: false,
+ };
+
+ const canvas = Object.create(WorkflowCanvas.prototype);
+ Object.defineProperty(canvas, "args", {
+ value: {
+ workflow,
+ workflowId: 1,
+ workflowName: "Workflow",
+ nodes: [{ clientId: "node-1", type: "trigger:manual" }],
+ get workflowPublished() {
+ return workflow.activeVersionId;
+ },
+ },
+ });
+
+ await canvas.unpublishWorkflow(() => assert.step("close menu"));
+
+ assert.verifySteps(["close menu"]);
+ assert.false(
+ canvas.workflowPublished,
+ "workflow is no longer published after unpublish"
+ );
+ assert.false(
+ canvas.showToolbarPublishButton,
+ "toolbar publish remains hidden for fully unpublished workflows"
+ );
+ assert.true(
+ canvas.showUnpublishedChangesMessage,
+ "publish status remains visible for fully unpublished workflows"
+ );
+ assert.false(
+ canvas.showDiscardChangesButton,
+ "discard changes is hidden for fully unpublished workflows"
+ );
+ });
+
+ test("discard success clears unpublished changes and syncs workflow", async function (assert) {
+ const restoredWorkflow = {
+ id: "1",
+ name: "Published workflow",
+ nodes: [{ id: "published-1", type: "trigger:manual" }],
+ connections: {},
+ version_id: "published-uuid",
+ active_version_id: "published-uuid",
+ has_unpublished_changes: false,
+ };
+
+ pretender.post(
+ "/admin/plugins/discourse-workflows/workflows/1/discard-draft.json",
+ () => response({ workflow: restoredWorkflow })
+ );
+
+ const state = {
+ hasUnpublishedChanges: true,
+ workflowPublished: "published-uuid",
+ };
+ const canvas = Object.create(WorkflowCanvas.prototype);
+ Object.defineProperty(canvas, "dialog", {
+ value: {
+ confirm({ message, confirmButtonLabel, cancelButtonLabel }) {
+ assert.strictEqual(
+ message,
+ i18n("discourse_workflows.discard_changes_confirmation")
+ );
+ assert.strictEqual(
+ confirmButtonLabel,
+ "discourse_workflows.discard_changes"
+ );
+ assert.strictEqual(
+ cancelButtonLabel,
+ "discourse_workflows.keep_editing"
+ );
+ return true;
+ },
+ },
+ });
+ Object.defineProperty(canvas, "args", {
+ value: {
+ workflowId: 1,
+ nodes: [{ clientId: "node-1", type: "trigger:manual" }],
+ get hasUnpublishedChanges() {
+ return state.hasUnpublishedChanges;
+ },
+ get workflowPublished() {
+ return state.workflowPublished;
+ },
+ onDiscardWorkflow(workflow) {
+ state.hasUnpublishedChanges = workflow.has_unpublished_changes;
+ state.workflowPublished = workflow.active_version_id;
+ assert.deepEqual(
+ workflow,
+ restoredWorkflow,
+ "restored workflow is passed to the editor"
+ );
+ assert.step("discarded");
+ },
+ },
+ });
+
+ assert.true(
+ canvas.showUnpublishedChangesMessage,
+ "unpublished changes message is visible before discard"
+ );
+
+ await canvas.discardWorkflow();
+
+ assert.verifySteps(["discarded"]);
+ assert.false(
+ canvas.showUnpublishedChangesMessage,
+ "unpublished changes message is hidden after discard"
+ );
+ assert.false(
+ canvas.showDiscardChangesButton,
+ "discard changes is hidden after discard"
+ );
+ });
+
+ test("publish is hidden until the workflow has a node", async function (assert) {
+ const canvas = Object.create(WorkflowCanvas.prototype);
+ Object.defineProperty(canvas, "args", {
+ value: {
+ workflowId: 1,
+ workflowName: "Workflow",
+ nodes: [],
+ workflowPublished: null,
+ hasUnpublishedChanges: true,
+ },
+ });
+
+ assert.false(canvas.hasNodes, "the workflow has no nodes");
+ assert.false(
+ canvas.showPublishButton,
+ "publish is hidden before a node is added"
+ );
+ assert.false(
+ canvas.showToolbarPublishButton,
+ "toolbar publish is hidden before a node is added"
+ );
+ assert.false(
+ canvas.showUnpublishedChangesMessage,
+ "unpublished changes publish message is hidden before a node is added"
+ );
+
+ await canvas.publishWorkflow();
+
+ assert.strictEqual(
+ canvas.workflowPublishedOverride,
+ null,
+ "publish action does not optimistically mark an empty workflow published"
+ );
+
+ canvas.args.nodes.push({ clientId: "node-1", type: "trigger:manual" });
+
+ assert.false(
+ canvas.showToolbarPublishButton,
+ "toolbar publish stays hidden once a node exists"
+ );
+ assert.true(
+ canvas.showUnpublishedChangesMessage,
+ "publish status is shown once a node exists"
+ );
+ assert.false(
+ canvas.showDiscardChangesButton,
+ "discard changes is hidden for an unpublished workflow"
+ );
+ });
+});
diff --git a/plugins/discourse-workflows/test/javascripts/unit/components/workflows/canvas/canvas-bridge-test.js b/plugins/discourse-workflows/test/javascripts/unit/components/workflows/canvas/canvas-bridge-test.js
new file mode 100644
index 00000000000..be51e96595a
--- /dev/null
+++ b/plugins/discourse-workflows/test/javascripts/unit/components/workflows/canvas/canvas-bridge-test.js
@@ -0,0 +1,418 @@
+import { setupTest } from "ember-qunit";
+import { module, test } from "qunit";
+import { createReteEditor } from "discourse/plugins/discourse-workflows/admin/components/workflows/canvas/rete-editor";
+
+const NODE_TYPES = [
+ {
+ identifier: "trigger:manual",
+ ports: [{ key: "main", primary: true }],
+ },
+ {
+ identifier: "action:data_table",
+ ports: [
+ { key: "results", primary: true, label: "Results" },
+ { key: "no_results", label: "No results" },
+ ],
+ },
+ {
+ identifier: "action:http_request",
+ ports: [{ key: "main", primary: true }],
+ },
+ {
+ identifier: "flow:loop_over_items",
+ ports: [
+ { key: "done", primary: true },
+ { key: "loop", primary: false },
+ ],
+ },
+];
+
+function noopCallbacks(overrides = {}) {
+ return {
+ onNodeDragged() {},
+ onNodeDragEnd() {},
+ onNodePicked() {},
+ onNodeDoubleClick() {},
+ onNodeDelete() {},
+ onManualTrigger() {},
+ onCanvasPointerDown() {},
+ onConnectionCreated() {},
+ onTransformChanged() {},
+ ...overrides,
+ };
+}
+
+module("Unit | Canvas Bridge", function (hooks) {
+ setupTest(hooks);
+
+ let container;
+
+ hooks.beforeEach(function () {
+ container = document.createElement("div");
+ container.style.cssText = "width:800px;height:600px;position:relative";
+ document.getElementById("qunit-fixture").appendChild(container);
+ });
+
+ test("create returns a bridge with empty state", async function (assert) {
+ const bridge = await createReteEditor(container, {
+ callbacks: noopCallbacks(),
+ nodeTypes: NODE_TYPES,
+ });
+
+ assert.strictEqual(bridge.nodeCount, 0);
+ assert.deepEqual(bridge.renderer.nodeEntryList, []);
+ assert.deepEqual(bridge.renderer.connectionEntryList, []);
+ assert.deepEqual(bridge.renderer.outputHandleEntryList, []);
+ assert.strictEqual(typeof bridge.transform.k, "number");
+
+ bridge.destroy();
+ });
+
+ test("syncState adds and removes nodes", async function (assert) {
+ const bridge = await createReteEditor(container, {
+ callbacks: noopCallbacks(),
+ nodeTypes: NODE_TYPES,
+ });
+
+ await bridge.syncState(
+ [
+ {
+ clientId: "n1",
+ type: "trigger:manual",
+ position: { x: 0, y: 0 },
+ },
+ {
+ clientId: "n2",
+ type: "action:http_request",
+ position: { x: 200, y: 0 },
+ },
+ ],
+ []
+ );
+
+ assert.strictEqual(bridge.nodeCount, 2);
+ assert.strictEqual(bridge.renderer.nodeEntryList.length, 2);
+
+ await bridge.syncState(
+ [
+ {
+ clientId: "n1",
+ type: "trigger:manual",
+ position: { x: 0, y: 0 },
+ },
+ ],
+ []
+ );
+
+ assert.strictEqual(bridge.nodeCount, 1);
+ assert.strictEqual(bridge.renderer.nodeEntryList.length, 1);
+
+ bridge.destroy();
+ });
+
+ test("syncState manages connections and creates connection entries", async function (assert) {
+ const bridge = await createReteEditor(container, {
+ callbacks: noopCallbacks(),
+ nodeTypes: NODE_TYPES,
+ });
+
+ await bridge.syncState(
+ [
+ {
+ clientId: "n1",
+ type: "trigger:manual",
+ position: { x: 0, y: 0 },
+ },
+ {
+ clientId: "n2",
+ type: "action:http_request",
+ position: { x: 200, y: 0 },
+ },
+ ],
+ [{ sourceClientId: "n1", sourceOutput: "main", targetClientId: "n2" }]
+ );
+
+ assert.true(
+ bridge.renderer.connectionEntryList.length > 0,
+ "connection entries created"
+ );
+
+ bridge.destroy();
+ });
+
+ test("connection entries carry pre-resolved client IDs", async function (assert) {
+ const bridge = await createReteEditor(container, {
+ callbacks: noopCallbacks(),
+ nodeTypes: NODE_TYPES,
+ });
+
+ await bridge.syncState(
+ [
+ {
+ clientId: "n1",
+ type: "trigger:manual",
+ position: { x: 0, y: 0 },
+ },
+ {
+ clientId: "n2",
+ type: "action:http_request",
+ position: { x: 200, y: 0 },
+ },
+ ],
+ [{ sourceClientId: "n1", sourceOutput: "main", targetClientId: "n2" }]
+ );
+
+ const entry = bridge.renderer.connectionEntryList[0];
+ assert.strictEqual(entry.connectionInfo.sourceClientId, "n1");
+ assert.strictEqual(entry.connectionInfo.targetClientId, "n2");
+ assert.strictEqual(entry.connectionInfo.sourceOutput, "main");
+
+ bridge.destroy();
+ });
+
+ test("loop back connections carry pre-resolved client IDs", async function (assert) {
+ const bridge = await createReteEditor(container, {
+ callbacks: noopCallbacks(),
+ nodeTypes: NODE_TYPES,
+ });
+
+ await bridge.syncState(
+ [
+ {
+ clientId: "trigger",
+ type: "trigger:manual",
+ position: { x: 0, y: 0 },
+ },
+ {
+ clientId: "loop",
+ type: "flow:loop_over_items",
+ position: { x: 200, y: 0 },
+ },
+ ],
+ [
+ {
+ sourceClientId: "trigger",
+ sourceOutput: "main",
+ targetClientId: "loop",
+ },
+ {
+ sourceClientId: "loop",
+ sourceOutput: "loop",
+ targetClientId: "loop",
+ },
+ ]
+ );
+
+ const loopBack = bridge.renderer.connectionEntryList.find(
+ (e) => e.isLoopBack
+ );
+ assert.true(!!loopBack, "loop back entry created");
+ assert.strictEqual(loopBack.loopNodeClientId, "loop");
+
+ bridge.destroy();
+ });
+
+ test("syncState resolves index-only connections to Rete socket keys", async function (assert) {
+ const bridge = await createReteEditor(container, {
+ callbacks: noopCallbacks(),
+ nodeTypes: NODE_TYPES,
+ });
+
+ await bridge.syncState(
+ [
+ {
+ clientId: "loop",
+ type: "flow:loop_over_items",
+ position: { x: 0, y: 0 },
+ },
+ {
+ clientId: "body",
+ type: "action:http_request",
+ position: { x: 200, y: 0 },
+ },
+ ],
+ [
+ {
+ sourceClientId: "loop",
+ sourceOutputIndex: 1,
+ targetClientId: "body",
+ targetInputIndex: 0,
+ },
+ ]
+ );
+
+ const connection = bridge.editor.getConnections()[0];
+ assert.strictEqual(connection.sourceOutput, "loop");
+ assert.strictEqual(connection.targetInput, "main");
+
+ bridge.destroy();
+ });
+
+ test("autoArrange returns position map keyed by client IDs", async function (assert) {
+ const bridge = await createReteEditor(container, {
+ callbacks: noopCallbacks(),
+ nodeTypes: NODE_TYPES,
+ });
+
+ await bridge.syncState(
+ [
+ {
+ clientId: "n1",
+ type: "trigger:manual",
+ position: { x: 0, y: 0 },
+ },
+ {
+ clientId: "n2",
+ type: "action:http_request",
+ position: { x: 0, y: 0 },
+ },
+ ],
+ [{ sourceClientId: "n1", sourceOutput: "main", targetClientId: "n2" }]
+ );
+
+ const positions = await bridge.autoArrange();
+ assert.true(positions instanceof Map);
+ assert.true(positions.has("n1"));
+ assert.true(positions.has("n2"));
+ assert.strictEqual(typeof positions.get("n1").x, "number");
+ assert.strictEqual(typeof positions.get("n1").y, "number");
+
+ bridge.destroy();
+ });
+
+ test("autoArrange is stable across a save-and-reload round trip", async function (assert) {
+ const bridge = await createReteEditor(container, {
+ callbacks: noopCallbacks(),
+ nodeTypes: NODE_TYPES,
+ });
+
+ const nodes = [
+ {
+ clientId: "trigger",
+ type: "trigger:manual",
+ position: { x: 0, y: 0 },
+ },
+ {
+ clientId: "branch",
+ type: "action:data_table",
+ position: { x: 0, y: 0 },
+ },
+ {
+ clientId: "results",
+ type: "action:http_request",
+ position: { x: 0, y: 0 },
+ },
+ {
+ clientId: "empty",
+ type: "action:http_request",
+ position: { x: 0, y: 0 },
+ },
+ ];
+ const connections = [
+ {
+ sourceClientId: "trigger",
+ sourceOutput: "main",
+ targetClientId: "branch",
+ },
+ {
+ sourceClientId: "branch",
+ sourceOutput: "results",
+ targetClientId: "results",
+ },
+ {
+ sourceClientId: "branch",
+ sourceOutput: "no_results",
+ targetClientId: "empty",
+ },
+ ];
+
+ await bridge.syncState(nodes, connections);
+
+ const firstPositions = await bridge.autoArrange();
+
+ await bridge.syncState(
+ nodes.map((node) => ({
+ ...node,
+ position: firstPositions.get(node.clientId),
+ })),
+ connections
+ );
+
+ const secondPositions = await bridge.autoArrange();
+
+ assert.deepEqual(
+ Object.fromEntries(secondPositions),
+ Object.fromEntries(firstPositions)
+ );
+
+ bridge.destroy();
+ });
+
+ test("containerToCanvas converts coordinates based on transform", async function (assert) {
+ const bridge = await createReteEditor(container, {
+ callbacks: noopCallbacks(),
+ nodeTypes: NODE_TYPES,
+ });
+
+ const result = bridge.containerToCanvas(100, 200);
+ assert.strictEqual(typeof result.canvasX, "number");
+ assert.strictEqual(typeof result.canvasY, "number");
+
+ bridge.destroy();
+ });
+
+ test("transform getter returns valid values", async function (assert) {
+ const bridge = await createReteEditor(container, {
+ callbacks: noopCallbacks(),
+ nodeTypes: NODE_TYPES,
+ });
+
+ const t = bridge.transform;
+ assert.strictEqual(typeof t.x, "number");
+ assert.strictEqual(typeof t.y, "number");
+ assert.strictEqual(typeof t.k, "number");
+ assert.true(t.k > 0);
+
+ bridge.destroy();
+ });
+
+ test("onTransformChanged callback fires on zoom", async function (assert) {
+ let transformValue = null;
+ const bridge = await createReteEditor(container, {
+ callbacks: noopCallbacks({
+ onTransformChanged(t) {
+ transformValue = t;
+ },
+ }),
+ nodeTypes: NODE_TYPES,
+ });
+
+ await bridge.zoomAtViewportCenter(2);
+ assert.strictEqual(transformValue.k, 2);
+
+ bridge.destroy();
+ });
+
+ test("destroy completes without error", async function (assert) {
+ const bridge = await createReteEditor(container, {
+ callbacks: noopCallbacks(),
+ nodeTypes: NODE_TYPES,
+ });
+ bridge.destroy();
+ assert.true(true, "destroy completed without error");
+ });
+
+ test("areaForHistory returns the area plugin for UndoManager", async function (assert) {
+ const bridge = await createReteEditor(container, {
+ callbacks: noopCallbacks(),
+ nodeTypes: NODE_TYPES,
+ });
+ assert.notStrictEqual(bridge.area, undefined, "areaForHistory is truthy");
+ assert.strictEqual(
+ typeof bridge.area.use,
+ "function",
+ "areaForHistory exposes use() for plugin registration"
+ );
+ bridge.destroy();
+ });
+});
diff --git a/plugins/discourse-workflows/test/javascripts/unit/components/workflows/canvas/canvas-keyboard-test.js b/plugins/discourse-workflows/test/javascripts/unit/components/workflows/canvas/canvas-keyboard-test.js
new file mode 100644
index 00000000000..afaadfff8ec
--- /dev/null
+++ b/plugins/discourse-workflows/test/javascripts/unit/components/workflows/canvas/canvas-keyboard-test.js
@@ -0,0 +1,202 @@
+import { setupTest } from "ember-qunit";
+import { module, test } from "qunit";
+import { setupCanvasKeyboard } from "discourse/plugins/discourse-workflows/admin/components/workflows/canvas/canvas-keyboard";
+
+function fakeKeyboardShortcutsService() {
+ return {
+ paused: [],
+ pause(keys) {
+ this.paused.push(...keys);
+ },
+ unpause(keys) {
+ this.paused = this.paused.filter((k) => !keys.includes(k));
+ },
+ };
+}
+
+module("Unit | Canvas Keyboard", function (hooks) {
+ setupTest(hooks);
+
+ let keyboard;
+ let canvasElement;
+ let service;
+
+ hooks.beforeEach(function () {
+ service = fakeKeyboardShortcutsService();
+ canvasElement = document.createElement("div");
+ document.getElementById("qunit-fixture").appendChild(canvasElement);
+ });
+
+ hooks.afterEach(function () {
+ keyboard?.teardown();
+ keyboard = null;
+ });
+
+ function setup(actions) {
+ return setupCanvasKeyboard(service, actions, canvasElement);
+ }
+
+ function press(key, opts = {}) {
+ const event = new KeyboardEvent("keydown", {
+ key,
+ code: opts.code ?? "",
+ metaKey: opts.meta ?? false,
+ ctrlKey: opts.ctrl ?? false,
+ shiftKey: opts.shift ?? false,
+ bubbles: true,
+ cancelable: true,
+ });
+ (opts.target ?? canvasElement).dispatchEvent(event);
+ return event;
+ }
+
+ test("pauses Discourse shortcuts on setup", function (assert) {
+ keyboard = setup({});
+ assert.deepEqual(service.paused, ["-", "="]);
+ });
+
+ test("teardown unpauses shortcuts and removes listener", function (assert) {
+ let called = false;
+ keyboard = setup({ onZoomIn: () => (called = true) });
+
+ keyboard.teardown();
+ keyboard = null;
+
+ press("=");
+ assert.false(called, "handler no longer fires after teardown");
+ assert.deepEqual(service.paused, [], "shortcuts unpaused");
+ });
+
+ test("Ctrl+Z triggers onUndo", function (assert) {
+ let undone = false;
+ keyboard = setup({ onUndo: () => (undone = true) });
+
+ press("z", { ctrl: true });
+ assert.true(undone);
+ });
+
+ test("Ctrl+Shift+Z triggers onRedo", function (assert) {
+ let redone = false;
+ keyboard = setup({ onRedo: () => (redone = true) });
+
+ press("z", { ctrl: true, shift: true });
+ assert.true(redone);
+ });
+
+ test("Ctrl+Y triggers onRedo", function (assert) {
+ let redone = false;
+ keyboard = setup({ onRedo: () => (redone = true) });
+
+ press("y", { ctrl: true });
+ assert.true(redone);
+ });
+
+ test("Ctrl+C triggers onCopy", function (assert) {
+ let copied = false;
+ keyboard = setup({ onCopy: () => (copied = true) });
+
+ press("c", { meta: true });
+ assert.true(copied);
+ });
+
+ test("Ctrl+V triggers onPaste", function (assert) {
+ let pasted = false;
+ keyboard = setup({ onPaste: () => (pasted = true) });
+
+ press("v", { meta: true });
+ assert.true(pasted);
+ });
+
+ test("Delete and Backspace trigger onDelete", function (assert) {
+ let deleteCount = 0;
+ keyboard = setup({ onDelete: () => deleteCount++ });
+
+ press("Delete");
+ press("Backspace");
+ assert.strictEqual(deleteCount, 2);
+ });
+
+ test("Escape triggers onEscape", function (assert) {
+ let escaped = false;
+ keyboard = setup({ onEscape: () => (escaped = true) });
+
+ press("Escape");
+ assert.true(escaped);
+ });
+
+ test("+ and = trigger onZoomIn, - triggers onZoomOut", function (assert) {
+ let zoomInCount = 0;
+ let zoomOutCount = 0;
+ keyboard = setup({
+ onZoomIn: () => zoomInCount++,
+ onZoomOut: () => zoomOutCount++,
+ });
+
+ press("+");
+ press("=");
+ press("-");
+ assert.strictEqual(zoomInCount, 2);
+ assert.strictEqual(zoomOutCount, 1);
+ });
+
+ test("Digit1 triggers onFitToView, Digit2 triggers onAutoLayout", function (assert) {
+ let fitCalled = false;
+ let layoutCalled = false;
+ keyboard = setup({
+ onFitToView: () => (fitCalled = true),
+ onAutoLayout: () => (layoutCalled = true),
+ });
+
+ press("1", { code: "Digit1" });
+ press("2", { code: "Digit2" });
+ assert.true(fitCalled);
+ assert.true(layoutCalled);
+ });
+
+ test("ignores keystrokes on input elements", function (assert) {
+ let called = false;
+ keyboard = setup({ onDelete: () => (called = true) });
+
+ const input = document.createElement("input");
+ canvasElement.appendChild(input);
+ press("Delete", { target: input });
+
+ assert.false(called);
+ });
+
+ test("ignores keystrokes on textarea elements", function (assert) {
+ let called = false;
+ keyboard = setup({ onDelete: () => (called = true) });
+
+ const textarea = document.createElement("textarea");
+ canvasElement.appendChild(textarea);
+ press("Delete", { target: textarea });
+
+ assert.false(called);
+ });
+
+ test("missing action callbacks do not throw", function (assert) {
+ keyboard = setup({});
+
+ press("z", { ctrl: true });
+ press("Delete");
+ press("+");
+ press("1", { code: "Digit1" });
+
+ assert.true(true, "no errors thrown");
+ });
+
+ test("teardown tolerates uninitialized keyboard shortcuts service", function (assert) {
+ const brokenService = {
+ pause() {},
+ unpause() {
+ throw new Error("not initialized");
+ },
+ };
+ keyboard = setupCanvasKeyboard(brokenService, {}, canvasElement);
+ keyboard.teardown();
+ keyboard = null;
+
+ assert.true(true, "teardown completed despite error");
+ });
+});
diff --git a/plugins/discourse-workflows/test/javascripts/unit/components/workflows/canvas/canvas-sticky-notes-test.js b/plugins/discourse-workflows/test/javascripts/unit/components/workflows/canvas/canvas-sticky-notes-test.js
new file mode 100644
index 00000000000..b815df8298e
--- /dev/null
+++ b/plugins/discourse-workflows/test/javascripts/unit/components/workflows/canvas/canvas-sticky-notes-test.js
@@ -0,0 +1,93 @@
+import { setupTest } from "ember-qunit";
+import { module, test } from "qunit";
+import {
+ buildStickyNoteTranslateHandler,
+ computeStickyNoteRects,
+} from "discourse/plugins/discourse-workflows/admin/components/workflows/canvas/canvas-sticky-notes";
+
+module("Unit | Canvas Sticky Notes", function (hooks) {
+ setupTest(hooks);
+
+ module("computeStickyNoteRects", function () {
+ test("maps sticky notes to position/size rects", function (assert) {
+ const notes = [
+ { position: { x: 10, y: 20 }, size: { width: 100, height: 50 } },
+ { position: { x: 30, y: 40 }, size: { width: 200, height: 150 } },
+ ];
+
+ const rects = computeStickyNoteRects(notes);
+
+ assert.deepEqual(rects, [
+ { x: 10, y: 20, width: 100, height: 50 },
+ { x: 30, y: 40, width: 200, height: 150 },
+ ]);
+ });
+
+ test("returns empty array for null/undefined input", function (assert) {
+ assert.deepEqual(computeStickyNoteRects(null), []);
+ assert.deepEqual(computeStickyNoteRects(undefined), []);
+ });
+
+ test("returns empty array for empty list", function (assert) {
+ assert.deepEqual(computeStickyNoteRects([]), []);
+ });
+ });
+
+ module("buildStickyNoteTranslateHandler", function () {
+ test("applies delta to matching note position", function (assert) {
+ const notes = [
+ {
+ clientId: "sn1",
+ position: { x: 100, y: 200 },
+ },
+ {
+ clientId: "sn2",
+ position: { x: 50, y: 75 },
+ },
+ ];
+
+ let movedId, movedPosition;
+ const handler = buildStickyNoteTranslateHandler(notes, (id, pos) => {
+ movedId = id;
+ movedPosition = pos;
+ });
+
+ handler("sn1", 10, -5);
+
+ assert.strictEqual(movedId, "sn1");
+ assert.deepEqual(movedPosition, { x: 110, y: 195 });
+ });
+
+ test("does nothing when note is not found", function (assert) {
+ const notes = [{ clientId: "sn1", position: { x: 0, y: 0 } }];
+ let called = false;
+ const handler = buildStickyNoteTranslateHandler(notes, () => {
+ called = true;
+ });
+
+ handler("nonexistent", 10, 10);
+
+ assert.false(called);
+ });
+
+ test("does nothing when onMove is not provided", function (assert) {
+ const notes = [{ clientId: "sn1", position: { x: 0, y: 0 } }];
+ const handler = buildStickyNoteTranslateHandler(notes, undefined);
+
+ handler("sn1", 10, 10);
+
+ assert.true(true, "no error thrown");
+ });
+
+ test("handles null stickyNotes list", function (assert) {
+ let called = false;
+ const handler = buildStickyNoteTranslateHandler(null, () => {
+ called = true;
+ });
+
+ handler("sn1", 10, 10);
+
+ assert.false(called);
+ });
+ });
+});
diff --git a/plugins/discourse-workflows/test/javascripts/unit/components/workflows/canvas/rete-graph-index-test.js b/plugins/discourse-workflows/test/javascripts/unit/components/workflows/canvas/rete-graph-index-test.js
new file mode 100644
index 00000000000..c7bfafa3c22
--- /dev/null
+++ b/plugins/discourse-workflows/test/javascripts/unit/components/workflows/canvas/rete-graph-index-test.js
@@ -0,0 +1,116 @@
+import { module, test } from "qunit";
+import {
+ buildWorkflowGraphIndex,
+ connectionMatchesEndpoint,
+ getConnectionKind,
+} from "discourse/plugins/discourse-workflows/admin/lib/workflows/graph-constants";
+
+function node(id, type) {
+ return { id, type };
+}
+
+function connection(source, sourceOutput, target) {
+ return { source, sourceOutput, target };
+}
+
+module("Unit | Utility | workflows rete graph index", function () {
+ test("classifies branched loop body and loop return connections", function (assert) {
+ const nodes = [
+ node("trigger", "trigger:manual"),
+ node("loop", "flow:loop_over_items"),
+ node("branch", "condition:if"),
+ node("true_body", "action:set_fields"),
+ node("false_body", "action:topic_tags"),
+ node("done", "action:http_request"),
+ ];
+ const connections = [
+ connection("trigger", "main", "loop"),
+ connection("loop", "loop", "loop"),
+ connection("loop", "loop", "branch"),
+ connection("branch", "true", "true_body"),
+ connection("branch", "false", "false_body"),
+ connection("true_body", "main", "loop"),
+ connection("false_body", "main", "loop"),
+ connection("loop", "done", "done"),
+ ];
+ const graphIndex = buildWorkflowGraphIndex(nodes, connections);
+
+ assert.strictEqual(graphIndex.loopOwnerByNodeId.get("branch"), "loop");
+ assert.strictEqual(graphIndex.loopOwnerByNodeId.get("true_body"), "loop");
+ assert.strictEqual(graphIndex.loopOwnerByNodeId.get("false_body"), "loop");
+
+ assert.strictEqual(
+ getConnectionKind(graphIndex, connection("loop", "loop", "branch")),
+ "loopBody"
+ );
+ assert.strictEqual(
+ getConnectionKind(graphIndex, connection("branch", "true", "true_body")),
+ "loopChain"
+ );
+ assert.strictEqual(
+ getConnectionKind(graphIndex, connection("true_body", "main", "loop")),
+ "loopReturn"
+ );
+ assert.strictEqual(
+ getConnectionKind(graphIndex, connection("loop", "done", "done")),
+ null
+ );
+ });
+
+ test("ignores the loop self-connection placeholder when indexing loop bodies", function (assert) {
+ const graphIndex = buildWorkflowGraphIndex(
+ [node("loop", "flow:loop_over_items")],
+ [connection("loop", "loop", "loop")]
+ );
+
+ assert.strictEqual(graphIndex.loopOwnerByNodeId.size, 0);
+ assert.strictEqual(
+ getConnectionKind(graphIndex, connection("loop", "loop", "loop")),
+ null
+ );
+ });
+
+ test("matches connections by normalized port indexes", function (assert) {
+ const storedTrueBranchConnection = {
+ sourceClientId: "if-1",
+ sourceOutput: "main",
+ sourceOutputIndex: 0,
+ targetClientId: "action-1",
+ targetInput: "main",
+ targetInputIndex: 0,
+ };
+ const storedFalseBranchConnection = {
+ sourceClientId: "if-1",
+ sourceOutput: "main",
+ sourceOutputIndex: 1,
+ targetClientId: "action-2",
+ targetInput: "main",
+ targetInputIndex: 0,
+ };
+
+ assert.true(
+ connectionMatchesEndpoint(storedTrueBranchConnection, {
+ sourceClientId: "if-1",
+ sourceOutput: "true",
+ targetClientId: "action-1",
+ targetInput: "main",
+ })
+ );
+ assert.true(
+ connectionMatchesEndpoint(storedFalseBranchConnection, {
+ sourceClientId: "if-1",
+ sourceOutput: "false",
+ targetClientId: "action-2",
+ targetInput: "main",
+ })
+ );
+ assert.false(
+ connectionMatchesEndpoint(storedFalseBranchConnection, {
+ sourceClientId: "if-1",
+ sourceOutput: "true",
+ targetClientId: "action-2",
+ targetInput: "main",
+ })
+ );
+ });
+});
diff --git a/plugins/discourse-workflows/test/javascripts/unit/components/workflows/editor-test.js b/plugins/discourse-workflows/test/javascripts/unit/components/workflows/editor-test.js
new file mode 100644
index 00000000000..a847d516bef
--- /dev/null
+++ b/plugins/discourse-workflows/test/javascripts/unit/components/workflows/editor-test.js
@@ -0,0 +1,315 @@
+import { module, test } from "qunit";
+import { i18n } from "discourse-i18n";
+import WorkflowsEditor, {
+ isNodeUnavailable,
+} from "discourse/plugins/discourse-workflows/admin/components/workflows/editor";
+
+function buildEditor(workflow, dialog = {}) {
+ const editor = Object.create(WorkflowsEditor.prototype);
+ editor.allowUnpublishedDraftTransition = false;
+
+ Object.defineProperty(editor, "args", {
+ value: { workflow },
+ });
+ Object.defineProperty(editor, "dialog", {
+ value: dialog,
+ });
+
+ return editor;
+}
+
+function setFormApi(editor, data) {
+ Object.defineProperty(editor, "formApi", {
+ value: {
+ get(key) {
+ return data[key];
+ },
+ },
+ });
+}
+
+function setRouter(editor, assert) {
+ Object.defineProperty(editor, "router", {
+ value: {
+ transitionTo(routeName, options) {
+ assert.strictEqual(
+ routeName,
+ "adminPlugins.show.discourse-workflows-templates"
+ );
+ assert.deepEqual(options.queryParams, { workflow_id: 12 });
+ },
+ },
+ });
+}
+
+module("Unit | Component | workflows editor", function () {
+ test("detects unavailable nodes", function (assert) {
+ const service = {
+ findNodeType(type) {
+ return {
+ "action:missing_plugin": null,
+ "action:disabled": { latest: { available: false } },
+ "action:available": { latest: { available: true } },
+ }[type];
+ },
+ };
+
+ assert.true(isNodeUnavailable(service, { type: "action:missing_plugin" }));
+ assert.true(isNodeUnavailable(service, { type: "action:disabled" }));
+ assert.false(isNodeUnavailable(service, { type: "action:available" }));
+ });
+
+ test("editNode does not open unavailable nodes", function (assert) {
+ assert.expect(0);
+
+ const editor = buildEditor({});
+ setFormApi(editor, {
+ nodes: [{ clientId: "node-1", type: "action:missing_plugin" }],
+ connections: [],
+ });
+
+ Object.defineProperty(editor, "workflowsNodeTypes", {
+ value: {
+ findNodeType() {
+ return null;
+ },
+ },
+ });
+ Object.defineProperty(editor, "modal", {
+ value: {
+ show() {
+ assert.true(false, "modal should not open");
+ },
+ },
+ });
+
+ editor.editNode("node-1");
+ });
+
+ test("beforeunload warns when the workflow has an unpublished draft", function (assert) {
+ const editor = buildEditor({
+ activeVersionId: "published-version",
+ hasUnpublishedChanges: true,
+ });
+ const event = {
+ returnValue: null,
+ preventDefault() {
+ assert.step("prevented");
+ },
+ };
+
+ const message = editor.handleBeforeUnload(event);
+
+ assert.verifySteps(["prevented"]);
+ assert.strictEqual(
+ message,
+ i18n("discourse_workflows.unpublished_changes_confirmation")
+ );
+ assert.strictEqual(event.returnValue, message);
+ });
+
+ test("beforeunload does not warn when the workflow has no unpublished draft", function (assert) {
+ const editor = buildEditor({ hasUnpublishedChanges: false });
+ const event = {
+ preventDefault() {
+ assert.true(false, "preventDefault should not be called");
+ },
+ };
+
+ assert.strictEqual(editor.handleBeforeUnload(event), undefined);
+ });
+
+ test("beforeunload does not warn for workflows that were never published", function (assert) {
+ const editor = buildEditor({
+ activeVersionId: null,
+ hasUnpublishedChanges: true,
+ });
+ const event = {
+ preventDefault() {
+ assert.true(false, "preventDefault should not be called");
+ },
+ };
+
+ assert.strictEqual(editor.handleBeforeUnload(event), undefined);
+ });
+
+ test("beforeunload warns while a draft save is in flight", function (assert) {
+ const editor = buildEditor({ hasUnpublishedChanges: false });
+ const event = {
+ returnValue: null,
+ preventDefault() {
+ assert.step("prevented");
+ },
+ };
+
+ editor.saving = true;
+
+ const message = editor.handleBeforeUnload(event);
+
+ assert.verifySteps(["prevented"]);
+ assert.strictEqual(
+ message,
+ i18n("discourse_workflows.unpublished_changes_confirmation")
+ );
+ });
+
+ test("route changes ask for confirmation when the workflow has an unpublished draft", function (assert) {
+ const transition = {
+ isAborted: false,
+ queryParamsOnly: false,
+ from: { name: "adminPlugins.show.discourse-workflows.show.index" },
+ to: { name: "adminPlugins.show.discourse-workflows" },
+ abort() {
+ assert.step("aborted");
+ },
+ retry() {
+ assert.step("retried");
+ },
+ };
+ const dialog = {
+ dialog({ class: dialogClass, message, buttons }) {
+ assert.strictEqual(dialogClass, "workflows-unpublished-draft-dialog");
+ assert.strictEqual(
+ message,
+ i18n("discourse_workflows.unpublished_changes_confirmation")
+ );
+ assert.deepEqual(
+ buttons.map((button) => button.label),
+ [
+ i18n("discourse_workflows.leave_without_publishing"),
+ i18n("discourse_workflows.keep_editing"),
+ i18n("discourse_workflows.discard_changes"),
+ ]
+ );
+ assert.true(
+ buttons[2].class.includes(
+ "workflows-unpublished-draft-dialog__discard-btn"
+ ),
+ "discard button is aligned separately"
+ );
+ buttons[0].action();
+ },
+ };
+ const editor = buildEditor(
+ {
+ activeVersionId: "published-version",
+ hasUnpublishedChanges: true,
+ },
+ dialog
+ );
+
+ editor.confirmUnpublishedDraftTransition(transition);
+
+ assert.true(editor.allowUnpublishedDraftTransition);
+ assert.verifySteps(["aborted", "retried"]);
+ });
+
+ test("route changes can discard changes before retrying", async function (assert) {
+ const transition = {
+ isAborted: false,
+ queryParamsOnly: false,
+ from: { name: "adminPlugins.show.discourse-workflows.show.index" },
+ to: { name: "adminPlugins.show.discourse-workflows" },
+ abort() {
+ assert.step("aborted");
+ },
+ retry() {
+ assert.step("retried");
+ },
+ };
+ let discardAction;
+ const dialog = {
+ dialog({ buttons }) {
+ discardAction = buttons[2].action;
+ },
+ confirm({ message, confirmButtonLabel, cancelButtonLabel }) {
+ assert.strictEqual(
+ message,
+ i18n("discourse_workflows.discard_changes_confirmation")
+ );
+ assert.strictEqual(
+ confirmButtonLabel,
+ "discourse_workflows.discard_changes"
+ );
+ assert.strictEqual(
+ cancelButtonLabel,
+ "discourse_workflows.keep_editing"
+ );
+ assert.step("confirmed discard");
+ return true;
+ },
+ };
+ const editor = buildEditor(
+ {
+ activeVersionId: "published-version",
+ hasUnpublishedChanges: true,
+ },
+ dialog
+ );
+ editor.discardWorkflowDraft = async () => assert.step("discarded");
+
+ editor.confirmUnpublishedDraftTransition(transition);
+ await discardAction();
+
+ assert.true(editor.allowUnpublishedDraftTransition);
+ assert.verifySteps([
+ "aborted",
+ "confirmed discard",
+ "discarded",
+ "retried",
+ ]);
+ });
+
+ test("browseTemplates skips draft confirmation for an empty workflow", function (assert) {
+ const editor = buildEditor({ id: 12, hasUnpublishedChanges: true });
+ setFormApi(editor, { nodes: [], stickyNotes: [] });
+ setRouter(editor, assert);
+
+ editor.browseTemplates();
+
+ assert.true(editor.allowUnpublishedDraftTransition);
+ });
+
+ test("browseTemplates keeps draft confirmation for non-empty workflows", function (assert) {
+ const editor = buildEditor({ id: 12, hasUnpublishedChanges: true });
+ setFormApi(editor, { nodes: [{ id: "n1" }], stickyNotes: [] });
+ setRouter(editor, assert);
+
+ editor.browseTemplates();
+
+ assert.false(editor.allowUnpublishedDraftTransition);
+ });
+
+ test("node panel hides triggers when adding after a trigger", function (assert) {
+ const editor = buildEditor({ id: 12 });
+ editor.nodePanelNodeTypes = [
+ { identifier: "trigger:manual" },
+ { identifier: "action:topic" },
+ ];
+ editor.nodePanelContext = { sourceClientId: "trigger-1" };
+ editor.nodePanelSearchTerm = "";
+ setFormApi(editor, {
+ nodes: [{ clientId: "trigger-1", type: "trigger:manual" }],
+ });
+
+ assert.deepEqual(
+ editor.filteredNodePanelTypes.map((nodeType) => nodeType.identifier),
+ ["action:topic"]
+ );
+ });
+
+ test("node panel keeps triggers when adding from the canvas", function (assert) {
+ const editor = buildEditor({ id: 12 });
+ editor.nodePanelNodeTypes = [
+ { identifier: "trigger:manual" },
+ { identifier: "action:topic" },
+ ];
+ editor.nodePanelContext = { canvasX: 10, canvasY: 20 };
+ editor.nodePanelSearchTerm = "";
+
+ assert.deepEqual(
+ editor.filteredNodePanelTypes.map((nodeType) => nodeType.identifier),
+ ["trigger:manual", "action:topic"]
+ );
+ });
+});
diff --git a/plugins/discourse-workflows/test/javascripts/unit/components/workflows/index-test.js b/plugins/discourse-workflows/test/javascripts/unit/components/workflows/index-test.js
new file mode 100644
index 00000000000..27a927a1f6f
--- /dev/null
+++ b/plugins/discourse-workflows/test/javascripts/unit/components/workflows/index-test.js
@@ -0,0 +1,42 @@
+import { module, test } from "qunit";
+import WorkflowsIndex from "discourse/plugins/discourse-workflows/admin/components/workflows";
+
+module("Unit | Component | workflows index", function () {
+ test("status label calls out published workflows with draft changes", function (assert) {
+ const component = Object.create(WorkflowsIndex.prototype);
+ const workflow = {
+ activeVersionId: 1,
+ hasUnpublishedChanges: true,
+ };
+
+ assert.strictEqual(
+ component.workflowStatusLabel(workflow),
+ "discourse_workflows.unpublished_changes"
+ );
+ assert.strictEqual(
+ component.workflowStatusClass(workflow),
+ "is-unpublished-changes"
+ );
+ });
+
+ test("status label keeps published and unpublished states distinct", function (assert) {
+ const component = Object.create(WorkflowsIndex.prototype);
+
+ assert.strictEqual(
+ component.workflowStatusLabel({ activeVersionId: 1 }),
+ "discourse_workflows.published"
+ );
+ assert.strictEqual(
+ component.workflowStatusClass({ activeVersionId: 1 }),
+ "is-published"
+ );
+ assert.strictEqual(
+ component.workflowStatusLabel({ activeVersionId: null }),
+ "discourse_workflows.unpublished"
+ );
+ assert.strictEqual(
+ component.workflowStatusClass({ activeVersionId: null }),
+ "is-unpublished"
+ );
+ });
+});
diff --git a/plugins/discourse-workflows/test/javascripts/unit/components/workflows/workflow-node-test.gjs b/plugins/discourse-workflows/test/javascripts/unit/components/workflows/workflow-node-test.gjs
new file mode 100644
index 00000000000..614c87a9429
--- /dev/null
+++ b/plugins/discourse-workflows/test/javascripts/unit/components/workflows/workflow-node-test.gjs
@@ -0,0 +1,84 @@
+import { module, test } from "qunit";
+import {
+ shouldEnableManualTrigger,
+ shouldShowManualTrigger,
+} from "discourse/plugins/discourse-workflows/admin/components/workflows/canvas/workflow-node";
+
+module("Unit | Component | workflows/canvas/workflow-node", function () {
+ test("shows manual trigger for trigger nodes", function (assert) {
+ assert.true(
+ shouldShowManualTrigger({
+ name: "Schedule",
+ type: "trigger:schedule",
+ typeVersion: "1.0",
+ })
+ );
+
+ assert.true(
+ shouldShowManualTrigger({
+ name: "Post created",
+ type: "trigger:post_created",
+ typeVersion: "1.0",
+ })
+ );
+ });
+
+ test("only enables data-dependent triggers after pinning data", function (assert) {
+ const node = {
+ name: "Post created",
+ type: "trigger:post_created",
+ typeVersion: "1.0",
+ };
+ const nodeType = {
+ capabilities: {
+ manually_triggerable: false,
+ },
+ };
+
+ assert.false(shouldEnableManualTrigger(node, nodeType));
+ assert.false(
+ shouldEnableManualTrigger(node, nodeType, {
+ isNodePinned() {
+ return false;
+ },
+ })
+ );
+ assert.true(
+ shouldEnableManualTrigger(node, nodeType, {
+ isNodePinned(nodeName) {
+ assert.strictEqual(nodeName, "Post created");
+ return true;
+ },
+ })
+ );
+ });
+
+ test("does not show or enable manual trigger for action nodes with pinned data", function (assert) {
+ assert.false(
+ shouldShowManualTrigger({
+ name: "HTTP request",
+ type: "action:http_request",
+ typeVersion: "1.0",
+ })
+ );
+ assert.false(
+ shouldEnableManualTrigger(
+ {
+ name: "HTTP request",
+ type: "action:http_request",
+ typeVersion: "1.0",
+ },
+ {
+ capabilities: {
+ manually_triggerable: true,
+ },
+ },
+ {
+ isNodePinned() {
+ return true;
+ },
+ }
+ )
+ );
+ });
+});
diff --git a/plugins/discourse-workflows/test/javascripts/unit/lib/expression-context-test.js b/plugins/discourse-workflows/test/javascripts/unit/lib/expression-context-test.js
new file mode 100644
index 00000000000..088dca73bfa
--- /dev/null
+++ b/plugins/discourse-workflows/test/javascripts/unit/lib/expression-context-test.js
@@ -0,0 +1,351 @@
+import { module, test } from "qunit";
+import {
+ buildScope,
+ lookupWorkflowMethodDoc,
+ resolveVariableId,
+ walkScope,
+} from "discourse/plugins/discourse-workflows/admin/lib/workflows/expression-context";
+
+module("Unit | lib | discourse-workflows | buildScope", function () {
+ test("builds $json from inputFields", function (assert) {
+ const scope = buildScope({
+ inputFields: [
+ { key: "title", type: "string" },
+ { key: "count", type: "integer" },
+ ],
+ });
+
+ assert.strictEqual(scope.$json.title, "");
+ assert.strictEqual(scope.$json.count, 0);
+ });
+
+ test("builds nested $json from children", function (assert) {
+ const scope = buildScope({
+ inputFields: [
+ {
+ key: "post",
+ type: "object",
+ children: [
+ { key: "id", type: "integer" },
+ { key: "raw", type: "string" },
+ ],
+ },
+ ],
+ });
+
+ assert.strictEqual(scope.$json.post.id, 0);
+ assert.strictEqual(scope.$json.post.raw, "");
+ });
+
+ test("trigger aliases $json", function (assert) {
+ const scope = buildScope({
+ inputFields: [{ key: "title", type: "string" }],
+ });
+
+ assert.strictEqual(scope.trigger, scope.$json);
+ });
+
+ test("$input.item.json aliases $json", function (assert) {
+ const scope = buildScope({
+ inputFields: [{ key: "title", type: "string" }],
+ });
+
+ assert.strictEqual(scope.$input.item.json, scope.$json);
+ assert.strictEqual(scope.$itemIndex, 0);
+ });
+
+ test("builds $input helpers for current node input", function (assert) {
+ const scope = buildScope({
+ inputFields: [{ key: "title", type: "string" }],
+ });
+
+ assert.strictEqual(scope.$input.all().length, 1);
+ assert.strictEqual(scope.$input.first(), scope.$input.item);
+ assert.strictEqual(scope.$input.last(), scope.$input.item);
+ assert.deepEqual(scope.$input.params, Object.create(null));
+ assert.deepEqual(scope.$input.context, Object.create(null));
+ });
+
+ test("exposes method docs for workflow-owned scope helpers", function (assert) {
+ assert.deepEqual(lookupWorkflowMethodDoc("$input", "all"), {
+ detail: "()",
+ info: "Returns an array of the current node's input items.",
+ });
+ assert.strictEqual(lookupWorkflowMethodDoc("$input", "missing"), null);
+ });
+
+ test("ancestor node outputs accessible via $()", function (assert) {
+ const scope = buildScope({
+ ancestorNodes: [
+ {
+ node: { name: "Fetch data" },
+ fields: [{ key: "name", type: "string" }],
+ },
+ ],
+ });
+
+ const ref = scope.$("Fetch data");
+ assert.strictEqual(ref.item.json.name, "");
+ assert.strictEqual(ref.first().json.name, "");
+ assert.strictEqual(ref.last().json.name, "");
+ assert.strictEqual(ref.itemMatching(0).json.name, "");
+ assert.strictEqual(ref.pairedItem().json.name, "");
+ assert.strictEqual(ref.all()[0].json.name, "");
+ });
+
+ test("$() returns empty structure for unknown nodes", function (assert) {
+ const ref = buildScope({}).$("Missing");
+ assert.deepEqual(Object.keys(ref.item.json), []);
+ });
+
+ test("builds $vars from workflowVars", function (assert) {
+ const scope = buildScope({
+ workflowVars: [
+ { key: "API_KEY", value: "secret" },
+ { key: "URL", value: "https://example.com" },
+ ],
+ });
+
+ assert.strictEqual(scope.$vars.API_KEY, "secret");
+ assert.strictEqual(scope.$vars.URL, "https://example.com");
+ });
+
+ test("builds $execution with standard fields", function (assert) {
+ const scope = buildScope({});
+
+ assert.strictEqual(scope.$execution.id, 0);
+ assert.strictEqual(scope.$execution.workflow_id, 0);
+ assert.strictEqual(scope.$execution.workflow_name, "");
+ });
+
+ test("includes resume_url when a webhook wait node exists", function (assert) {
+ const scope = buildScope({
+ nodes: [{ type: "flow:wait", configuration: { resume: "webhook" } }],
+ });
+
+ assert.strictEqual(scope.$execution.resume_url, "");
+ });
+
+ test("omits resume_url when no webhook wait", function (assert) {
+ assert.strictEqual(
+ buildScope({ nodes: [] }).$execution.resume_url,
+ undefined
+ );
+ });
+
+ test("includes resumeFormUrl when a form page node exists", function (assert) {
+ const scope = buildScope({
+ nodes: [{ type: "action:form", configuration: { page_type: "page" } }],
+ });
+
+ assert.strictEqual(scope.$execution.resumeFormUrl, "");
+ });
+
+ test("omits resumeFormUrl when no form page node exists", function (assert) {
+ const scope = buildScope({
+ nodes: [
+ { type: "action:form", configuration: { page_type: "completion" } },
+ ],
+ });
+
+ assert.strictEqual(scope.$execution.resumeFormUrl, undefined);
+ });
+
+ test("exposes global constructors", function (assert) {
+ const scope = buildScope({});
+
+ assert.strictEqual(scope.Math, Math);
+ assert.strictEqual(scope.JSON, JSON);
+ assert.strictEqual(scope.parseInt, parseInt);
+ });
+
+ test("builds $current_user with id and username", function (assert) {
+ const scope = buildScope({});
+
+ assert.strictEqual(scope.$current_user.id, 0);
+ assert.strictEqual(scope.$current_user.username, "");
+ });
+
+ test("filters private/theme keys from siteSettings", function (assert) {
+ const scope = buildScope({
+ siteSettings: {
+ title: "My Forum",
+ _internal: "hidden",
+ theme_key: "skip",
+ max_users: 100,
+ },
+ });
+
+ assert.strictEqual(scope.$site_settings.title, "My Forum");
+ assert.strictEqual(scope.$site_settings.max_users, 100);
+ assert.strictEqual(scope.$site_settings._internal, undefined);
+ assert.strictEqual(scope.$site_settings.theme_key, undefined);
+ });
+
+ test("maps boolean and array field types", function (assert) {
+ const scope = buildScope({
+ inputFields: [
+ { key: "active", type: "boolean" },
+ { key: "items", type: "array" },
+ ],
+ });
+
+ assert.false(scope.$json.active);
+ assert.deepEqual(scope.$json.items, []);
+ });
+
+ test("maps unknown field types to string exemplar", function (assert) {
+ const scope = buildScope({
+ inputFields: [{ key: "custom", type: "unknown_type" }],
+ });
+
+ assert.strictEqual(scope.$json.custom, "");
+ });
+});
+
+module("Unit | lib | discourse-workflows | walkScope", function () {
+ test("resolves top-level scope key", function (assert) {
+ assert.deepEqual(walkScope({ $json: { title: "hello" } }, "$json"), {
+ title: "hello",
+ });
+ });
+
+ test("resolves nested dot path", function (assert) {
+ assert.strictEqual(
+ walkScope({ $json: { post: { id: 42 } } }, "$json.post.id"),
+ 42
+ );
+ });
+
+ test("returns undefined for missing path", function (assert) {
+ assert.strictEqual(
+ walkScope({ $json: {} }, "$json.missing.deep"),
+ undefined
+ );
+ });
+
+ test("returns undefined for null path", function (assert) {
+ assert.strictEqual(walkScope({}, null), undefined);
+ });
+
+ test("returns undefined for empty path", function (assert) {
+ assert.strictEqual(walkScope({}, ""), undefined);
+ });
+
+ test("resolves node reference via $() path", function (assert) {
+ const scope = {
+ $: (name) => ({ item: { json: { name: `node-${name}` } } }),
+ };
+
+ assert.strictEqual(
+ walkScope(scope, "$('MyNode').item.json.name"),
+ "node-MyNode"
+ );
+ });
+
+ test("resolves node reference method calls via $() path", function (assert) {
+ const scope = {
+ $itemIndex: 0,
+ $: (name) => ({
+ first: () => ({ json: { name: `node-${name}` } }),
+ itemMatching: (index) => ({ json: { index } }),
+ all: (branchIndex, runIndex) => [{ json: { branchIndex, runIndex } }],
+ }),
+ };
+
+ assert.strictEqual(
+ walkScope(scope, "$('MyNode').first().json.name"),
+ "node-MyNode"
+ );
+ assert.strictEqual(
+ walkScope(scope, "$('MyNode').itemMatching(2).json.index"),
+ 2
+ );
+ assert.deepEqual(walkScope(scope, "$('MyNode').all(1, 0)"), [
+ { json: { branchIndex: 1, runIndex: 0 } },
+ ]);
+ assert.strictEqual(
+ walkScope(scope, "$('MyNode').all(1)[$itemIndex].json.branchIndex"),
+ 1
+ );
+ });
+
+ test("resolves node reference with double quotes", function (assert) {
+ const scope = {
+ $: (name) => ({ item: { json: { name: `node-${name}` } } }),
+ };
+
+ assert.strictEqual(
+ walkScope(scope, '$("MyNode").item.json.name'),
+ "node-MyNode"
+ );
+ });
+
+ test("resolves escaped node references", function (assert) {
+ const scope = {
+ $: (name) => ({ item: { json: { name: `node-${name}` } } }),
+ };
+
+ assert.strictEqual(
+ walkScope(scope, '$("Fetch \\"quoted\\" \\\\ data").item.json.name'),
+ 'node-Fetch "quoted" \\ data'
+ );
+ assert.strictEqual(
+ walkScope(scope, "$('Fetch \\'quoted\\' \\\\ data').item.json.name"),
+ "node-Fetch 'quoted' \\ data"
+ );
+ });
+
+ test("returns undefined when $() throws for unknown node", function (assert) {
+ const scope = {
+ $: () => {
+ throw new Error("not found");
+ },
+ };
+
+ assert.strictEqual(walkScope(scope, "$('Missing').item"), undefined);
+ });
+
+ test("resolves array values", function (assert) {
+ assert.deepEqual(walkScope({ $json: { tags: ["a", "b"] } }, "$json.tags"), [
+ "a",
+ "b",
+ ]);
+ });
+
+ test("resolves boolean values", function (assert) {
+ assert.true(walkScope({ $json: { active: true } }, "$json.active"));
+ });
+
+ test("stops at null intermediate", function (assert) {
+ assert.strictEqual(
+ walkScope({ $json: { post: null } }, "$json.post.id"),
+ undefined
+ );
+ });
+
+ test("handles node ref with no further path", function (assert) {
+ const nodeData = { item: { json: { id: 1 } } };
+ assert.deepEqual(walkScope({ $: () => nodeData }, "$('Node')"), nodeData);
+ });
+});
+
+module("Unit | lib | discourse-workflows | resolveVariableId", function () {
+ test("keeps dollar-prefixed IDs as-is", function (assert) {
+ assert.strictEqual(
+ resolveVariableId({ id: "$current_user.username" }),
+ "$current_user.username"
+ );
+ });
+
+ test("prepends $json to non-dollar IDs", function (assert) {
+ assert.strictEqual(resolveVariableId({ id: "topic_id" }), "$json.topic_id");
+ });
+
+ test("uses custom itemPrefix", function (assert) {
+ assert.strictEqual(
+ resolveVariableId({ id: "topic_id" }, "$item"),
+ "$item.topic_id"
+ );
+ });
+});
diff --git a/plugins/discourse-workflows/test/javascripts/unit/lib/workflows-canvas-file-io-test.js b/plugins/discourse-workflows/test/javascripts/unit/lib/workflows-canvas-file-io-test.js
new file mode 100644
index 00000000000..61ad33c4ad5
--- /dev/null
+++ b/plugins/discourse-workflows/test/javascripts/unit/lib/workflows-canvas-file-io-test.js
@@ -0,0 +1,289 @@
+import { module, test } from "qunit";
+import {
+ buildWorkflowExportPayload,
+ parseWorkflowImport,
+} from "discourse/plugins/discourse-workflows/admin/components/workflows/canvas/canvas-file-io";
+import { mergeImportedStaticData } from "discourse/plugins/discourse-workflows/admin/lib/workflows/static-data";
+import WorkflowNode from "discourse/plugins/discourse-workflows/admin/models/workflow-node";
+
+module("Unit | lib | discourse-workflows | canvas-file-io", function () {
+ test("buildWorkflowExportPayload returns workflow JSON", function (assert) {
+ const node = WorkflowNode.create({
+ clientId: "node-1",
+ type: "action:http_request",
+ typeVersion: "1.0",
+ name: "Send request",
+ configuration: {
+ method: "GET",
+ url: "https://example.com",
+ alwaysOutputData: true,
+ authentication: "bearer_token",
+ credentials: {
+ auth: {
+ id: "42",
+ credential_type: "bearer_token",
+ },
+ },
+ },
+ });
+
+ const payload = buildWorkflowExportPayload([node], [], [], {
+ id: 42,
+ name: "Imported workflow",
+ settings: { executionOrder: "v1" },
+ staticData: { "node:Send request": { count: 1 } },
+ pinData: { "node-1": [{ json: { ok: true } }] },
+ versionId: "version-1",
+ activeVersionId: "version-1",
+ versionCounter: 3,
+ });
+
+ assert.strictEqual(payload.id, "42");
+ assert.strictEqual(payload.name, "Imported workflow");
+ assert.deepEqual(payload.settings, { executionOrder: "v1" });
+ assert.deepEqual(payload.staticData, { "node:Send request": { count: 1 } });
+ assert.deepEqual(payload.pinData, { "node-1": [{ json: { ok: true } }] });
+ assert.strictEqual(payload.versionId, "version-1");
+ assert.strictEqual(payload.activeVersionId, "version-1");
+ assert.strictEqual(payload.versionCounter, 3);
+ assert.deepEqual(payload.connections, {});
+ assert.deepEqual(payload.nodes[0].credentials, {
+ auth: {
+ id: "42",
+ credential_type: "bearer_token",
+ },
+ });
+ assert.true(payload.nodes[0].alwaysOutputData);
+ assert.false("settings" in payload.nodes[0]);
+ assert.false("credentials" in payload.nodes[0].parameters);
+ });
+
+ test("buildWorkflowExportPayload serializes multi-output connections without null holes", function (assert) {
+ const source = WorkflowNode.create({
+ clientId: "node-1",
+ type: "condition:if",
+ typeVersion: "1.0",
+ name: "If",
+ });
+ const target = WorkflowNode.create({
+ clientId: "node-2",
+ type: "action:log",
+ typeVersion: "1.0",
+ name: "Log",
+ });
+
+ const payload = buildWorkflowExportPayload(
+ [source, target],
+ [
+ {
+ sourceClientId: "node-1",
+ targetClientId: "node-2",
+ connectionType: "main",
+ sourceOutputIndex: 1,
+ targetInputIndex: 0,
+ },
+ ],
+ []
+ );
+
+ assert.deepEqual(payload.connections, {
+ If: {
+ main: [[], [{ node: "Log", type: "main", index: 0 }]],
+ },
+ });
+ });
+
+ test("parseWorkflowImport strips credential references", function (assert) {
+ const result = parseWorkflowImport(
+ JSON.stringify({
+ nodes: [
+ {
+ type: "action:http_request",
+ typeVersion: "1.0",
+ name: "Send request",
+ parameters: {
+ method: "GET",
+ url: "https://example.com",
+ authentication: "bearer_token",
+ credentials: {
+ auth: {
+ id: "99",
+ credential_type: "bearer_token",
+ },
+ },
+ },
+ credentials: {
+ auth: {
+ id: "42",
+ credential_type: "bearer_token",
+ },
+ },
+ notes: "Imported note",
+ notesInFlow: false,
+ alwaysOutputData: true,
+ },
+ ],
+ connections: {},
+ })
+ );
+
+ assert.deepEqual(result.nodes[0].credentials, {});
+ assert.false("credentials" in result.nodes[0].parameters);
+ assert.false("settings" in result.nodes[0]);
+ assert.false("credentials" in result.nodes[0].configuration);
+ assert.strictEqual(result.nodes[0].notes, "Imported note");
+ assert.false(result.nodes[0].notesInFlow);
+ assert.true(result.nodes[0].alwaysOutputData);
+ });
+
+ test("parseWorkflowImport preserves imported static data", function (assert) {
+ const result = parseWorkflowImport(
+ JSON.stringify({
+ nodes: [
+ {
+ type: "action:log",
+ typeVersion: "1.0",
+ name: "Log",
+ parameters: {},
+ },
+ ],
+ connections: {},
+ staticData: {
+ global: {
+ tenant_id: "acme",
+ },
+ "node:Log": {
+ cursor: "abc",
+ },
+ },
+ })
+ );
+
+ assert.deepEqual(result.staticData, {
+ global: {
+ tenant_id: "acme",
+ },
+ "node:Log": {
+ cursor: "abc",
+ },
+ });
+ });
+
+ test("parseWorkflowImport rejects nested staticData node buckets", function (assert) {
+ const result = parseWorkflowImport(
+ JSON.stringify({
+ nodes: [
+ {
+ type: "action:log",
+ typeVersion: "1.0",
+ name: "Log",
+ parameters: {},
+ },
+ ],
+ connections: {},
+ staticData: {
+ node: {
+ Log: {},
+ },
+ },
+ })
+ );
+
+ assert.deepEqual(result, { error: "invalid" });
+ });
+
+ test("parseWorkflowImport rejects non-object staticData slots", function (assert) {
+ const result = parseWorkflowImport(
+ JSON.stringify({
+ nodes: [
+ {
+ type: "action:log",
+ typeVersion: "1.0",
+ name: "Log",
+ parameters: {},
+ },
+ ],
+ connections: {},
+ staticData: {
+ "node:Log": "bad",
+ },
+ })
+ );
+
+ assert.deepEqual(result, { error: "invalid" });
+ });
+
+ test("mergeImportedStaticData preserves existing runtime state while appending imported state", function (assert) {
+ const result = mergeImportedStaticData(
+ {
+ global: {
+ tenant_id: "acme",
+ shared: "existing",
+ },
+ "node:Existing": {
+ cursor: "existing",
+ },
+ },
+ {
+ global: {
+ shared: "imported",
+ imported: true,
+ },
+ "node:Imported": {
+ cursor: "imported",
+ },
+ }
+ );
+
+ assert.deepEqual(result, {
+ global: {
+ tenant_id: "acme",
+ shared: "imported",
+ imported: true,
+ },
+ "node:Existing": {
+ cursor: "existing",
+ },
+ "node:Imported": {
+ cursor: "imported",
+ },
+ });
+ });
+
+ test("parseWorkflowImport rejects unsupported export format", function (assert) {
+ const result = parseWorkflowImport(
+ JSON.stringify({
+ version: 2,
+ nodes: [{ type: "action:log", type_version: "1.0", name: "Log" }],
+ connections: [
+ {
+ source_index: 0,
+ target_index: 1,
+ connection_type: "main",
+ },
+ ],
+ })
+ );
+
+ assert.deepEqual(result, { error: "invalid" });
+ });
+
+ test("parseWorkflowImport rejects unsupported node keys by key presence", function (assert) {
+ for (const node of [
+ { type: "action:log", type_version: "", name: "Log" },
+ { type: "action:log", webhook_id: null, name: "Log" },
+ { type: "action:log", position_index: 0, name: "Log" },
+ { type: "action:log", settings: {}, name: "Log" },
+ ]) {
+ assert.deepEqual(
+ parseWorkflowImport(JSON.stringify({ nodes: [node], connections: {} })),
+ { error: "invalid" }
+ );
+ }
+ });
+
+ test("parseWorkflowImport rejects non-object workflow JSON", function (assert) {
+ assert.deepEqual(parseWorkflowImport("null"), { error: "invalid" });
+ assert.deepEqual(parseWorkflowImport("[]"), { error: "invalid" });
+ });
+});
diff --git a/plugins/discourse-workflows/test/javascripts/unit/lib/workflows-canvas-manual-trigger-test.js b/plugins/discourse-workflows/test/javascripts/unit/lib/workflows-canvas-manual-trigger-test.js
new file mode 100644
index 00000000000..32b43ec00fb
--- /dev/null
+++ b/plugins/discourse-workflows/test/javascripts/unit/lib/workflows-canvas-manual-trigger-test.js
@@ -0,0 +1,72 @@
+import { setupTest } from "ember-qunit";
+import { module, test } from "qunit";
+import sinon from "sinon";
+import pretender, { response } from "discourse/tests/helpers/create-pretender";
+import { runManualTrigger } from "discourse/plugins/discourse-workflows/admin/components/workflows/canvas/canvas-manual-trigger";
+
+module("Unit | Utility | workflows canvas manual trigger", function (hooks) {
+ setupTest(hooks);
+
+ hooks.afterEach(function () {
+ sinon.restore();
+ });
+
+ test("starts a form test session instead of opening the production form URL", async function (assert) {
+ sinon.stub(window, "open");
+ pretender.post(
+ "/admin/plugins/discourse-workflows/workflows/7/form-test-sessions.json",
+ (request) => {
+ assert.strictEqual(request.requestBody, "trigger_node_id=trigger-1");
+ return response(201, {
+ test_url: "/workflows/form-test/test-token",
+ });
+ }
+ );
+
+ await runManualTrigger({
+ node: {
+ type: "trigger:form",
+ webhookId: "a1b2c3d4-e5f6-7890-abcd-ef0123456789",
+ },
+ clientId: "trigger-1",
+ workflowId: 7,
+ });
+
+ assert.true(window.open.calledOnce);
+ assert.true(
+ window.open.calledWith(
+ "http://localhost:3000/workflows/form-test/test-token",
+ "_blank"
+ )
+ );
+ });
+
+ test("starts a webhook test listener instead of opening the production webhook URL", async function (assert) {
+ sinon.stub(window, "open");
+ const toasts = { success: sinon.stub() };
+ const session = {
+ startWebhookTestListener: sinon.stub().resolves({
+ listenerId: "listener-1",
+ testUrl: "/workflows/webhook-test/listener-1/test-hook",
+ expiresAt: "2026-05-22T12:00:00Z",
+ }),
+ };
+
+ await runManualTrigger({
+ node: {
+ type: "trigger:webhook",
+ configuration: {
+ path: "test-hook",
+ },
+ },
+ clientId: "webhook-1",
+ workflowId: 7,
+ toasts,
+ session,
+ });
+
+ assert.true(window.open.notCalled);
+ assert.true(session.startWebhookTestListener.calledWith("webhook-1"));
+ assert.true(toasts.success.calledOnce);
+ });
+});
diff --git a/plugins/discourse-workflows/test/javascripts/unit/lib/workflows-condition-operators-test.js b/plugins/discourse-workflows/test/javascripts/unit/lib/workflows-condition-operators-test.js
new file mode 100644
index 00000000000..1b46d40e622
--- /dev/null
+++ b/plugins/discourse-workflows/test/javascripts/unit/lib/workflows-condition-operators-test.js
@@ -0,0 +1,39 @@
+import { module, test } from "qunit";
+import {
+ implicitValueFor,
+ isSingleValueOperator,
+ operatorsForType,
+} from "discourse/plugins/discourse-workflows/admin/lib/workflows/condition-operators";
+
+module("Unit | lib | discourse-workflows | condition operators", function () {
+ test("returns workflow operators by canonical type", function (assert) {
+ assert.deepEqual(operatorsForType("number"), [
+ "equals",
+ "notEquals",
+ "gt",
+ "lt",
+ "gte",
+ "lte",
+ ]);
+ });
+
+ test("returns data-table operators by context", function (assert) {
+ assert.deepEqual(operatorsForType("boolean", { context: "data_table" }), [
+ "empty",
+ "notEmpty",
+ "true",
+ "false",
+ ]);
+ });
+
+ test("exposes single-value operator metadata", function (assert) {
+ assert.true(isSingleValueOperator("empty"));
+ assert.false(isSingleValueOperator("equals"));
+ assert.true(implicitValueFor("true"));
+ assert.strictEqual(implicitValueFor("empty"), null);
+ });
+
+ test("defaults missing types to string operators", function (assert) {
+ assert.deepEqual(operatorsForType(null), operatorsForType("string"));
+ });
+});
diff --git a/plugins/discourse-workflows/test/javascripts/unit/lib/workflows-data-schema-test.js b/plugins/discourse-workflows/test/javascripts/unit/lib/workflows-data-schema-test.js
new file mode 100644
index 00000000000..3574290ac45
--- /dev/null
+++ b/plugins/discourse-workflows/test/javascripts/unit/lib/workflows-data-schema-test.js
@@ -0,0 +1,319 @@
+import { module, test } from "qunit";
+import {
+ ancestorOutputNodes,
+ exemplarFromFields,
+ inputConnectionsForNode,
+ inputFieldPrefixForConnection,
+ inputForRun,
+ inputSummaryForNode,
+ nodeItemJsonPath,
+ nodeOutputItemJsonPath,
+ outputForRun,
+ outputSchemaForNode,
+ outputSummaryForNode,
+ schemaFieldsForItems,
+ schemaFieldsForNodeInput,
+ schemaFieldsForNodeOutput,
+} from "discourse/plugins/discourse-workflows/admin/lib/workflows/data-schema";
+
+module("Unit | lib | discourse-workflows | data-schema", function () {
+ test("schemaFieldsForItems infers and merges nested JSON fields", function (assert) {
+ const fields = schemaFieldsForItems([
+ {
+ json: {
+ title: "Hello",
+ count: 1,
+ published: true,
+ author: { username: "sam" },
+ },
+ },
+ {
+ json: {
+ count: 2,
+ author: { id: 12 },
+ tags: ["support"],
+ },
+ },
+ ]);
+
+ assert.deepEqual(
+ fields.map((field) => [field.key, field.type, field.id]),
+ [
+ ["title", "string", "$json.title"],
+ ["count", "number", "$json.count"],
+ ["published", "boolean", "$json.published"],
+ ["author", "object", "$json.author"],
+ ["tags", "array", "$json.tags"],
+ ]
+ );
+ assert.deepEqual(
+ fields.find((field) => field.key === "author").children.map((f) => f.key),
+ ["username", "id"]
+ );
+ assert.strictEqual(
+ fields.find((field) => field.key === "tags").children[0].id,
+ "$json.tags[0]"
+ );
+ });
+
+ test("schemaFieldsForItems uses bracket paths for unsafe keys", function (assert) {
+ const fields = schemaFieldsForItems([
+ { json: { "topic title": { "post-count": 2 } } },
+ ]);
+
+ assert.strictEqual(fields[0].id, '$json["topic title"]');
+ assert.strictEqual(
+ fields[0].children[0].id,
+ '$json["topic title"]["post-count"]'
+ );
+ });
+
+ test("schemaFieldsForItems preserves null values", function (assert) {
+ const fields = schemaFieldsForItems([
+ { json: { deleted_at: null, title: null } },
+ { json: { title: "Topic" } },
+ ]);
+
+ const deletedAt = fields.find((field) => field.key === "deleted_at");
+ const title = fields.find((field) => field.key === "title");
+
+ assert.strictEqual(deletedAt.type, "null");
+ assert.strictEqual(deletedAt.value, null);
+ assert.strictEqual(title.type, "string");
+ assert.strictEqual(title.value, "Topic");
+ assert.deepEqual(exemplarFromFields(fields), {
+ deleted_at: null,
+ title: "Topic",
+ });
+ });
+
+ test("schemaFieldsForNodeOutput uses the latest successful run", function (assert) {
+ const runData = {
+ "Node 1": [
+ {
+ status: "success",
+ outputs: [
+ { index: 0, items: [{ json: { old: true } }], item_count: 1 },
+ ],
+ },
+ {
+ status: "success",
+ outputs: [
+ { index: 0, items: [{ json: { current: true } }], item_count: 1 },
+ ],
+ },
+ ],
+ };
+
+ assert.deepEqual(
+ schemaFieldsForNodeOutput(runData, "Node 1").map((f) => f.key),
+ ["current"]
+ );
+ });
+
+ test("schemaFieldsForNodeOutput does not reuse older item data after a zero-item run", function (assert) {
+ const runData = {
+ "Node 1": [
+ {
+ status: "success",
+ outputs: [
+ { index: 0, items: [{ json: { stale: true } }], item_count: 1 },
+ ],
+ },
+ {
+ status: "success",
+ outputs: [{ index: 0, items: [], item_count: 0 }],
+ },
+ ],
+ };
+
+ assert.deepEqual(schemaFieldsForNodeOutput(runData, "Node 1"), []);
+ assert.deepEqual(outputSummaryForNode(runData, "Node 1"), {
+ outputIndex: 0,
+ itemCount: 0,
+ truncated: false,
+ });
+ });
+
+ test("outputForRun keeps output indexes positional", function (assert) {
+ const run = {
+ outputs: [{ index: 0, items: [{ json: { primary: true } }] }],
+ };
+
+ assert.strictEqual(outputForRun(run, 1), null);
+ });
+
+ test("outputSchemaForNode combines output indexes into one preview item", function (assert) {
+ const runData = {
+ "Node 1": [
+ {
+ status: "success",
+ outputs: [
+ { index: 0, items: [{ json: { matched: true } }], item_count: 1 },
+ {
+ index: 1,
+ items: [{ json: { rejected: true } }],
+ item_count: 1,
+ },
+ ],
+ },
+ ],
+ };
+ const schema = outputSchemaForNode(runData, "Node 1");
+
+ assert.deepEqual(schema.summary, {
+ itemCount: 1,
+ truncated: false,
+ });
+ assert.deepEqual(
+ schema.fields.map((field) => field.key),
+ ["matched", "rejected"]
+ );
+ });
+
+ test("schemaFieldsForNodeInput reads recorded node inputs", function (assert) {
+ const runData = {
+ "Node 1": [
+ {
+ status: "success",
+ inputs: [
+ {
+ index: 1,
+ items: [{ json: { topic: { id: 1 } } }],
+ item_count: 2,
+ source: { node_name: "Upstream", output_index: 0 },
+ },
+ ],
+ },
+ ],
+ };
+
+ assert.deepEqual(
+ schemaFieldsForNodeInput(runData, "Node 1", { inputIndex: 1 }).map(
+ (f) => f.key
+ ),
+ ["topic"]
+ );
+ assert.deepEqual(inputSummaryForNode(runData, "Node 1", 1), {
+ inputIndex: 1,
+ itemCount: 2,
+ truncated: false,
+ });
+ assert.strictEqual(inputForRun(runData["Node 1"][0], 0), null);
+ });
+
+ test("nodeItemJsonPath escapes node names for expressions", function (assert) {
+ assert.strictEqual(
+ nodeItemJsonPath('Fetch "quoted" \\ data'),
+ '$("Fetch \\"quoted\\" \\\\ data").item.json'
+ );
+ });
+
+ test("nodeOutputItemJsonPath builds explicit output and item index references", function (assert) {
+ assert.strictEqual(
+ nodeOutputItemJsonPath("Second input", { outputIndex: 1 }),
+ '$("Second input").all(1)[$itemIndex].json'
+ );
+ });
+
+ test("inputFieldPrefixForConnection uses $json only for the primary input connection", function (assert) {
+ const primaryConnection = {
+ sourceClientId: "left",
+ targetClientId: "merge",
+ targetInputIndex: 0,
+ };
+ const secondaryConnection = {
+ sourceClientId: "right",
+ targetClientId: "merge",
+ targetInputIndex: 1,
+ sourceOutputIndex: 2,
+ };
+
+ assert.strictEqual(
+ inputFieldPrefixForConnection(
+ primaryConnection,
+ { name: "Left" },
+ { primaryConnection }
+ ),
+ "$json"
+ );
+ assert.strictEqual(
+ inputFieldPrefixForConnection(
+ secondaryConnection,
+ { name: "Right" },
+ { primaryConnection }
+ ),
+ '$("Right").all(2)[$itemIndex].json'
+ );
+ });
+
+ test("outputSummaryForNode exposes item counts and truncation metadata", function (assert) {
+ const runData = {
+ "Node 1": [
+ {
+ status: "success",
+ outputs: [
+ {
+ index: 1,
+ items: [{ json: { value: 1 } }],
+ item_count: 3,
+ truncated: true,
+ },
+ ],
+ },
+ ],
+ };
+
+ assert.deepEqual(outputSummaryForNode(runData, "Node 1", 1), {
+ outputIndex: 1,
+ itemCount: 3,
+ truncated: true,
+ });
+ });
+
+ test("ancestorOutputNodes follows the upstream chain with output indexes", function (assert) {
+ const trigger = { clientId: "trigger" };
+ const branch = { clientId: "branch" };
+ const current = { clientId: "current" };
+ const graph = {
+ nodes: [trigger, branch, current],
+ connections: [
+ { sourceClientId: "trigger", targetClientId: "branch" },
+ {
+ sourceClientId: "branch",
+ targetClientId: "current",
+ sourceOutputIndex: 1,
+ },
+ ],
+ };
+
+ assert.deepEqual(ancestorOutputNodes(current, graph), [
+ { node: branch, outputIndex: 1 },
+ { node: trigger, outputIndex: 0 },
+ ]);
+ });
+
+ test("inputConnectionsForNode returns all incoming connections by input index", function (assert) {
+ const graph = {
+ connections: [
+ {
+ sourceClientId: "right",
+ targetClientId: "merge",
+ targetInputIndex: 1,
+ },
+ {
+ sourceClientId: "left",
+ targetClientId: "merge",
+ targetInputIndex: 0,
+ },
+ ],
+ };
+
+ assert.deepEqual(
+ inputConnectionsForNode({ clientId: "merge" }, graph).map(
+ (connection) => connection.sourceClientId
+ ),
+ ["left", "right"]
+ );
+ });
+});
diff --git a/plugins/discourse-workflows/test/javascripts/unit/lib/workflows-field-processors-test.js b/plugins/discourse-workflows/test/javascripts/unit/lib/workflows-field-processors-test.js
new file mode 100644
index 00000000000..9c97e59bf00
--- /dev/null
+++ b/plugins/discourse-workflows/test/javascripts/unit/lib/workflows-field-processors-test.js
@@ -0,0 +1,48 @@
+import { module, test } from "qunit";
+import processFields from "discourse/plugins/discourse-workflows/admin/lib/workflows/field-processors";
+
+module("Unit | lib | discourse-workflows | field-processors", function () {
+ test("returns fields unchanged", function (assert) {
+ const node = {
+ clientId: "node1",
+ type: "action:http_request",
+ configuration: {},
+ };
+ const graph = { nodes: [node], connections: [], nodeTypes: [] };
+ const fields = [
+ { key: "url", type: "string", id: "url" },
+ { key: "method", type: "string", id: "method" },
+ ];
+
+ assert.deepEqual(processFields(fields, node, graph), fields);
+ });
+
+ test("does not merge ancestor form fields into current form output", function (assert) {
+ const trigger = {
+ clientId: "trigger",
+ type: "trigger:form",
+ configuration: {
+ form_fields: {
+ values: [{ field_label: "Email", field_type: "text" }],
+ },
+ },
+ };
+ const action = {
+ clientId: "action",
+ type: "action:form",
+ configuration: {},
+ };
+ const graph = {
+ nodes: [trigger, action],
+ connections: [{ sourceClientId: "trigger", targetClientId: "action" }],
+ nodeTypes: [],
+ };
+ const fields = [
+ { key: "feedback", type: "string", id: "feedback" },
+ { key: "submitted_at", type: "string", id: "submitted_at" },
+ { key: "form_mode", type: "string", id: "form_mode" },
+ ];
+
+ assert.deepEqual(processFields(fields, action, graph), fields);
+ });
+});
diff --git a/plugins/discourse-workflows/test/javascripts/unit/lib/workflows-format-node-issue-test.js b/plugins/discourse-workflows/test/javascripts/unit/lib/workflows-format-node-issue-test.js
new file mode 100644
index 00000000000..182093ee64f
--- /dev/null
+++ b/plugins/discourse-workflows/test/javascripts/unit/lib/workflows-format-node-issue-test.js
@@ -0,0 +1,27 @@
+import { module, test } from "qunit";
+import formatNodeIssue from "discourse/plugins/discourse-workflows/admin/lib/workflows/format-node-issue";
+
+module("Unit | lib | discourse-workflows | format-node-issue", function () {
+ const nodeType = {
+ identifier: "action:test",
+ metadata: { i18n_prefix: "discourse_workflows", i18n_scope: "test_node" },
+ };
+
+ test("formats a required-message with the property's localized label", function (assert) {
+ const formatted = formatNodeIssue(
+ { path: "code", name: "code", message: "required" },
+ nodeType
+ );
+
+ assert.strictEqual(formatted, "Code is required");
+ });
+
+ test("falls back to a generic message for unknown issue types", function (assert) {
+ const formatted = formatNodeIssue(
+ { path: "code", name: "code", message: "out_of_range" },
+ nodeType
+ );
+
+ assert.strictEqual(formatted, "Code: out_of_range");
+ });
+});
diff --git a/plugins/discourse-workflows/test/javascripts/unit/lib/workflows-graph-utils-test.js b/plugins/discourse-workflows/test/javascripts/unit/lib/workflows-graph-utils-test.js
new file mode 100644
index 00000000000..d27fd846510
--- /dev/null
+++ b/plugins/discourse-workflows/test/javascripts/unit/lib/workflows-graph-utils-test.js
@@ -0,0 +1,483 @@
+import { module, test } from "qunit";
+import {
+ normalizeConnectionsForNodes,
+ normalizeMergeConfiguration,
+ removeNodesFromGraph,
+} from "discourse/plugins/discourse-workflows/admin/components/workflows/editor/graph-utils";
+
+function sortByKey(items, keyFn) {
+ return [...items].sort((a, b) => keyFn(a).localeCompare(keyFn(b)));
+}
+
+function normalizeGraph(graph) {
+ return {
+ nodes: sortByKey(graph.nodes, (node) => node.clientId).map((node) => ({
+ clientId: node.clientId,
+ type: node.type,
+ })),
+ connections: sortByKey(
+ graph.connections,
+ (connection) =>
+ `${connection.sourceClientId}::${connection.sourceOutput || "main"}::${connection.targetClientId}`
+ ).map((connection) => ({
+ sourceClientId: connection.sourceClientId,
+ sourceOutput: connection.sourceOutput || "main",
+ targetClientId: connection.targetClientId,
+ })),
+ };
+}
+
+module("Unit | Utility | workflows graph utils", function () {
+ test("reconnects a regular node with one incoming and one outgoing edge", function (assert) {
+ const graph = removeNodesFromGraph(
+ [
+ { clientId: "trigger", type: "trigger:manual" },
+ { clientId: "action", type: "action:set_fields" },
+ { clientId: "done", type: "action:topic_tags" },
+ ],
+ [
+ {
+ sourceClientId: "trigger",
+ sourceOutput: "main",
+ targetClientId: "action",
+ },
+ {
+ sourceClientId: "action",
+ sourceOutput: "main",
+ targetClientId: "done",
+ },
+ ],
+ ["action"]
+ );
+
+ assert.deepEqual(normalizeGraph(graph), {
+ nodes: [
+ { clientId: "done", type: "action:topic_tags" },
+ { clientId: "trigger", type: "trigger:manual" },
+ ],
+ connections: [
+ {
+ sourceClientId: "trigger",
+ sourceOutput: "main",
+ targetClientId: "done",
+ },
+ ],
+ });
+ });
+
+ test("removing a loop node keeps the former body node standalone and reconnects the done path", function (assert) {
+ const graph = removeNodesFromGraph(
+ [
+ { clientId: "trigger", type: "trigger:manual" },
+ { clientId: "loop", type: "flow:loop_over_items" },
+ { clientId: "body", type: "action:set_fields" },
+ { clientId: "done", type: "action:topic_tags" },
+ ],
+ [
+ {
+ sourceClientId: "trigger",
+ sourceOutput: "main",
+ targetClientId: "loop",
+ },
+ {
+ sourceClientId: "loop",
+ sourceOutput: "loop",
+ targetClientId: "loop",
+ },
+ {
+ sourceClientId: "loop",
+ sourceOutput: "loop",
+ targetClientId: "body",
+ },
+ {
+ sourceClientId: "body",
+ sourceOutput: "main",
+ targetClientId: "loop",
+ },
+ {
+ sourceClientId: "loop",
+ sourceOutput: "done",
+ targetClientId: "done",
+ },
+ ],
+ ["loop"]
+ );
+
+ assert.deepEqual(normalizeGraph(graph), {
+ nodes: [
+ { clientId: "body", type: "action:set_fields" },
+ { clientId: "done", type: "action:topic_tags" },
+ { clientId: "trigger", type: "trigger:manual" },
+ ],
+ connections: [
+ {
+ sourceClientId: "trigger",
+ sourceOutput: "main",
+ targetClientId: "done",
+ },
+ ],
+ });
+ });
+
+ test("removing a loop node handles index-only loop connections", function (assert) {
+ const graph = removeNodesFromGraph(
+ [
+ { clientId: "trigger", type: "trigger:manual" },
+ { clientId: "loop", type: "flow:loop_over_items" },
+ { clientId: "body", type: "action:set_fields" },
+ { clientId: "done", type: "action:topic_tags" },
+ ],
+ [
+ {
+ sourceClientId: "trigger",
+ sourceOutputIndex: 0,
+ targetClientId: "loop",
+ targetInputIndex: 0,
+ },
+ {
+ sourceClientId: "loop",
+ sourceOutputIndex: 1,
+ targetClientId: "body",
+ targetInputIndex: 0,
+ },
+ {
+ sourceClientId: "body",
+ sourceOutputIndex: 0,
+ targetClientId: "loop",
+ targetInputIndex: 0,
+ },
+ {
+ sourceClientId: "loop",
+ sourceOutputIndex: 0,
+ targetClientId: "done",
+ targetInputIndex: 0,
+ },
+ ],
+ ["loop"]
+ );
+
+ assert.deepEqual(normalizeGraph(graph), {
+ nodes: [
+ { clientId: "body", type: "action:set_fields" },
+ { clientId: "done", type: "action:topic_tags" },
+ { clientId: "trigger", type: "trigger:manual" },
+ ],
+ connections: [
+ {
+ sourceClientId: "trigger",
+ sourceOutput: "main",
+ targetClientId: "done",
+ },
+ ],
+ });
+ });
+
+ test("removing the only loop body preserves the loop self-connection", function (assert) {
+ const graph = removeNodesFromGraph(
+ [
+ { clientId: "trigger", type: "trigger:manual" },
+ { clientId: "loop", type: "flow:loop_over_items" },
+ { clientId: "body", type: "action:set_fields" },
+ { clientId: "done", type: "action:topic_tags" },
+ ],
+ [
+ {
+ sourceClientId: "trigger",
+ sourceOutput: "main",
+ targetClientId: "loop",
+ },
+ {
+ sourceClientId: "loop",
+ sourceOutput: "loop",
+ targetClientId: "loop",
+ },
+ {
+ sourceClientId: "loop",
+ sourceOutput: "loop",
+ targetClientId: "body",
+ },
+ {
+ sourceClientId: "body",
+ sourceOutput: "main",
+ targetClientId: "loop",
+ },
+ {
+ sourceClientId: "loop",
+ sourceOutput: "done",
+ targetClientId: "done",
+ },
+ ],
+ ["body"]
+ );
+
+ assert.deepEqual(normalizeGraph(graph), {
+ nodes: [
+ { clientId: "done", type: "action:topic_tags" },
+ { clientId: "loop", type: "flow:loop_over_items" },
+ { clientId: "trigger", type: "trigger:manual" },
+ ],
+ connections: [
+ {
+ sourceClientId: "loop",
+ sourceOutput: "done",
+ targetClientId: "done",
+ },
+ {
+ sourceClientId: "loop",
+ sourceOutput: "loop",
+ targetClientId: "loop",
+ },
+ {
+ sourceClientId: "trigger",
+ sourceOutput: "main",
+ targetClientId: "loop",
+ },
+ ],
+ });
+ });
+
+ test("removing a loop node preserves the internal body subgraph", function (assert) {
+ const graph = removeNodesFromGraph(
+ [
+ { clientId: "trigger", type: "trigger:manual" },
+ { clientId: "loop", type: "flow:loop_over_items" },
+ { clientId: "branch", type: "condition:if" },
+ { clientId: "true_body", type: "action:set_fields" },
+ { clientId: "false_body", type: "action:topic_tags" },
+ { clientId: "done", type: "action:http_request" },
+ ],
+ [
+ {
+ sourceClientId: "trigger",
+ sourceOutput: "main",
+ targetClientId: "loop",
+ },
+ {
+ sourceClientId: "loop",
+ sourceOutput: "loop",
+ targetClientId: "branch",
+ },
+ {
+ sourceClientId: "branch",
+ sourceOutput: "true",
+ targetClientId: "true_body",
+ },
+ {
+ sourceClientId: "branch",
+ sourceOutput: "false",
+ targetClientId: "false_body",
+ },
+ {
+ sourceClientId: "true_body",
+ sourceOutput: "main",
+ targetClientId: "loop",
+ },
+ {
+ sourceClientId: "false_body",
+ sourceOutput: "main",
+ targetClientId: "loop",
+ },
+ {
+ sourceClientId: "loop",
+ sourceOutput: "done",
+ targetClientId: "done",
+ },
+ ],
+ ["loop"]
+ );
+
+ assert.deepEqual(normalizeGraph(graph), {
+ nodes: [
+ { clientId: "branch", type: "condition:if" },
+ { clientId: "done", type: "action:http_request" },
+ { clientId: "false_body", type: "action:topic_tags" },
+ { clientId: "trigger", type: "trigger:manual" },
+ { clientId: "true_body", type: "action:set_fields" },
+ ],
+ connections: [
+ {
+ sourceClientId: "branch",
+ sourceOutput: "false",
+ targetClientId: "false_body",
+ },
+ {
+ sourceClientId: "branch",
+ sourceOutput: "true",
+ targetClientId: "true_body",
+ },
+ {
+ sourceClientId: "trigger",
+ sourceOutput: "main",
+ targetClientId: "done",
+ },
+ ],
+ });
+ });
+
+ test("bulk loop deletion does not reconnect surviving body nodes to the done path", function (assert) {
+ const graph = removeNodesFromGraph(
+ [
+ { clientId: "trigger", type: "trigger:manual" },
+ { clientId: "loop", type: "flow:loop_over_items" },
+ { clientId: "body_1", type: "action:set_fields" },
+ { clientId: "body_2", type: "action:topic_tags" },
+ { clientId: "done", type: "action:http_request" },
+ ],
+ [
+ {
+ sourceClientId: "trigger",
+ sourceOutput: "main",
+ targetClientId: "loop",
+ },
+ {
+ sourceClientId: "loop",
+ sourceOutput: "loop",
+ targetClientId: "body_1",
+ },
+ {
+ sourceClientId: "body_1",
+ sourceOutput: "main",
+ targetClientId: "body_2",
+ },
+ {
+ sourceClientId: "body_2",
+ sourceOutput: "main",
+ targetClientId: "loop",
+ },
+ {
+ sourceClientId: "loop",
+ sourceOutput: "done",
+ targetClientId: "done",
+ },
+ ],
+ ["loop", "body_1"]
+ );
+
+ assert.deepEqual(normalizeGraph(graph), {
+ nodes: [
+ { clientId: "body_2", type: "action:topic_tags" },
+ { clientId: "done", type: "action:http_request" },
+ { clientId: "trigger", type: "trigger:manual" },
+ ],
+ connections: [
+ {
+ sourceClientId: "trigger",
+ sourceOutput: "main",
+ targetClientId: "done",
+ },
+ ],
+ });
+ });
+
+ test("normalizes merge target inputs for the selected mode", function (assert) {
+ const connections = [
+ {
+ sourceClientId: "a",
+ sourceOutput: "main",
+ targetClientId: "merge",
+ targetInput: "main",
+ },
+ {
+ sourceClientId: "b",
+ sourceOutput: "main",
+ targetClientId: "merge",
+ targetInput: "main",
+ },
+ {
+ sourceClientId: "c",
+ sourceOutput: "main",
+ targetClientId: "merge",
+ targetInput: "main",
+ },
+ ];
+
+ assert.deepEqual(
+ normalizeConnectionsForNodes(connections, [
+ {
+ clientId: "merge",
+ type: "flow:merge",
+ configuration: { mode: "combine" },
+ },
+ ]).map((connection) => connection.targetInput),
+ ["input_1", "input_2"]
+ );
+
+ assert.deepEqual(
+ normalizeConnectionsForNodes(
+ [
+ {
+ sourceClientId: "a",
+ sourceOutput: "main",
+ targetClientId: "merge",
+ targetInput: "main",
+ },
+ {
+ sourceClientId: "b",
+ sourceOutput: "main",
+ targetClientId: "merge",
+ targetInput: "main",
+ },
+ ],
+ [
+ {
+ clientId: "merge",
+ type: "flow:merge",
+ configuration: { mode: "append" },
+ },
+ ]
+ ).map((connection) => connection.targetInput),
+ ["input_1", "input_2"]
+ );
+ assert.deepEqual(
+ normalizeConnectionsForNodes(
+ [
+ {
+ sourceClientId: "a",
+ sourceOutput: "main",
+ targetClientId: "merge",
+ targetInputIndex: 1,
+ },
+ {
+ sourceClientId: "b",
+ sourceOutput: "main",
+ targetClientId: "merge",
+ targetInput: "main",
+ },
+ ],
+ [
+ {
+ clientId: "merge",
+ type: "flow:merge",
+ configuration: { mode: "append" },
+ },
+ ]
+ ).map((connection) => connection.targetInputIndex),
+ [1, 0]
+ );
+ });
+
+ test("normalizes merge configuration to the selected mode", function (assert) {
+ assert.deepEqual(
+ normalizeMergeConfiguration({
+ mode: "choose_branch",
+ use_data_of_input: "input_2",
+ combine_by: "matching_fields",
+ fields_to_match: [{ field_1: "id", field_2: "id" }],
+ }),
+ {
+ mode: "choose_branch",
+ use_data_of_input: "input_2",
+ use_data_of_input_index: 1,
+ choose_output: "specified_input",
+ }
+ );
+
+ assert.deepEqual(
+ normalizeMergeConfiguration({
+ mode: "append",
+ use_data_of_input: "input_2",
+ }),
+ { mode: "append", number_inputs: 2 }
+ );
+ });
+});
diff --git a/plugins/discourse-workflows/test/javascripts/unit/lib/workflows-node-factory-test.js b/plugins/discourse-workflows/test/javascripts/unit/lib/workflows-node-factory-test.js
new file mode 100644
index 00000000000..43b9ad11894
--- /dev/null
+++ b/plugins/discourse-workflows/test/javascripts/unit/lib/workflows-node-factory-test.js
@@ -0,0 +1,177 @@
+import { setupTest } from "ember-qunit";
+import { module, test } from "qunit";
+import {
+ createNode,
+ generateNodeName,
+} from "discourse/plugins/discourse-workflows/admin/components/workflows/editor/node-factory";
+import { FORM_TRIGGER_TYPE } from "discourse/plugins/discourse-workflows/admin/lib/workflows/node-data-shape";
+import WorkflowNode from "discourse/plugins/discourse-workflows/admin/models/workflow-node";
+
+module("Unit | lib | discourse-workflows | node-factory", function (hooks) {
+ setupTest(hooks);
+
+ test("generateNodeName returns a non-empty string for a valid identifier", function (assert) {
+ const name = generateNodeName("trigger:webhook", []);
+ assert.strictEqual(typeof name, "string");
+ assert.true(name.length > 0);
+ });
+
+ test("generateNodeName appends counter on single name collision", function (assert) {
+ const baseName = generateNodeName("trigger:webhook", []);
+ const existingNodes = [{ name: baseName }];
+ const name = generateNodeName("trigger:webhook", existingNodes);
+ assert.strictEqual(name, `${baseName} 1`);
+ });
+
+ test("generateNodeName increments counter past multiple collisions", function (assert) {
+ const baseName = generateNodeName("trigger:webhook", []);
+ const existingNodes = [
+ { name: baseName },
+ { name: `${baseName} 1` },
+ { name: `${baseName} 2` },
+ ];
+ const name = generateNodeName("trigger:webhook", existingNodes);
+ assert.strictEqual(name, `${baseName} 3`);
+ });
+
+ test("createNode returns a node with correct type and default version", function (assert) {
+ const node = createNode("trigger:webhook", []);
+ assert.strictEqual(node.type, "trigger:webhook");
+ assert.strictEqual(node.typeVersion, "1.0");
+ });
+
+ test("createNode generates a unique clientId for each call", function (assert) {
+ const node1 = createNode("trigger:webhook", []);
+ const node2 = createNode("trigger:webhook", []);
+ assert.strictEqual(typeof node1.clientId, "string");
+ assert.strictEqual(typeof node2.clientId, "string");
+ assert.notStrictEqual(node1.clientId, node2.clientId);
+ });
+
+ test("createNode applies position when provided", function (assert) {
+ const position = { x: 100, y: 200 };
+ const node = createNode("trigger:webhook", [], position);
+ assert.deepEqual(node.position, position);
+ });
+
+ test("createNode applies built-in defaults for webhook trigger", function (assert) {
+ const node = createNode("trigger:webhook", []);
+ assert.true("http_method" in node.configuration);
+ assert.true("path" in node.configuration);
+ });
+
+ test("createNode applies built-in defaults for schedule trigger", function (assert) {
+ const node = createNode("trigger:schedule", []);
+ assert.deepEqual(node.configuration.rule, {
+ interval: [{ field: "hours", hoursInterval: 1, triggerAtMinute: 0 }],
+ });
+ });
+
+ test("createNode merges configOverrides over defaults", function (assert) {
+ const node = createNode("trigger:webhook", [], null, {
+ configOverrides: { http_method: "POST", custom_key: "custom_value" },
+ });
+ assert.strictEqual(node.configuration.http_method, "POST");
+ assert.strictEqual(node.configuration.custom_key, "custom_value");
+ });
+
+ test("createNode accepts typeVersion override", function (assert) {
+ const node = createNode("trigger:webhook", [], null, {
+ typeVersion: "2.0",
+ });
+ assert.strictEqual(node.typeVersion, "2.0");
+ });
+
+ test("WorkflowNode.serialize splits parameters, credentials, direct settings, and webhookId", function (assert) {
+ const node = WorkflowNode.create({
+ type: FORM_TRIGGER_TYPE,
+ typeVersion: "1.0",
+ name: "Signup",
+ webhookId: "form-uuid",
+ configuration: {
+ form_title: "Signup",
+ authentication: "basic_auth",
+ credentials: {
+ auth: {
+ id: "42",
+ credential_type: "basic_auth",
+ },
+ },
+ notes: "Shown on canvas",
+ notesInFlow: true,
+ alwaysOutputData: true,
+ },
+ });
+
+ const serialized = WorkflowNode.serialize(node);
+
+ assert.deepEqual(serialized.parameters, {
+ form_title: "Signup",
+ authentication: "basic_auth",
+ });
+ assert.deepEqual(serialized.credentials, {
+ auth: {
+ id: "42",
+ credential_type: "basic_auth",
+ },
+ });
+ assert.false("settings" in serialized);
+ assert.strictEqual(serialized.notes, "Shown on canvas");
+ assert.true(serialized.notesInFlow);
+ assert.true(serialized.alwaysOutputData);
+ assert.strictEqual(serialized.webhookId, "form-uuid");
+ });
+
+ test("WorkflowNode.serialize can explicitly clear credentials", function (assert) {
+ const node = WorkflowNode.create({
+ type: "trigger:webhook",
+ typeVersion: "1.0",
+ name: "Webhook",
+ parameters: {
+ path: "my-hook",
+ http_method: "POST",
+ authentication: "basic_auth",
+ },
+ credentials: {
+ auth: {
+ id: "42",
+ credential_type: "basic_auth",
+ },
+ },
+ });
+
+ node.configuration.authentication = "none";
+ node.configuration.credentials = {};
+
+ const serialized = WorkflowNode.serialize(node);
+
+ assert.deepEqual(serialized.parameters, {
+ path: "my-hook",
+ http_method: "POST",
+ authentication: "none",
+ });
+ assert.deepEqual(serialized.credentials, {});
+ });
+
+ test("WorkflowNode exposes saved credential slots in configuration", function (assert) {
+ const node = WorkflowNode.create({
+ type: "action:http_request",
+ parameters: {
+ authentication: "basic_auth",
+ },
+ credentials: {
+ auth: {
+ id: "42",
+ credential_type: "basic_auth",
+ },
+ },
+ });
+
+ assert.deepEqual(node.configuration.credentials, {
+ auth: {
+ id: "42",
+ credential_type: "basic_auth",
+ },
+ });
+ });
+});
diff --git a/plugins/discourse-workflows/test/javascripts/unit/lib/workflows-node-issues-test.js b/plugins/discourse-workflows/test/javascripts/unit/lib/workflows-node-issues-test.js
new file mode 100644
index 00000000000..1a7de2afe1e
--- /dev/null
+++ b/plugins/discourse-workflows/test/javascripts/unit/lib/workflows-node-issues-test.js
@@ -0,0 +1,139 @@
+import { module, test } from "qunit";
+import getNodeIssues from "discourse/plugins/discourse-workflows/admin/lib/workflows/node-issues";
+
+module("Unit | lib | discourse-workflows | node-issues", function () {
+ test("reports no issues when all required fields are set", function (assert) {
+ const schema = {
+ form_title: { type: "string", required: true },
+ };
+ const config = { form_title: "My form" };
+
+ assert.deepEqual(getNodeIssues(config, schema), []);
+ });
+
+ test("reports a top-level required field as missing", function (assert) {
+ const schema = {
+ form_title: { type: "string", required: true },
+ };
+
+ const issues = getNodeIssues({}, schema);
+
+ assert.strictEqual(issues.length, 1);
+ assert.strictEqual(issues[0].path, "form_title");
+ assert.strictEqual(issues[0].message, "required");
+ });
+
+ test("treats blank strings as missing", function (assert) {
+ const schema = {
+ form_title: { type: "string", required: true },
+ };
+
+ assert.strictEqual(getNodeIssues({ form_title: " " }, schema).length, 1);
+ });
+
+ test("treats empty arrays as missing when required", function (assert) {
+ const schema = {
+ form_fields: {
+ type: "fixed_collection",
+ required: true,
+ options: [{ name: "values", values: {} }],
+ },
+ };
+
+ assert.strictEqual(
+ getNodeIssues({ form_fields: { values: [] } }, schema).length,
+ 1
+ );
+ });
+
+ test("walks fixed collection items and reports missing nested required fields", function (assert) {
+ const schema = {
+ form_fields: {
+ type: "fixed_collection",
+ options: [
+ {
+ name: "values",
+ values: {
+ field_label: { type: "string", required: true },
+ field_type: { type: "options", required: true },
+ },
+ },
+ ],
+ },
+ };
+ const config = {
+ form_fields: {
+ values: [
+ { field_label: "", field_type: "text" },
+ { field_label: "Name", field_type: "" },
+ ],
+ },
+ };
+
+ const issues = getNodeIssues(config, schema);
+
+ assert.deepEqual(issues.map((i) => i.path).sort(), [
+ "form_fields.values.0.field_label",
+ "form_fields.values.1.field_type",
+ ]);
+ });
+
+ test("respects display_options show rules — hidden required fields are not reported", function (assert) {
+ const schema = {
+ page_type: { type: "options", default: "page" },
+ completion_title: {
+ type: "string",
+ required: true,
+ display_options: { show: { page_type: ["completion"] } },
+ },
+ };
+
+ assert.deepEqual(getNodeIssues({ page_type: "page" }, schema), []);
+
+ assert.strictEqual(
+ getNodeIssues({ page_type: "completion" }, schema).length,
+ 1
+ );
+ });
+
+ test("walks optional fields inside fixed collections", function (assert) {
+ const schema = {
+ form_fields: {
+ type: "fixed_collection",
+ options: [
+ {
+ name: "values",
+ values: {
+ field_label: { type: "string", required: true },
+ field_name: { type: "string" },
+ custom_required: { type: "string", required: true },
+ },
+ },
+ ],
+ },
+ };
+
+ const issues = getNodeIssues(
+ { form_fields: { values: [{ field_label: "Name" }] } },
+ schema
+ );
+
+ assert.deepEqual(
+ issues.map((i) => i.path),
+ ["form_fields.values.0.custom_required"]
+ );
+ });
+
+ test("returns empty array when schema is missing", function (assert) {
+ assert.deepEqual(getNodeIssues({}, null), []);
+ assert.deepEqual(getNodeIssues({}, undefined), []);
+ });
+
+ test("applies field defaults before checking required", function (assert) {
+ const schema = {
+ operation: { type: "options", required: true, default: "add" },
+ };
+
+ assert.deepEqual(getNodeIssues({}, schema), []);
+ });
+});
diff --git a/plugins/discourse-workflows/test/javascripts/unit/lib/workflows-node-types-test.js b/plugins/discourse-workflows/test/javascripts/unit/lib/workflows-node-types-test.js
new file mode 100644
index 00000000000..9fa59b6265d
--- /dev/null
+++ b/plugins/discourse-workflows/test/javascripts/unit/lib/workflows-node-types-test.js
@@ -0,0 +1,563 @@
+import { setupTest } from "ember-qunit";
+import { module, test } from "qunit";
+import pretender, { response } from "discourse/tests/helpers/create-pretender";
+import ComboBoxField from "discourse/plugins/discourse-workflows/admin/components/workflows/configurators/combo-box";
+import WorkflowEditorSession from "discourse/plugins/discourse-workflows/admin/lib/workflows/editor-session";
+import {
+ nodeTypeI18nPrefix,
+ nodeTypeI18nScope,
+ nodeTypeInputLabel,
+ nodeTypeInputs,
+ nodeTypeOperationLabel,
+ nodeTypeOutputKeys,
+ nodeTypePaletteGroup,
+ nodeTypePortLabel,
+ nodeTypePrimaryOutputKey,
+ nodeTypeRunScopeLabelKey,
+ nodeTypeVersion,
+ resolveNodeTypeVersion,
+} from "discourse/plugins/discourse-workflows/admin/lib/workflows/node-types";
+
+module("Unit | Utility | workflows node types", function () {
+ test("reads i18n metadata from the descriptor ui", function (assert) {
+ const nodeType = {
+ identifier: "action:ai_agent",
+ ui: {
+ i18n_prefix: "discourse_ai.discourse_workflows",
+ i18n_scope: "ai_agent",
+ },
+ };
+
+ assert.strictEqual(
+ nodeTypeI18nPrefix(nodeType),
+ "discourse_ai.discourse_workflows"
+ );
+ assert.strictEqual(nodeTypeI18nScope(nodeType), "ai_agent");
+ });
+
+ test("reads operation labels and palette groups from the descriptor", function (assert) {
+ const nodeType = {
+ identifier: "action:data_table",
+ operations: [
+ {
+ value: "insert",
+ label_key: "discourse_workflows.data_table_node.operations.insert",
+ },
+ ],
+ ui: {
+ palette_group: {
+ id: "data",
+ icon: "table",
+ label_key: "discourse_workflows.add_node.categories.data",
+ order: 50,
+ },
+ },
+ };
+
+ assert.strictEqual(nodeTypeOperationLabel(nodeType, "insert"), "Insert");
+ assert.deepEqual(nodeTypePaletteGroup(nodeType), {
+ id: "data",
+ icon: "table",
+ label_key: "discourse_workflows.add_node.categories.data",
+ order: 50,
+ });
+ });
+
+ test("uses descriptor ports for labels and routing", function (assert) {
+ const filterNodeType = {
+ identifier: "condition:filter",
+ ports: [
+ {
+ key: "true",
+ primary: true,
+ label_key: "discourse_workflows.executions.statuses.kept",
+ },
+ {
+ key: "false",
+ primary: false,
+ label_key: "discourse_workflows.executions.statuses.rejected",
+ },
+ ],
+ };
+ const loopNodeType = {
+ identifier: "flow:loop_over_items",
+ ports: [
+ {
+ key: "done",
+ primary: true,
+ label_key: "discourse_workflows.branch.done",
+ },
+ {
+ key: "loop",
+ primary: false,
+ label_key: "discourse_workflows.branch.loop",
+ },
+ ],
+ };
+
+ assert.strictEqual(nodeTypePortLabel(filterNodeType, "true"), "Kept");
+ assert.strictEqual(nodeTypePortLabel(filterNodeType, "false"), "Rejected");
+ assert.strictEqual(nodeTypePrimaryOutputKey(loopNodeType), "done");
+ });
+
+ test("resolves a full node definition for a saved type version", function (assert) {
+ const nodeType = {
+ identifier: "action:versioned",
+ latest: {
+ identifier: "action:versioned",
+ version: "2.0",
+ outputs: [{ key: "new", primary: true }],
+ },
+ versions: {
+ "1.0": {
+ identifier: "action:versioned",
+ version: "1.0",
+ outputs: [{ key: "old", primary: true }],
+ },
+ "2.0": {
+ identifier: "action:versioned",
+ version: "2.0",
+ outputs: [{ key: "new", primary: true }],
+ },
+ },
+ };
+
+ assert.strictEqual(resolveNodeTypeVersion(nodeType, "1.0").version, "1.0");
+ assert.strictEqual(nodeTypeVersion(nodeType), "2.0");
+ assert.deepEqual(nodeTypeOutputKeys(nodeType, { typeVersion: "1.0" }), [
+ "old",
+ ]);
+ assert.deepEqual(nodeTypeOutputKeys(nodeType), ["new"]);
+ });
+
+ test("uses merge mode configuration for input sockets", function (assert) {
+ const mergeNodeType = {
+ identifier: "flow:merge",
+ inputs: [
+ { key: "main" },
+ { key: "input_1", required: true },
+ { key: "input_2", required: true },
+ ],
+ };
+
+ assert.deepEqual(
+ nodeTypeInputs(mergeNodeType, {
+ configuration: { mode: "append" },
+ }).map((input) => input.key),
+ ["input_1", "input_2"]
+ );
+ assert.deepEqual(
+ nodeTypeInputs(mergeNodeType, {
+ configuration: { mode: "append", number_inputs: 3 },
+ }).map((input) => input.key),
+ ["input_1", "input_2", "input_3"]
+ );
+ assert.deepEqual(
+ nodeTypeInputs(mergeNodeType, {
+ configuration: { mode: "combine" },
+ }).map((input) => input.key),
+ ["input_1", "input_2"]
+ );
+ assert.strictEqual(
+ nodeTypeInputLabel(mergeNodeType, "input_1", {
+ configuration: { mode: "combine" },
+ }),
+ "Input 1"
+ );
+ });
+
+ test("resolves run scope labels from capabilities", function (assert) {
+ const nodeType = {
+ identifier: "action:code",
+ description: {
+ capabilities: {
+ run_scope: {
+ parameter: "mode",
+ values: {
+ runOnceForEachItem: "per_item",
+ runOnceForAllItems: "all_items",
+ },
+ },
+ },
+ },
+ properties: {
+ mode: {
+ default: "runOnceForAllItems",
+ },
+ },
+ };
+
+ assert.strictEqual(
+ nodeTypeRunScopeLabelKey(nodeType, { configuration: {} }),
+ "discourse_workflows.run_scope.all_items"
+ );
+ assert.strictEqual(
+ nodeTypeRunScopeLabelKey(nodeType, {
+ configuration: { mode: "runOnceForEachItem" },
+ }),
+ "discourse_workflows.run_scope.per_item"
+ );
+ assert.strictEqual(
+ nodeTypeRunScopeLabelKey(nodeType, {
+ configuration: { mode: "append" },
+ }),
+ null
+ );
+ assert.strictEqual(
+ nodeTypeRunScopeLabelKey({
+ identifier: "condition:if",
+ capabilities: { run_scope: "per_item" },
+ }),
+ "discourse_workflows.run_scope.per_item"
+ );
+ assert.strictEqual(
+ nodeTypeRunScopeLabelKey({
+ identifier: "action:sort",
+ capabilities: { run_scope: "all_items" },
+ }),
+ "discourse_workflows.run_scope.all_items"
+ );
+ });
+});
+
+module("Unit | Service | workflows-node-types", function (hooks) {
+ setupTest(hooks);
+
+ test("buildNodeParameterOptionsPayload includes current node, parameters, credentials, and execution context", function (assert) {
+ const service = this.owner.lookup("service:workflows-node-types");
+ const node = {
+ clientId: "node-1",
+ name: "Group",
+ type: "action:group",
+ typeVersion: "1.0",
+ };
+ const upstreamNode = {
+ clientId: "node-0",
+ name: "Upstream",
+ type: "trigger:topic",
+ };
+ const upstreamOutput = [{ json: { username: "sam" } }];
+ const runData = {
+ Upstream: [
+ {
+ status: "success",
+ outputs: [
+ {
+ index: 0,
+ items: upstreamOutput,
+ item_count: upstreamOutput.length,
+ },
+ ],
+ },
+ ],
+ };
+
+ const session = new WorkflowEditorSession({
+ workflowId: 7,
+ lastExecutionRunData: runData,
+ });
+ session.setEditingContext(
+ node,
+ [upstreamNode, node],
+ [{ sourceClientId: "node-0", targetClientId: "node-1" }]
+ );
+
+ const payload = service.buildNodeParameterOptionsPayload({
+ identifier: "action:group",
+ typeVersion: "1.0",
+ methodName: "groups",
+ ...session.nodeParameterOptionsContext({
+ path: "group_id",
+ currentNodeParameters: { operation: "get" },
+ credentials: { auth: { id: "12", credential_type: "basic_auth" } },
+ filter: "staff",
+ }),
+ });
+
+ assert.deepEqual(payload.currentNodeParameters, { operation: "get" });
+ assert.deepEqual(payload.credentials, {
+ auth: { id: "12", credential_type: "basic_auth" },
+ });
+ assert.deepEqual(payload.nodeTypeAndVersion, {
+ name: "action:group",
+ version: "1.0",
+ });
+ assert.deepEqual(payload.node, {
+ id: "node-1",
+ name: "Group",
+ type: "action:group",
+ typeVersion: "1.0",
+ });
+ assert.strictEqual(payload.path, "group_id");
+ assert.strictEqual(payload.methodName, "groups");
+ assert.strictEqual(payload.workflowId, 7);
+ assert.strictEqual(payload.filter, "staff");
+ assert.deepEqual(payload.inputContext, {
+ available: true,
+ item: upstreamOutput[0],
+ items: upstreamOutput,
+ source_node_outputs: { "node-0": upstreamOutput },
+ });
+ assert.deepEqual(payload.executionContext, {
+ last_node_outputs: runData,
+ });
+ });
+
+ test("input context uses source output keys when output indexes are not stored", function (assert) {
+ const upstreamNode = {
+ clientId: "node-0",
+ name: "Branch",
+ type: "condition:if",
+ };
+ const node = {
+ clientId: "node-1",
+ name: "Log",
+ type: "action:log",
+ typeVersion: "1.0",
+ };
+ const rejectedOutput = [{ json: { matched: false } }];
+
+ const session = new WorkflowEditorSession({
+ workflowId: 7,
+ lastExecutionRunData: {
+ Branch: [
+ {
+ status: "success",
+ outputs: [
+ {
+ index: 0,
+ items: [{ json: { matched: true } }],
+ item_count: 1,
+ },
+ {
+ index: 1,
+ items: rejectedOutput,
+ item_count: 1,
+ },
+ ],
+ },
+ ],
+ },
+ });
+ session.setEditingContext(
+ node,
+ [upstreamNode, node],
+ [
+ {
+ sourceClientId: "node-0",
+ sourceOutput: "false",
+ targetClientId: "node-1",
+ },
+ ]
+ );
+
+ assert.deepEqual(session.inputContextForNode(node), {
+ available: true,
+ item: rejectedOutput[0],
+ items: rejectedOutput,
+ source_node_outputs: { "node-0": rejectedOutput },
+ });
+ });
+
+ test("input context prefers current node inputs over upstream outputs", function (assert) {
+ const upstreamNode = {
+ clientId: "node-0",
+ name: "Logger",
+ type: "action:log",
+ };
+ const node = {
+ clientId: "node-1",
+ name: "After log",
+ type: "action:group",
+ typeVersion: "1.0",
+ };
+ const upstreamOutput = [];
+ const currentInput = [{ json: { username: "sam" } }];
+
+ const session = new WorkflowEditorSession({
+ workflowId: 7,
+ lastExecutionRunData: {
+ Logger: [
+ {
+ status: "success",
+ outputs: [{ index: 0, items: upstreamOutput, item_count: 0 }],
+ },
+ ],
+ "After log": [
+ {
+ status: "success",
+ inputs: [
+ {
+ index: 0,
+ items: currentInput,
+ item_count: currentInput.length,
+ source: { node_name: "Logger", output_index: 0 },
+ },
+ ],
+ },
+ ],
+ },
+ });
+ session.setEditingContext(
+ node,
+ [upstreamNode, node],
+ [{ sourceClientId: "node-0", targetClientId: "node-1" }]
+ );
+
+ assert.deepEqual(session.inputContextForNode(node), {
+ available: true,
+ item: currentInput[0],
+ items: currentInput,
+ source_node_outputs: { "node-0": currentInput },
+ });
+ });
+
+ test("outputItemsForNode returns the latest empty output", function (assert) {
+ const node = { clientId: "node-1", name: "Node 1" };
+
+ const session = new WorkflowEditorSession({
+ lastExecutionRunData: {
+ "Node 1": [
+ {
+ status: "success",
+ outputs: [
+ { index: 0, items: [{ json: { stale: true } }], item_count: 1 },
+ ],
+ },
+ {
+ status: "success",
+ outputs: [{ index: 0, items: [], item_count: 0 }],
+ },
+ ],
+ },
+ });
+
+ assert.deepEqual(session.outputItemsForNode(node), []);
+ });
+
+ test("dynamic options use full node parameters even inside nested configurators", function (assert) {
+ const component = Object.create(ComboBoxField.prototype);
+
+ Object.defineProperty(component, "args", {
+ value: {
+ fieldName: "nested_group_id",
+ configuration: { local: true },
+ nodeParameters: { operation: "get", authentication: "basic_auth" },
+ credentials: { auth: { id: "12", credential_type: "basic_auth" } },
+ node: { clientId: "node-1", type: "action:group" },
+ },
+ });
+
+ const context = component.remoteOptionsContext("staff");
+
+ assert.deepEqual(context.currentNodeParameters, {
+ operation: "get",
+ authentication: "basic_auth",
+ });
+ assert.deepEqual(context.credentials, {
+ auth: { id: "12", credential_type: "basic_auth" },
+ });
+ assert.deepEqual(context.node, {
+ clientId: "node-1",
+ type: "action:group",
+ });
+ assert.strictEqual(context.path, "nested_group_id");
+ assert.strictEqual(context.filter, "staff");
+ });
+
+ test("clearEditingContext preserves workflow execution run data", function (assert) {
+ const runData = {
+ "node-1": [
+ {
+ status: "success",
+ outputs: [
+ {
+ index: 0,
+ items: [{ json: { value: 1 } }],
+ item_count: 1,
+ },
+ ],
+ },
+ ],
+ };
+
+ const session = new WorkflowEditorSession({
+ workflowId: 7,
+ lastExecutionRunData: runData,
+ });
+ session.setEditingContext(
+ { clientId: "node-1", type: "action:code" },
+ [{ clientId: "node-1", type: "action:code" }],
+ []
+ );
+
+ session.clearEditingContext();
+
+ assert.strictEqual(session.editingNode, null);
+ assert.strictEqual(session.graphNodes, null);
+ assert.strictEqual(session.graphConnections, null);
+ assert.strictEqual(session.workflowId, 7);
+ assert.strictEqual(session.lastExecutionRunData, runData);
+ });
+
+ test("loadNodeParameterOptions posts structured context and caches by context", async function (assert) {
+ const requests = [];
+
+ pretender.post(
+ "/admin/plugins/discourse-workflows/dynamic-node-parameters/options.json",
+ (request) => {
+ const body = JSON.parse(request.requestBody);
+ requests.push(body);
+
+ return response([
+ { id: requests.length, name: body.currentNodeParameters.operation },
+ ]);
+ }
+ );
+
+ const service = this.owner.lookup("service:workflows-node-types");
+ const context = {
+ path: "group_id",
+ currentNodeParameters: { operation: "add" },
+ filter: "alp",
+ node: { clientId: "node-1", name: "Group" },
+ };
+
+ const first = await service.loadNodeParameterOptions(
+ "action:group",
+ "groups",
+ "1.0",
+ context
+ );
+ const second = await service.loadNodeParameterOptions(
+ "action:group",
+ "groups",
+ "1.0",
+ context
+ );
+ const third = await service.loadNodeParameterOptions(
+ "action:group",
+ "groups",
+ "1.0",
+ { ...context, currentNodeParameters: { operation: "get" } }
+ );
+
+ assert.strictEqual(requests.length, 2);
+ assert.deepEqual(second, first);
+ assert.deepEqual(requests[0].currentNodeParameters, { operation: "add" });
+ assert.strictEqual(requests[0].path, "group_id");
+ assert.strictEqual(requests[0].methodName, "groups");
+ assert.strictEqual(requests[0].filter, "alp");
+ assert.deepEqual(requests[0].nodeTypeAndVersion, {
+ name: "action:group",
+ version: "1.0",
+ });
+ assert.deepEqual(requests[0].node, {
+ id: "node-1",
+ name: "Group",
+ type: "action:group",
+ typeVersion: "1.0",
+ });
+ assert.strictEqual(third[0].name, "get");
+ });
+});
diff --git a/plugins/discourse-workflows/test/javascripts/unit/lib/workflows-node-utils-test.js b/plugins/discourse-workflows/test/javascripts/unit/lib/workflows-node-utils-test.js
new file mode 100644
index 00000000000..93ee4435dd4
--- /dev/null
+++ b/plugins/discourse-workflows/test/javascripts/unit/lib/workflows-node-utils-test.js
@@ -0,0 +1,64 @@
+import { module, test } from "qunit";
+import {
+ NODE_WIDTH,
+ nodeDescription,
+ nodeWidth,
+} from "discourse/plugins/discourse-workflows/admin/lib/workflows/node-utils";
+
+module("Unit | Utility | workflows node utils", function () {
+ test("keeps the base width for single-output nodes", function (assert) {
+ assert.strictEqual(nodeWidth({ type: "trigger:manual" }), NODE_WIDTH);
+ });
+
+ test("reserves extra width for branching output labels", function (assert) {
+ const nodeType = {
+ identifier: "action:data_table",
+ ports: [
+ {
+ key: "results",
+ primary: true,
+ label: "Results",
+ },
+ {
+ key: "no_results",
+ label: "No results",
+ },
+ ],
+ };
+
+ assert.true(
+ nodeWidth({ type: "action:data_table" }, { nodeType }) > NODE_WIDTH
+ );
+ });
+
+ test("can infer branch width from output keys alone", function (assert) {
+ assert.true(
+ nodeWidth(
+ { type: "action:data_table" },
+ { outputKeys: ["results", "no_results"] }
+ ) > NODE_WIDTH
+ );
+ });
+
+ test("nodeDescription only displays notes when notesInFlow is enabled", function (assert) {
+ assert.strictEqual(
+ nodeDescription({
+ configuration: {
+ notes: "Imported note",
+ notesInFlow: false,
+ },
+ }),
+ ""
+ );
+
+ assert.strictEqual(
+ nodeDescription({
+ configuration: {
+ notes: "Visible note",
+ notesInFlow: true,
+ },
+ }),
+ "Visible note"
+ );
+ });
+});
diff --git a/plugins/discourse-workflows/test/javascripts/unit/lib/workflows-property-engine-test.js b/plugins/discourse-workflows/test/javascripts/unit/lib/workflows-property-engine-test.js
new file mode 100644
index 00000000000..6f9f4ebeb0f
--- /dev/null
+++ b/plugins/discourse-workflows/test/javascripts/unit/lib/workflows-property-engine-test.js
@@ -0,0 +1,354 @@
+import { module, test } from "qunit";
+import { normalizeCodeEditorValue } from "discourse/plugins/discourse-workflows/admin/components/workflows/configurators/code-control";
+import {
+ collectionAddLabel,
+ emptyCollectionItem,
+ fieldControl,
+ fieldFormat,
+ fieldSupportsExpression,
+ fieldValue,
+ fieldVisible,
+ getPropertySchema,
+ i18nPrefix,
+ i18nScope,
+ localeKeyPart,
+ normalizeOptions,
+ propertyDescription,
+ propertyDynamicValueHint,
+ propertyLabel,
+ propertyOptionLabel,
+ propertyPlaceholder,
+ propertySelectNoneKey,
+} from "discourse/plugins/discourse-workflows/admin/lib/workflows/property-engine";
+
+module("Unit | Utility | workflows property engine", function () {
+ const ifNodeType = {
+ identifier: "condition:if",
+ ui: { i18n_scope: "if" },
+ };
+ const dataTableNodeType = {
+ identifier: "action:data_table",
+ ui: { i18n_scope: "data_table_node" },
+ };
+
+ test("derives the translation scope from the node identifier", function (assert) {
+ assert.strictEqual(i18nScope("action:topic"), "topic");
+ assert.strictEqual(i18nScope(dataTableNodeType), "data_table_node");
+ });
+
+ test("resolves translated labels, descriptions, and placeholders", function (assert) {
+ assert.strictEqual(propertyLabel("action:topic", "title"), "Title");
+ assert.strictEqual(propertyLabel(ifNodeType, "combinator"), "Match mode");
+ assert.strictEqual(
+ propertyLabel("trigger:schedule", "minutesInterval"),
+ "Minutes between triggers"
+ );
+ assert.strictEqual(propertyLabel("header_auth", "name"), "Header name");
+ assert.strictEqual(propertyLabel("header_auth", "value"), "Header value");
+ assert.strictEqual(
+ propertyDescription("action:topic", "raw"),
+ "Raw content for the first post"
+ );
+ assert.strictEqual(
+ propertyDescription("action:code", "code"),
+ "Access the previous step's output via $json. Return an object to pass data to the next step."
+ );
+ assert.strictEqual(
+ propertyDescription("trigger:schedule", "minutesInterval"),
+ "Must be in range 1-59"
+ );
+ assert.strictEqual(
+ propertyPlaceholder("trigger:webhook", "path"),
+ "my-webhook"
+ );
+ });
+
+ test("resolves dynamic value hints for expression fields", function (assert) {
+ assert.strictEqual(
+ propertyDynamicValueHint("action:topic", "category_id", {
+ type: "integer",
+ ui: { control: "category" },
+ }),
+ "Must resolve to a category ID."
+ );
+ assert.strictEqual(
+ propertyDynamicValueHint("action:badge", "badge_id", {
+ type: "integer",
+ ui: { control: "combo_box", dynamic_value: "badge_id" },
+ }),
+ "Must resolve to a badge ID."
+ );
+ assert.strictEqual(
+ propertyDynamicValueHint("action:group", "actor_username", {
+ type: "string",
+ ui: { control: "user" },
+ }),
+ "Must resolve to a username."
+ );
+ });
+
+ test("supports plugin translation roots", function (assert) {
+ const nodeDefinition = {
+ identifier: "action:ai_agent",
+ ui: {
+ i18n_prefix: "discourse_ai.discourse_workflows",
+ },
+ };
+
+ assert.strictEqual(
+ i18nPrefix(nodeDefinition),
+ "discourse_ai.discourse_workflows"
+ );
+ assert.strictEqual(propertyLabel(nodeDefinition, "agent_id"), "Agent");
+ assert.strictEqual(
+ propertySelectNoneKey(nodeDefinition, "agent_id"),
+ "discourse_ai.discourse_workflows.ai_agent.select_agent"
+ );
+ });
+
+ test("gets property schema from the saved node type version", function (assert) {
+ const nodeTypes = [
+ {
+ identifier: "action:versioned",
+ latest: {
+ properties: {
+ new_field: { type: "string" },
+ },
+ },
+ versions: {
+ "1.0": {
+ properties: {
+ old_field: { type: "string" },
+ },
+ },
+ "2.0": {
+ properties: {
+ new_field: { type: "string" },
+ },
+ },
+ },
+ },
+ ];
+
+ assert.deepEqual(getPropertySchema(nodeTypes, "action:versioned", "1.0"), {
+ old_field: { type: "string" },
+ });
+ assert.deepEqual(getPropertySchema(nodeTypes, "action:versioned"), {
+ new_field: { type: "string" },
+ });
+ });
+
+ test("normalizes options and option labels", function (assert) {
+ const options = normalizeOptions(["GET", { value: "deny" }]);
+
+ assert.deepEqual(options, [{ value: "GET" }, { value: "deny" }]);
+ assert.strictEqual(
+ propertyOptionLabel("flow:wait", "resume", {
+ value: "webhook",
+ }),
+ "On webhook call"
+ );
+ assert.strictEqual(
+ propertyOptionLabel("action:http_request", "method", { value: "GET" }),
+ "GET"
+ );
+ assert.strictEqual(
+ propertyOptionLabel(dataTableNodeType, "operation", {
+ value: "insert",
+ }),
+ "Insert"
+ );
+ assert.strictEqual(
+ propertyOptionLabel("action:code", "mode", {
+ value: "runOnceForEachItem",
+ }),
+ "Run once for each item"
+ );
+ assert.strictEqual(
+ propertyOptionLabel("trigger:schedule", "field", {
+ value: "cronExpression",
+ }),
+ "Custom (Cron)"
+ );
+ });
+
+ test("normalizes camelCase values for locale key lookup", function (assert) {
+ assert.strictEqual(localeKeyPart("fooBarBaz"), "foo_bar_baz");
+ assert.strictEqual(localeKeyPart("cronExpression"), "cron_expression");
+ assert.strictEqual(
+ localeKeyPart("runOnceForAllItems"),
+ "run_once_for_all_items"
+ );
+ });
+
+ test("uses defaults and sensible fallbacks for field values", function (assert) {
+ assert.strictEqual(fieldValue({ type: "string", default: "GET" }), "GET");
+ assert.false(fieldValue({ type: "boolean" }));
+ assert.deepEqual(fieldValue({ type: "collection" }), {});
+ assert.deepEqual(fieldValue({ type: "fixed_collection" }), {});
+ assert.deepEqual(fieldValue({ type: "assignment_collection" }), {
+ assignments: [],
+ });
+ assert.strictEqual(fieldValue({ type: "string" }, "custom"), "custom");
+ });
+
+ test("builds empty collection items from item schema defaults", function (assert) {
+ assert.deepEqual(
+ emptyCollectionItem({
+ key: { type: "string" },
+ enabled: { type: "boolean", default: true },
+ }),
+ { key: "", enabled: true }
+ );
+ });
+
+ test("respects UI control and expression hints", function (assert) {
+ assert.strictEqual(
+ fieldControl({ type: "string", ui: { control: "textarea" } }),
+ "textarea"
+ );
+ assert.strictEqual(fieldControl({ type: "icon" }), "icon");
+ assert.strictEqual(
+ fieldControl({ type: "multi_options" }),
+ "multi_combo_box"
+ );
+ assert.strictEqual(fieldControl({ type: "collection" }), "collection");
+ assert.strictEqual(
+ fieldControl({ type: "fixed_collection" }),
+ "fixed_collection"
+ );
+ assert.strictEqual(
+ fieldControl({ type: "assignment_collection" }),
+ "assignment_collection"
+ );
+ assert.strictEqual(fieldControl({ type: "fixedCollection" }), "input");
+ assert.strictEqual(fieldFormat({ type: "string" }), "full");
+ assert.strictEqual(
+ fieldFormat({ type: "string", ui: { format: "small" } }),
+ "small"
+ );
+ assert.true(fieldSupportsExpression({ type: "integer" }));
+ assert.true(fieldSupportsExpression({ type: "icon" }));
+ assert.false(fieldSupportsExpression({ type: "multi_options" }));
+ assert.false(
+ fieldSupportsExpression({ type: "string", no_data_expression: true })
+ );
+ assert.true(
+ fieldSupportsExpression({ type: "options", ui: { expression: true } })
+ );
+ });
+
+ test("multi_options defaults to an empty array", function (assert) {
+ assert.deepEqual(fieldValue({ type: "multi_options" }), []);
+ assert.deepEqual(
+ fieldValue({ type: "multi_options", default: [1, 2] }),
+ [1, 2]
+ );
+ });
+
+ test("evaluates simple visibility rules against the current configuration", function (assert) {
+ const schema = {
+ type: "string",
+ display_options: {
+ show: {
+ method: ["POST", "PUT"],
+ },
+ },
+ };
+
+ assert.true(fieldVisible(schema, { method: "POST" }));
+ assert.false(fieldVisible(schema, { method: "GET" }));
+ assert.false(fieldVisible({ type: "string", ui: { hidden: true } }, {}));
+ });
+
+ test("supports the exists condition for empty checks", function (assert) {
+ const schema = {
+ type: "notice",
+ display_options: { hide: { columns: [{ _cnd: { exists: true } }] } },
+ };
+
+ assert.true(fieldVisible(schema, {}));
+ assert.true(fieldVisible(schema, { columns: null }));
+ assert.true(fieldVisible(schema, { columns: [] }));
+ assert.true(fieldVisible(schema, { columns: "" }));
+ assert.false(fieldVisible(schema, { columns: [{ header: "A" }] }));
+ assert.false(fieldVisible(schema, { columns: "value" }));
+
+ const presentSchema = {
+ display_options: { show: { columns: [{ _cnd: { exists: true } }] } },
+ };
+ assert.false(fieldVisible(presentSchema, {}));
+ assert.true(fieldVisible(presentSchema, { columns: [{ header: "A" }] }));
+ });
+
+ test("supports the not condition", function (assert) {
+ const schema = {
+ display_options: { show: { operation: [{ _cnd: { not: "delete" } }] } },
+ };
+ assert.true(fieldVisible(schema, { operation: "insert" }));
+ assert.true(fieldVisible(schema, {}));
+ assert.false(fieldVisible(schema, { operation: "delete" }));
+ });
+
+ test("display_options.hide hides a field when its rules match", function (assert) {
+ const schema = { display_options: { hide: { method: ["GET", "HEAD"] } } };
+ assert.false(fieldVisible(schema, { method: "GET" }));
+ assert.true(fieldVisible(schema, { method: "POST" }));
+
+ const combined = {
+ display_options: {
+ show: { method: ["POST", "PUT", "PATCH"] },
+ hide: { content_type: "raw" },
+ },
+ };
+ assert.true(
+ fieldVisible(combined, { method: "POST", content_type: "json" })
+ );
+ assert.false(
+ fieldVisible(combined, { method: "GET", content_type: "json" })
+ );
+ assert.false(
+ fieldVisible(combined, { method: "POST", content_type: "raw" })
+ );
+ });
+
+ test("reuses field-specific add labels before falling back to a generic one", function (assert) {
+ assert.strictEqual(
+ collectionAddLabel("action:http_request", "headers"),
+ "Add header"
+ );
+ assert.strictEqual(
+ collectionAddLabel("action:http_request", "query_params"),
+ "Add parameter"
+ );
+ assert.strictEqual(
+ collectionAddLabel("action:topic", "attachments"),
+ "Add item"
+ );
+ });
+
+ test("lets ui.singular_name override the derived singular", function (assert) {
+ assert.strictEqual(
+ collectionAddLabel("action:http_request", "attachments", {
+ ui: { singular_name: "header" },
+ }),
+ "Add header"
+ );
+ assert.strictEqual(
+ collectionAddLabel("action:http_request", "attachments"),
+ "Add item"
+ );
+ });
+
+ test("normalizes object values for JSON code controls", function (assert) {
+ assert.strictEqual(
+ normalizeCodeEditorValue({ "x-broccoli": { enabled: true } }, "json"),
+ '{\n "x-broccoli": {\n "enabled": true\n }\n}'
+ );
+ assert.strictEqual(
+ normalizeCodeEditorValue(["alpha", "beta"], "json"),
+ '[\n "alpha",\n "beta"\n]'
+ );
+ assert.strictEqual(normalizeCodeEditorValue("plain", "json"), "plain");
+ });
+});
diff --git a/plugins/discourse-workflows/test/javascripts/unit/lib/workflows-template-workflow-test.js b/plugins/discourse-workflows/test/javascripts/unit/lib/workflows-template-workflow-test.js
new file mode 100644
index 00000000000..dca070a2421
--- /dev/null
+++ b/plugins/discourse-workflows/test/javascripts/unit/lib/workflows-template-workflow-test.js
@@ -0,0 +1,50 @@
+import { module, test } from "qunit";
+import { workflowFromTemplate } from "discourse/plugins/discourse-workflows/admin/lib/workflows/template-workflow";
+
+module("Unit | lib | discourse-workflows | template workflow", function () {
+ test("builds workflow attributes from template JSON", function (assert) {
+ const workflow = workflowFromTemplate({
+ name: "Template workflow",
+ nodes: [
+ {
+ id: "n1",
+ type: "trigger:manual",
+ typeVersion: 1,
+ name: "Manual trigger",
+ parameters: { value: "x" },
+ credentials: { api: { id: 1 } },
+ webhookId: "webhook-1",
+ position: { x: 10, y: 20 },
+ notes: "Template note",
+ },
+ ],
+ connections: {
+ "Manual trigger": {
+ main: [],
+ },
+ },
+ });
+
+ assert.deepEqual(workflow, {
+ name: "Template workflow",
+ nodes: [
+ {
+ id: "n1",
+ type: "trigger:manual",
+ typeVersion: 1,
+ name: "Manual trigger",
+ parameters: { value: "x" },
+ credentials: { api: { id: 1 } },
+ webhookId: "webhook-1",
+ position: { x: 10, y: 20 },
+ notes: "Template note",
+ },
+ ],
+ connections: {
+ "Manual trigger": {
+ main: [],
+ },
+ },
+ });
+ });
+});
diff --git a/plugins/discourse-workflows/test/javascripts/unit/models/discourse-workflows-workflow-test.js b/plugins/discourse-workflows/test/javascripts/unit/models/discourse-workflows-workflow-test.js
new file mode 100644
index 00000000000..d235cc5fe01
--- /dev/null
+++ b/plugins/discourse-workflows/test/javascripts/unit/models/discourse-workflows-workflow-test.js
@@ -0,0 +1,64 @@
+import { module, test } from "qunit";
+import DiscourseWorkflowsWorkflow from "discourse/plugins/discourse-workflows/admin/models/discourse-workflows-workflow";
+
+module("Unit | model | discourse-workflows-workflow", function () {
+ test("munge maps API snake_case fields to model camelCase fields", function (assert) {
+ const payload = DiscourseWorkflowsWorkflow.munge({
+ id: "1",
+ error_workflow_id: 2,
+ error_workflow_name: "Error handler",
+ version_id: "draft-version",
+ active_version_id: "published-version",
+ version_counter: 3,
+ has_unpublished_changes: true,
+ last_execution_status: "success",
+ last_execution_at: "2026-05-27T10:00:00.000Z",
+ last_execution_run_data: { "Node A": [{ json: { ok: true } }] },
+ created_at: "2026-05-26T10:00:00.000Z",
+ updated_at: "2026-05-27T10:00:00.000Z",
+ created_by: { id: 1, username: "admin" },
+ updated_by: { id: 2, username: "moderator" },
+ static_data: { global: { cursor: "abc" } },
+ pin_data: { "Node A": [{ json: { ok: true } }] },
+ });
+
+ assert.strictEqual(payload.errorWorkflowId, 2);
+ assert.strictEqual(payload.errorWorkflowName, "Error handler");
+ assert.strictEqual(payload.versionId, "draft-version");
+ assert.strictEqual(payload.activeVersionId, "published-version");
+ assert.strictEqual(payload.versionCounter, 3);
+ assert.true(payload.hasUnpublishedChanges);
+ assert.strictEqual(payload.lastExecutionStatus, "success");
+ assert.strictEqual(payload.lastExecutionAt, "2026-05-27T10:00:00.000Z");
+ assert.deepEqual(payload.lastExecutionRunData, {
+ "Node A": [{ json: { ok: true } }],
+ });
+ assert.strictEqual(payload.createdAt, "2026-05-26T10:00:00.000Z");
+ assert.strictEqual(payload.updatedAt, "2026-05-27T10:00:00.000Z");
+ assert.deepEqual(payload.createdBy, { id: 1, username: "admin" });
+ assert.deepEqual(payload.updatedBy, { id: 2, username: "moderator" });
+ assert.deepEqual(payload.staticData, { global: { cursor: "abc" } });
+ assert.deepEqual(payload.pinData, {
+ "Node A": [{ json: { ok: true } }],
+ });
+ });
+
+ test("updateProperties maps model fields to API snake_case fields", function (assert) {
+ const workflow = DiscourseWorkflowsWorkflow.create({
+ name: "Workflow",
+ errorWorkflowId: 2,
+ staticData: { global: { cursor: "abc" } },
+ nodes: [],
+ stickyNotes: [],
+ connections: [],
+ });
+
+ assert.deepEqual(workflow.updateProperties(), {
+ name: "Workflow",
+ error_workflow_id: 2,
+ static_data: { global: { cursor: "abc" } },
+ nodes: [],
+ connections: {},
+ });
+ });
+});
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index d093de57dee..3aaa6d39a23 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -206,6 +206,24 @@ importers:
frontend/discourse:
dependencies:
+ '@codemirror/autocomplete':
+ specifier: ^6.20.1
+ version: 6.20.2
+ '@codemirror/commands':
+ specifier: ^6.10.3
+ version: 6.10.3
+ '@codemirror/lang-javascript':
+ specifier: ^6.2.5
+ version: 6.2.5
+ '@codemirror/language':
+ specifier: ^6.12.3
+ version: 6.12.3
+ '@codemirror/state':
+ specifier: ^6.6.0
+ version: 6.6.0
+ '@codemirror/view':
+ specifier: ^6.40.0
+ version: 6.43.0
'@discourse/gif':
specifier: ^1.0.0
version: 1.0.0
@@ -266,6 +284,18 @@ importers:
'@json-editor/json-editor':
specifier: 2.15.2
version: 2.15.2
+ '@lezer/common':
+ specifier: ^1.5.2
+ version: 1.5.2
+ '@lezer/highlight':
+ specifier: ^1.2.3
+ version: 1.2.3
+ '@lezer/javascript':
+ specifier: ^1.5.4
+ version: 1.5.4
+ '@lezer/lr':
+ specifier: ^1.4.8
+ version: 1.4.10
ace-builds:
specifier: ^1.43.6
version: 1.43.6
@@ -278,12 +308,18 @@ importers:
chartjs-plugin-datalabels:
specifier: 2.2.0
version: 2.2.0([email protected])
+ codemirror:
+ specifier: ^6.0.2
+ version: 6.0.2
decorator-transforms:
specifier: ^2.3.2
version: 2.3.2(@babel/[email protected])
diff:
specifier: ^9.0.0
version: 9.0.0
+ elkjs:
+ specifier: ^0.8.2
+ version: 0.8.2
ember-curry-component:
specifier: ^0.4.0
version: 0.4.0(@babel/[email protected])
@@ -374,9 +410,30 @@ importers:
prosemirror-view:
specifier: ^1.41.8
version: 1.41.8
+ rete:
+ specifier: ^2.0.6
+ version: 2.0.6
+ rete-area-plugin:
+ specifier: ^2.1.5
+ version: 2.1.5([email protected])
+ rete-auto-arrange-plugin:
+ specifier: ^2.0.2
+ rete-connection-plugin:
+ specifier: ^2.0.5
+ rete-history-plugin:
+ specifier: ^2.1.1
+ rete-render-utils:
+ specifier: ^2.0.3
rrule:
specifier: ^2.8.1
version: 2.8.1
+ web-worker:
+ specifier: ^1.5.0
+ version: 1.5.0
devDependencies:
'@babel/core':
specifier: ^7.28.5
@@ -1576,6 +1633,30 @@ packages:
engines: {node: '>=0.1.95'}
hasBin: true
+ '@codemirror/[email protected]':
+ resolution: {integrity: sha512-G5FPkgIiLjOgZMjqVjvuKQ1rGPtHogLldJr33eFJdVLtmwY+giGrlv/ewljLz6b9BSQLkjxuwBc6g6omDM+YxQ==}
+
+ '@codemirror/[email protected]':
+ resolution: {integrity: sha512-JFRiqhKu+bvSkDLI+rUhJwSxQxYb759W5GBezE8Uc8mHLqC9aV/9aTC7yJSqCtB3F00pylrLCwnyS91Ap5ej4Q==}
+
+ '@codemirror/[email protected]':
+ resolution: {integrity: sha512-zD4e5mS+50htS7F+TYjBPsiIFGanfVqg4HyUz6WNFikgOPf2BgKlx+TQedI1w6n/IqRBVBbBWmGFdLB/7uxO4A==}
+
+ '@codemirror/[email protected]':
+ resolution: {integrity: sha512-QwCZW6Tt1siP37Jet9Tb02Zs81TQt6qQrZR2H+eGMcFsL1zMrk2/b9CLC7/9ieP1fjIUMgviLWMmgiHoJrj+ZA==}
+
+ '@codemirror/[email protected]':
+ resolution: {integrity: sha512-6Kp7r6XfCi/D/5sdXieMfg9pJU1bUEx96WITuLU6ESaKizCz0QHFMjY/TaFSbigDdEAIgi93itLBIUETP4oK+A==}
+
+ '@codemirror/[email protected]':
+ resolution: {integrity: sha512-ZvGm99wc/s2cITtMT15LFdn8aH/aS+V+DqyGq/N5ZlV5vWtH+nILvC2nw0zX7ByNoHHDZ2IxxdW38O0tc5nVHg==}
+
+ '@codemirror/[email protected]':
+ resolution: {integrity: sha512-4nbvra5R5EtiCzr9BTHiTLc+MLXK2QGiAVYMyi8PkQd3SR+6ixar/Q/01Fa21TBIDOZXgeWV4WppsQolSreAPQ==}
+
+ '@codemirror/[email protected]':
+ resolution: {integrity: sha512-V7ZCLQO3Jus9hzh2jVCCPW3mO4IBMr43O37PqSUYautJSnnJF41YlgLw21x0fLJTYvJ+Vkm6Gp+qKGH9pltgXA==}
+
'@colors/[email protected]':
resolution: {integrity: sha512-ooWCrlZP11i8GImSjTHYHLkvFDP48nS4+204nGb1RiX/WXYHmJA2III9/e2DWVabCESdW7hBAEzHRqUn9OUVvQ==}
engines: {node: '>=0.1.90'}
@@ -2569,6 +2650,21 @@ packages:
'@kurkle/[email protected]':
resolution: {integrity: sha512-M5UknZPHRu3DEDWoipU6sE8PdkZ6Z/S+v4dD+Ke8IaNlpdSQah50lz1KtcFBa2vsdOnwbbnxJwVM4wty6udA5w==}
+ '@lezer/[email protected]':
+ resolution: {integrity: sha512-sxQE460fPZyU3sdc8lafxiPwJHBzZRy/udNFynGQky1SePYBdhkBl1kOagA9uT3pxR8K09bOrmTUqA9wb/PjSQ==}
+
+ '@lezer/[email protected]':
+ resolution: {integrity: sha512-qXdH7UqTvGfdVBINrgKhDsVTJTxactNNxLk7+UMwZhU13lMHaOBlJe9Vqp907ya56Y3+ed2tlqzys7jDkTmW0g==}
+
+ '@lezer/[email protected]':
+ resolution: {integrity: sha512-vvYx3MhWqeZtGPwDStM2dwgljd5smolYD2lR2UyFcHfxbBQebqx8yjmFmxtJ/E6nN6u1D9srOiVWm3Rb4tmcUA==}
+
+ '@lezer/[email protected]':
+ resolution: {integrity: sha512-rnCpTIBafOx4mRp43xOxDJbFipJm/c0cia/V5TiGlhmMa+wsSdoGmUN3w5Bqrks/09Q/D4tNAmWaT8p6NRi77A==}
+
+ '@marijn/[email protected]':
+ resolution: {integrity: sha512-l0h88YhZFyKdXIFNfSWpyjStDjGHwZ/U7iobcK1cQQD8sejsONdQtTVU+1wVN1PBw40PiiHB1vA5S7VTfQiP9g==}
+
'@messageformat/[email protected]':
resolution: {integrity: sha512-dkIPDCjXcfhSHgNE1/qV6TeczQZR59Yx0xXeafVKgK3QVWoxc38ljwpksUpnzCGvN151KUbCJTDZVmahtf1YZw==}
@@ -4166,6 +4262,9 @@ packages:
resolution: {integrity: sha512-FMabTRlc5t5zjdenF6mS0MBeFZm0XqHqeOkcskKFb/LYCcRQ5fVgLOHVc4Lq9CqABd9zhjwPjMBCJvMCziSVtA==}
engines: {node: ^14.17.0 || ^16.13.0 || >=18.0.0}
+ resolution: {integrity: sha512-VhydHotNW5w1UGK0Qj96BwSk/Zqbp9WbnyK2W/eVMv4QyF41INRGpjUhFJY7/uDNuudSc33a/PKr4iDqRduvHw==}
+
resolution: {integrity: sha512-YIFQQ1n2NSgwoB3sCe7RpkZzsrPxTMek6jc7wC9fXOm1wwfWAKja9gLOMEjlXOUd3LKV3o6Jci7n9BoHs5Z8Sg==}
engines: {node: '>=14.18.0'}
@@ -4491,6 +4590,9 @@ packages:
typescript:
optional: true
+ resolution: {integrity: sha512-VQ2MBenTq1fWZUH9DJNGti7kKv6EeAuYr3cLwxUWhIu1baTaXh4Ib5W2CqHVqib4/MqbYGJqiL3Zb8GJZr3l4g==}
+
resolution: {integrity: sha512-VqCUuhcd1iB+dsv8gxPttb5iZh/D0iubSP21g36KXdEuf6I5JiioesUVjpCdHV9MZRUfVFlvwtIUyPfxo5trtw==}
engines: {node: '>=4.8'}
@@ -4705,6 +4807,9 @@ packages:
resolution: {integrity: sha512-908qahOGocRMinT2nM3ajCEM99H4iPdv84eagPP3FfZy/1ZGeOy2CZYzjhms81ckOPCXPlW7LkY4XpxD8r1DrA==}
+ resolution: {integrity: sha512-L6uRgvZTH+4OF5NE/MBbzQx/WYpru1xCBE9respNj6qznEewGUIfhzmm7horWWxbNO2M0WckQypGctR8lH79xQ==}
+
resolution: {integrity: sha512-yCQlVR3NLgjGA09LMc1NYX0XiAd0tHTM4/AmIHD0wq87QpHGmWcpMxyKGEe/TBczyCwBEJifaZNtAjMDsW1YdA==}
@@ -7858,6 +7963,40 @@ packages:
resolution: {integrity: sha512-TTlYpa+OL+vMMNG24xSlQGEJ3B/RzEfUlLct7b5G/ytav+wPrplCpVMFuwzXbkecJrb6IYo1iFb0S9v37754mg==}
engines: {node: '>=0.12'}
+ resolution: {integrity: sha512-iquEvwkQlcsO4cmgM3Z37TG0AWaE536dfA+lCJAze5YJzVx4RBaViUCqdB4dUA/utSytpBCkiDC4D3ztM9akGQ==}
+ peerDependencies:
+ rete: ^2.0.0
+
+ resolution: {integrity: sha512-VLTnVb9tqHfQKkFMZzpYgYxDWcIa+nXHRC+Po0k+gUh2zJqegkx8bFSA1n6VkMv+wPYa9EnWsTMfUDD3k1QEzg==}
+ peerDependencies:
+ elkjs: ^0.8.2
+ rete: ^2.0.1
+ rete-area-plugin: ^2.0.0
+ web-worker: ^1.2.0
+
+ resolution: {integrity: sha512-KFtlOyEJRc0y9STVgo2T+t+j9u5fxiTxbyzPbMCm0uqncb3b8d2ABDIzvWoNo5zQAh2Oz/OvlUovupbzrGzpSg==}
+ peerDependencies:
+ rete: ^2.0.1
+ rete-area-plugin: ^2.0.0
+
+ resolution: {integrity: sha512-Kb2FF51qwl9axSVzusZDJ7ojksg0qPBY3CIhAusHxTLYzO5Di1Nu3cAzHUOHik6kcb3eZI+GYdfqaj/E8xggxQ==}
+ peerDependencies:
+ rete: ^2.0.1
+ rete-area-plugin: ^2.0.0
+
+ resolution: {integrity: sha512-Oz4W2PNayHocRvlzadb5BCNf+tDzJ8RhTwB3ucBPCdCLKZ974wWDiTSCRfA287L2hmHVzRfBdyAwC03K9eP+4g==}
+ peerDependencies:
+ rete: ^2.0.0
+ rete-area-plugin: ^2.0.0
+
+ resolution: {integrity: sha512-kPmlKCGFES2VWtY7Y7SCB8ZeXRMsgX5deza9cu4OwmfM/ZUimd461kC3hRyccoyVxE4POlHUx0gg2jcGfusHFg==}
+
resolution: {integrity: sha512-9LkiTwjUh6rT555DtE9rTX+BKByPfrMzEAtnlEtdEwr3Nkffwiihqe2bWADg+OQRjt9gl6ICdmB/ZFDCGAtSow==}
engines: {node: '>= 4'}
@@ -8403,6 +8542,9 @@ packages:
peerDependencies:
webpack: ^4.0.0 || ^5.0.0
+ resolution: {integrity: sha512-i/n8VsZydrugj3Iuzll8+x/00GH2vnYsk1eomD8QiRrSAeW6ItbCQDtfXCeJHd0iwiNagqjQkvpvREEPtW3IoQ==}
+
resolution: {integrity: sha512-DU2KZiB6VbPkO2tGSqQ9n96ZstUPjW7X4sGO6V2m1myIQluX0p1Ol8BrA/l6/EesqhMqXOIXs3cJNOy1UuU2BA==}
@@ -9035,6 +9177,9 @@ packages:
resolution: {integrity: sha512-d2JWLCivmZYTSIoge9MsgFCZrt571BikcWGYkjC1khllbTeDlGqZ2D8vD8E/lJa8WGWbb7Plm8/XJYV7IJHZZw==}
engines: {node: '>= 8'}
+ resolution: {integrity: sha512-RiMReJrTAiA+mBjGONMnjVDP2u3p9R1vkcGz6gDIrOMT3oGuYwX2WRMYI9ipkphSuE5XKEhydbhNEJh4NY9mlw==}
+
resolution: {integrity: sha512-2JAn3z8AR6rjK8Sm8orRC0h/bcl/DqL7tRPdGZ4I1CjdF+EaMLmYxBHyXuKL849eucPFhvBoxMsflfOb8kxaeQ==}
@@ -10059,6 +10204,62 @@ snapshots:
exec-sh: 0.3.6
minimist: 1.2.8
+ '@codemirror/[email protected]':
+ dependencies:
+ '@codemirror/language': 6.12.3
+ '@codemirror/state': 6.6.0
+ '@codemirror/view': 6.43.0
+ '@lezer/common': 1.5.2
+
+ '@codemirror/[email protected]':
+ dependencies:
+ '@codemirror/language': 6.12.3
+ '@codemirror/state': 6.6.0
+ '@codemirror/view': 6.43.0
+ '@lezer/common': 1.5.2
+
+ '@codemirror/[email protected]':
+ dependencies:
+ '@codemirror/autocomplete': 6.20.2
+ '@codemirror/language': 6.12.3
+ '@codemirror/lint': 6.9.6
+ '@codemirror/state': 6.6.0
+ '@codemirror/view': 6.43.0
+ '@lezer/common': 1.5.2
+ '@lezer/javascript': 1.5.4
+
+ '@codemirror/[email protected]':
+ dependencies:
+ '@codemirror/state': 6.6.0
+ '@codemirror/view': 6.43.0
+ '@lezer/common': 1.5.2
+ '@lezer/highlight': 1.2.3
+ '@lezer/lr': 1.4.10
+ style-mod: 4.1.3
+
+ '@codemirror/[email protected]':
+ dependencies:
+ '@codemirror/state': 6.6.0
+ '@codemirror/view': 6.43.0
+ crelt: 1.0.6
+
+ '@codemirror/[email protected]':
+ dependencies:
+ '@codemirror/state': 6.6.0
+ '@codemirror/view': 6.43.0
+ crelt: 1.0.6
+
+ '@codemirror/[email protected]':
+ dependencies:
+ '@marijn/find-cluster-break': 1.0.2
+
+ '@codemirror/[email protected]':
+ dependencies:
+ '@codemirror/state': 6.6.0
+ crelt: 1.0.6
+ style-mod: 4.1.3
+ w3c-keyname: 2.2.8
+
'@colors/[email protected]':
optional: true
@@ -11226,6 +11427,24 @@ snapshots:
'@kurkle/[email protected]': {}
+ '@lezer/[email protected]': {}
+
+ '@lezer/[email protected]':
+ dependencies:
+ '@lezer/common': 1.5.2
+
+ '@lezer/[email protected]':
+ dependencies:
+ '@lezer/common': 1.5.2
+ '@lezer/highlight': 1.2.3
+ '@lezer/lr': 1.4.10
+
+ '@lezer/[email protected]':
+ dependencies:
+ '@lezer/common': 1.5.2
+
+ '@marijn/[email protected]': {}
+
'@messageformat/[email protected]':
dependencies:
make-plural: 7.5.0
@@ -13188,6 +13407,16 @@ snapshots:
+ dependencies:
+ '@codemirror/autocomplete': 6.20.2
+ '@codemirror/commands': 6.10.3
+ '@codemirror/language': 6.12.3
+ '@codemirror/lint': 6.9.6
+ '@codemirror/search': 6.7.0
+ '@codemirror/state': 6.6.0
+ '@codemirror/view': 6.43.0
+
dependencies:
rfdc: 1.4.1
@@ -13366,6 +13595,8 @@ snapshots:
optionalDependencies:
typescript: 5.9.3
+
dependencies:
nice-try: 1.0.5
@@ -13588,6 +13819,8 @@ snapshots:
+
dependencies:
'@ember/test-waiters': 4.1.1(@babel/[email protected])(@glint/[email protected])
@@ -17568,6 +17801,41 @@ snapshots:
+ dependencies:
+ '@babel/runtime': 7.28.4
+ rete: 2.0.6
+
+ dependencies:
+ '@babel/runtime': 7.28.4
+ elkjs: 0.8.2
+ rete: 2.0.6
+ rete-area-plugin: 2.1.5([email protected])
+ web-worker: 1.5.0
+
+ dependencies:
+ '@babel/runtime': 7.28.4
+ rete: 2.0.6
+ rete-area-plugin: 2.1.5([email protected])
+
+ dependencies:
+ '@babel/runtime': 7.28.4
+ rete: 2.0.6
+ rete-area-plugin: 2.1.5([email protected])
+
+ dependencies:
+ '@babel/runtime': 7.28.4
+ rete: 2.0.6
+ rete-area-plugin: 2.1.5([email protected])
+
+ dependencies:
+ '@babel/runtime': 7.28.4
+
@@ -18244,6 +18512,8 @@ snapshots:
schema-utils: 3.3.0
webpack: 5.99.9
+
@@ -19063,6 +19333,8 @@ snapshots:
+
diff --git a/spec/models/topic_spec.rb b/spec/models/topic_spec.rb
index 09b8d8205da..509e024f9b6 100644
--- a/spec/models/topic_spec.rb
+++ b/spec/models/topic_spec.rb
@@ -1918,6 +1918,15 @@ RSpec.describe Topic do
}.not_to change(category, :topic_count)
end
+ it "does not trigger topic_category_changed when category stays the same" do
+ events =
+ DiscourseEvent.track_events(:topic_category_changed) do
+ topic.change_category_to_id(category.id)
+ end
+
+ expect(events).to be_empty
+ end
+
it "doesn't reset the category when an id that doesn't exist" do
topic.change_category_to_id(55_556)
expect(topic.category_id).to eq(category.id)
@@ -1936,6 +1945,17 @@ RSpec.describe Topic do
expect(category.reload.topic_count).to eq(0)
end
+ it "triggers a topic_category_changed event" do
+ events =
+ DiscourseEvent.track_events(:topic_category_changed) do
+ topic.change_category_to_id(new_category.id)
+ end
+
+ expect(events.length).to eq(1)
+ expect(events.first[:params][0]).to eq(topic)
+ expect(events.first[:params][1]).to eq(category)
+ end
+
describe "user that is watching the new category" do
before do
Jobs.run_immediately!
diff --git a/spec/support/discourse_workflows_data_table_helpers.rb b/spec/support/discourse_workflows_data_table_helpers.rb
new file mode 100644
index 00000000000..61d79b1b7e1
--- /dev/null
+++ b/spec/support/discourse_workflows_data_table_helpers.rb
@@ -0,0 +1,40 @@
+# frozen_string_literal: true
+
+module DataTableHelpers
+ def data_table_facade(data_table)
+ DiscourseWorkflows::DataTables::Facade.new(data_table.reload)
+ end
+
+ def insert_data_table_row(data_table, data = {})
+ dt = data_table.reload
+ facade = DiscourseWorkflows::DataTables::Facade.new(dt)
+ facade.insert(facade.build_row_input(data: data, fill_missing: true))
+ end
+
+ def list_data_table_rows(data_table, **options)
+ facade = data_table_facade(data_table)
+ query =
+ facade.build_query(
+ filter: options[:normalized_filter],
+ limit: options[:limit],
+ offset: options[:offset],
+ sort_by: options[:sort_by],
+ sort_direction: options[:sort_direction],
+ optional_filter: true,
+ )
+
+ facade.query(query)
+ end
+
+ def count_data_table_rows(data_table, normalized_filter: nil)
+ facade = data_table_facade(data_table)
+ query = facade.build_query(filter: normalized_filter, optional_filter: true)
+ facade.count(query)
+ end
+
+ def find_data_table_row(data_table, row_id)
+ data_table_facade(data_table).find_row(row_id)
+ end
+end
+
+RSpec.configure { |config| config.include(DataTableHelpers) }