Skip to content

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

FEATURE: Add sub workflow call support (#41019)

Sam73a990f98fe9
diff --git a/db/structure.sql b/db/structure.sql
index eede6c99f87..2d91d7059d3 100644
--- a/db/structure.sql
+++ b/db/structure.sql
@@ -4549,6 +4549,46 @@ CREATE SEQUENCE public.discourse_workflows_webhooks_id_seq
ALTER SEQUENCE public.discourse_workflows_webhooks_id_seq OWNED BY public.discourse_workflows_webhooks.id;
+--
+-- Name: discourse_workflows_workflow_call_runs; Type: TABLE; Schema: public; Owner: -
+--
+
+CREATE TABLE public.discourse_workflows_workflow_call_runs (
+ id bigint NOT NULL,
+ parent_execution_id bigint NOT NULL,
+ parent_node_id character varying(100) NOT NULL,
+ parent_resume_token character varying(64) NOT NULL,
+ child_execution_id bigint,
+ target_workflow_id bigint NOT NULL,
+ target_workflow_version_id character varying(36) NOT NULL,
+ user_id bigint,
+ trigger_data jsonb DEFAULT '{}'::jsonb NOT NULL,
+ status integer DEFAULT 0 NOT NULL,
+ error text,
+ created_at timestamp(6) without time zone NOT NULL,
+ updated_at timestamp(6) without time zone NOT NULL
+);
+
+
+--
+-- Name: discourse_workflows_workflow_call_runs_id_seq; Type: SEQUENCE; Schema: public; Owner: -
+--
+
+CREATE SEQUENCE public.discourse_workflows_workflow_call_runs_id_seq
+ START WITH 1
+ INCREMENT BY 1
+ NO MINVALUE
+ NO MAXVALUE
+ CACHE 1;
+
+
+--
+-- Name: discourse_workflows_workflow_call_runs_id_seq; Type: SEQUENCE OWNED BY; Schema: public; Owner: -
+--
+
+ALTER SEQUENCE public.discourse_workflows_workflow_call_runs_id_seq OWNED BY public.discourse_workflows_workflow_call_runs.id;
+
+
--
-- Name: discourse_workflows_workflow_dependencies; Type: TABLE; Schema: public; Owner: -
--
@@ -12702,6 +12742,13 @@ ALTER TABLE ONLY public.discourse_workflows_variables ALTER COLUMN id SET DEFAUL
ALTER TABLE ONLY public.discourse_workflows_webhooks ALTER COLUMN id SET DEFAULT nextval('public.discourse_workflows_webhooks_id_seq'::regclass);
+--
+-- Name: discourse_workflows_workflow_call_runs id; Type: DEFAULT; Schema: public; Owner: -
+--
+
+ALTER TABLE ONLY public.discourse_workflows_workflow_call_runs ALTER COLUMN id SET DEFAULT nextval('public.discourse_workflows_workflow_call_runs_id_seq'::regclass);
+
+
--
-- Name: discourse_workflows_workflow_dependencies id; Type: DEFAULT; Schema: public; Owner: -
--
@@ -14979,6 +15026,14 @@ ALTER TABLE ONLY public.discourse_workflows_webhooks
ADD CONSTRAINT discourse_workflows_webhooks_pkey PRIMARY KEY (id);
+--
+-- Name: discourse_workflows_workflow_call_runs discourse_workflows_workflow_call_runs_pkey; Type: CONSTRAINT; Schema: public; Owner: -
+--
+
+ALTER TABLE ONLY public.discourse_workflows_workflow_call_runs
+ ADD CONSTRAINT discourse_workflows_workflow_call_runs_pkey PRIMARY KEY (id);
+
+
--
-- Name: discourse_workflows_workflow_dependencies discourse_workflows_workflow_dependencies_pkey; Type: CONSTRAINT; Schema: public; Owner: -
--
@@ -16854,6 +16909,20 @@ CREATE INDEX idx_dwf_ai_sessions_on_user_id ON public.discourse_workflows_ai_aut
CREATE INDEX idx_dwf_ai_sessions_on_workflow_id ON public.discourse_workflows_ai_authoring_sessions USING btree (workflow_id);
+--
+-- Name: idx_dwf_call_runs_on_child_execution_id; Type: INDEX; Schema: public; Owner: -
+--
+
+CREATE UNIQUE INDEX idx_dwf_call_runs_on_child_execution_id ON public.discourse_workflows_workflow_call_runs USING btree (child_execution_id) WHERE (child_execution_id IS NOT NULL);
+
+
+--
+-- Name: idx_dwf_call_runs_on_parent_execution_id; Type: INDEX; Schema: public; Owner: -
+--
+
+CREATE INDEX idx_dwf_call_runs_on_parent_execution_id ON public.discourse_workflows_workflow_call_runs USING btree (parent_execution_id);
+
+
--
-- Name: idx_dwf_credentials_on_created_by_id; Type: INDEX; Schema: public; Owner: -
--
@@ -22065,6 +22134,7 @@ SET search_path TO "$user", public;
INSERT INTO "schema_migrations" (version) VALUES
('20260624140945'),
+('20260623090824'),
('20260617053237'),
('20260615084100'),
('20260615082047'),
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
index ae81f5fa061..83885ce01d2 100644
--- 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
@@ -10,6 +10,26 @@ import {
} from "../../../lib/workflows/property-engine";
import Field from "./field";
+const ASSIGNMENT_TYPE_LABEL_KEY_PREFIX =
+ "discourse_workflows.property_engine.assignment_types";
+
+const DEFAULT_ASSIGNMENT_TYPES = [
+ "string",
+ "number",
+ "boolean",
+ "array",
+ "object",
+];
+
+function normalizeAssignmentType(type) {
+ const option = typeof type === "object" ? { ...type } : { value: type };
+
+ return {
+ label_key: `${ASSIGNMENT_TYPE_LABEL_KEY_PREFIX}.${option.value}`,
+ ...option,
+ };
+}
+
export default class AssignmentCollection extends Component {
get assignmentsPath() {
return `${this.args.fieldName}.assignments`;
@@ -34,15 +54,9 @@ export default class AssignmentCollection extends Component {
return this.args.schema.type_options || {};
}
- get assignment_types() {
- return (
- this.type_options.assignment_types || [
- "string",
- "number",
- "boolean",
- "array",
- "object",
- ]
+ get assignmentTypes() {
+ return (this.type_options.assignment_types || DEFAULT_ASSIGNMENT_TYPES).map(
+ normalizeAssignmentType
);
}
@@ -59,7 +73,7 @@ export default class AssignmentCollection extends Component {
type: "options",
required: true,
default: "string",
- options: this.assignment_types,
+ options: this.assignmentTypes,
no_data_expression: true,
};
}
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
index 412c73aaf99..d235552bcb4 100644
--- 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
@@ -32,6 +32,14 @@ function optionName(option, nameProperty) {
return option[nameProperty] ?? option.name ?? option.label;
}
+function hasValue(value) {
+ return value !== null && value !== undefined && value !== "";
+}
+
+function usesFieldValue(model) {
+ return model?.source === "field_value";
+}
+
export default class ComboBoxField extends Component {
@service router;
@service workflowsNodeTypes;
@@ -145,7 +153,9 @@ export default class ComboBoxField extends Component {
return [];
}
- return Array.isArray(models) ? models : [models];
+ return (Array.isArray(models) ? models : [models]).map((model) =>
+ usesFieldValue(model) ? this.args.field.value : model
+ );
}
get actionIcon() {
@@ -156,6 +166,19 @@ export default class ComboBoxField extends Component {
return this.controlOptions.action_label;
}
+ get actionRequiresValue() {
+ const models = this.controlOptions.action_route_models;
+
+ return (Array.isArray(models) ? models : [models]).some(usesFieldValue);
+ }
+
+ get showActionButton() {
+ return (
+ this.actionRoute &&
+ (!this.actionRequiresValue || hasValue(this.args.field.value))
+ );
+ }
+
get options() {
if (this.metadataOptions) {
return this.formatOptions(this.metadataOptions);
@@ -248,6 +271,10 @@ export default class ComboBoxField extends Component {
@action
performAction() {
+ if (!this.showActionButton) {
+ return;
+ }
+
this.router.transitionTo(this.actionRoute, ...this.actionRouteModels);
}
@@ -260,7 +287,7 @@ export default class ComboBoxField extends Component {
@dynamicValueHint={{@dynamicValueHint}}
@session={{@session}}
>
- {{#if this.actionRoute}}
+ {{#if this.showActionButton}}
<div class="workflows-property-engine__select-with-action">
<DynamicOptionsComboBox
@content={{this.options}}
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
index eaae08bd5d2..d377a28ab48 100644
--- 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
@@ -1,5 +1,5 @@
import Component from "@glimmer/component";
-import { concat } from "@ember/helper";
+import { array, concat } from "@ember/helper";
import { action } from "@ember/object";
import didInsert from "@ember/render-modifiers/modifiers/did-insert";
import { service } from "@ember/service";
@@ -296,6 +296,39 @@ export default class ExecutionDetail extends Component {
<template>
<div class="workflows-execution-detail" {{didInsert this.ensureNodeTypes}}>
+ {{#if @execution.workflow_call_caller}}
+ <div class="workflows-execution-detail__workflow-call --caller">
+ <div class="workflows-execution-detail__workflow-call-main">
+ <span class="workflows-execution-detail__workflow-call-label">
+ {{i18n "discourse_workflows.executions.workflow_call_called_by"}}
+ </span>
+ <span class="workflows-execution-detail__workflow-call-name">
+ {{#if @execution.workflow_call_caller.workflow_name}}
+ {{@execution.workflow_call_caller.workflow_name}}
+ {{else}}
+ {{i18n
+ "discourse_workflows.executions.workflow_call_workflow"
+ [email protected]_call_caller.workflow_id
+ }}
+ {{/if}}
+ </span>
+ </div>
+
+ {{#if @execution.workflow_call_caller.execution_url}}
+ <DButton
+ @route="adminPlugins.show.discourse-workflows.show.executions.show"
+ @routeModels={{array
+ @execution.workflow_call_caller.workflow_id
+ @execution.workflow_call_caller.execution_id
+ }}
+ @icon="up-right-from-square"
+ @label="discourse_workflows.executions.workflow_call_open_parent"
+ class="btn-default btn-small workflows-execution-detail__workflow-call-link workflows-execution-detail__workflow-call-parent-link"
+ />
+ {{/if}}
+ </div>
+ {{/if}}
+
<div class="workflows-execution-detail__steps">
{{#each @execution.steps as |step|}}
<div
@@ -417,6 +450,71 @@ export default class ExecutionDetail extends Component {
</details>
{{/if}}
+ {{#if step.workflow_call_run}}
+ <div class="workflows-execution-detail__workflow-call">
+ <div class="workflows-execution-detail__workflow-call-main">
+ <span
+ class="workflows-execution-detail__workflow-call-icon"
+ >
+ {{dIcon "arrows-turn-to-dots"}}
+ </span>
+ <span
+ class="workflows-execution-detail__workflow-call-content"
+ >
+ <span
+ class="workflows-execution-detail__workflow-call-label"
+ >
+ {{i18n "discourse_workflows.executions.workflow_call"}}
+ </span>
+ <span
+ class="workflows-execution-detail__workflow-call-name"
+ >
+ {{#if step.workflow_call_run.workflow_name}}
+ {{step.workflow_call_run.workflow_name}}
+ {{else}}
+ {{i18n
+ "discourse_workflows.executions.workflow_call_workflow"
+ id=step.workflow_call_run.workflow_id
+ }}
+ {{/if}}
+ </span>
+ </span>
+ </div>
+
+ <span
+ class="workflows-execution-detail__step-badge --{{step.workflow_call_run.status}}"
+ >
+ {{i18n
+ (concat
+ "discourse_workflows.executions.statuses."
+ step.workflow_call_run.status
+ )
+ }}
+ </span>
+
+ {{#if step.workflow_call_run.execution_url}}
+ <DButton
+ @route="adminPlugins.show.discourse-workflows.show.executions.show"
+ @routeModels={{array
+ step.workflow_call_run.workflow_id
+ step.workflow_call_run.execution_id
+ }}
+ @icon="up-right-from-square"
+ @label="discourse_workflows.executions.workflow_call_open"
+ class="btn-default btn-small workflows-execution-detail__workflow-call-link"
+ />
+ {{/if}}
+
+ {{#if step.workflow_call_run.error}}
+ <div
+ class="workflows-execution-detail__workflow-call-error"
+ >
+ {{step.workflow_call_run.error}}
+ </div>
+ {{/if}}
+ </div>
+ {{/if}}
+
<details class="workflows-execution-detail__step-section">
<summary>
{{i18n "discourse_workflows.executions.input"}}
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
index 495ae362dfa..dd54e9a1a8a 100644
--- a/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/settings.gjs
+++ b/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/settings.gjs
@@ -8,6 +8,7 @@ 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";
+import InUseDialog from "./in-use-dialog";
export default class WorkflowSettings extends Component {
@service router;
@@ -42,7 +43,20 @@ export default class WorkflowSettings extends Component {
"adminPlugins.show.discourse-workflows.index"
);
} catch (e) {
- popupAjaxError(e);
+ const body = e.jqXHR?.responseJSON;
+ if (body?.type === "workflow_called_by_other_workflows") {
+ this.dialog.alert({
+ title: i18n("discourse_workflows.in_use_title"),
+ bodyComponent: InUseDialog,
+ bodyComponentModel: {
+ description: i18n("discourse_workflows.in_use_description"),
+ workflows: body.referencing_workflows,
+ close: () => this.dialog.cancel(),
+ },
+ });
+ } else {
+ popupAjaxError(e);
+ }
}
},
});
diff --git a/plugins/discourse-workflows/app/controllers/discourse_workflows/workflows_controller.rb b/plugins/discourse-workflows/app/controllers/discourse_workflows/workflows_controller.rb
index c4cc1e6d14a..22c6f1ce4fd 100644
--- a/plugins/discourse-workflows/app/controllers/discourse_workflows/workflows_controller.rb
+++ b/plugins/discourse-workflows/app/controllers/discourse_workflows/workflows_controller.rb
@@ -114,6 +114,16 @@ module DiscourseWorkflows
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 }
+ on_failed_policy(:workflow_not_called_by_other_workflows) do
+ render(
+ json:
+ failed_json.merge(
+ type: "workflow_called_by_other_workflows",
+ referencing_workflows: result[:referencing_workflows],
+ ),
+ status: :unprocessable_entity,
+ )
+ end
end
end
diff --git a/plugins/discourse-workflows/app/jobs/regular/discourse_workflows/run_workflow_call.rb b/plugins/discourse-workflows/app/jobs/regular/discourse_workflows/run_workflow_call.rb
new file mode 100644
index 00000000000..4c3c69ce00c
--- /dev/null
+++ b/plugins/discourse-workflows/app/jobs/regular/discourse_workflows/run_workflow_call.rb
@@ -0,0 +1,11 @@
+# frozen_string_literal: true
+
+module Jobs
+ module DiscourseWorkflows
+ class RunWorkflowCall < ::Jobs::Base
+ def execute(args)
+ ::DiscourseWorkflows::WorkflowCallContinuation.run!(run_id: args[:run_id])
+ 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
index 2ef73f8c19c..1e3230a76f4 100644
--- a/plugins/discourse-workflows/app/models/discourse_workflows/execution.rb
+++ b/plugins/discourse-workflows/app/models/discourse_workflows/execution.rb
@@ -11,6 +11,11 @@ module DiscourseWorkflows
foreign_key: "execution_id",
dependent: :destroy
+ has_many :initiated_workflow_call_runs,
+ class_name: "DiscourseWorkflows::WorkflowCallRun",
+ foreign_key: "parent_execution_id",
+ dependent: :delete_all
+
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 }
@@ -26,6 +31,11 @@ module DiscourseWorkflows
TERMINAL_STATUSES_FOR_PURGE = %i[success error rate_limited skipped].freeze
PURGE_BATCH_SIZE = 5_000
+ def self.admin_execution_url(workflow_id, execution_id)
+ "#{Discourse.base_url}/admin/plugins/discourse-workflows/workflows/" \
+ "#{workflow_id}/executions/#{execution_id}"
+ end
+
def self.create_pending_manual!(workflow:, trigger_node_id:, trigger_data:)
transaction do
create!(
@@ -60,6 +70,7 @@ module DiscourseWorkflows
break if ids.empty?
ExecutionData.where(execution_id: ids).delete_all
+ WorkflowCallRun.remove_execution_references(ids)
where(id: ids).delete_all
end
end
@@ -148,6 +159,8 @@ module DiscourseWorkflows
)
end
+ DiscourseWorkflows::WorkflowCallContinuation.child_failed!(reload) if claimed
+
claimed
end
diff --git a/plugins/discourse-workflows/app/models/discourse_workflows/workflow.rb b/plugins/discourse-workflows/app/models/discourse_workflows/workflow.rb
index 1eee654f611..cb2725c0406 100644
--- a/plugins/discourse-workflows/app/models/discourse_workflows/workflow.rb
+++ b/plugins/discourse-workflows/app/models/discourse_workflows/workflow.rb
@@ -33,6 +33,10 @@ module DiscourseWorkflows
class_name: "DiscourseWorkflows::AiAuthoringSession",
foreign_key: "workflow_id",
dependent: :delete_all
+ has_many :workflow_call_runs,
+ class_name: "DiscourseWorkflows::WorkflowCallRun",
+ foreign_key: "target_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
@@ -182,6 +186,10 @@ module DiscourseWorkflows
active_version_id.present?
end
+ def callable_as_subworkflow?
+ published? && Nodes::WorkflowCallTrigger::V1.find_in(active_version&.nodes).present?
+ end
+
def has_unpublished_changes?
published? && version_id != active_version_id
end
diff --git a/plugins/discourse-workflows/app/models/discourse_workflows/workflow_call_run.rb b/plugins/discourse-workflows/app/models/discourse_workflows/workflow_call_run.rb
new file mode 100644
index 00000000000..e0f98e63ecd
--- /dev/null
+++ b/plugins/discourse-workflows/app/models/discourse_workflows/workflow_call_run.rb
@@ -0,0 +1,68 @@
+# frozen_string_literal: true
+
+module DiscourseWorkflows
+ class WorkflowCallRun < ActiveRecord::Base
+ self.table_name = "discourse_workflows_workflow_call_runs"
+
+ belongs_to :parent_execution,
+ class_name: "DiscourseWorkflows::Execution",
+ foreign_key: "parent_execution_id"
+ belongs_to :child_execution,
+ class_name: "DiscourseWorkflows::Execution",
+ foreign_key: "child_execution_id",
+ optional: true
+ belongs_to :target_workflow,
+ class_name: "DiscourseWorkflows::Workflow",
+ foreign_key: "target_workflow_id"
+ belongs_to :user, optional: true
+
+ enum :status, { pending: 0, running: 1, success: 2, error: 3, waiting: 4 }
+
+ scope :active, -> { where(status: statuses.values_at(:pending, :running, :waiting)) }
+
+ def self.remove_execution_references(execution_ids)
+ return if execution_ids.blank?
+
+ where(child_execution_id: execution_ids).update_all(child_execution_id: nil)
+ where(parent_execution_id: execution_ids).delete_all
+ end
+
+ def self.claim_pending(run)
+ now = Time.current
+ affected =
+ where(id: run.id, status: statuses[:pending]).update_all(
+ status: statuses[:running],
+ updated_at: now,
+ )
+ return if affected.zero?
+
+ run.status = :running
+ run.updated_at = now
+ run
+ end
+ end
+end
+
+# == Schema Information
+#
+# Table name: discourse_workflows_workflow_call_runs
+#
+# id :bigint not null, primary key
+# error :text
+# parent_resume_token :string(64) not null
+# status :integer default("pending"), not null
+# trigger_data :jsonb not null
+# created_at :datetime not null
+# updated_at :datetime not null
+# child_execution_id :bigint
+# parent_execution_id :bigint not null
+# parent_node_id :string(100) not null
+# target_workflow_id :bigint not null
+# target_workflow_version_id :string(36) not null
+# user_id :bigint
+#
+# Indexes
+#
+# idx_dwf_call_runs_on_child_execution_id (child_execution_id) UNIQUE WHERE (child_execution_id IS NOT NULL)
+# idx_dwf_call_runs_on_parent_execution_id (parent_execution_id)
+#
diff --git a/plugins/discourse-workflows/app/models/discourse_workflows/workflow_dependency.rb b/plugins/discourse-workflows/app/models/discourse_workflows/workflow_dependency.rb
index f5159c24911..44957548e8b 100644
--- a/plugins/discourse-workflows/app/models/discourse_workflows/workflow_dependency.rb
+++ b/plugins/discourse-workflows/app/models/discourse_workflows/workflow_dependency.rb
@@ -20,6 +20,13 @@ module DiscourseWorkflows
validates :dependency_type, inclusion: { in: TYPES }
scope :of_type, ->(type) { where(dependency_type: type) }
+ scope :on_active_version,
+ -> do
+ joins(:workflow).where(
+ "discourse_workflows_workflow_dependencies.workflow_version_id = " \
+ "discourse_workflows_workflows.active_version_id",
+ )
+ end
def self.cache
@cache ||= DistributedCache.new("discourse_workflows_dependencies")
@@ -46,15 +53,7 @@ module DiscourseWorkflows
def self.active_node_types
cache.defer_get_set(ACTIVE_NODE_TYPES_KEY) do
- of_type("node_type")
- .joins(:workflow)
- .where(
- "discourse_workflows_workflow_dependencies.workflow_version_id = " \
- "discourse_workflows_workflows.active_version_id",
- )
- .distinct
- .pluck(:dependency_key)
- .to_set
+ of_type("node_type").on_active_version.distinct.pluck(:dependency_key).to_set
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
index 5ea92f55e51..035130e8716 100644
--- a/plugins/discourse-workflows/app/serializers/discourse_workflows/execution_serializer.rb
+++ b/plugins/discourse-workflows/app/serializers/discourse_workflows/execution_serializer.rb
@@ -11,7 +11,8 @@ module DiscourseWorkflows
:run_time_ms,
:started_at,
:finished_at,
- :created_at
+ :created_at,
+ :workflow_call_caller
attribute :steps
@@ -19,6 +20,17 @@ module DiscourseWorkflows
object.workflow_snapshot_name
end
+ def workflow_call_caller
+ return @workflow_call_caller if defined?(@workflow_call_caller)
+
+ @workflow_call_caller =
+ DiscourseWorkflows::WorkflowCallContinuation.caller_metadata_for(object)
+ end
+
+ def include_workflow_call_caller?
+ workflow_call_caller.present?
+ end
+
STEP_FIELDS = %w[
node_id
node_name
@@ -35,7 +47,57 @@ module DiscourseWorkflows
def steps
return [] unless object.execution_data
- object.execution_data.steps_array.map { |step| step.slice(*STEP_FIELDS).symbolize_keys }
+
+ workflow_call_runs = workflow_call_runs_by_parent_node_id
+ object.execution_data.steps_array.map do |step|
+ serialized_step = step.slice(*STEP_FIELDS).symbolize_keys
+ metadata = serialized_step[:metadata]
+ serialized_step[:metadata] = metadata.except("workflow_call") if metadata
+
+ if (workflow_call_run = workflow_call_runs[step["node_id"]])
+ serialized_step[:workflow_call_run] = workflow_call_run_data(workflow_call_run)
+ end
+
+ serialized_step
+ end
+ end
+
+ private
+
+ def workflow_call_runs_by_parent_node_id
+ # Workflow executions currently record one step entry per node, so the
+ # parent node id is enough to attach the child run. If a node can run
+ # more than once in one execution, WorkflowCallRun will need a step/run
+ # correlation id instead.
+ @workflow_call_runs_by_parent_node_id ||=
+ object
+ .initiated_workflow_call_runs
+ .includes(:child_execution, :target_workflow)
+ .order(:id)
+ .index_by(&:parent_node_id)
+ end
+
+ def workflow_call_run_data(workflow_call_run)
+ child_execution = workflow_call_run.child_execution
+
+ {
+ "run_id" => workflow_call_run.id,
+ "workflow_id" => workflow_call_run.target_workflow_id,
+ "workflow_name" => workflow_call_run.target_workflow&.name,
+ "execution_id" => workflow_call_run.child_execution_id,
+ "execution_url" => workflow_call_execution_url(workflow_call_run),
+ "status" => child_execution&.status || workflow_call_run.status,
+ "error" => workflow_call_run.error,
+ }.compact
+ end
+
+ def workflow_call_execution_url(workflow_call_run)
+ return if workflow_call_run.child_execution_id.blank?
+
+ DiscourseWorkflows::Execution.admin_execution_url(
+ workflow_call_run.target_workflow_id,
+ workflow_call_run.child_execution_id,
+ )
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
index 4c2d83f8c90..ab3a85b5d4e 100644
--- a/plugins/discourse-workflows/app/services/discourse_workflows/execution/destroy.rb
+++ b/plugins/discourse-workflows/app/services/discourse_workflows/execution/destroy.rb
@@ -15,6 +15,7 @@ module DiscourseWorkflows
transaction do
step :delete_execution_data
+ step :remove_workflow_call_run_references
model :deleted_count, :delete_executions
end
@@ -24,6 +25,10 @@ module DiscourseWorkflows
DiscourseWorkflows::ExecutionData.where(execution_id: params.execution_ids).delete_all
end
+ def remove_workflow_call_run_references(params:)
+ DiscourseWorkflows::WorkflowCallRun.remove_execution_references(params.execution_ids)
+ end
+
def delete_executions(params:)
DiscourseWorkflows::Execution.where(id: params.execution_ids).delete_all
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
index c9ec6d2768b..cba908aa2bd 100644
--- a/plugins/discourse-workflows/app/services/discourse_workflows/workflow/destroy.rb
+++ b/plugins/discourse-workflows/app/services/discourse_workflows/workflow/destroy.rb
@@ -11,9 +11,10 @@ module DiscourseWorkflows
policy :can_manage_workflows, class_name: Policy::CanManageWorkflows
model :workflow
+ model :referencing_workflows, optional: true
+ policy :workflow_not_called_by_other_workflows
- transaction { step :delete_workflow }
-
+ step :delete_workflow
step :log
step :expire_workflow_caches
@@ -23,6 +24,24 @@ module DiscourseWorkflows
DiscourseWorkflows::Workflow.find_by(id: params.workflow_id)
end
+ def fetch_referencing_workflows(workflow:)
+ workflow_ids =
+ DiscourseWorkflows::WorkflowDependency
+ .workflows_referencing("workflow_call", workflow.id)
+ .where.not(workflow_id: workflow.id)
+ .pluck(:workflow_id)
+
+ DiscourseWorkflows::Workflow
+ .where(id: workflow_ids)
+ .order(:name)
+ .pluck(:id, :name)
+ .map { |id, name| { id:, name: } }
+ end
+
+ def workflow_not_called_by_other_workflows(referencing_workflows:)
+ referencing_workflows.blank?
+ end
+
def delete_workflow(workflow:)
workflow.destroy!
end
diff --git a/plugins/discourse-workflows/assets/stylesheets/common/executions/execution-detail.scss b/plugins/discourse-workflows/assets/stylesheets/common/executions/execution-detail.scss
index a9e067f7535..cc17e4b728b 100644
--- a/plugins/discourse-workflows/assets/stylesheets/common/executions/execution-detail.scss
+++ b/plugins/discourse-workflows/assets/stylesheets/common/executions/execution-detail.scss
@@ -257,6 +257,69 @@
font-size: var(--font-down-1);
}
+ &__workflow-call {
+ display: flex;
+ align-items: center;
+ gap: var(--space-2);
+ flex-wrap: wrap;
+ padding: var(--space-2);
+ margin-bottom: var(--space-2);
+ border: 1px solid var(--primary-low);
+ border-radius: 0.25em;
+ background: var(--primary-very-low);
+
+ &.--caller {
+ padding: 0;
+ border: 0;
+ background: transparent;
+ }
+ }
+
+ &__workflow-call-main {
+ display: inline-flex;
+ align-items: center;
+ gap: var(--space-2);
+ flex: 1 1 auto;
+ min-width: 0;
+ }
+
+ &__workflow-call.--caller &__workflow-call-main {
+ flex: 0 1 auto;
+ flex-wrap: wrap;
+ gap: var(--space-1);
+ }
+
+ &__workflow-call-icon {
+ flex-shrink: 0;
+ color: var(--primary-medium);
+ }
+
+ &__workflow-call-content {
+ display: flex;
+ flex-direction: column;
+ min-width: 0;
+ }
+
+ &__workflow-call-label {
+ font-size: var(--font-down-2);
+ color: var(--primary-medium);
+ }
+
+ &__workflow-call-name {
+ font-weight: bold;
+ overflow-wrap: anywhere;
+ }
+
+ &__workflow-call-link {
+ margin-inline-start: auto;
+ }
+
+ &__workflow-call-error {
+ flex-basis: 100%;
+ color: var(--workflow-status-error);
+ overflow-wrap: anywhere;
+ }
+
&__item-count {
font-size: var(--font-down-1);
color: var(--primary-medium);
diff --git a/plugins/discourse-workflows/config/locales/client.en.yml b/plugins/discourse-workflows/config/locales/client.en.yml
index 55aefcbb243..be0ebed742e 100644
--- a/plugins/discourse-workflows/config/locales/client.en.yml
+++ b/plugins/discourse-workflows/config/locales/client.en.yml
@@ -130,6 +130,8 @@ en:
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}\"?"
+ in_use_title: "Workflow in use"
+ in_use_description: "This workflow cannot be deleted because it is called by the following workflows:"
tabs:
workflow: "Workflow"
executions: "Executions"
@@ -213,6 +215,7 @@ en:
"trigger:topic_tag_changed": "Topic tag changed"
"trigger:reviewable_approved": "Approved reviewable"
"trigger:webhook": "Webhook"
+ "trigger:workflow_call": "Workflow call"
"trigger:manual": "Manual trigger"
"condition:if": "If"
"condition:filter": "Filter"
@@ -229,6 +232,7 @@ en:
"action:split_out": "Split out"
"action:sort": "Sort"
"action:http_request": "HTTP request"
+ "action:workflow_call": "Call workflow"
"action:data_table": "Data table"
"action:group": "Group"
"action:badge": "Badge"
@@ -253,6 +257,7 @@ en:
"trigger:topic_tag_changed": "Fires when tags are added to or removed from a topic"
"trigger:reviewable_approved": "Fires when a reviewable is approved"
"trigger:webhook": "Fires when an external service sends a webhook request"
+ "trigger:workflow_call": "Fires when another workflow calls this workflow"
"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"
@@ -269,6 +274,7 @@ en:
"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:workflow_call": "Run another workflow and use its result"
"action:data_table": "Read, write, or query a workflow data table"
"action:group": "Read, check, or update group membership"
"action:badge": "Grant or revoke a badge"
@@ -492,11 +498,6 @@ en:
include_fields_placeholder: "company, id"
exclude_fields: "Fields to exclude"
exclude_fields_placeholder: "debug, internal.notes"
- type_string: "String"
- type_number: "Number"
- type_boolean: "Boolean"
- type_array: "Array"
- type_object: "Object"
add_field: "Add field"
code:
mode: "Mode"
@@ -540,6 +541,12 @@ en:
add_field: "Add field"
remove_item: "Remove item"
dynamic_hint: "Must resolve to %{value}."
+ assignment_types:
+ string: "String"
+ number: "Number"
+ boolean: "Boolean"
+ array: "Array"
+ object: "Object"
dynamic_values:
badge_id: "a badge ID"
boolean: "true or false"
@@ -751,6 +758,16 @@ en:
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"
+ workflow_call:
+ workflow_id: "Workflow"
+ workflow_id_placeholder: "Select a callable workflow..."
+ open_workflow: "Open workflow"
+ mapping_mode: "Input"
+ mapping_mode_auto: "Map automatically"
+ mapping_mode_manual: "Map fields manually"
+ fields: "Fields"
+ workflow_call_trigger:
+ description: "This workflow can be called by another workflow."
split_out:
field: "Fields to split out"
field_description: "Comma-separated field name(s) containing arrays to split. Supports dot notation for nested fields."
@@ -958,6 +975,11 @@ en:
output: "Output"
items: "items"
logs: "Console"
+ workflow_call: "Workflow call"
+ workflow_call_called_by: "Called by"
+ workflow_call_workflow: "Workflow %{id}"
+ workflow_call_open: "Open execution"
+ workflow_call_open_parent: "Open parent execution"
total_time: "Total time:"
export: "Export"
error: "Error"
diff --git a/plugins/discourse-workflows/config/locales/server.en.yml b/plugins/discourse-workflows/config/locales/server.en.yml
index 9eeccce2948..ee6ccc7998a 100644
--- a/plugins/discourse-workflows/config/locales/server.en.yml
+++ b/plugins/discourse-workflows/config/locales/server.en.yml
@@ -120,6 +120,17 @@ en:
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."
+ workflow_call:
+ workflow_required: "Select a workflow to call."
+ self_reference: "%{node} cannot call its own workflow."
+ target_not_found: "The selected workflow could not be found."
+ target_not_callable: "The selected workflow must be published and contain a Workflow call trigger."
+ cycle: "%{node} creates a workflow call loop."
+ recursive_call: "Workflow call loop detected."
+ max_depth_exceeded: "Workflow call depth cannot exceed %{max}."
+ execution_failed: "Called workflow finished with status '%{status}'."
+ execution_failed_with_error: "Called workflow finished with status '%{status}': %{error}"
+ payload_too_large: "Workflow call payload exceeds the maximum size of %{max} bytes."
pin_data:
errors:
unsupported_node: "Only nodes with a single output can have pinned data."
diff --git a/plugins/discourse-workflows/db/migrate/20260623090824_create_workflow_call_runs.rb b/plugins/discourse-workflows/db/migrate/20260623090824_create_workflow_call_runs.rb
new file mode 100644
index 00000000000..ea54a3bdf52
--- /dev/null
+++ b/plugins/discourse-workflows/db/migrate/20260623090824_create_workflow_call_runs.rb
@@ -0,0 +1,28 @@
+# frozen_string_literal: true
+
+class CreateWorkflowCallRuns < ActiveRecord::Migration[8.0]
+ def change
+ create_table :discourse_workflows_workflow_call_runs do |t|
+ t.bigint :parent_execution_id, null: false
+ t.string :parent_node_id, null: false, limit: 100
+ t.string :parent_resume_token, null: false, limit: 64
+ t.bigint :child_execution_id
+ t.bigint :target_workflow_id, null: false
+ t.string :target_workflow_version_id, null: false, limit: 36
+ t.bigint :user_id
+ t.jsonb :trigger_data, default: {}, null: false
+ t.integer :status, null: false, default: 0
+ t.text :error
+ t.timestamps null: false
+ end
+
+ add_index :discourse_workflows_workflow_call_runs,
+ :child_execution_id,
+ unique: true,
+ where: "child_execution_id IS NOT NULL",
+ name: "idx_dwf_call_runs_on_child_execution_id"
+ add_index :discourse_workflows_workflow_call_runs,
+ :parent_execution_id,
+ name: "idx_dwf_call_runs_on_parent_execution_id"
+ end
+end
diff --git a/plugins/discourse-workflows/lib/discourse_workflows/executor.rb b/plugins/discourse-workflows/lib/discourse_workflows/executor.rb
index e1b24ffe6fa..b20fa630695 100644
--- a/plugins/discourse-workflows/lib/discourse_workflows/executor.rb
+++ b/plugins/discourse-workflows/lib/discourse_workflows/executor.rb
@@ -6,12 +6,14 @@ module DiscourseWorkflows
MAX_WAIT_DURATION_SECONDS = 30.days.to_i
MAX_NODE_OUTPUT_BYTES = 50.megabytes
- class WaitRequested < StandardError
- attr_reader :waiting_until
+ class ExecutionPaused < StandardError
+ attr_reader :wait_request
- def initialize(waiting_until)
- @waiting_until = waiting_until
- super("Wait requested")
+ delegate :waiting_until, to: :@wait_request
+
+ def initialize(wait_request)
+ @wait_request = wait_request
+ super("Execution paused")
end
end
@@ -45,6 +47,7 @@ module DiscourseWorkflows
user: @options.user,
workflow_nodes: workflow_nodes,
workflow_name: workflow_version&.name,
+ workflow_call_caller: @options.workflow_call_caller,
)
@store =
ExecutionStore.new(
@@ -64,41 +67,57 @@ module DiscourseWorkflows
@waiting_node = nil
@waiting_step = nil
@pin_data_by_node_name = resolved_pin_data
+ @workflow_call_stack = normalized_workflow_call_stack
end
def self.resume(execution, response_items, user: nil, webhook_context: nil)
+ build_resume_executor(execution, user: user, webhook_context: webhook_context).resume_from(
+ execution,
+ response_items,
+ )
+ end
+
+ def self.resume_with_error(execution, error, user: nil)
+ build_resume_executor(execution, user: user).resume_from_error(execution, error)
+ end
+
+ def self.build_resume_executor(execution, user:, webhook_context: nil)
+ workflow_call_caller = WorkflowCallContinuation.caller_metadata_for(execution)
+ options =
+ ExecutionOptions.new(
+ user: user,
+ execution_mode: execution.execution_mode.to_sym,
+ workflow_snapshot: build_resume_snapshot!(execution),
+ webhook_context: webhook_context,
+ workflow_call_stack: WorkflowCallContinuation.workflow_call_stack_for(execution),
+ workflow_call_child: workflow_call_caller.present?,
+ workflow_call_caller: workflow_call_caller,
+ )
+ new(execution.workflow, execution.trigger_node_id, execution.trigger_data, options)
+ end
+ private_class_method :build_resume_executor
+
+ def self.build_resume_snapshot!(execution)
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)
+ WorkflowSnapshot.from_workflow(execution.workflow, published: true)
end
- unless snapshot.find_node(trigger_node_id)
- raise "Trigger node #{trigger_node_id} not found in workflow #{workflow.id}"
+ unless snapshot.find_node(execution.trigger_node_id)
+ raise "Trigger node #{execution.trigger_node_id} not found in workflow #{execution.workflow.id}"
end
- options =
- ExecutionOptions.new(
- user: user,
- execution_mode: execution.execution_mode.to_sym,
- workflow_snapshot: snapshot,
- webhook_context: webhook_context,
- )
- new(workflow, trigger_node_id, execution.trigger_data, options).resume_from(
- execution,
- response_items,
- )
+ snapshot
end
+ private_class_method :build_resume_snapshot!
def run
unless @workflow.published? || @options.draft_execution || @options.workflow_version ||
@@ -149,15 +168,53 @@ module DiscourseWorkflows
end
end
+ def resume_from_error(execution, error)
+ 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?
+
+ step = @steps.find { |entry| entry.node_id == waiting_node.id.to_s && entry.waiting? }
+ input_items = execution.waiting_step_input_items
+ input_groups = { 0 => input_items }
+
+ if (handled_outputs = continued_error_outputs(waiting_node, input_groups, error))
+ handled_outputs = enforce_node_output_budget(handled_outputs, nil)
+ all_items = handled_outputs.flatten(1)
+ step&.add_metadata("handled_error", error_metadata(error))
+ step&.succeed!(output: all_items)
+ step&.apply_updates!("error" => nil)
+ @context.store_node_output(waiting_node, all_items)
+ @context.store_node_run(
+ waiting_node,
+ inputs: [input_items],
+ outputs: handled_outputs,
+ input_sources: @context.consume_waiting_input_sources,
+ )
+ clear_waiting!
+ route_downstream(waiting_node, handled_outputs)
+ else
+ step&.fail!(error.message)
+ raise error
+ end
+ end
+ end
+
private
+ def normalized_workflow_call_stack
+ stack = Array(@options.workflow_call_stack).map(&:to_s)
+ workflow_id = @workflow.id.to_s
+ stack.last == workflow_id ? stack : stack + [workflow_id]
+ end
+
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 ExecutionPaused => e
+ begin_wait!(e.wait_request)
rescue => e
@store.fail!(error: e, steps: @steps)
ensure
@@ -266,7 +323,7 @@ module DiscourseWorkflows
@context.store_waiting_input_sources(
input_sources_for_storage(input_sources, input_groups),
)
- raise WaitRequested, wait_request.waiting_until
+ raise ExecutionPaused, wait_request
end
step_log = collect_step_log(exec_ctx, resolver)
@@ -298,7 +355,7 @@ module DiscourseWorkflows
input_sources: input_sources_for_storage(input_sources, input_groups),
)
route_downstream(node, output_arrays)
- rescue WaitRequested
+ rescue ExecutionPaused
raise
rescue => e
if (handled_outputs = continued_error_outputs(node, input_groups, e))
@@ -471,6 +528,7 @@ module DiscourseWorkflows
workflow_dependencies: preloaded_workflow_dependencies,
workflow_snapshot: @snapshot,
webhook_context: @options.webhook_context,
+ workflow_call_stack: @workflow_call_stack,
runtime_state: runtime_state,
static_data_state: @context.static_data_state,
)
@@ -816,30 +874,52 @@ module DiscourseWorkflows
)
end
- def begin_wait!(waiting_until)
- now = Time.current
- ceiling = now + MAX_WAIT_DURATION_SECONDS
- resolved = waiting_until.blank? ? ceiling : [waiting_until, ceiling].min
+ def begin_wait!(wait_request)
+ store_pending_wait_state!
+
+ if wait_request.workflow_call?
+ begin_workflow_call_wait!(wait_request)
+ else
+ begin_timed_wait!(wait_request.waiting_until)
+ end
+ rescue => e
+ @store.fail!(error: e, steps: @steps)
+ end
+
+ def store_pending_wait_state!
@context.store_pending_input_groups(
inputs: @waiting_inputs,
sources: @waiting_input_sources,
target_ids: @waiting_input_targets.keys,
)
@context.store_pending_queue(@queue.drop(@queue_index || 0))
+ end
+
+ def begin_timed_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,
+ [resolved - now, 0].max,
Jobs::DiscourseWorkflows::ResumeWaitingExecution,
execution_id: @store.execution.id,
)
+ execution
+ end
+
+ def begin_workflow_call_wait!(wait_request)
+ execution = @store.pause_waiting_execution!(node: @waiting_node, steps: @steps)
+ DiscourseWorkflows::WorkflowCallContinuation.begin_child_call!(
+ execution: execution,
+ node: @waiting_node,
+ request: wait_request,
+ )
execution
- rescue => e
- @store.fail!(error: e, steps: @steps)
end
def start_execution!
@@ -989,6 +1069,10 @@ module DiscourseWorkflows
if parameters["data_table_id"].present?
dependencies << ["data_table_id", parameters["data_table_id"]]
end
+ if node.type == DiscourseWorkflows::Nodes::WorkflowCall::V1.identifier &&
+ parameters["workflow_id"].present?
+ dependencies << ["workflow_call", parameters["workflow_id"]]
+ end
dependencies
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
index ad79405038e..2b401e1c11c 100644
--- a/plugins/discourse-workflows/lib/discourse_workflows/executor/error_workflow_trigger.rb
+++ b/plugins/discourse-workflows/lib/discourse_workflows/executor/error_workflow_trigger.rb
@@ -64,8 +64,7 @@ module DiscourseWorkflows
def execution_url
return nil unless @execution
- "#{Discourse.base_url}/admin/plugins/discourse-workflows/workflows/" \
- "#{@workflow.id}/executions/#{@execution.id}"
+ DiscourseWorkflows::Execution.admin_execution_url(@workflow.id, @execution.id)
end
def serialized_error(error)
diff --git a/plugins/discourse-workflows/lib/discourse_workflows/executor/execution_context.rb b/plugins/discourse-workflows/lib/discourse_workflows/executor/execution_context.rb
index 59123906d54..cf3ca74f554 100644
--- a/plugins/discourse-workflows/lib/discourse_workflows/executor/execution_context.rb
+++ b/plugins/discourse-workflows/lib/discourse_workflows/executor/execution_context.rb
@@ -24,7 +24,13 @@ module DiscourseWorkflows
$itemIndex
].freeze
- attr_reader :workflow, :trigger_data, :context, :user, :workflow_name, :static_data_state
+ attr_reader :workflow,
+ :trigger_data,
+ :context,
+ :user,
+ :workflow_name,
+ :workflow_call_caller,
+ :static_data_state
attr_accessor :execution
def initialize(
@@ -33,11 +39,13 @@ module DiscourseWorkflows
user:,
execution: nil,
workflow_nodes: nil,
- workflow_name: nil
+ workflow_name: nil,
+ workflow_call_caller: nil
)
@workflow = workflow
@workflow_nodes = workflow_nodes
@workflow_name = workflow_name || workflow.name
+ @workflow_call_caller = workflow_call_caller&.deep_stringify_keys
@trigger_data = trigger_data
@user = user
@execution = execution
@@ -180,6 +188,9 @@ module DiscourseWorkflows
"workflow_name" => ->(execution_context, _extra_context) do
execution_context.workflow_name
end,
+ "called_by" => ->(execution_context, _extra_context) do
+ execution_context.workflow_call_caller
+ end,
"resume_url" =>
lambda do |execution_context, extra_context|
token = execution_context.resume_token
diff --git a/plugins/discourse-workflows/lib/discourse_workflows/executor/execution_options.rb b/plugins/discourse-workflows/lib/discourse_workflows/executor/execution_options.rb
index 0271b197770..0bb428afec9 100644
--- a/plugins/discourse-workflows/lib/discourse_workflows/executor/execution_options.rb
+++ b/plugins/discourse-workflows/lib/discourse_workflows/executor/execution_options.rb
@@ -11,6 +11,10 @@ module DiscourseWorkflows
:workflow_snapshot,
:existing_execution,
:webhook_context,
+ :workflow_call_stack,
+ :workflow_call_caller,
+ :workflow_call_run_id,
+ :workflow_call_child,
) do
def initialize(
user: nil,
@@ -19,10 +23,18 @@ module DiscourseWorkflows
workflow_version: nil,
workflow_snapshot: nil,
existing_execution: nil,
- webhook_context: nil
+ webhook_context: nil,
+ workflow_call_stack: [],
+ workflow_call_caller: nil,
+ workflow_call_run_id: nil,
+ workflow_call_child: false
)
super
end
+
+ def workflow_call_child?
+ workflow_call_run_id.present? || workflow_call_child
+ 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
index 6192c579d9b..8f6debd7b40 100644
--- a/plugins/discourse-workflows/lib/discourse_workflows/executor/execution_store.rb
+++ b/plugins/discourse-workflows/lib/discourse_workflows/executor/execution_store.rb
@@ -60,6 +60,9 @@ module DiscourseWorkflows
timeout_action: nil,
)
publish_execution_run_data
+ if @options.workflow_call_child?
+ DiscourseWorkflows::WorkflowCallContinuation.child_succeeded!(execution)
+ end
execution
end
@@ -79,6 +82,9 @@ module DiscourseWorkflows
publish_execution_run_data(
force: @options.draft_execution || @options.workflow_snapshot.present?,
)
+ if @options.workflow_call_child?
+ DiscourseWorkflows::WorkflowCallContinuation.child_failed!(execution)
+ end
execution
end
@@ -131,9 +137,19 @@ module DiscourseWorkflows
started_at: @execution.started_at || Time.current,
finished_at: finished_at,
)
+ attach_workflow_call_run!
@execution
end
+ def attach_workflow_call_run!
+ return if @options.workflow_call_run_id.blank?
+
+ DiscourseWorkflows::WorkflowCallRun.where(id: @options.workflow_call_run_id).update_all(
+ child_execution_id: @execution.id,
+ updated_at: Time.current,
+ )
+ end
+
def execution_workflow_version_id
@options.workflow_version&.version_id || workflow.version_id
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
index a061ec50f85..6ca605409a0 100644
--- a/plugins/discourse-workflows/lib/discourse_workflows/executor/node_execution_context.rb
+++ b/plugins/discourse-workflows/lib/discourse_workflows/executor/node_execution_context.rb
@@ -9,7 +9,12 @@ module DiscourseWorkflows
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)
+ WaitRequest =
+ Data.define(:waiting_until, :kind, :payload) do
+ def workflow_call?
+ kind == "workflow_call"
+ end
+ end
def self.serialize_post(
post,
@@ -62,8 +67,8 @@ module DiscourseWorkflows
@wait_request = nil
end
- def request_wait(waiting_until)
- @wait_request = WaitRequest.new(waiting_until)
+ def request_wait(waiting_until, kind: "default", payload: {})
+ @wait_request = WaitRequest.new(waiting_until, kind.to_s, payload.deep_stringify_keys)
end
def add_condition_details(details)
@@ -86,7 +91,7 @@ module DiscourseWorkflows
end
end
- attr_reader :user, :vars, :execution_id, :node_id, :webhook_ctx
+ attr_reader :user, :vars, :execution_id, :node_id, :webhook_ctx, :workflow_call_stack
def initialize(
input_items:,
@@ -113,6 +118,7 @@ module DiscourseWorkflows
workflow_dependencies: nil,
workflow_snapshot: nil,
webhook_context: nil,
+ workflow_call_stack: [],
runtime_state: RuntimeState.new,
static_data_state: nil
)
@@ -147,6 +153,7 @@ module DiscourseWorkflows
@workflow_dependencies = workflow_dependencies
@workflow_snapshot = workflow_snapshot
@webhook_ctx = webhook_context
+ @workflow_call_stack = Array(workflow_call_stack).map(&:to_s)
@static_data_state = static_data_state
end
@@ -367,8 +374,8 @@ module DiscourseWorkflows
self.class.serialize_topic(topic, guardian:, custom_field_names:)
end
- def put_execution_to_wait(waiting_until = nil)
- @runtime_state.request_wait(waiting_until)
+ def put_execution_to_wait(waiting_until = nil, kind: "default", payload: {})
+ @runtime_state.request_wait(waiting_until, kind: kind, payload: payload)
end
def resume_action_id(action)
@@ -428,6 +435,17 @@ module DiscourseWorkflows
paired_item
end
+ def ensure_workflow_call_access!(workflow_id)
+ workflow_id = workflow_id.to_s
+ if @workflow && @node_id
+ return if workflow_references_dependency?("workflow_call", workflow_id)
+ elsif @parameters["workflow_id"].to_s == workflow_id
+ return
+ end
+
+ raise Discourse::InvalidAccess
+ end
+
private
def fetch_credentials(slot, item_index)
diff --git a/plugins/discourse-workflows/lib/discourse_workflows/expression_context_schema.rb b/plugins/discourse-workflows/lib/discourse_workflows/expression_context_schema.rb
index c40a3b83a69..bfa0a02d24b 100644
--- a/plugins/discourse-workflows/lib/discourse_workflows/expression_context_schema.rb
+++ b/plugins/discourse-workflows/lib/discourse_workflows/expression_context_schema.rb
@@ -33,6 +33,37 @@ module DiscourseWorkflows
"workflow_name" => {
type: :string,
},
+ "called_by" => {
+ type: :object,
+ fields: {
+ "workflow_id" => {
+ type: :integer,
+ },
+ "workflow_name" => {
+ type: :string,
+ },
+ "execution_id" => {
+ type: :integer,
+ },
+ "execution_url" => {
+ type: :string,
+ },
+ "node_id" => {
+ type: :string,
+ },
+ "node_name" => {
+ type: :string,
+ },
+ "node_type" => {
+ type: :string,
+ },
+ },
+ display_options: {
+ show: {
+ node_present: [{ type: "trigger:workflow_call" }],
+ },
+ },
+ },
"resume_url" => {
type: :string,
display_options: {
diff --git a/plugins/discourse-workflows/lib/discourse_workflows/node_type.rb b/plugins/discourse-workflows/lib/discourse_workflows/node_type.rb
index c49820b7b57..6d7247b9696 100644
--- a/plugins/discourse-workflows/lib/discourse_workflows/node_type.rb
+++ b/plugins/discourse-workflows/lib/discourse_workflows/node_type.rb
@@ -37,6 +37,10 @@ module DiscourseWorkflows
registered_nodes.select(&:waits_for_resume?).map(&:identifier)
end
+ def self.find_in(nodes)
+ Array(nodes).find { |node| node["type"] == identifier }
+ end
+
def self.description(value = nil)
if value
@description = DESCRIPTION_DEFAULTS.deep_merge(value.deep_symbolize_keys).freeze
diff --git a/plugins/discourse-workflows/lib/discourse_workflows/nodes/log/v1.rb b/plugins/discourse-workflows/lib/discourse_workflows/nodes/log/v1.rb
index c2bc0ea9970..57d582c732d 100644
--- a/plugins/discourse-workflows/lib/discourse_workflows/nodes/log/v1.rb
+++ b/plugins/discourse-workflows/lib/discourse_workflows/nodes/log/v1.rb
@@ -68,7 +68,7 @@ module DiscourseWorkflows
end
end
- [[]]
+ [exec_ctx.input_items]
end
private
diff --git a/plugins/discourse-workflows/lib/discourse_workflows/nodes/wait/v1.rb b/plugins/discourse-workflows/lib/discourse_workflows/nodes/wait/v1.rb
index d32720b3523..86f6a04c246 100644
--- a/plugins/discourse-workflows/lib/discourse_workflows/nodes/wait/v1.rb
+++ b/plugins/discourse-workflows/lib/discourse_workflows/nodes/wait/v1.rb
@@ -103,6 +103,7 @@ module DiscourseWorkflows
end,
capabilities: {
waits_for_resume: true,
+ produces_data: false,
},
)
diff --git a/plugins/discourse-workflows/lib/discourse_workflows/nodes/workflow_call/v1.rb b/plugins/discourse-workflows/lib/discourse_workflows/nodes/workflow_call/v1.rb
new file mode 100644
index 00000000000..1c50fbca6e8
--- /dev/null
+++ b/plugins/discourse-workflows/lib/discourse_workflows/nodes/workflow_call/v1.rb
@@ -0,0 +1,206 @@
+# frozen_string_literal: true
+
+module DiscourseWorkflows
+ module Nodes
+ module WorkflowCall
+ class V1 < NodeType
+ AUTO = "auto"
+ MANUAL = "manual"
+ MAPPING_MODES = [AUTO, MANUAL].freeze
+
+ description(
+ name: "action:workflow_call",
+ version: "1.0",
+ defaults: {
+ icon: "arrows-turn-to-dots",
+ color: "teal",
+ },
+ group: "flow",
+ capabilities: {
+ waits_for_resume: true,
+ },
+ properties: {
+ workflow_id: {
+ type: :integer,
+ required: true,
+ no_data_expression: true,
+ type_options: {
+ load_options_method: "callable_workflows",
+ },
+ ui: {
+ control: :combo_box,
+ },
+ control_options: {
+ action_icon: "up-right-from-square",
+ action_label: "discourse_workflows.workflow_call.open_workflow",
+ action_route: "adminPlugins.show.discourse-workflows.show",
+ action_route_models: [{ source: "field_value" }],
+ value_property: "id",
+ name_property: "name",
+ filterable: true,
+ none: "discourse_workflows.workflow_call.workflow_id_placeholder",
+ },
+ },
+ mapping_mode: {
+ type: :options,
+ required: true,
+ default: AUTO,
+ options: MAPPING_MODES,
+ no_data_expression: true,
+ },
+ fields: {
+ type: :assignment_collection,
+ required: false,
+ default: {
+ assignments: [],
+ },
+ type_options: {
+ assignment_types: %w[string number boolean array object],
+ },
+ display_options: {
+ show: {
+ mapping_mode: [MANUAL],
+ },
+ },
+ },
+ },
+ i18n_scope: "workflow_call",
+ )
+
+ def self.load_options_context(context)
+ case context.method_name
+ when "callable_workflows"
+ callable_workflow_options(context)
+ end
+ end
+
+ def self.callable_workflow_options(context)
+ scope =
+ DiscourseWorkflows::Workflow
+ .published
+ .joins(:workflow_dependencies)
+ .where(
+ discourse_workflows_workflow_dependencies: {
+ dependency_type: "node_type",
+ dependency_key: DiscourseWorkflows::Nodes::WorkflowCallTrigger::V1.identifier,
+ },
+ )
+ .where(
+ "discourse_workflows_workflows.active_version_id = " \
+ "discourse_workflows_workflow_dependencies.workflow_version_id",
+ )
+ scope = scope.where.not(id: context.workflow_id) if context.workflow_id.present?
+ scope = scope.filter_by_name(context.filter) if context.filter.present?
+
+ scope.distinct.order(:name).pluck(:id, :name).map { |id, name| { id:, name: } }
+ end
+ private_class_method :callable_workflow_options
+
+ def execute(exec_ctx)
+ mapping_mode = exec_ctx.get_node_parameter("mapping_mode", 0, default: AUTO)
+
+ call = prepare_call(exec_ctx, mapping_mode:)
+
+ exec_ctx.put_execution_to_wait(
+ nil,
+ kind: "workflow_call",
+ payload: wait_payload(exec_ctx, call),
+ )
+ [exec_ctx.input_items]
+ end
+
+ private
+
+ def prepare_call(exec_ctx, mapping_mode:)
+ WorkflowCallPreparer.new(
+ exec_ctx:,
+ workflow_id: exec_ctx.get_node_parameter("workflow_id", 0),
+ trigger_data: trigger_data(exec_ctx, mapping_mode),
+ ).prepare
+ end
+
+ def trigger_data(exec_ctx, mapping_mode)
+ return manual_trigger_data(exec_ctx) if mapping_mode == MANUAL
+
+ exec_ctx.input_items.map { |item| item.fetch("json") { {} } }
+ end
+
+ def manual_trigger_data(exec_ctx)
+ exec_ctx.input_items.map.with_index { |_item, index| manual_payload(exec_ctx, index) }
+ end
+
+ def manual_payload(exec_ctx, item_index)
+ exec_ctx
+ .get_node_parameter("fields.assignments", item_index, default: [])
+ .each_with_object({}) do |field, result|
+ key = field["name"].to_s
+ next if key.blank?
+
+ value = cast_value(field["value"], field.fetch("type") { "string" })
+ set_field(result, key, value)
+ end
+ end
+
+ def cast_value(value, type)
+ cast_value!(value, type)
+ rescue JSON::ParserError, ArgumentError => e
+ raise_node_error!("Invalid field value", description: e.message)
+ end
+
+ def cast_value!(value, type)
+ case type
+ 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)
+ when "object"
+ cast_json_value(value, Hash)
+ else
+ value.to_s
+ end
+ end
+
+ def cast_json_value(value, expected_class)
+ return value if value.is_a?(expected_class)
+
+ parsed = JSON.parse(value.to_s)
+ return parsed if parsed.is_a?(expected_class)
+
+ expected_type = expected_class == Array ? "array" : "object"
+ raise_node_error!("Invalid field value", description: "Expected #{expected_type}")
+ end
+
+ def set_field(result, field, value)
+ if field.exclude?(".")
+ 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 wait_payload(exec_ctx, call)
+ {
+ "user_id" => exec_ctx.user&.id,
+ "call" => {
+ "workflow_id" => call.workflow.id,
+ "workflow_version_id" => call.workflow_version.version_id,
+ "trigger_data" => call.trigger_data,
+ },
+ }
+ end
+ end
+ end
+ end
+end
diff --git a/plugins/discourse-workflows/lib/discourse_workflows/nodes/workflow_call_trigger/v1.rb b/plugins/discourse-workflows/lib/discourse_workflows/nodes/workflow_call_trigger/v1.rb
new file mode 100644
index 00000000000..68253c93e58
--- /dev/null
+++ b/plugins/discourse-workflows/lib/discourse_workflows/nodes/workflow_call_trigger/v1.rb
@@ -0,0 +1,29 @@
+# frozen_string_literal: true
+
+module DiscourseWorkflows
+ module Nodes
+ module WorkflowCallTrigger
+ class V1 < NodeType
+ description(
+ name: "trigger:workflow_call",
+ version: "1.0",
+ defaults: {
+ icon: "arrows-turn-to-dots",
+ color: "teal",
+ },
+ inputs: [],
+ max_nodes: 1,
+ capabilities: {
+ manually_triggerable: true,
+ provides_current_user: true,
+ },
+ i18n_scope: "workflow_call_trigger",
+ )
+
+ def output
+ {}
+ end
+ end
+ end
+ end
+end
diff --git a/plugins/discourse-workflows/lib/discourse_workflows/workflow_call_continuation.rb b/plugins/discourse-workflows/lib/discourse_workflows/workflow_call_continuation.rb
new file mode 100644
index 00000000000..6b9f554ef35
--- /dev/null
+++ b/plugins/discourse-workflows/lib/discourse_workflows/workflow_call_continuation.rb
@@ -0,0 +1,198 @@
+# frozen_string_literal: true
+
+module DiscourseWorkflows
+ class WorkflowCallContinuation
+ class << self
+ def begin_child_call!(execution:, node:, request:)
+ payload = request.payload.deep_stringify_keys
+ call = payload.fetch("call")
+
+ run =
+ WorkflowCallRun.create!(
+ parent_execution_id: execution.id,
+ parent_node_id: node.id,
+ parent_resume_token: execution.resume_token,
+ target_workflow_id: call.fetch("workflow_id"),
+ target_workflow_version_id: call.fetch("workflow_version_id"),
+ user_id: payload["user_id"],
+ trigger_data: call.fetch("trigger_data"),
+ )
+
+ enqueue_run(run)
+ end
+
+ def run!(run_id:)
+ return unless SiteSetting.discourse_workflows_enabled
+
+ run = WorkflowCallRun.find_by(id: run_id)
+ return if run.blank?
+
+ run_workflow_call!(run)
+ end
+
+ def child_succeeded!(execution)
+ run = transition_run!(execution, status: :success) or return
+
+ resume_parent_success(run)
+ end
+
+ def child_failed!(execution)
+ message = execution_failed_message(execution)
+ run = transition_run!(execution, status: :error, error: message) or return
+
+ finalize_failed!(run, DiscourseWorkflows::NodeError.new(message))
+ end
+
+ def workflow_call_stack_for(parent_execution, visited = Set.new)
+ return [] unless visited.add?(parent_execution.id)
+
+ parent_run = WorkflowCallRun.find_by(child_execution_id: parent_execution.id)
+ stack =
+ if parent_run
+ workflow_call_stack_for(parent_run.parent_execution, visited)
+ else
+ []
+ end
+
+ stack + [parent_execution.workflow_id.to_s]
+ end
+
+ def caller_metadata_for(child_execution)
+ run = WorkflowCallRun.find_by(child_execution_id: child_execution.id)
+ run && caller_metadata(run)
+ end
+
+ private
+
+ def transition_run!(execution, status:, error: nil)
+ run = WorkflowCallRun.find_by(child_execution_id: execution.id)
+ return if run.blank?
+
+ updated =
+ WorkflowCallRun
+ .active
+ .where(id: run.id)
+ .update_all(
+ status: WorkflowCallRun.statuses[status],
+ error: error,
+ updated_at: Time.current,
+ )
+ return if updated.zero?
+
+ run.reload
+ end
+
+ def enqueue_run(run)
+ Jobs.enqueue(Jobs::DiscourseWorkflows::RunWorkflowCall, run_id: run.id)
+ end
+
+ def run_workflow_call!(run)
+ claimed = WorkflowCallRun.claim_pending(run)
+ return if claimed.blank?
+
+ workflow = Workflow.find_by(id: claimed.target_workflow_id)
+ workflow_version =
+ WorkflowVersion.find_by(
+ workflow_id: claimed.target_workflow_id,
+ version_id: claimed.target_workflow_version_id,
+ )
+ trigger_node = Nodes::WorkflowCallTrigger::V1.find_in(workflow_version&.nodes)
+
+ if workflow.blank? || workflow_version.blank? || trigger_node.blank?
+ return(
+ fail_run!(
+ claimed,
+ I18n.t("discourse_workflows.errors.workflow_call.target_not_callable"),
+ )
+ )
+ end
+
+ executor =
+ Executor.new(
+ workflow,
+ trigger_node["id"],
+ claimed.trigger_data,
+ Executor::ExecutionOptions.new(
+ user: claimed.user,
+ workflow_version: workflow_version,
+ workflow_call_stack: workflow_call_stack_for(claimed.parent_execution),
+ workflow_call_caller: caller_metadata(claimed),
+ workflow_call_run_id: claimed.id,
+ ),
+ )
+ execution = executor.run
+
+ claimed.update!(child_execution_id: execution.id, status: :waiting) if execution.waiting?
+ rescue => e
+ fail_run!(claimed || run, e.message)
+ end
+
+ def fail_run!(run, message)
+ run.update!(status: :error, error: message)
+ finalize_failed!(run, DiscourseWorkflows::NodeError.new(message))
+ end
+
+ def finalize_failed!(run, error)
+ resume_parent_error(run, error)
+ end
+
+ def resume_parent_success(run)
+ with_claimed_parent(run) do |claimed|
+ DiscourseWorkflows::Executor.resume(claimed, child_output_items(run))
+ end
+ end
+
+ def resume_parent_error(run, error)
+ with_claimed_parent(run) do |claimed|
+ DiscourseWorkflows::Executor.resume_with_error(claimed, error)
+ end
+ end
+
+ def with_claimed_parent(run)
+ claimed =
+ DiscourseWorkflows::Execution.claim_for_resume(
+ run.parent_execution.reload,
+ resume_token: run.parent_resume_token,
+ )
+ yield claimed if claimed.present?
+ end
+
+ def child_output_items(run)
+ output = run.child_execution.execution_data&.steps_array&.last&.dig("output") || []
+ output.map { |item| item.except(Item::PAIRED_ITEM_KEY) }
+ end
+
+ def caller_metadata(run)
+ parent = run.parent_execution
+ node = parent.workflow_node(run.parent_node_id) || {}
+ workflow_id = parent.workflow_id
+ execution_id = parent.id
+
+ {
+ "workflow_id" => workflow_id,
+ "workflow_name" => parent.workflow_snapshot_name,
+ "execution_id" => execution_id,
+ "execution_url" =>
+ DiscourseWorkflows::Execution.admin_execution_url(workflow_id, execution_id),
+ "node_id" => node["id"] || run.parent_node_id,
+ "node_name" => node["name"],
+ "node_type" => node["type"],
+ }.compact
+ end
+
+ def execution_failed_message(execution)
+ status = execution&.status || "unknown"
+ error = execution&.error.presence
+ if error.present?
+ I18n.t(
+ "discourse_workflows.errors.workflow_call.execution_failed_with_error",
+ status: status,
+ error: error,
+ )
+ else
+ I18n.t("discourse_workflows.errors.workflow_call.execution_failed", status: status)
+ end
+ end
+ end
+ end
+end
diff --git a/plugins/discourse-workflows/lib/discourse_workflows/workflow_call_preparer.rb b/plugins/discourse-workflows/lib/discourse_workflows/workflow_call_preparer.rb
new file mode 100644
index 00000000000..b8b1411ea11
--- /dev/null
+++ b/plugins/discourse-workflows/lib/discourse_workflows/workflow_call_preparer.rb
@@ -0,0 +1,85 @@
+# frozen_string_literal: true
+
+module DiscourseWorkflows
+ class WorkflowCallPreparer
+ include DiscourseWorkflows::NodeErrorHandling
+
+ MAX_WORKFLOW_CALL_DEPTH = 10
+ MAX_TRIGGER_DATA_BYTES = 1.megabyte
+
+ PreparedCall = Data.define(:workflow, :workflow_version, :trigger_data)
+
+ def initialize(exec_ctx:, workflow_id:, trigger_data:)
+ @exec_ctx = exec_ctx
+ @workflow_id = workflow_id.to_s
+ @trigger_data = trigger_data
+ end
+
+ def prepare
+ validate_workflow_id!
+ @exec_ctx.ensure_workflow_call_access!(@workflow_id)
+ ensure_stack_allows_call!
+ ensure_trigger_data_within_budget!
+
+ workflow = target_workflow
+ workflow_version = workflow&.active_version
+ ensure_callable_workflow!(workflow)
+
+ PreparedCall.new(
+ workflow: workflow,
+ workflow_version: workflow_version,
+ trigger_data: @trigger_data,
+ )
+ end
+
+ private
+
+ def validate_workflow_id!
+ if @workflow_id.blank?
+ raise_node_error!(I18n.t("discourse_workflows.errors.workflow_call.workflow_required"))
+ end
+ end
+
+ def ensure_trigger_data_within_budget!
+ return if @trigger_data.to_json.bytesize <= MAX_TRIGGER_DATA_BYTES
+
+ raise_node_error!(
+ I18n.t(
+ "discourse_workflows.errors.workflow_call.payload_too_large",
+ max: MAX_TRIGGER_DATA_BYTES,
+ ),
+ )
+ end
+
+ def ensure_stack_allows_call!
+ stack = @exec_ctx.workflow_call_stack.map(&:to_s)
+
+ if stack.include?(@workflow_id)
+ raise_node_error!(I18n.t("discourse_workflows.errors.workflow_call.recursive_call"))
+ end
+
+ if stack.length >= MAX_WORKFLOW_CALL_DEPTH
+ raise_node_error!(
+ I18n.t(
+ "discourse_workflows.errors.workflow_call.max_depth_exceeded",
+ max: MAX_WORKFLOW_CALL_DEPTH,
+ ),
+ )
+ end
+ end
+
+ def target_workflow
+ @target_workflow ||= Workflow.includes(:active_version).find_by(id: @workflow_id)
+ end
+
+ def ensure_callable_workflow!(workflow)
+ if workflow.nil?
+ raise_node_error!(I18n.t("discourse_workflows.errors.workflow_call.target_not_found"))
+ end
+
+ unless workflow.callable_as_subworkflow?
+ raise_node_error!(I18n.t("discourse_workflows.errors.workflow_call.target_not_callable"))
+ end
+ end
+ 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
index 08d3ce99a50..cd6e64c022e 100644
--- a/plugins/discourse-workflows/lib/discourse_workflows/workflow_dependency_indexer.rb
+++ b/plugins/discourse-workflows/lib/discourse_workflows/workflow_dependency_indexer.rb
@@ -40,6 +40,11 @@ module DiscourseWorkflows
if (dt_id = parameters["data_table_id"]).present?
rows << build_row("data_table_id", dt_id, node_id)
end
+
+ if node_type == DiscourseWorkflows::Nodes::WorkflowCall::V1.identifier &&
+ (workflow_id = parameters["workflow_id"]).present?
+ rows << build_row("workflow_call", workflow_id, node_id)
+ end
end
if @workflow.error_workflow_id.present?
diff --git a/plugins/discourse-workflows/lib/discourse_workflows/workflow_graph_validator.rb b/plugins/discourse-workflows/lib/discourse_workflows/workflow_graph_validator.rb
index 006dbfa2ed8..e8aa6e90303 100644
--- a/plugins/discourse-workflows/lib/discourse_workflows/workflow_graph_validator.rb
+++ b/plugins/discourse-workflows/lib/discourse_workflows/workflow_graph_validator.rb
@@ -39,6 +39,7 @@ module DiscourseWorkflows
return false if workflow.errors.any?
validate_connections
+ validate_workflow_call_dependencies
workflow.errors.empty?
end
@@ -209,6 +210,87 @@ module DiscourseWorkflows
end
end
+ def validate_workflow_call_dependencies
+ calls = workflow_call_nodes
+ return if calls.empty?
+
+ target_ids = calls.filter_map { |node| workflow_call_target_id(node) }
+ targets_by_id =
+ DiscourseWorkflows::Workflow.includes(:active_version).where(id: target_ids).index_by(&:id)
+
+ calls.each do |node|
+ validate_workflow_call_target(node, targets_by_id[workflow_call_target_id(node)])
+ end
+
+ validate_workflow_call_cycles(calls) if workflow.errors.empty?
+ end
+
+ def validate_workflow_call_target(node, target_workflow)
+ target_id = workflow_call_target_id(node)
+ return if target_id.blank?
+
+ if workflow.id.present? && target_id == workflow.id
+ return add_call_error(:self_reference, node: node["name"])
+ end
+
+ return add_call_error(:target_not_found) if target_workflow.nil?
+ return if target_workflow.callable_as_subworkflow?
+
+ add_call_error(:target_not_callable)
+ end
+
+ def validate_workflow_call_cycles(calls)
+ return if workflow.id.blank?
+
+ edges = active_workflow_call_edges
+ edges[workflow.id] = calls.filter_map { |node| workflow_call_target_id(node) }.to_set
+
+ calls.each do |node|
+ target_id = workflow_call_target_id(node)
+ next if target_id.blank?
+
+ next unless workflow_call_reaches?(target_id, workflow.id, edges, Set.new)
+
+ add_call_error(:cycle, node: node["name"])
+ end
+ end
+
+ def add_call_error(key, **args)
+ workflow.errors.add(:base, I18n.t("discourse_workflows.errors.workflow_call.#{key}", **args))
+ end
+
+ def workflow_call_nodes
+ nodes.select { |node| node["type"] == DiscourseWorkflows::Nodes::WorkflowCall::V1.identifier }
+ end
+
+ def workflow_call_target_id(node)
+ to_workflow_id(DiscourseWorkflows::NodeData.parameters(node)["workflow_id"])
+ end
+
+ def to_workflow_id(value)
+ Integer(value, exception: false) if value.present?
+ end
+
+ def active_workflow_call_edges
+ DiscourseWorkflows::WorkflowDependency
+ .of_type("workflow_call")
+ .on_active_version
+ .pluck(:workflow_id, :dependency_key)
+ .each_with_object(
+ Hash.new { |hash, key| hash[key] = Set.new },
+ ) do |(source_id, target_key), edges|
+ target_id = to_workflow_id(target_key)
+ edges[source_id] << target_id if target_id
+ end
+ end
+
+ def workflow_call_reaches?(start_id, target_id, edges, visited)
+ return true if start_id == target_id
+ return false unless visited.add?(start_id)
+
+ edges[start_id].any? { |next_id| workflow_call_reaches?(next_id, target_id, edges, visited) }
+ end
+
def connection_records
DiscourseWorkflows::WorkflowDocument.connection_records(nodes, connections_data)
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
index 550ff02580d..fa137f7690f 100644
--- a/plugins/discourse-workflows/spec/lib/discourse_workflows/executor_spec.rb
+++ b/plugins/discourse-workflows/spec/lib/discourse_workflows/executor_spec.rb
@@ -381,7 +381,6 @@ RSpec.describe DiscourseWorkflows::Executor do
g.node "log-1",
"action:log",
configuration: {
- "alwaysOutputData" => true,
"entries" => {
"values" => [{ "key" => "topic", "value" => "={{ $json.topic_id }}" }],
},
@@ -401,7 +400,7 @@ RSpec.describe DiscourseWorkflows::Executor do
expect(logs.first).to include("key" => "topic", "value" => topic.id.to_s)
end
- it "does not route downstream when log returns no output" do
+ it "routes downstream with log input items" do
graph =
build_workflow_graph do |g|
g.node "trigger-1", "trigger:topic_closed"
@@ -412,8 +411,16 @@ RSpec.describe DiscourseWorkflows::Executor do
"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"
+ g.node "set-fields-1",
+ "action:set_fields",
+ configuration: {
+ "assignments" => {
+ "assignments" => [
+ { "name" => "logged", "value" => "true", "type" => "boolean" },
+ ],
+ },
+ }
+ g.chain "trigger-1", "log-1", "set-fields-1"
end
workflow =
Fabricate(:discourse_workflows_workflow, created_by: user, published: true, **graph)
@@ -423,19 +430,23 @@ RSpec.describe DiscourseWorkflows::Executor do
expect(execution.status).to eq("success")
+ expected_item = { "json" => trigger_data.stringify_keys, "pairedItem" => { "item" => 0 } }
log_step = execution.execution_data.find_step(node_id: "log-1")
- expect(log_step["output"]).to eq([])
+ expect(log_step["output"]).to eq([expected_item])
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
+ set_fields_step = execution.execution_data.find_step(node_id: "set-fields-1")
+ expect(set_fields_step["output"]).to eq(
+ [expected_item.deep_merge("json" => { "logged" => true })],
+ )
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
+ expect(run_data.dig("Log-1", 0, "outputs", 0, "item_count")).to eq(1)
+ expect(run_data.dig("Log-1", 0, "outputs", 0, "items")).to eq([expected_item])
+ expect(run_data.dig(set_fields_step["node_name"], 0, "inputs", 0, "item_count")).to eq(1)
end
it "fails the step when expression errors are logged" do
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
index da1fa54cdbf..79918bcd854 100644
--- 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
@@ -25,6 +25,7 @@ RSpec.describe DiscourseWorkflows::ExpressionContextSchema do
"id",
"workflow_id",
"workflow_name",
+ "called_by",
"resume_url",
"resumeFormUrl",
)
@@ -48,6 +49,15 @@ RSpec.describe DiscourseWorkflows::ExpressionContextSchema do
)
end
+ it "marks called_by as conditionally visible for workflow call triggers" do
+ field = described_class.environment_symbols.dig("$execution", :fields, "called_by")
+ expect(field[:display_options]).to eq(
+ show: {
+ node_present: [{ type: "trigger:workflow_call" }],
+ },
+ )
+ 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)
@@ -147,6 +157,21 @@ RSpec.describe DiscourseWorkflows::ExpressionContextSchema do
sandbox&.dispose
end
+ it "omits $execution.called_by for normal executions" 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,
+ )
+
+ expect(context.resolver_context["__execution"]).not_to have_key("called_by")
+ end
+
it "ExpressionResolver exposes current-input helpers" do
context = {
"$json" => {
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
index b4f20a701e5..b212f7a17ae 100644
--- 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
@@ -6,7 +6,7 @@ RSpec.describe DiscourseWorkflows::Nodes::Log::V1 do
end
describe "#execute" do
- it "returns no output items" do
+ it "passes input items through" do
items = [{ "json" => { "name" => "Alice" } }, { "json" => { "count" => 42 } }]
result =
execute_node_output(
@@ -15,7 +15,7 @@ RSpec.describe DiscourseWorkflows::Nodes::Log::V1 do
},
input_items: items,
)
- expect(result.first).to eq([])
+ expect(result.first).to eq(items)
end
it "records structured key/value logs" do
@@ -52,7 +52,7 @@ RSpec.describe DiscourseWorkflows::Nodes::Log::V1 do
"value" => "Bob",
)
end
- expect(result.first).to eq([])
+ expect(result.first).to eq(items)
end
it "handles empty entries gracefully" do
@@ -61,7 +61,7 @@ RSpec.describe DiscourseWorkflows::Nodes::Log::V1 do
execute_node_output(configuration: { "entries" => entries }, input_items: items) do |ctx|
expect(ctx.log.entries).to be_empty
end
- expect(result.first).to eq([])
+ expect(result.first).to eq(items)
end
it "handles missing entries key" do
@@ -70,7 +70,7 @@ RSpec.describe DiscourseWorkflows::Nodes::Log::V1 do
execute_node_output(configuration: {}, input_items: items) do |ctx|
expect(ctx.log.entries).to be_empty
end
- expect(result.first).to eq([])
+ expect(result.first).to eq(items)
end
it "defaults to runOnceForEachItem, resolving expressions per item" do
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
index cc6752de1ff..670bbe135d3 100644
--- 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
@@ -16,6 +16,12 @@ RSpec.describe DiscourseWorkflows::Nodes::Wait::V1 do
)
end
+ describe ".capabilities" do
+ it "marks the node as not producing data" do
+ expect(described_class.capabilities).to include(produces_data: false)
+ end
+ end
+
describe "#execute" do
it "returns input items for interval mode" do
config = { "resume" => "time_interval", "wait_amount" => 2, "wait_unit" => "hours" }
diff --git a/plugins/discourse-workflows/spec/lib/discourse_workflows/nodes/workflow_call_spec.rb b/plugins/discourse-workflows/spec/lib/discourse_workflows/nodes/workflow_call_spec.rb
new file mode 100644
index 00000000000..c4251ae6449
--- /dev/null
+++ b/plugins/discourse-workflows/spec/lib/discourse_workflows/nodes/workflow_call_spec.rb
@@ -0,0 +1,796 @@
+# frozen_string_literal: true
+
+RSpec.describe DiscourseWorkflows::Nodes::WorkflowCall::V1 do
+ fab!(:admin)
+
+ def assignment(name, value, type: "string")
+ { "name" => name, "type" => type, "value" => value }
+ end
+
+ def execute_workflow(workflow, trigger_node_id: "trigger-1", trigger_data: { "name" => "Ada" })
+ executor =
+ DiscourseWorkflows::Executor.new(
+ workflow,
+ trigger_node_id,
+ trigger_data,
+ DiscourseWorkflows::Executor::ExecutionOptions.new(
+ user: admin,
+ workflow_version: workflow.active_version,
+ ),
+ )
+ executor.run
+ executor.execution
+ end
+
+ def run_workflow_call_job
+ job = Jobs::DiscourseWorkflows::RunWorkflowCall.jobs.shift
+ expect(job).to be_present
+
+ Jobs::DiscourseWorkflows::RunWorkflowCall.new.execute(job["args"].first.symbolize_keys)
+ end
+
+ def run_workflow_call_jobs
+ count = 0
+
+ while Jobs::DiscourseWorkflows::RunWorkflowCall.jobs.any?
+ run_workflow_call_job
+ count += 1
+ end
+
+ count
+ end
+
+ def resume_child_execution(child_execution, response_items = nil)
+ claimed = DiscourseWorkflows::Execution.claim_for_resume(child_execution.reload)
+ expect(claimed).to be_present
+
+ DiscourseWorkflows::Executor.resume(claimed, response_items || claimed.waiting_step_input_items)
+ end
+
+ def expect_parent_waiting_at_call(execution, node_id: "call-1")
+ expect(execution).to have_attributes(
+ status: "waiting",
+ waiting_node_id: node_id,
+ waiting_until: nil,
+ )
+
+ call_step = execution.execution_data.find_step(node_id: node_id)
+ expect(call_step["status"]).to eq("waiting")
+ expect(Jobs::DiscourseWorkflows::ResumeWaitingExecution.jobs).to be_empty
+ call_step
+ end
+
+ def serialized_step(execution, node_id: "call-1")
+ serialized_execution =
+ DiscourseWorkflows::ExecutionSerializer.new(execution.reload, root: false).as_json
+
+ serialized_execution[:steps].find { |step| step[:node_id] == node_id }
+ end
+
+ def expected_called_by(caller, execution, node_id: "call-1", node_name: "Call workflow")
+ {
+ "workflow_id" => caller.id,
+ "workflow_name" => caller.name,
+ "execution_id" => execution.id,
+ "execution_url" =>
+ "#{Discourse.base_url}/admin/plugins/discourse-workflows/workflows/" \
+ "#{caller.id}/executions/#{execution.id}",
+ "node_id" => node_id,
+ "node_name" => node_name,
+ "node_type" => "action:workflow_call",
+ }
+ end
+
+ def callable_workflow_with_set_fields(assignments, trigger_id: "call-trigger")
+ graph =
+ build_workflow_graph do |workflow_graph|
+ workflow_graph.node trigger_id, "trigger:workflow_call", name: "Workflow call"
+ workflow_graph.node "set-fields",
+ "action:set_fields",
+ name: "Set fields",
+ configuration: {
+ "assignments" => {
+ "assignments" => assignments,
+ },
+ }
+ workflow_graph.chain trigger_id, "set-fields"
+ end
+
+ Fabricate(:discourse_workflows_workflow, created_by: admin, published: true, **graph)
+ end
+
+ def callable_workflow_with_wait(
+ wait_type,
+ wait_configuration,
+ assignments: [assignment("called", "yes")]
+ )
+ graph =
+ build_workflow_graph do |workflow_graph|
+ workflow_graph.node "call-trigger", "trigger:workflow_call", name: "Workflow call"
+ workflow_graph.node "wait-1", wait_type, name: "Wait", configuration: wait_configuration
+ workflow_graph.node "set-fields",
+ "action:set_fields",
+ name: "Set fields",
+ configuration: {
+ "assignments" => {
+ "assignments" => assignments,
+ },
+ }
+ workflow_graph.chain "call-trigger", "wait-1", "set-fields"
+ end
+
+ Fabricate(:discourse_workflows_workflow, created_by: admin, published: true, **graph)
+ end
+
+ def caller_workflow_for(target, call_configuration: {}, after_call: false)
+ caller_graph =
+ build_workflow_graph do |workflow_graph|
+ workflow_graph.node "trigger-1", "trigger:manual", name: "Manual"
+ workflow_graph.node "call-1",
+ "action:workflow_call",
+ name: "Call workflow",
+ configuration: { "workflow_id" => target.id }.merge(call_configuration)
+ if after_call
+ workflow_graph.node "after",
+ "action:set_fields",
+ name: "After",
+ configuration: {
+ "assignments" => {
+ "assignments" => [assignment("after", "yes")],
+ },
+ }
+ workflow_graph.chain "trigger-1", "call-1", "after"
+ else
+ workflow_graph.chain "trigger-1", "call-1"
+ end
+ end
+
+ Fabricate(:discourse_workflows_workflow, created_by: admin, published: true, **caller_graph)
+ end
+
+ def failing_callable_workflow
+ graph =
+ build_workflow_graph do |workflow_graph|
+ workflow_graph.node "call-trigger", "trigger:workflow_call", name: "Workflow call"
+ workflow_graph.node "wait-1",
+ "flow:wait",
+ name: "Invalid wait",
+ configuration: {
+ "resume" => "time_interval",
+ "wait_amount" => 0,
+ "wait_unit" => "seconds",
+ }
+ workflow_graph.chain "call-trigger", "wait-1"
+ end
+
+ Fabricate(:discourse_workflows_workflow, created_by: admin, published: true, **graph)
+ end
+
+ describe "#execute" do
+ it "pauses the parent, runs a published callable workflow job, and returns its output" do
+ target = callable_workflow_with_set_fields([assignment("called", "yes")])
+ caller = caller_workflow_for(target)
+
+ execution = execute_workflow(caller)
+ call_step = expect_parent_waiting_at_call(execution)
+
+ expect(Jobs::DiscourseWorkflows::RunWorkflowCall.jobs.size).to eq(1)
+ expect(call_step["metadata"] || {}).not_to have_key("workflow_call")
+ workflow_call_run = serialized_step(execution)[:workflow_call_run]
+ expect(workflow_call_run).to include(
+ "workflow_id" => target.id,
+ "workflow_name" => target.name,
+ "status" => "pending",
+ )
+ expect(workflow_call_run).not_to have_key("execution_id")
+
+ expect(run_workflow_call_jobs).to eq(1)
+
+ execution.reload
+ call_step = execution.execution_data.find_step(node_id: "call-1")
+ expect(execution).to be_success
+ expect(call_step["output"].map { |item| item["json"] }).to eq(
+ [{ "name" => "Ada", "called" => "yes" }],
+ )
+ expect(call_step.dig("output", 0, "json")).not_to have_key("workflow_call")
+ expect(call_step["metadata"] || {}).not_to have_key("workflow_call")
+ expect(serialized_step(execution)[:workflow_call_run]).to include(
+ "workflow_id" => target.id,
+ "workflow_name" => target.name,
+ "execution_id" => DiscourseWorkflows::WorkflowCallRun.last.child_execution_id,
+ "status" => "success",
+ )
+ end
+
+ it "records caller details on the called workflow trigger" do
+ target =
+ callable_workflow_with_set_fields(
+ [assignment("called_by", "={{ $execution.called_by }}", type: "object")],
+ )
+ caller = caller_workflow_for(target)
+
+ execution = execute_workflow(caller)
+ expect_parent_waiting_at_call(execution)
+ run_workflow_call_jobs
+
+ execution.reload
+ call_step = execution.execution_data.find_step(node_id: "call-1")
+ child_execution_id = serialized_step(execution).dig(:workflow_call_run, "execution_id")
+ child_execution = DiscourseWorkflows::Execution.find(child_execution_id)
+ trigger_step = child_execution.execution_data.find_step(node_id: "call-trigger")
+ expected_caller = expected_called_by(caller, execution)
+
+ expect(execution).to be_success
+ expect(call_step.dig("output", 0, "json", "called_by")).to eq(expected_caller)
+ expect(trigger_step.dig("output", 0, "json", "name")).to eq("Ada")
+ expect(trigger_step.dig("output", 0, "json")).not_to have_key("workflow_call")
+ expect(trigger_step["metadata"] || {}).not_to have_key("workflow_call")
+ end
+
+ it "passes every input item to the sub-workflow in a single call" do
+ target = callable_workflow_with_set_fields([assignment("called", "yes")])
+ caller = caller_workflow_for(target)
+
+ execution =
+ execute_workflow(caller, trigger_data: [{ "name" => "Ada" }, { "name" => "Grace" }])
+ expect_parent_waiting_at_call(execution)
+
+ expect(run_workflow_call_jobs).to eq(1)
+ expect(DiscourseWorkflows::WorkflowCallRun.count).to eq(1)
+
+ execution.reload
+ call_step = execution.execution_data.find_step(node_id: "call-1")
+ workflow_call_run = serialized_step(execution)[:workflow_call_run]
+ child_execution_id = workflow_call_run["execution_id"]
+ child_execution = DiscourseWorkflows::Execution.find(child_execution_id)
+ trigger_step = child_execution.execution_data.find_step(node_id: "call-trigger")
+
+ expect(execution).to be_success
+ expect(call_step["metadata"] || {}).not_to have_key("workflow_call")
+ expect(workflow_call_run["run_id"]).to eq(DiscourseWorkflows::WorkflowCallRun.last.id)
+ expect(trigger_step.dig("output").map { |item| item.dig("json", "name") }).to eq(
+ %w[Ada Grace],
+ )
+ end
+
+ it "passes manually mapped fields to the sub-workflow" do
+ target = callable_workflow_with_set_fields([assignment("called", "yes")])
+ caller =
+ caller_workflow_for(
+ target,
+ call_configuration: {
+ "mapping_mode" => "manual",
+ "fields" => {
+ "assignments" => [
+ assignment("full_name", "={{ $json.name }}"),
+ assignment("profile.score", "12.5", type: "number"),
+ assignment("active", "true", type: "boolean"),
+ assignment("tags", '["workflow"]', type: "array"),
+ assignment("source", "={{ $json }}", type: "object"),
+ ],
+ },
+ },
+ )
+
+ execution =
+ execute_workflow(caller, trigger_data: [{ "name" => "Ada" }, { "name" => "Grace" }])
+ expect_parent_waiting_at_call(execution)
+
+ expect(run_workflow_call_jobs).to eq(1)
+
+ execution.reload
+ call_step = execution.execution_data.find_step(node_id: "call-1")
+ child_execution_id = serialized_step(execution).dig(:workflow_call_run, "execution_id")
+ child_execution = DiscourseWorkflows::Execution.find(child_execution_id)
+ trigger_step = child_execution.execution_data.find_step(node_id: "call-trigger")
+ expected_items = [
+ {
+ "full_name" => "Ada",
+ "profile" => {
+ "score" => 12.5,
+ },
+ "active" => true,
+ "tags" => ["workflow"],
+ "source" => {
+ "name" => "Ada",
+ },
+ },
+ {
+ "full_name" => "Grace",
+ "profile" => {
+ "score" => 12.5,
+ },
+ "active" => true,
+ "tags" => ["workflow"],
+ "source" => {
+ "name" => "Grace",
+ },
+ },
+ ]
+
+ expect(execution).to be_success
+ expect(trigger_step["output"].map { |item| item["json"] }).to eq(expected_items)
+ expect(call_step["output"].map { |item| item["json"] }).to eq(
+ expected_items.map { |item| item.merge("called" => "yes") },
+ )
+ end
+
+ it "returns the last node output" do
+ target_graph =
+ build_workflow_graph do |workflow_graph|
+ workflow_graph.node "call-trigger", "trigger:workflow_call", name: "Workflow call"
+ workflow_graph.node "first",
+ "action:set_fields",
+ name: "First",
+ configuration: {
+ "assignments" => {
+ "assignments" => [assignment("first", "yes")],
+ },
+ }
+ workflow_graph.node "second",
+ "action:set_fields",
+ name: "Second",
+ configuration: {
+ "assignments" => {
+ "assignments" => [assignment("second", "yes")],
+ },
+ }
+ workflow_graph.chain "call-trigger", "first", "second"
+ end
+ target =
+ Fabricate(:discourse_workflows_workflow, created_by: admin, published: true, **target_graph)
+ caller = caller_workflow_for(target)
+
+ execution = execute_workflow(caller)
+ expect_parent_waiting_at_call(execution)
+ run_workflow_call_jobs
+
+ execution.reload
+ call_step = execution.execution_data.find_step(node_id: "call-1")
+ expect(execution).to be_success
+ expect(call_step["output"].map { |item| item["json"] }).to eq(
+ [{ "name" => "Ada", "first" => "yes", "second" => "yes" }],
+ )
+ end
+
+ it "fails the node when a manual object field is invalid JSON" do
+ target = callable_workflow_with_set_fields([assignment("called", "yes")])
+ caller =
+ caller_workflow_for(
+ target,
+ call_configuration: {
+ "mapping_mode" => "manual",
+ "fields" => {
+ "assignments" => [assignment("payload", "{ not valid json", type: "object")],
+ },
+ },
+ )
+
+ execution = execute_workflow(caller)
+
+ call_step = execution.execution_data.find_step(node_id: "call-1")
+ expect(execution).to be_error
+ expect(call_step["status"]).to eq("error")
+ expect(call_step["error"]).to include("Invalid field value")
+ expect(Jobs::DiscourseWorkflows::RunWorkflowCall.jobs).to be_empty
+ end
+
+ it "fails the node when the trigger payload exceeds the size budget" do
+ max_bytes = DiscourseWorkflows::WorkflowCallPreparer::MAX_TRIGGER_DATA_BYTES
+ target = callable_workflow_with_set_fields([assignment("called", "yes")])
+ caller =
+ caller_workflow_for(
+ target,
+ call_configuration: {
+ "mapping_mode" => "manual",
+ "fields" => {
+ "assignments" => [assignment("blob", "x" * (max_bytes + 1))],
+ },
+ },
+ )
+
+ execution = execute_workflow(caller)
+
+ call_step = execution.execution_data.find_step(node_id: "call-1")
+ expect(execution).to be_error
+ expect(call_step["status"]).to eq("error")
+ expect(call_step["error"]).to include(
+ I18n.t("discourse_workflows.errors.workflow_call.payload_too_large", max: max_bytes),
+ )
+ expect(Jobs::DiscourseWorkflows::RunWorkflowCall.jobs).to be_empty
+ end
+
+ [
+ [
+ "flow wait",
+ "flow:wait",
+ { "resume" => "time_interval", "wait_amount" => 1, "wait_unit" => "seconds" },
+ ],
+ ["webhook wait", "flow:wait", { "resume" => "webhook" }],
+ [
+ "form wait",
+ "action:form",
+ {
+ "form_title" => "Approval",
+ "form_fields" => [{ "field_label" => "Reason", "field_type" => "text" }],
+ },
+ ],
+ [
+ "modal wait",
+ "action:modal",
+ lambda do
+ {
+ "target_user" => admin.username,
+ "title" => "Approve?",
+ "body" => "Choose an option",
+ "buttons" => {
+ "values" => [{ "label" => "Approve", "value" => "approve", "style" => "primary" }],
+ },
+ }
+ end,
+ ],
+ ].each do |label, wait_type, wait_configuration|
+ it "keeps the parent waiting while a child #{label} is waiting" do
+ allow(MessageBus).to receive(:publish)
+ resolved_wait_configuration =
+ if wait_configuration.respond_to?(:call)
+ instance_exec(&wait_configuration)
+ else
+ wait_configuration
+ end
+ target = callable_workflow_with_wait(wait_type, resolved_wait_configuration)
+ caller = caller_workflow_for(target)
+
+ execution = execute_workflow(caller)
+ expect_parent_waiting_at_call(execution)
+ run_workflow_call_job
+
+ run = DiscourseWorkflows::WorkflowCallRun.last
+ child_execution = run.child_execution
+ expect(run).to be_waiting
+ expect(child_execution).to be_waiting
+ expect(execution.reload).to be_waiting
+ expect(
+ Jobs::DiscourseWorkflows::ResumeWaitingExecution.jobs.map do |job|
+ job["args"].first["execution_id"]
+ end,
+ ).to include(child_execution.id)
+
+ resume_child_execution(child_execution, [{ "json" => { "approved" => true } }])
+
+ execution.reload
+ call_step = execution.execution_data.find_step(node_id: "call-1")
+ expect(execution).to be_success
+ expect(call_step["output"].map { |item| item["json"] }).to eq(
+ [{ "approved" => true, "called" => "yes" }],
+ )
+ end
+ end
+
+ it "keeps $execution.called_by available to child nodes after the child waits and resumes" do
+ target =
+ callable_workflow_with_wait(
+ "flow:wait",
+ { "resume" => "webhook" },
+ assignments: [assignment("called_by", "={{ $execution.called_by }}", type: "object")],
+ )
+ caller = caller_workflow_for(target)
+
+ execution = execute_workflow(caller)
+ expect_parent_waiting_at_call(execution)
+ run_workflow_call_job
+
+ child_execution = DiscourseWorkflows::WorkflowCallRun.last.child_execution
+ expect(child_execution).to be_waiting
+
+ resume_child_execution(child_execution, [{ "json" => { "approved" => true } }])
+
+ set_fields_step = child_execution.reload.execution_data.find_step(node_id: "set-fields")
+ expect(execution.reload).to be_success
+ expect(set_fields_step.dig("output", 0, "json", "called_by")).to eq(
+ expected_called_by(caller, execution),
+ )
+ end
+
+ it "fails the parent node when the async child execution fails" do
+ target = failing_callable_workflow
+ caller = caller_workflow_for(target)
+
+ execution = execute_workflow(caller)
+ expect_parent_waiting_at_call(execution)
+ run_workflow_call_jobs
+
+ execution.reload
+ call_step = execution.execution_data.find_step(node_id: "call-1")
+ run = DiscourseWorkflows::WorkflowCallRun.last
+ expect(execution).to be_error
+ expect(execution.error).to include("finished with status 'error'")
+ expect(call_step["status"]).to eq("error")
+ expect(call_step["error"]).to include("finished with status 'error'")
+ expect(run).to be_error
+ end
+
+ it "continues through regular output when an async child failure uses continueOnFail" do
+ target = failing_callable_workflow
+ caller =
+ caller_workflow_for(
+ target,
+ call_configuration: {
+ "continueOnFail" => true,
+ },
+ after_call: true,
+ )
+
+ execution = execute_workflow(caller)
+ expect_parent_waiting_at_call(execution)
+ run_workflow_call_jobs
+
+ execution.reload
+ call_step = execution.execution_data.find_step(node_id: "call-1")
+ after_step = execution.execution_data.find_step(node_id: "after")
+ expect(execution).to be_success
+ expect(call_step["status"]).to eq("success")
+ expect(call_step.dig("metadata", "handled_error", "message")).to include(
+ "finished with status 'error'",
+ )
+ expect(after_step.dig("input", 0, "json")).to include("name" => "Ada")
+ end
+
+ it "routes async child failures through the error output" do
+ target = failing_callable_workflow
+ caller_graph =
+ build_workflow_graph do |workflow_graph|
+ workflow_graph.node "trigger-1", "trigger:manual", name: "Manual"
+ workflow_graph.node "call-1",
+ "action:workflow_call",
+ name: "Call workflow",
+ configuration: {
+ "workflow_id" => target.id,
+ "onError" => "continueErrorOutput",
+ }
+ workflow_graph.node "after",
+ "action:set_fields",
+ name: "After",
+ configuration: {
+ "assignments" => {
+ "assignments" => [assignment("after", "yes")],
+ },
+ }
+ workflow_graph.connect "trigger-1", "call-1"
+ workflow_graph.connect "call-1", "after", output: 1
+ end
+ caller =
+ Fabricate(:discourse_workflows_workflow, created_by: admin, published: true, **caller_graph)
+
+ execution = execute_workflow(caller)
+ expect_parent_waiting_at_call(execution)
+ run_workflow_call_jobs
+
+ execution.reload
+ call_step = execution.execution_data.find_step(node_id: "call-1")
+ after_step = execution.execution_data.find_step(node_id: "after")
+ expect(execution).to be_success
+ expect(call_step["status"]).to eq("success")
+ expect(after_step.dig("input", 0, "json")).to include("name" => "Ada")
+ expect(after_step.dig("input", 0, "error", "message")).to include(
+ "finished with status 'error'",
+ )
+ expect(after_step.dig("input", 0, "pairedItem")).to eq("item" => 0)
+ end
+
+ it "fails the parent when a waiting child times out" do
+ target =
+ callable_workflow_with_wait(
+ "flow:wait",
+ {
+ "resume" => "webhook",
+ "limit_wait_time" => true,
+ "timeout_amount" => 1,
+ "timeout_unit" => "seconds",
+ },
+ )
+ caller = caller_workflow_for(target)
+
+ execution = execute_workflow(caller)
+ expect_parent_waiting_at_call(execution)
+ run_workflow_call_job
+
+ run = DiscourseWorkflows::WorkflowCallRun.last
+ child_execution = run.child_execution
+ expect(child_execution).to be_waiting
+
+ child_execution.fail_with_timeout!
+
+ execution.reload
+ call_step = execution.execution_data.find_step(node_id: "call-1")
+ expect(execution).to be_error
+ expect(call_step["status"]).to eq("error")
+ expect(call_step["error"]).to include("timed out")
+ expect(run.reload).to be_error
+ end
+
+ it "ignores duplicate child terminal hooks" do
+ target = callable_workflow_with_set_fields([assignment("called", "yes")])
+ caller = caller_workflow_for(target)
+
+ execution = execute_workflow(caller)
+ expect_parent_waiting_at_call(execution)
+ run_workflow_call_jobs
+
+ run = DiscourseWorkflows::WorkflowCallRun.last
+ child_execution = run.child_execution
+ original_steps = execution.reload.execution_data.reload.steps_array
+
+ expect {
+ DiscourseWorkflows::WorkflowCallContinuation.child_succeeded!(child_execution.reload)
+ }.not_to change { execution.reload.execution_data.reload.steps_array }
+ expect(execution).to be_success
+ expect(original_steps).to eq(execution.execution_data.steps_array)
+ end
+
+ it "preserves the workflow-call stack when a child resumes after waiting" do
+ caller_graph =
+ build_workflow_graph do |workflow_graph|
+ workflow_graph.node "trigger-1", "trigger:workflow_call"
+ end
+ caller =
+ Fabricate(:discourse_workflows_workflow, created_by: admin, published: true, **caller_graph)
+ target_graph =
+ build_workflow_graph do |workflow_graph|
+ workflow_graph.node "target-trigger", "trigger:workflow_call", name: "Target trigger"
+ workflow_graph.node "wait-1", "flow:wait", configuration: { "resume" => "webhook" }
+ workflow_graph.node "target-call",
+ "action:workflow_call",
+ name: "Target call",
+ configuration: {
+ "workflow_id" => caller.id,
+ }
+ workflow_graph.chain "target-trigger", "wait-1", "target-call"
+ end
+ target =
+ Fabricate(:discourse_workflows_workflow, created_by: admin, published: true, **target_graph)
+ updated_caller_graph =
+ build_workflow_graph do |workflow_graph|
+ workflow_graph.node "trigger-1", "trigger:workflow_call", name: "Caller trigger"
+ workflow_graph.node "caller-call",
+ "action:workflow_call",
+ name: "Caller call",
+ configuration: {
+ "workflow_id" => target.id,
+ }
+ workflow_graph.chain "trigger-1", "caller-call"
+ end
+ caller.update!(
+ nodes: updated_caller_graph[:nodes],
+ connections: updated_caller_graph[:connections],
+ )
+ version = caller.snapshot!(user: admin)
+ caller.publish!(user: admin)
+ DiscourseWorkflows::WorkflowDependencyIndexer.call(caller, version: version)
+
+ execution = execute_workflow(caller)
+ expect_parent_waiting_at_call(execution, node_id: "caller-call")
+ run_workflow_call_job
+
+ run = DiscourseWorkflows::WorkflowCallRun.last
+ expect(run).to be_waiting
+
+ resume_child_execution(run.child_execution, [{ "json" => { "approved" => true } }])
+
+ execution.reload
+ expect(execution).to be_error
+ expect(execution.error).to include("Workflow call loop detected")
+ expect(Jobs::DiscourseWorkflows::RunWorkflowCall.jobs).to be_empty
+ end
+
+ it "detects recursive workflow calls at runtime" do
+ caller_graph =
+ build_workflow_graph do |workflow_graph|
+ workflow_graph.node "trigger-1", "trigger:workflow_call"
+ end
+ caller =
+ Fabricate(:discourse_workflows_workflow, created_by: admin, published: true, **caller_graph)
+ target_graph =
+ build_workflow_graph do |workflow_graph|
+ workflow_graph.node "target-trigger", "trigger:workflow_call", name: "Target trigger"
+ workflow_graph.node "target-call",
+ "action:workflow_call",
+ name: "Target call",
+ configuration: {
+ "workflow_id" => caller.id,
+ }
+ workflow_graph.chain "target-trigger", "target-call"
+ end
+ target =
+ Fabricate(:discourse_workflows_workflow, created_by: admin, published: true, **target_graph)
+ updated_caller_graph =
+ build_workflow_graph do |workflow_graph|
+ workflow_graph.node "trigger-1", "trigger:workflow_call", name: "Caller trigger"
+ workflow_graph.node "caller-call",
+ "action:workflow_call",
+ name: "Caller call",
+ configuration: {
+ "workflow_id" => target.id,
+ }
+ workflow_graph.chain "trigger-1", "caller-call"
+ end
+ caller.update!(
+ nodes: updated_caller_graph[:nodes],
+ connections: updated_caller_graph[:connections],
+ )
+ version = caller.snapshot!(user: admin)
+ caller.publish!(user: admin)
+ DiscourseWorkflows::WorkflowDependencyIndexer.call(caller, version: version)
+
+ execution = execute_workflow(caller)
+ expect_parent_waiting_at_call(execution, node_id: "caller-call")
+ run_workflow_call_jobs
+
+ execution.reload
+ expect(execution).to be_error
+ expect(execution.error).to include("Workflow call loop detected")
+ end
+ end
+
+ describe "call run cleanup" do
+ def completed_call
+ target = callable_workflow_with_set_fields([assignment("called", "yes")])
+ caller = caller_workflow_for(target)
+ execution = execute_workflow(caller)
+ run_workflow_call_jobs
+
+ run = DiscourseWorkflows::WorkflowCallRun.last
+ [execution.reload, run.reload, caller, target]
+ end
+
+ it "removes the run when its executions are purged by retention" do
+ _, run, _, _ = completed_call
+ SiteSetting.workflow_executions_retention_days = 30
+ DiscourseWorkflows::Execution.update_all(created_at: 60.days.ago)
+
+ DiscourseWorkflows::Execution.purge_old
+
+ expect(DiscourseWorkflows::WorkflowCallRun.exists?(run.id)).to eq(false)
+ end
+
+ it "removes the run when its executions are deleted by an admin" do
+ _, run, _, _ = completed_call
+
+ DiscourseWorkflows::Execution::Destroy.call(
+ params: {
+ execution_ids: [run.parent_execution_id, run.child_execution_id],
+ },
+ guardian: admin.guardian,
+ )
+
+ expect(DiscourseWorkflows::WorkflowCallRun.exists?(run.id)).to eq(false)
+ end
+
+ it "removes the run when the caller workflow is destroyed" do
+ _, run, caller, _ = completed_call
+
+ DiscourseWorkflows::Workflow::Destroy.call(
+ params: {
+ workflow_id: caller.id,
+ },
+ guardian: admin.guardian,
+ )
+
+ expect(DiscourseWorkflows::WorkflowCallRun.exists?(run.id)).to eq(false)
+ end
+
+ it "clears the back-reference when only the child execution is deleted" do
+ _, run, _, _ = completed_call
+
+ DiscourseWorkflows::Execution::Destroy.call(
+ params: {
+ execution_ids: [run.child_execution_id],
+ },
+ guardian: admin.guardian,
+ )
+
+ expect(run.reload.parent_execution_id).to be_present
+ expect(run.child_execution_id).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
index 750f097f8b2..cce2af6e41a 100644
--- 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
@@ -101,6 +101,21 @@ RSpec.describe DiscourseWorkflows::WorkflowDependencyIndexer do
expect(tables).to contain_exactly([data_table.id.to_s, "a1"])
end
+ it "extracts workflow_call dependencies" do
+ target = Fabricate(:discourse_workflows_workflow, created_by: admin)
+ graph =
+ build_workflow_graph do |g|
+ g.node "a1", "action:workflow_call", configuration: { "workflow_id" => target.id }
+ end
+ workflow = Fabricate(:discourse_workflows_workflow, created_by: admin, **graph)
+
+ index(workflow)
+
+ workflow_calls =
+ dependency_rows(workflow).of_type("workflow_call").pluck(:dependency_key, :node_id)
+ expect(workflow_calls).to contain_exactly([target.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" }
diff --git a/plugins/discourse-workflows/spec/plugin_helper.rb b/plugins/discourse-workflows/spec/plugin_helper.rb
index 5af8bd327c7..d4ab6753775 100644
--- a/plugins/discourse-workflows/spec/plugin_helper.rb
+++ b/plugins/discourse-workflows/spec/plugin_helper.rb
@@ -14,6 +14,7 @@ module DiscourseWorkflowsSpecHelper
Jobs::DiscourseWorkflows::ExecuteManualWorkflow.jobs.clear
Jobs::DiscourseWorkflows::ResumeWebhookWaiting.jobs.clear
Jobs::DiscourseWorkflows::ResumeWaitingExecution.jobs.clear
+ Jobs::DiscourseWorkflows::RunWorkflowCall.jobs.clear
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
index d9292c6c39a..7cf747766eb 100644
--- a/plugins/discourse-workflows/spec/requests/discourse_workflows/executions_controller_spec.rb
+++ b/plugins/discourse-workflows/spec/requests/discourse_workflows/executions_controller_spec.rb
@@ -173,6 +173,50 @@ RSpec.describe DiscourseWorkflows::ExecutionsController do
expect(json["execution"]["steps"].length).to eq(1)
end
+ it "returns caller workflow data for child executions" do
+ target_workflow = Fabricate(:discourse_workflows_workflow, created_by: admin)
+ child_execution =
+ Fabricate(:discourse_workflows_completed_execution, workflow: target_workflow)
+ Fabricate(:discourse_workflows_execution_data_with_steps, execution: child_execution)
+
+ execution.execution_data.update!(
+ workflow_data: {
+ "name" => "Parent workflow",
+ "nodes" => [
+ { "id" => "call-1", "name" => "Call child workflow", "type" => "action:workflow_call" },
+ ],
+ "connections" => {
+ },
+ },
+ )
+ DiscourseWorkflows::WorkflowCallRun.create!(
+ parent_execution: execution,
+ parent_node_id: "call-1",
+ parent_resume_token: SecureRandom.hex(16),
+ target_workflow: target_workflow,
+ target_workflow_version_id: target_workflow.version_id,
+ child_execution: child_execution,
+ user: admin,
+ trigger_data: {
+ },
+ status: :success,
+ )
+
+ get "/admin/plugins/discourse-workflows/executions/#{child_execution.id}.json"
+
+ expect(response).to have_http_status(:ok)
+ expect(response.parsed_body.dig("execution", "workflow_call_caller")).to include(
+ "workflow_id" => workflow.id,
+ "workflow_name" => "Parent workflow",
+ "execution_id" => execution.id,
+ "execution_url" =>
+ DiscourseWorkflows::Execution.admin_execution_url(workflow.id, execution.id),
+ "node_id" => "call-1",
+ "node_name" => "Call child workflow",
+ "node_type" => "action:workflow_call",
+ )
+ 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")
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
index 701cc0d08f4..7727a56dd03 100644
--- a/plugins/discourse-workflows/spec/requests/discourse_workflows/workflows_controller_spec.rb
+++ b/plugins/discourse-workflows/spec/requests/discourse_workflows/workflows_controller_spec.rb
@@ -312,6 +312,30 @@ RSpec.describe DiscourseWorkflows::WorkflowsController do
expect(response).to have_http_status(:bad_request)
end
+ it "returns referenced workflows when the workflow is called by another workflow" do
+ workflow = Fabricate(:discourse_workflows_workflow, created_by: admin)
+ caller_graph =
+ build_workflow_graph do |workflow_graph|
+ workflow_graph.node "trigger-1", "trigger:manual"
+ workflow_graph.node "call-1",
+ "action:workflow_call",
+ configuration: {
+ "workflow_id" => workflow.id,
+ }
+ end
+ caller =
+ Fabricate(:discourse_workflows_workflow, created_by: admin, published: true, **caller_graph)
+
+ delete "/admin/plugins/discourse-workflows/workflows/#{workflow.id}.json"
+
+ expect(response).to have_http_status(:unprocessable_entity)
+ expect(response.parsed_body).to include(
+ "type" => "workflow_called_by_other_workflows",
+ "referencing_workflows" => [include("id" => caller.id, "name" => caller.name)],
+ )
+ expect(DiscourseWorkflows::Workflow.exists?(workflow.id)).to be(true)
+ end
+
it "returns 404 when workflow does not exist" do
put "/admin/plugins/discourse-workflows/workflows/-1.json",
params: {
diff --git a/plugins/discourse-workflows/spec/services/discourse_workflows/workflow/action/populate_graph_spec.rb b/plugins/discourse-workflows/spec/services/discourse_workflows/workflow/action/populate_graph_spec.rb
index 588169910ad..055400feacc 100644
--- a/plugins/discourse-workflows/spec/services/discourse_workflows/workflow/action/populate_graph_spec.rb
+++ b/plugins/discourse-workflows/spec/services/discourse_workflows/workflow/action/populate_graph_spec.rb
@@ -82,6 +82,145 @@ RSpec.describe DiscourseWorkflows::Workflow::Action::PopulateGraph do
end
end
+ context "when workflow calls reference other workflows" do
+ it "allows a draft workflow call node without a selected target" do
+ result =
+ described_class.call(
+ workflow: workflow,
+ nodes_data: [
+ { id: "trigger-1", type: "trigger:manual", name: "Manual" },
+ { id: "call-1", type: "action:workflow_call", name: "Call workflow", parameters: {} },
+ ],
+ connections_data: {
+ "Manual" => {
+ "main" => [[{ "node" => "Call workflow", "type" => "main", "index" => 0 }]],
+ },
+ },
+ )
+
+ expect(result).to eq(true)
+ expect(workflow.errors).to be_empty
+ expect(workflow.nodes.find { |node| node["id"] == "call-1" }["parameters"]).to eq({})
+ end
+
+ it "accepts a published callable workflow target" do
+ target_graph =
+ build_workflow_graph { |graph| graph.node "call-trigger", "trigger:workflow_call" }
+ target =
+ Fabricate(
+ :discourse_workflows_workflow,
+ created_by: workflow.created_by,
+ published: true,
+ **target_graph,
+ )
+
+ result =
+ described_class.call(
+ workflow: workflow,
+ nodes_data: [
+ { id: "trigger-1", type: "trigger:manual", name: "Manual" },
+ {
+ id: "call-1",
+ type: "action:workflow_call",
+ name: "Call workflow",
+ parameters: {
+ "workflow_id" => target.id,
+ },
+ },
+ ],
+ connections_data: {
+ "Manual" => {
+ "main" => [[{ "node" => "Call workflow", "type" => "main", "index" => 0 }]],
+ },
+ },
+ )
+
+ expect(result).to eq(true)
+ end
+
+ it "rejects self references and non-callable targets" do
+ non_callable = Fabricate(:discourse_workflows_workflow, created_by: workflow.created_by)
+
+ result =
+ described_class.call(
+ workflow: workflow,
+ nodes_data: [
+ { id: "trigger-1", type: "trigger:manual", name: "Manual" },
+ {
+ id: "self-call",
+ type: "action:workflow_call",
+ name: "Self call",
+ parameters: {
+ "workflow_id" => workflow.id,
+ },
+ },
+ {
+ id: "bad-call",
+ type: "action:workflow_call",
+ name: "Bad call",
+ parameters: {
+ "workflow_id" => non_callable.id,
+ },
+ },
+ ],
+ connections_data: {
+ },
+ )
+
+ expect(result).to eq(false)
+ expect(workflow.errors.full_messages).to include(
+ I18n.t("discourse_workflows.errors.workflow_call.self_reference", node: "Self call"),
+ I18n.t("discourse_workflows.errors.workflow_call.target_not_callable"),
+ )
+ end
+
+ it "rejects workflow call cycles" do
+ cyclic_target_graph =
+ build_workflow_graph do |graph|
+ graph.node "call-trigger", "trigger:workflow_call"
+ graph.node "call-back",
+ "action:workflow_call",
+ configuration: {
+ "workflow_id" => workflow.id,
+ }
+ graph.chain "call-trigger", "call-back"
+ end
+ cyclic_target =
+ Fabricate(
+ :discourse_workflows_workflow,
+ created_by: workflow.created_by,
+ published: true,
+ **cyclic_target_graph,
+ )
+
+ result =
+ described_class.call(
+ workflow: workflow,
+ nodes_data: [
+ { id: "trigger-1", type: "trigger:workflow_call", name: "Workflow call" },
+ {
+ id: "cycle-call",
+ type: "action:workflow_call",
+ name: "Cycle call",
+ parameters: {
+ "workflow_id" => cyclic_target.id,
+ },
+ },
+ ],
+ connections_data: {
+ "Workflow call" => {
+ "main" => [[{ "node" => "Cycle call", "type" => "main", "index" => 0 }]],
+ },
+ },
+ )
+
+ expect(result).to eq(false)
+ expect(workflow.errors.full_messages).to include(
+ I18n.t("discourse_workflows.errors.workflow_call.cycle", node: "Cycle call"),
+ )
+ end
+ end
+
context "when nodes have invalid versions" do
it "returns false and adds errors to the workflow" do
result =
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
index 9b9e6a8c675..d31a7be9f97 100644
--- a/plugins/discourse-workflows/spec/services/discourse_workflows/workflow/destroy_spec.rb
+++ b/plugins/discourse-workflows/spec/services/discourse_workflows/workflow/destroy_spec.rb
@@ -33,6 +33,23 @@ RSpec.describe DiscourseWorkflows::Workflow::Destroy do
it { is_expected.to fail_a_policy(:can_manage_workflows) }
end
+ context "when another workflow calls this workflow" do
+ fab!(:caller_workflow) do
+ graph =
+ build_workflow_graph do |workflow_graph|
+ workflow_graph.node "trigger-1", "trigger:manual"
+ workflow_graph.node "call-1",
+ "action:workflow_call",
+ configuration: {
+ "workflow_id" => workflow.id,
+ }
+ end
+ Fabricate(:discourse_workflows_workflow, created_by: admin, published: true, **graph)
+ end
+
+ it { is_expected.to fail_a_policy(:workflow_not_called_by_other_workflows) }
+ end
+
context "when everything's ok" do
it { is_expected.to run_successfully }
diff --git a/plugins/discourse-workflows/test/javascripts/integration/components/workflows/executions/detail-test.gjs b/plugins/discourse-workflows/test/javascripts/integration/components/workflows/executions/detail-test.gjs
new file mode 100644
index 00000000000..77f05c8ef82
--- /dev/null
+++ b/plugins/discourse-workflows/test/javascripts/integration/components/workflows/executions/detail-test.gjs
@@ -0,0 +1,152 @@
+import Service from "@ember/service";
+import { click, render } from "@ember/test-helpers";
+import { module, test } from "qunit";
+import { setupRenderingTest } from "discourse/tests/helpers/component-test";
+import ExecutionDetail from "discourse/plugins/discourse-workflows/admin/components/workflows/executions/detail";
+
+let transitions;
+
+class RouterStub extends Service {
+ transitionTo(...args) {
+ transitions.push(args);
+ }
+}
+
+class WorkflowsNodeTypesStub extends Service {
+ nodeTypes = [];
+
+ load() {}
+
+ findNodeType() {
+ return null;
+ }
+}
+
+module(
+ "Integration | Component | Workflows | Executions | ExecutionDetail",
+ function (hooks) {
+ setupRenderingTest(hooks);
+
+ hooks.beforeEach(function () {
+ transitions = [];
+
+ this.owner.unregister("service:router");
+ this.owner.register("service:router", RouterStub);
+ this.owner.unregister("service:workflows-node-types");
+ this.owner.register(
+ "service:workflows-node-types",
+ WorkflowsNodeTypesStub
+ );
+ });
+
+ test("opens workflow call child executions through the admin route", async function (assert) {
+ this.execution = {
+ id: 11471,
+ workflow_id: 30,
+ workflow_name: "Parent workflow",
+ status: "success",
+ started_at: "2026-06-24T10:00:00Z",
+ finished_at: "2026-06-24T10:00:01Z",
+ steps: [
+ {
+ node_id: "call-1",
+ node_name: "Call workflow",
+ node_type: "action:workflow_call",
+ status: "success",
+ input: [],
+ output: [],
+ metadata: {
+ operation: "run",
+ },
+ started_at: "2026-06-24T10:00:00Z",
+ finished_at: "2026-06-24T10:00:01Z",
+ workflow_call_run: {
+ run_id: 1,
+ workflow_id: 31,
+ workflow_name: "Child workflow",
+ execution_id: 11472,
+ execution_url:
+ "https://example.com/admin/plugins/discourse-workflows/workflows/31/executions/11472",
+ status: "success",
+ },
+ },
+ ],
+ };
+
+ await render(
+ <template><ExecutionDetail @execution={{this.execution}} /></template>
+ );
+
+ assert
+ .dom(".workflows-execution-detail__workflow-call-link")
+ .exists("the open execution button renders");
+ assert
+ .dom(".workflows-execution-detail__workflow-call-link")
+ .doesNotHaveAttribute("href", "the button does not force a page load");
+
+ await click(".workflows-execution-detail__workflow-call-link");
+
+ assert.deepEqual(
+ transitions,
+ [
+ [
+ "adminPlugins.show.discourse-workflows.show.executions.show",
+ 31,
+ 11472,
+ ],
+ ],
+ "the button transitions to the child execution route"
+ );
+ });
+
+ test("opens parent workflow executions through the admin route", async function (assert) {
+ this.execution = {
+ id: 11472,
+ workflow_id: 31,
+ workflow_name: "Child workflow",
+ workflow_call_caller: {
+ workflow_id: 30,
+ workflow_name: "Parent workflow",
+ execution_id: 11471,
+ execution_url:
+ "https://example.com/admin/plugins/discourse-workflows/workflows/30/executions/11471",
+ node_id: "call-1",
+ node_name: "Call child workflow",
+ node_type: "action:workflow_call",
+ },
+ status: "success",
+ started_at: "2026-06-24T10:00:00Z",
+ finished_at: "2026-06-24T10:00:01Z",
+ steps: [],
+ };
+
+ await render(
+ <template><ExecutionDetail @execution={{this.execution}} /></template>
+ );
+
+ assert
+ .dom(".workflows-execution-detail__workflow-call.--caller")
+ .hasText(
+ "Called by Parent workflow Open parent execution",
+ "the compact parent execution row renders"
+ );
+ assert
+ .dom(".workflows-execution-detail__workflow-call-parent-link")
+ .doesNotHaveAttribute("href", "the button does not force a page load");
+
+ await click(".workflows-execution-detail__workflow-call-parent-link");
+
+ assert.deepEqual(
+ transitions,
+ [
+ [
+ "adminPlugins.show.discourse-workflows.show.executions.show",
+ 30,
+ 11471,
+ ],
+ ],
+ "the button transitions to the parent execution route"
+ );
+ });
+ }
+);
diff --git a/plugins/discourse-workflows/test/javascripts/integration/components/workflows/property-engine-test.gjs b/plugins/discourse-workflows/test/javascripts/integration/components/workflows/property-engine-test.gjs
index 58d601c64f8..ca8911fa01a 100644
--- a/plugins/discourse-workflows/test/javascripts/integration/components/workflows/property-engine-test.gjs
+++ b/plugins/discourse-workflows/test/javascripts/integration/components/workflows/property-engine-test.gjs
@@ -1074,6 +1074,83 @@ module("Integration | Component | workflows property engine", function (hooks) {
assert.strictEqual(this.formApi.get("llm_model_id"), null);
});
+ test("renders combo box actions with the selected field value as a route model", async function (assert) {
+ const router = this.owner.lookup("service:router");
+ const transitionTo = sinon.stub(router, "transitionTo");
+
+ this.setProperties({
+ configuration: {
+ workflow_id: null,
+ },
+ nodeType: "action:workflow_call",
+ nodeTypes: [
+ {
+ identifier: "action:workflow_call",
+ metadata: {
+ callable_workflows: [{ id: 8, name: "Child workflow" }],
+ },
+ },
+ ],
+ schema: {
+ workflow_id: {
+ type: "integer",
+ required: true,
+ type_options: {
+ load_options_method: "callable_workflows",
+ },
+ no_data_expression: true,
+ ui: {
+ control: "combo_box",
+ },
+ control_options: {
+ action_icon: "up-right-from-square",
+ action_label: "discourse_workflows.workflow_call.open_workflow",
+ action_route: "adminPlugins.show.discourse-workflows.show",
+ action_route_models: [{ source: "field_value" }],
+ name_property: "name",
+ value_property: "id",
+ },
+ },
+ },
+ });
+
+ await render(
+ <template>
+ <Form @data={{this.configuration}} as |form transientData|>
+ <PropertyEngineConfigurator
+ @form={{form}}
+ @configuration={{transientData}}
+ @nodeType={{this.nodeType}}
+ @nodeTypes={{this.nodeTypes}}
+ @schema={{this.schema}}
+ @session={{this.session}}
+ />
+ </Form>
+ </template>
+ );
+
+ assert
+ .dom(".workflows-property-engine__select-with-action > .btn")
+ .doesNotExist();
+
+ const selector = selectKit(".combo-box");
+ await selector.expand();
+ await selector.selectRowByValue("8");
+
+ assert
+ .dom(".workflows-property-engine__select-with-action > .btn")
+ .hasText("Open workflow");
+
+ await click(".workflows-property-engine__select-with-action > .btn");
+
+ assert.true(
+ transitionTo.calledWith(
+ "adminPlugins.show.discourse-workflows.show",
+ sinon.match((value) => String(value) === "8", "selected workflow id")
+ )
+ );
+ });
+
test("applies option patches from remote combo box options", async function (assert) {
const requests = [];
pretender.post(