Skip to content

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

UI: workflows UI improvements (#41872)

Joffrey JAFFEUX2c3dab5adee4
diff --git a/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/canvas/canvas-execute-step.js b/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/canvas/canvas-execute-step.js
new file mode 100644
index 00000000000..c1b085dd157
--- /dev/null
+++ b/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/canvas/canvas-execute-step.js
@@ -0,0 +1,34 @@
+import { ajax } from "discourse/lib/ajax";
+import { i18n } from "discourse-i18n";
+
+export async function runExecuteStep({ clientId, workflowId, toasts, router }) {
+ const result = await ajax(
+ "/admin/plugins/discourse-workflows/step-executions.json",
+ {
+ type: "POST",
+ data: { workflow_id: workflowId, node_id: clientId },
+ }
+ );
+
+ const { workflow_id, id } = result.execution;
+
+ toasts.success({
+ data: {
+ message: i18n("discourse_workflows.execute_step.triggered"),
+ actions: [
+ {
+ label: i18n("discourse_workflows.execute_step.view_execution"),
+ class: "btn-primary btn-small",
+ action: ({ close }) => {
+ close();
+ router.transitionTo(
+ "adminPlugins.show.discourse-workflows.show.executions.show",
+ workflow_id,
+ id
+ );
+ },
+ },
+ ],
+ },
+ });
+}
diff --git a/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/canvas/index.gjs b/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/canvas/index.gjs
index 7a49c0d6378..8d0bbdd2976 100644
--- a/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/canvas/index.gjs
+++ b/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/canvas/index.gjs
@@ -25,6 +25,7 @@ import {
serializeCanvasClipboardPayload,
} from "./canvas-clipboard";
import CanvasContextMenu from "./canvas-context-menu";
+import { runExecuteStep } from "./canvas-execute-step";
import { exportWorkflowToFile, parseWorkflowImport } from "./canvas-file-io";
import { setupCanvasKeyboard } from "./canvas-keyboard";
import { runManualTrigger } from "./canvas-manual-trigger";
@@ -65,6 +66,8 @@ export default class WorkflowCanvas extends Component {
#hasSetupStarted = false;
#pendingSync = false;
#syncTask = null;
+ #pendingInsertHighlights = new Set();
+ #syncedNodeClientIds = null;
#outsideClickAbort = null;
#ZOOM_STEP = 0.1;
#ZOOM_MIN = 0.25;
@@ -274,6 +277,19 @@ export default class WorkflowCanvas extends Component {
}
}
+ async #handleExecuteStep(clientId) {
+ try {
+ await runExecuteStep({
+ clientId,
+ workflowId: this.args.workflowId,
+ toasts: this.toasts,
+ router: this.router,
+ });
+ } catch (e) {
+ popupAjaxError(e);
+ }
+ }
+
#reteCallbacks() {
return {
onNodeDragged: (...a) => this.args.onUpdateNodePosition?.(...a),
@@ -290,6 +306,7 @@ export default class WorkflowCanvas extends Component {
onConnectionCreated: (...a) => this.args.onCreateConnection?.(...a),
onNodeDelete: (clientId) => this.args.onRemoveNodes?.([clientId]),
onManualTrigger: (clientId) => this.#handleManualTrigger(clientId),
+ onExecuteStep: (clientId) => this.#handleExecuteStep(clientId),
onNodeDoubleClick: (clientId) => this.args.onEditNode?.(clientId),
onTransformChanged: (t) => (this.areaTransform = t),
};
@@ -365,6 +382,28 @@ export default class WorkflowCanvas extends Component {
}
}
+ // Rete re-renders node views on selection and config changes, remounting
+ // their components, so the insert pulse is keyed off client ids appearing
+ // in the synced data rather than DOM insertion.
+ #trackInsertedNodes(nodes) {
+ const clientIds = new Set(nodes.map((node) => node.clientId));
+
+ if (this.#syncedNodeClientIds) {
+ for (const clientId of clientIds) {
+ if (!this.#syncedNodeClientIds.has(clientId)) {
+ this.#pendingInsertHighlights.add(clientId);
+ }
+ }
+ }
+
+ this.#syncedNodeClientIds = clientIds;
+ }
+
+ @action
+ consumeInsertHighlight(clientId) {
+ return this.#pendingInsertHighlights.delete(clientId);
+ }
+
async #performSync() {
const snapshot = {
nodes: this.#nodes(),
@@ -374,6 +413,7 @@ export default class WorkflowCanvas extends Component {
};
const prevNodeCount = this.rete.nodeCount;
+ this.#trackInsertedNodes(snapshot.nodes);
await this.rete.syncState(snapshot.nodes, snapshot.connections);
if (this.#shouldHydrateInitialAutoLayout(snapshot.nodes)) {
@@ -950,8 +990,10 @@ export default class WorkflowCanvas extends Component {
{{#in-element entry.element insertBefore=null}}
<WorkflowNode
@node={{entry.node}}
+ @consumeInsertHighlight={{this.consumeInsertHighlight}}
@onDelete={{this.rete.renderer.onNodeDelete}}
@onManualTrigger={{this.rete.renderer.onManualTrigger}}
+ @onExecuteStep={{this.rete.renderer.onExecuteStep}}
@onSocketRendered={{this.rete.renderer.onSocketRendered}}
@onEditNode={{@onEditNode}}
@workflowPublished={{this.workflowPublished}}
diff --git a/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/canvas/rete-editor.js b/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/canvas/rete-editor.js
index 62640ef30f1..27e0b954ab4 100644
--- a/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/canvas/rete-editor.js
+++ b/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/canvas/rete-editor.js
@@ -26,6 +26,8 @@ import {
} from "../../../lib/workflows/node-utils";
import { createCustomRenderer } from "./custom-renderer";
+export const DRAG_LENIENCE_PX = 4;
+
export class ReteEditorBridge {
static async create(container, { callbacks, nodeTypes = [] }) {
const {
@@ -114,6 +116,7 @@ export class ReteEditorBridge {
const connectionPlugin = new ConnectionPlugin();
const renderer = new CustomRenderer();
renderer.onManualTrigger = callbacks.onManualTrigger;
+ renderer.onExecuteStep = callbacks.onExecuteStep;
connectionPlugin.addPreset(ConnectionPresets.classic.setup());
@@ -268,6 +271,7 @@ export class ReteEditorBridge {
this.selectionBoxElement = null;
this.lastPickedId = null;
this.lastPickedTime = 0;
+ this.nodeDragOrigin = null;
}
setupPipes() {
@@ -283,6 +287,23 @@ export class ReteEditorBridge {
}
break;
+ case "nodetranslate": {
+ const origin = this.nodeDragOrigin;
+ if (origin && origin.id === context.data.id) {
+ const { position } = context.data;
+ const { k } = this.area.area.transform;
+ const distance = Math.hypot(
+ (position.x - origin.x) * k,
+ (position.y - origin.y) * k
+ );
+ if (distance < DRAG_LENIENCE_PX) {
+ return;
+ }
+ this.nodeDragOrigin = null;
+ }
+ break;
+ }
+
case "nodetranslated":
this.callbacks.onNodeDragged?.(
context.data.id,
@@ -301,9 +322,13 @@ export class ReteEditorBridge {
}
case "nodepicked": {
+ const pickedId = context.data.id;
+ const view = this.area.nodeViews.get(pickedId);
+ this.nodeDragOrigin = view
+ ? { id: pickedId, x: view.position.x, y: view.position.y }
+ : null;
this.callbacks.onNodePicked?.();
const now = Date.now();
- const pickedId = context.data.id;
if (
pickedId === this.lastPickedId &&
now - this.lastPickedTime < 500
@@ -325,6 +350,8 @@ export class ReteEditorBridge {
break;
case "pointerup":
+ this.nodeDragOrigin = null;
+
if (this.selectionDrag) {
await this.finishSelectionDrag(context.data);
return;
@@ -355,12 +382,14 @@ export class ReteEditorBridge {
this.connectionPlugin.addPipe((context) => {
if (context.type === "connectionpick") {
- const pickedSide = context.data.socket?.side;
+ const pickedSocket = context.data.socket;
this.container.classList.add("is-connection-dragging");
- this.updateInvalidConnectionTargets(pickedSide);
+ this.updateInvalidConnectionTargets(pickedSocket?.side);
+ this.markConnectionSourceNode(pickedSocket?.nodeId);
} else if (context.type === "connectiondrop") {
this.container.classList.remove("is-connection-dragging");
this.clearInvalidConnectionTargets();
+ this.clearConnectionSourceNode();
}
return context;
});
@@ -428,6 +457,23 @@ export class ReteEditorBridge {
}
}
+ markConnectionSourceNode(nodeId) {
+ this.clearConnectionSourceNode();
+ if (nodeId) {
+ this.area.nodeViews
+ .get(nodeId)
+ ?.element.classList.add("is-connection-source");
+ }
+ }
+
+ clearConnectionSourceNode() {
+ for (const element of this.container.querySelectorAll(
+ ".workflow-rete-node-view.is-connection-source"
+ )) {
+ element.classList.remove("is-connection-source");
+ }
+ }
+
pointerPosition(data) {
const event = data.event;
@@ -500,7 +546,7 @@ export class ReteEditorBridge {
await this.selector.unselectAll();
- if (distance < 4) {
+ if (distance < DRAG_LENIENCE_PX) {
return;
}
@@ -1068,17 +1114,21 @@ export class ReteEditorBridge {
});
}
- for (const conn of this.editor.getConnections()) {
- if (
- conn.source !== conn.target &&
- graph.hasNode(conn.source) &&
- graph.hasNode(conn.target)
- ) {
- graph.setEdge(conn.source, conn.target);
- }
+ const connections = this.editor
+ .getConnections()
+ .filter(
+ (conn) =>
+ conn.source !== conn.target &&
+ graph.hasNode(conn.source) &&
+ graph.hasNode(conn.target)
+ );
+ for (const conn of connections) {
+ graph.setEdge(conn.source, conn.target);
}
- this.dagre.layout(graph);
+ this.dagre.layout(graph, {
+ constraints: this.branchOrderConstraints(connections),
+ });
await Promise.all(
nodes.map((node) => {
@@ -1091,6 +1141,59 @@ export class ReteEditorBridge {
);
}
+ // Dagre has no notion of ports and stacks a node's branch targets in an
+ // arbitrary order; constrain siblings to follow the output port order
+ // (e.g. if yes above no), like elk's port support used to.
+ branchOrderConstraints(connections) {
+ const constraints = [];
+ const rightsByLeft = new Map();
+
+ const wouldCycle = (left, right) => {
+ const stack = [right];
+ const seen = new Set();
+ while (stack.length) {
+ const current = stack.pop();
+ if (current === left) {
+ return true;
+ }
+ if (seen.has(current)) {
+ continue;
+ }
+ seen.add(current);
+ stack.push(...(rightsByLeft.get(current) || []));
+ }
+ return false;
+ };
+
+ for (const [sourceId, conns] of buildOutgoingIndex(connections, "source")) {
+ const sourceNode = this.editor.getNode(sourceId);
+ const targets = conns
+ .sort(
+ (a, b) =>
+ this.outputIndexFor(sourceNode, a) -
+ this.outputIndexFor(sourceNode, b) ||
+ normalizeTargetInputIndex(a) - normalizeTargetInputIndex(b)
+ )
+ .map((conn) => conn.target)
+ .filter((target, index, list) => list.indexOf(target) === index);
+
+ for (let i = 0; i < targets.length - 1; i++) {
+ const left = targets[i];
+ const right = targets[i + 1];
+ if (rightsByLeft.get(left)?.has(right) || wouldCycle(left, right)) {
+ continue;
+ }
+ if (!rightsByLeft.has(left)) {
+ rightsByLeft.set(left, new Set());
+ }
+ rightsByLeft.get(left).add(right);
+ constraints.push({ left, right });
+ }
+ }
+
+ return constraints;
+ }
+
get areaContentElement() {
return this.area.area.content.holder;
}
diff --git a/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/canvas/sticky-note.gjs b/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/canvas/sticky-note.gjs
index 1d7b133e3f0..746abda7ebf 100644
--- a/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/canvas/sticky-note.gjs
+++ b/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/canvas/sticky-note.gjs
@@ -13,6 +13,7 @@ import dIcon from "discourse/ui-kit/helpers/d-icon";
import dAutoFocus from "discourse/ui-kit/modifiers/d-auto-focus";
import { i18n } from "discourse-i18n";
import CanvasHoverToolbar from "./hover-toolbar";
+import { DRAG_LENIENCE_PX } from "./rete-editor";
const COLORS = ["yellow", "blue", "green", "pink", "purple", "orange"].map(
(name) => ({
@@ -103,8 +104,17 @@ export default class StickyNote extends Component {
const zoom = this.args.zoom ?? 1;
const startX = event.clientX;
const startY = event.clientY;
+ let withinLenience = true;
const moveHandler = (e) => {
+ if (withinLenience) {
+ if (
+ Math.hypot(e.clientX - startX, e.clientY - startY) < DRAG_LENIENCE_PX
+ ) {
+ return;
+ }
+ withinLenience = false;
+ }
const dx = (e.clientX - startX) / zoom;
const dy = (e.clientY - startY) / zoom;
onMove(dx, dy);
@@ -246,6 +256,7 @@ export default class StickyNote extends Component {
class={{dConcatClass
"workflow-sticky-note"
(if @isSelected "is-selected")
+ (if this.isEditing "is-editing")
}}
style={{this.style}}
{{registerStickyNoteElement this}}
diff --git a/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/canvas/workflow-node.gjs b/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/canvas/workflow-node.gjs
index 8b8ca1d1e5f..acbf72f46c7 100644
--- a/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/canvas/workflow-node.gjs
+++ b/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/canvas/workflow-node.gjs
@@ -18,7 +18,6 @@ import {
nodeTypeInputLabel,
nodeTypeIsManuallyTriggerable,
nodeTypePortLabel,
- nodeTypeRunScopeLabelKey,
nodeTypeStyle,
resolveNodeTypeVersion,
typeVersionForNode,
@@ -35,7 +34,11 @@ function resolveType(workflowsNodeTypes, node) {
return resolveNodeTypeVersion(nodeType, typeVersionForNode(node));
}
-const highlightOnInsert = modifier((element) => {
+const highlightOnInsert = modifier((element, [shouldHighlight]) => {
+ if (!shouldHighlight()) {
+ return;
+ }
+
if (window.matchMedia?.("(prefers-reduced-motion: reduce)").matches) {
return;
}
@@ -55,6 +58,10 @@ export function shouldShowManualTrigger(node) {
return Boolean(node?.type?.startsWith("trigger:"));
}
+export function shouldShowExecuteStep(node) {
+ return Boolean(node?.type) && !node.type.startsWith("trigger:");
+}
+
export function shouldEnableManualTrigger(node, nodeType, session) {
if (!node?.type?.startsWith("trigger:")) {
return false;
@@ -72,6 +79,9 @@ export default class WorkflowNode extends Component {
stopPropagation = (e) => e.stopPropagation();
+ consumeInsertHighlight = () =>
+ Boolean(this.args.consumeInsertHighlight?.(this.data.clientId));
+
handleDelete = (e) => {
e.stopPropagation();
e.preventDefault();
@@ -83,6 +93,11 @@ export default class WorkflowNode extends Component {
this.args.onManualTrigger?.(this.data.clientId);
};
+ handleExecuteStep = (e) => {
+ e.stopPropagation();
+ this.args.onExecuteStep?.(this.data.clientId);
+ };
+
handleOpenIssues = (e) => {
e.stopPropagation();
e.preventDefault();
@@ -121,11 +136,6 @@ export default class WorkflowNode extends Component {
return nodeDescription(this.data);
}
- get runScopeLabel() {
- const labelKey = nodeTypeRunScopeLabelKey(this.resolvedNodeType, this.data);
- return labelKey ? i18n(labelKey) : null;
- }
-
get outputKeys() {
return Object.keys(this.args.node.outputs);
}
@@ -180,6 +190,14 @@ export default class WorkflowNode extends Component {
: i18n("discourse_workflows.manual_trigger.needs_pin_data");
}
+ get showExecuteStep() {
+ return shouldShowExecuteStep(this.data);
+ }
+
+ get executeStepLabel() {
+ return i18n("discourse_workflows.execute_step.run");
+ }
+
get dataTableId() {
if (this.data.type !== "action:data_table") {
return null;
@@ -202,8 +220,9 @@ export default class WorkflowNode extends Component {
}
get dimensionsStyle() {
+ const { width, height } = this.args.node;
return trustHTML(
- `width: ${this.args.node.width}px; height: ${this.args.node.height}px;`
+ `width: ${width}px; height: ${height}px; --node-width: ${width}px; --node-height: ${height}px;`
);
}
@@ -228,16 +247,8 @@ export default class WorkflowNode extends Component {
style={{this.dimensionsStyle}}
data-client-id={{this.data.clientId}}
data-unavailable={{if this.isUnavailable "true" "false"}}
- {{highlightOnInsert}}
+ {{highlightOnInsert this.consumeInsertHighlight}}
>
- {{#if @node.selected}}
- {{#if this.runScopeLabel}}
- <div class="workflow-rete-node__run-scope-tooltip">
- {{this.runScopeLabel}}
- </div>
- {{/if}}
- {{/if}}
-
<div class="workflow-rete-node__icon-row">
<div
class={{dConcatClass
@@ -296,6 +307,28 @@ export default class WorkflowNode extends Component {
</:trigger>
</DTooltip>
{{/if}}
+ {{#if this.showExecuteStep}}
+ <DTooltip
+ @identifier="workflow-node-execute-step"
+ @content={{this.executeStepLabel}}
+ >
+ <:trigger>
+ <button
+ type="button"
+ class={{dConcatClass
+ "workflow-canvas-toolbar__btn --success"
+ (if this.isUnavailable "is-disabled")
+ }}
+ disabled={{if this.isUnavailable true false}}
+ aria-label={{this.executeStepLabel}}
+ {{on "pointerdown" this.stopPropagation}}
+ {{on "click" this.handleExecuteStep}}
+ >
+ {{dIcon "play"}}
+ </button>
+ </:trigger>
+ </DTooltip>
+ {{/if}}
{{#if this.dataTableId}}
<button
type="button"
diff --git a/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/editor/index.gjs b/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/editor/index.gjs
index cdc3cf6e199..9f575cfe744 100644
--- a/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/editor/index.gjs
+++ b/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/editor/index.gjs
@@ -3,7 +3,6 @@ import { tracked } from "@glimmer/tracking";
import { action } from "@ember/object";
import { service } from "@ember/service";
import Form from "discourse/components/form";
-import { ajax } from "discourse/lib/ajax";
import { popupAjaxError } from "discourse/lib/ajax-error";
import { bind } from "discourse/lib/decorators";
import { i18n } from "discourse-i18n";
@@ -127,7 +126,6 @@ export function buildPastedGraph({
export default class WorkflowsEditor extends Component {
@service router;
- @service dialog;
@service modal;
@service toasts;
@service workflowsNodeTypes;
@@ -142,7 +140,6 @@ export default class WorkflowsEditor extends Component {
formApi = null;
ignoreDirty = () => false;
undoManager = new UndoManager();
- allowUnpublishedDraftTransition = false;
currentSavePromise = null;
pendingGraphSnapshot = null;
pendingSaveOptions = null;
@@ -165,7 +162,6 @@ export default class WorkflowsEditor extends Component {
constructor() {
super(...arguments);
this.#subscribeToExecutions();
- this.router.on("routeWillChange", this.confirmUnpublishedDraftTransition);
window.addEventListener("beforeunload", this.handleBeforeUnload);
}
@@ -173,7 +169,6 @@ export default class WorkflowsEditor extends Component {
super.willDestroy(...arguments);
this.undoManager.destroy();
this.#unsubscribeFromExecutions();
- this.router.off("routeWillChange", this.confirmUnpublishedDraftTransition);
window.removeEventListener("beforeunload", this.handleBeforeUnload);
}
@@ -200,70 +195,6 @@ export default class WorkflowsEditor extends Component {
return message;
}
- @bind
- confirmUnpublishedDraftTransition(transition) {
- const routeChanging = transition.to?.name !== transition.from?.name;
- const shouldCheck =
- this.hasUnpublishedDraft &&
- !this.allowUnpublishedDraftTransition &&
- !transition.isAborted &&
- (!transition.queryParamsOnly || routeChanging);
-
- if (!shouldCheck) {
- return;
- }
-
- transition.abort();
-
- this.dialog.dialog({
- class: "workflows-unpublished-draft-dialog",
- message: i18n("discourse_workflows.unpublished_changes_confirmation"),
- type: "confirm",
- buttons: [
- {
- label: i18n("discourse_workflows.leave_without_publishing"),
- class: "btn-primary",
- action: () => this.leaveWithoutPublishing(transition),
- },
- {
- label: i18n("discourse_workflows.keep_editing"),
- class: "btn-default",
- },
- {
- label: i18n("discourse_workflows.discard_changes"),
- class: "btn-default workflows-unpublished-draft-dialog__discard-btn",
- action: () => this.discardDraftAndRetryTransition(transition),
- },
- ],
- });
- }
-
- @action
- leaveWithoutPublishing(transition) {
- this.allowUnpublishedDraftTransition = true;
- transition.retry();
- }
-
- @action
- async discardDraftAndRetryTransition(transition) {
- const confirmed = await this.confirmDiscardChanges();
-
- if (!confirmed) {
- return;
- }
-
- await this.discardWorkflowDraft();
- this.leaveWithoutPublishing(transition);
- }
-
- confirmDiscardChanges() {
- return this.dialog.confirm({
- message: i18n("discourse_workflows.discard_changes_confirmation"),
- confirmButtonLabel: "discourse_workflows.discard_changes",
- cancelButtonLabel: "discourse_workflows.keep_editing",
- });
- }
-
#subscribeToExecutions() {
const workflowId = this.args.workflow?.id;
if (!workflowId) {
@@ -446,13 +377,6 @@ export default class WorkflowsEditor extends Component {
@action
browseTemplates() {
- const nodes = this.formApi.get("nodes") || [];
- const stickyNotes = this.formApi.get("stickyNotes") || [];
-
- if (nodes.length === 0 && stickyNotes.length === 0) {
- this.allowUnpublishedDraftTransition = true;
- }
-
this.router.transitionTo(
"adminPlugins.show.discourse-workflows-templates",
{
@@ -1452,22 +1376,6 @@ export default class WorkflowsEditor extends Component {
this.#refreshUndoState();
}
- async discardWorkflowDraft() {
- try {
- const response = await ajax(
- `/admin/plugins/discourse-workflows/workflows/${this.args.workflow.id}/discard-draft.json`,
- {
- type: "POST",
- }
- );
-
- this.replaceWorkflow(response.workflow);
- } catch (e) {
- popupAjaxError(e);
- throw e;
- }
- }
-
async #saveWorkflow(options = {}) {
this.saving = true;
try {
@@ -1509,7 +1417,6 @@ export default class WorkflowsEditor extends Component {
this.#refreshUndoState();
if (this.args.isNew) {
- this.allowUnpublishedDraftTransition = true;
this.router.transitionTo(
"adminPlugins.show.discourse-workflows.show",
this.args.workflow.id
diff --git a/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/node/configurator.gjs b/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/node/configurator.gjs
index 34290608993..3aa0d26f434 100644
--- a/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/node/configurator.gjs
+++ b/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/node/configurator.gjs
@@ -7,6 +7,7 @@ import { cancel, later } from "@ember/runloop";
import { service } from "@ember/service";
import { modifier } from "ember-modifier";
import Form from "discourse/components/form";
+import { popupAjaxError } from "discourse/lib/ajax-error";
import { eq, not, or } from "discourse/truth-helpers";
import DButton from "discourse/ui-kit/d-button";
import DConditionalLoadingSpinner from "discourse/ui-kit/d-conditional-loading-spinner";
@@ -20,6 +21,7 @@ import {
nodeTypeIcon,
nodeTypeLabel,
nodeTypeProducesData,
+ nodeTypeRunScopeLabelKey,
nodeTypeStyle,
resolveNodeTypeVersion,
typeVersionForNode,
@@ -32,6 +34,8 @@ import {
findNodeType,
getPropertySchema,
} from "../../../lib/workflows/property-engine";
+import { runExecuteStep } from "../canvas/canvas-execute-step";
+import { shouldShowExecuteStep } from "../canvas/workflow-node";
import CredentialControl from "../configurators/credential";
import PropertyEngineConfigurator from "../configurators/property-engine";
import InputContext from "../context/input";
@@ -59,6 +63,8 @@ const SAVED_FADE_DELAY_MS = 2500;
const SAVED_REMOVE_DELAY_MS = 3000;
export default class NodeConfigurator extends Component {
+ @service router;
+ @service toasts;
@service workflowsNodeTypes;
@tracked nodeName = this.args.model.node.name || "";
@@ -300,6 +306,14 @@ export default class NodeConfigurator extends Component {
}
}
+ get runScopeLabel() {
+ const labelKey = nodeTypeRunScopeLabelKey(this.resolvedNodeType, {
+ typeVersion: this.args.model.node.typeVersion,
+ configuration: this.configuration,
+ });
+ return labelKey ? i18n(labelKey) : null;
+ }
+
get configuration() {
if (!this.parametersApi) {
return this.configurationWithDirectSettings(this.initialConfiguration);
@@ -445,6 +459,25 @@ export default class NodeConfigurator extends Component {
this.args.model.session.clearEditingContext();
}
+ get canExecuteStep() {
+ return shouldShowExecuteStep(this.args.model.node);
+ }
+
+ @action
+ async executeStep() {
+ try {
+ await this.saveCurrentConfiguration();
+ await runExecuteStep({
+ clientId: this.args.model.node.clientId || this.args.model.node.id,
+ workflowId: this.args.model.session?.workflowId,
+ toasts: this.toasts,
+ router: this.router,
+ });
+ } catch (e) {
+ popupAjaxError(e);
+ }
+ }
+
<template>
<DModal
@closeModal={{this.handleClose}}
@@ -524,6 +557,14 @@ export default class NodeConfigurator extends Component {
{{/if}}
</span>
{{/if}}
+ {{#if this.canExecuteStep}}
+ <DButton
+ @action={{this.executeStep}}
+ @icon="play"
+ @label="discourse_workflows.execute_step.run"
+ class="btn-small workflows-configurator-modal__execute-step"
+ />
+ {{/if}}
<DButton
@action={{this.handleClose}}
@icon="xmark"
@@ -632,6 +673,12 @@ export default class NodeConfigurator extends Component {
{{/if}}
{{#if (eq this.activeTab "settings")}}
+ {{#if this.runScopeLabel}}
+ <div class="workflows-configurator-modal__run-scope">
+ {{dIcon "circle-info"}}
+ <span>{{this.runScopeLabel}}</span>
+ </div>
+ {{/if}}
<Form
@data={{this.settingsFormData}}
@onRegisterApi={{this.registerSettingsApi}}
diff --git a/plugins/discourse-workflows/admin/assets/javascripts/admin/lib/workflows/run-data.js b/plugins/discourse-workflows/admin/assets/javascripts/admin/lib/workflows/run-data.js
index aaa0e5aeabe..2ee87f9836e 100644
--- a/plugins/discourse-workflows/admin/assets/javascripts/admin/lib/workflows/run-data.js
+++ b/plugins/discourse-workflows/admin/assets/javascripts/admin/lib/workflows/run-data.js
@@ -31,9 +31,13 @@ function portSourceMatches(port, sourceNode, outputIndex) {
);
}
-function latestSuccessfulRun(runData, nodeName, { node } = {}) {
+const RUNS_WITH_FLOWING_OUTPUT = ["success", "filtered", "skipped"];
+
+const EXECUTED_RUN_STATUSES = ["success", "filtered"];
+
+function latestRunWithStatus(runData, nodeName, statuses, { node } = {}) {
const runs = (runData?.[nodeName] || []).filter(
- (run) => run.status === "success" && nodeRunMatches(run, node)
+ (run) => statuses.includes(run.status) && nodeRunMatches(run, node)
);
if (!runs?.length) {
return null;
@@ -42,8 +46,16 @@ function latestSuccessfulRun(runData, nodeName, { node } = {}) {
return runs[runs.length - 1] || null;
}
+function latestExecutedRun(runData, nodeName, { node } = {}) {
+ return latestRunWithStatus(runData, nodeName, EXECUTED_RUN_STATUSES, {
+ node,
+ });
+}
+
export function latestRunWithOutput(runData, nodeName, { node } = {}) {
- return latestSuccessfulRun(runData, nodeName, { node });
+ return latestRunWithStatus(runData, nodeName, RUNS_WITH_FLOWING_OUTPUT, {
+ node,
+ });
}
export function latestRunWithInput(
@@ -51,7 +63,7 @@ export function latestRunWithInput(
nodeName,
{ inputIndex = 0, node, sourceNode, outputIndex = 0 } = {}
) {
- const run = latestSuccessfulRun(runData, nodeName, { node });
+ const run = latestExecutedRun(runData, nodeName, { node });
if (!inputForRun(run, inputIndex, { sourceNode, outputIndex })) {
return null;
}
@@ -89,7 +101,7 @@ function connectedSourceOutputForInput(
nodeName,
{ node, sourceNode, outputIndex = 0 } = {}
) {
- if (latestSuccessfulRun(runData, nodeName, { node }) || !sourceNode?.name) {
+ if (latestExecutedRun(runData, nodeName, { node }) || !sourceNode?.name) {
return null;
}
@@ -115,7 +127,7 @@ export function inputPreviewPort(
return { port: input, source: "input" };
}
- if (latestSuccessfulRun(runData, nodeName, { node })) {
+ if (latestExecutedRun(runData, nodeName, { node })) {
return { port: null, source: null };
}
diff --git a/plugins/discourse-workflows/app/controllers/discourse_workflows/step_executions_controller.rb b/plugins/discourse-workflows/app/controllers/discourse_workflows/step_executions_controller.rb
new file mode 100644
index 00000000000..546d0fe8b19
--- /dev/null
+++ b/plugins/discourse-workflows/app/controllers/discourse_workflows/step_executions_controller.rb
@@ -0,0 +1,43 @@
+# frozen_string_literal: true
+
+module DiscourseWorkflows
+ class StepExecutionsController < ::Admin::AdminController
+ requires_plugin DiscourseWorkflows::PLUGIN_NAME
+
+ def create
+ DiscourseWorkflows::Workflow::ExecuteStep.call(service_params) do |result|
+ on_success do |execution:|
+ render json: {
+ execution: {
+ id: execution.id,
+ workflow_id: execution.workflow_id,
+ },
+ },
+ status: :created
+ end
+ on_failed_policy(:can_manage_workflows) { raise Discourse::InvalidAccess }
+ on_failed_policy(:step_node_executable) { render_step_execution_error("not_executable") }
+ on_failed_policy(:step_node_not_waiting) do
+ render_step_execution_error("waiting_not_supported")
+ end
+ on_failed_policy(:step_data_reachable) { render_step_execution_error("missing_input_data") }
+ on_failed_policy(:execution_path_not_waiting) do
+ render_step_execution_error("waiting_not_supported")
+ end
+ on_model_not_found(:workflow) { raise Discourse::NotFound }
+ on_model_not_found(:step_node) { raise Discourse::NotFound }
+ on_failure { render(json: failed_json, status: :unprocessable_entity) }
+ end
+ end
+
+ private
+
+ def render_step_execution_error(key)
+ render json:
+ failed_json.merge(
+ errors: [I18n.t("discourse_workflows.errors.step_execution.#{key}")],
+ ),
+ status: :unprocessable_entity
+ end
+ end
+end
diff --git a/plugins/discourse-workflows/app/jobs/regular/discourse_workflows/execute_manual_workflow.rb b/plugins/discourse-workflows/app/jobs/regular/discourse_workflows/execute_manual_workflow.rb
index 0b99722187c..e0be6f70113 100644
--- a/plugins/discourse-workflows/app/jobs/regular/discourse_workflows/execute_manual_workflow.rb
+++ b/plugins/discourse-workflows/app/jobs/regular/discourse_workflows/execute_manual_workflow.rb
@@ -28,6 +28,7 @@ module Jobs
execution_mode: :manual,
workflow_snapshot: workflow_snapshot,
existing_execution: execution,
+ step_node_id: args[:step_node_id],
)
::DiscourseWorkflows::Executor.new(
diff --git a/plugins/discourse-workflows/app/models/discourse_workflows/execution.rb b/plugins/discourse-workflows/app/models/discourse_workflows/execution.rb
index 2304fd363e4..ee791ee2084 100644
--- a/plugins/discourse-workflows/app/models/discourse_workflows/execution.rb
+++ b/plugins/discourse-workflows/app/models/discourse_workflows/execution.rb
@@ -56,6 +56,33 @@ module DiscourseWorkflows
end
end
+ def self.create_pending_step!(workflow:, node_id:, trigger_data: {}, run_data: {})
+ transaction do
+ create!(
+ workflow: workflow,
+ workflow_version_id: workflow.version_id,
+ trigger_node_id: node_id,
+ trigger_data: trigger_data,
+ status: :pending,
+ execution_mode: :manual,
+ ).tap do |execution|
+ ExecutionData.create!(
+ execution: execution,
+ workflow_data: WorkflowSnapshot.from_workflow(workflow, published: false).to_h,
+ data: {
+ "entries" => {
+ },
+ "context" => {
+ },
+ "node_contexts" => {
+ },
+ "run_data" => run_data,
+ },
+ )
+ end
+ end
+ end
+
def self.purge_old
retention_days = SiteSetting.workflow_executions_retention_days
return if retention_days <= 0
diff --git a/plugins/discourse-workflows/app/services/discourse_workflows/workflow/execute_step.rb b/plugins/discourse-workflows/app/services/discourse_workflows/workflow/execute_step.rb
new file mode 100644
index 00000000000..ee04843db7b
--- /dev/null
+++ b/plugins/discourse-workflows/app/services/discourse_workflows/workflow/execute_step.rb
@@ -0,0 +1,111 @@
+# frozen_string_literal: true
+
+module DiscourseWorkflows
+ class Workflow::ExecuteStep
+ include Service::Base
+
+ params do
+ attribute :workflow_id, :integer
+ attribute :node_id, :string
+
+ validates :node_id, presence: true
+ end
+
+ policy :can_manage_workflows, class_name: Policy::CanManageWorkflows
+ model :workflow
+ model :workflow_snapshot
+ model :step_node
+ policy :step_node_executable
+ policy :step_node_not_waiting
+ model :source_execution, optional: true
+ model :source_run_data, optional: true
+ model :execution_plan
+ policy :step_data_reachable
+ policy :execution_path_not_waiting
+ model :trigger_data, optional: true
+ model :execution, :create_execution
+ step :enqueue_execution
+
+ private
+
+ def fetch_workflow(params:)
+ DiscourseWorkflows::Workflow.find_by(id: params.workflow_id)
+ end
+
+ def fetch_workflow_snapshot(workflow:)
+ DiscourseWorkflows::WorkflowSnapshot.from_workflow(workflow, published: false)
+ end
+
+ def fetch_step_node(workflow_snapshot:, params:)
+ workflow_snapshot.find_node(params.node_id)
+ end
+
+ def step_node_executable(step_node:)
+ return false if step_node.type.to_s.start_with?("trigger:")
+
+ node_type_class =
+ DiscourseWorkflows::Registry.find_node_type(step_node.type, version: step_node.type_version)
+ node_type_class.present? && node_type_class.available?
+ end
+
+ def step_node_not_waiting(step_node:)
+ DiscourseWorkflows::NodeType.waiting_identifiers.exclude?(step_node.type)
+ end
+
+ def fetch_source_execution(workflow:)
+ workflow.executions.successful.includes(:execution_data).order(created_at: :desc).first
+ end
+
+ def fetch_source_run_data(source_execution:)
+ source_execution&.execution_data&.run_data || {}
+ end
+
+ def fetch_execution_plan(workflow_snapshot:, step_node:, source_run_data:)
+ DiscourseWorkflows::StepExecutionPlan.new(
+ snapshot: workflow_snapshot,
+ target: step_node,
+ run_data: source_run_data,
+ )
+ end
+
+ def step_data_reachable(execution_plan:)
+ execution_plan.target_reachable?
+ end
+
+ def execution_path_not_waiting(execution_plan:)
+ waiting_identifiers = DiscourseWorkflows::NodeType.waiting_identifiers
+ execution_plan.executable_nodes.none? { |node| waiting_identifiers.include?(node.type) }
+ end
+
+ def fetch_trigger_data(execution_plan:, workflow:, source_execution:, guardian:)
+ trigger_root = execution_plan.trigger_roots_to_run.first
+ if trigger_root
+ DiscourseWorkflows::TriggerRuntime.manual_payload_for(
+ workflow: workflow,
+ trigger_node: trigger_root.to_workflow_node,
+ user: guardian.user,
+ )
+ else
+ source_execution&.trigger_data || {}
+ end
+ end
+
+ def create_execution(workflow:, step_node:, source_run_data:, trigger_data:)
+ DiscourseWorkflows::Execution.create_pending_step!(
+ workflow: workflow,
+ node_id: step_node.id,
+ trigger_data: trigger_data || {},
+ run_data: source_run_data,
+ )
+ end
+
+ def enqueue_execution(execution:, step_node:, guardian:)
+ Jobs.enqueue(
+ Jobs::DiscourseWorkflows::ExecuteManualWorkflow,
+ execution_id: execution.id,
+ user_id: guardian.user.id,
+ step_node_id: step_node.id,
+ )
+ end
+ end
+end
diff --git a/plugins/discourse-workflows/app/services/discourse_workflows/workflow/manual_execute.rb b/plugins/discourse-workflows/app/services/discourse_workflows/workflow/manual_execute.rb
index 90ae42d17c2..aa23904226f 100644
--- a/plugins/discourse-workflows/app/services/discourse_workflows/workflow/manual_execute.rb
+++ b/plugins/discourse-workflows/app/services/discourse_workflows/workflow/manual_execute.rb
@@ -46,28 +46,8 @@ module DiscourseWorkflows
def trigger_data(workflow:, trigger_node:, params:, user:)
return params.trigger_data if params.trigger_data.present?
return {} if workflow.node_pinned?(trigger_node["name"])
- return {} if trigger_node["type"] == "trigger:manual"
- node_type_class = node_type_for(trigger_node)
-
- if node_type_class.respond_to?(:trigger_data_for)
- return(
- node_type_class.trigger_data_for(DiscourseWorkflows::TriggerNodeContext.new(trigger_node))
- )
- end
-
- if node_type_class&.capability_enabled?(:synthesizes_manual_data)
- return TriggerRuntime.manual_trigger_data(workflow:, trigger_node:, user:)
- end
-
- {}
- end
-
- def node_type_for(trigger_node)
- DiscourseWorkflows::Registry.find_node_type(
- trigger_node["type"],
- version: trigger_node["typeVersion"],
- )
+ DiscourseWorkflows::TriggerRuntime.manual_payload_for(workflow:, trigger_node:, user:)
end
end
end
diff --git a/plugins/discourse-workflows/assets/stylesheets/common/canvas/canvas.scss b/plugins/discourse-workflows/assets/stylesheets/common/canvas/canvas.scss
index d024d724b5e..111c3f72772 100644
--- a/plugins/discourse-workflows/assets/stylesheets/common/canvas/canvas.scss
+++ b/plugins/discourse-workflows/assets/stylesheets/common/canvas/canvas.scss
@@ -315,6 +315,8 @@
}
.workflow-rete-node {
+ --icon-block-size: 56px;
+ --icon-block-width: var(--icon-block-size);
display: flex;
flex-direction: column;
align-items: center;
@@ -323,13 +325,21 @@
user-select: none;
width: 130px;
+ &__icon-block,
+ &__socket,
+ &__label,
+ &__description,
+ &__unavailable-pill {
+ pointer-events: auto;
+ }
+
&__icon-row {
position: relative;
}
&__icon-block {
- width: 56px;
- height: 56px;
+ width: var(--icon-block-width);
+ height: var(--icon-block-size);
display: flex;
align-items: center;
justify-content: center;
@@ -347,9 +357,7 @@
&.is-selected &__icon-block {
border-color: var(--tertiary);
background: color-mix(in srgb, var(--tertiary) 12%, var(--secondary));
- box-shadow:
- 0 0 0 2px var(--secondary),
- 0 0 0 5px var(--tertiary);
+ box-shadow: 0 0 0 1px var(--tertiary);
}
@media (prefers-reduced-motion: no-preference) {
@@ -360,8 +368,11 @@
}
}
+ &.is-trigger {
+ --icon-block-width: 74px;
+ }
+
&.is-trigger &__icon-block {
- width: 74px;
border-width: 2px;
border-color: var(--node-icon-color, var(--primary-medium));
border-radius: 999px 14px 14px 999px;
@@ -378,24 +389,6 @@
border-color: var(--tertiary);
}
- &__run-scope-tooltip {
- position: absolute;
- left: 50%;
- bottom: calc(100% + 2rem);
- transform: translateX(-50%);
- z-index: calc(var(--z-canvas-elements) + 2);
- padding: var(--space-half) var(--space-2);
- border-radius: var(--d-border-radius);
- background: var(--secondary);
- border: 1px solid var(--primary-low-mid);
- box-shadow: var(--shadow-dropdown);
- color: var(--primary);
- font-size: var(--font-down-3);
- line-height: 1.2;
- white-space: nowrap;
- pointer-events: none;
- }
-
&__icon {
display: flex;
align-items: center;
@@ -648,8 +641,40 @@
transform: scale(0.75);
}
+.is-connection-dragging
+ .workflow-rete-node-view:not(.is-connection-source)
+ .workflow-rete-node {
+ .workflow-rete-node__inputs:not(.has-multiple-inputs)
+ .workflow-rete-node__socket.--input::after,
+ &:not(.is-branching)
+ .workflow-rete-node__socket.--output:not(.--loop)::after {
+ content: "";
+ position: absolute;
+ top: calc((var(--socket-size) - var(--icon-block-size)) / 2);
+ width: calc(var(--node-width) + var(--socket-size));
+ height: var(--node-height);
+ }
+
+ .workflow-rete-node__inputs:not(.has-multiple-inputs)
+ .workflow-rete-node__socket.--input::after {
+ left: calc((var(--icon-block-width) - var(--node-width)) / 2);
+ }
+
+ &:not(.is-branching)
+ .workflow-rete-node__socket.--output:not(.--loop)::after {
+ left: calc(2px - (var(--node-width) + var(--icon-block-width)) / 2);
+ }
+}
+
+.is-connection-dragging
+ .workflow-rete-node:has(.workflow-rete-node__socket:hover)
+ .workflow-rete-node__icon-block {
+ border-color: var(--tertiary);
+}
+
.workflow-rete-node-view {
z-index: var(--z-canvas-elements);
+ pointer-events: none;
}
@keyframes workflow-socket-connectable-pulse {
diff --git a/plugins/discourse-workflows/assets/stylesheets/common/canvas/sticky-note.scss b/plugins/discourse-workflows/assets/stylesheets/common/canvas/sticky-note.scss
index 62f7bdd872b..f407abf945e 100644
--- a/plugins/discourse-workflows/assets/stylesheets/common/canvas/sticky-note.scss
+++ b/plugins/discourse-workflows/assets/stylesheets/common/canvas/sticky-note.scss
@@ -1,6 +1,6 @@
.workflow-sticky-note {
position: absolute;
- z-index: 0;
+ z-index: -1;
border-radius: 4px;
box-shadow: 0 2px 8px rgb(0 0 0 / 0.12);
pointer-events: auto;
@@ -24,6 +24,10 @@
}
}
+ &.is-editing {
+ z-index: calc(var(--z-canvas-elements) + 1);
+ }
+
&.is-selected {
outline: 2px solid var(--tertiary);
outline-offset: -1px;
diff --git a/plugins/discourse-workflows/assets/stylesheets/common/configurator/configurator-modal.scss b/plugins/discourse-workflows/assets/stylesheets/common/configurator/configurator-modal.scss
index c70340465cc..98600c93134 100644
--- a/plugins/discourse-workflows/assets/stylesheets/common/configurator/configurator-modal.scss
+++ b/plugins/discourse-workflows/assets/stylesheets/common/configurator/configurator-modal.scss
@@ -189,6 +189,19 @@
}
}
+ &__run-scope {
+ display: flex;
+ align-items: center;
+ gap: var(--space-1);
+ margin-bottom: var(--space-3);
+ color: var(--primary-medium);
+ font-size: var(--font-down-1);
+
+ .d-icon {
+ color: var(--primary-medium);
+ }
+ }
+
&__node {
border: 1px solid var(--content-border-color);
padding: var(--space-2);
diff --git a/plugins/discourse-workflows/assets/stylesheets/common/editor/editor.scss b/plugins/discourse-workflows/assets/stylesheets/common/editor/editor.scss
index 03bb0e0ae66..31702e0fc5a 100644
--- a/plugins/discourse-workflows/assets/stylesheets/common/editor/editor.scss
+++ b/plugins/discourse-workflows/assets/stylesheets/common/editor/editor.scss
@@ -59,9 +59,3 @@
padding: 0 var(--space-2);
}
}
-
-.workflows-unpublished-draft-dialog {
- .dialog-footer &__discard-btn {
- margin-left: auto;
- }
-}
diff --git a/plugins/discourse-workflows/config/locales/client.en.yml b/plugins/discourse-workflows/config/locales/client.en.yml
index 35ecba28423..61cc491ad23 100644
--- a/plugins/discourse-workflows/config/locales/client.en.yml
+++ b/plugins/discourse-workflows/config/locales/client.en.yml
@@ -116,7 +116,6 @@ en:
unpublished_changes_message: "You have unpublished changes"
unpublished_changes_message_detail: "Publish to make them live"
unpublished_changes_confirmation: "This workflow has unpublished changes. If you leave now, those changes will stay in draft and won't run until you publish them."
- leave_without_publishing: "Leave without publishing"
keep_editing: "Keep editing"
workflow_name: "Workflow name"
creator: "Creator"
@@ -1207,6 +1206,10 @@ en:
view_execution: "View execution"
listening: "Listening for test webhook event"
needs_pin_data: "Pin sample data on this trigger before running it manually."
+ execute_step:
+ run: "Execute step"
+ triggered: "Step execution started"
+ view_execution: "View execution"
pin_data:
pin: "Pin data"
unpin: "Unpin"
diff --git a/plugins/discourse-workflows/config/locales/server.en.yml b/plugins/discourse-workflows/config/locales/server.en.yml
index da3c22ab221..79a84d40669 100644
--- a/plugins/discourse-workflows/config/locales/server.en.yml
+++ b/plugins/discourse-workflows/config/locales/server.en.yml
@@ -41,6 +41,11 @@ en:
summarizing: "Preparing workflow authoring response"
errors:
approval_timed_out: "Approval timed out"
+ step_execution:
+ not_executable: "This node cannot be executed as a single step."
+ waiting_not_supported: "Nodes that wait for a response cannot run during a step execution. Run the workflow or pin data past them first."
+ missing_input_data: "No data can reach this node. Run the workflow or pin data on an upstream node first."
+ wait_requested: "This node requested to wait, which is not supported when executing a single step."
webhook_timed_out: "Webhook timed out"
schedule_rules_required: "At least one schedule rule is required."
invalid_schedule_rule: "One or more schedule rules are invalid."
diff --git a/plugins/discourse-workflows/config/routes.rb b/plugins/discourse-workflows/config/routes.rb
index d2817b0e4fa..8919cf9e94a 100644
--- a/plugins/discourse-workflows/config/routes.rb
+++ b/plugins/discourse-workflows/config/routes.rb
@@ -45,6 +45,7 @@ DiscourseWorkflows::Engine.routes.draw do
get "/templates" => "templates#index"
get "/templates/:id" => "templates#show"
post "/executions" => "executions#create"
+ post "/step-executions" => "step_executions#create"
get "/executions" => "executions#index"
get "/workflows/:workflow_id/executions" => "executions#index"
get "/workflows/:workflow_id/versions" => "workflow_versions#index"
diff --git a/plugins/discourse-workflows/lib/discourse_workflows/executor.rb b/plugins/discourse-workflows/lib/discourse_workflows/executor.rb
index b20fa630695..77ec1f808e9 100644
--- a/plugins/discourse-workflows/lib/discourse_workflows/executor.rb
+++ b/plugins/discourse-workflows/lib/discourse_workflows/executor.rb
@@ -127,23 +127,12 @@ module DiscourseWorkflows
return @store.create_rate_limited_execution unless rate_limiter.within_limits?
execute_flow(:start_execution!) do
+ next prepare_step_flow! if step_mode?
+
trigger_node = @snapshot.find_node(@trigger_node_id)
raise "Trigger node #{@trigger_node_id} not found in workflow snapshot" if trigger_node.nil?
- trigger_items =
- pinned_items_for(trigger_node) ||
- (
- if @trigger_data.is_a?(Array)
- @trigger_data.map { |data| Item.wrap(data) }
- else
- [Item.wrap(@trigger_data)]
- end
- )
- ItemContract.validate_items!(trigger_items, source: "trigger:#{trigger_node.type}")
- record_step(trigger_node, [], output: trigger_items, status: Step::SUCCESS)
- @context.store_node_output(trigger_node, trigger_items)
- @context.store_node_run(trigger_node, inputs: [], outputs: [trigger_items])
- enqueue_downstream(trigger_node, 0, trigger_items)
+ seed_trigger_node!(trigger_node)
end
end
@@ -202,6 +191,56 @@ module DiscourseWorkflows
private
+ def step_mode?
+ @options.step_node_id.present?
+ end
+
+ def prepare_step_flow!
+ step_node = @snapshot.find_node(@options.step_node_id)
+ raise "Step node #{@options.step_node_id} not found in workflow snapshot" if step_node.nil?
+
+ @pin_data_by_node_name.delete(step_node.name.to_s)
+ @step_plan =
+ StepExecutionPlan.new(
+ snapshot: @snapshot,
+ target: step_node,
+ run_data: @store.existing_run_data,
+ )
+
+ if @step_plan.standalone_target?
+ @queue << [step_node, { 0 => [Item.wrap({})] }, {}]
+ return
+ end
+
+ @step_plan.cached_frontier.each { |node| emit_cached_node!(node) }
+ @step_plan.trigger_roots_to_run.each { |trigger_node| seed_trigger_node!(trigger_node) }
+ end
+
+ def emit_cached_node!(node)
+ output_groups = @step_plan.cached_outputs(node)
+ step = record_step(node, [])
+ step.succeed!(output: output_groups.flatten(1))
+ step.add_metadata("cached", true)
+ route_downstream(node, output_groups)
+ end
+
+ def seed_trigger_node!(trigger_node)
+ trigger_items =
+ pinned_items_for(trigger_node) ||
+ (
+ if @trigger_data.is_a?(Array)
+ @trigger_data.map { |data| Item.wrap(data) }
+ else
+ [Item.wrap(@trigger_data)]
+ end
+ )
+ ItemContract.validate_items!(trigger_items, source: "trigger:#{trigger_node.type}")
+ record_step(trigger_node, [], output: trigger_items, status: Step::SUCCESS)
+ @context.store_node_output(trigger_node, trigger_items)
+ @context.store_node_run(trigger_node, inputs: [], outputs: [trigger_items])
+ enqueue_downstream(trigger_node, 0, trigger_items)
+ end
+
def normalized_workflow_call_stack
stack = Array(@options.workflow_call_stack).map(&:to_s)
workflow_id = @workflow.id.to_s
@@ -317,6 +356,10 @@ module DiscourseWorkflows
wait_request = runtime_state.wait_request
if wait_request
+ if step_mode?
+ raise StandardError, I18n.t("discourse_workflows.errors.step_execution.wait_requested")
+ end
+
step.mark_waiting!
@waiting_node = node
@waiting_step = step
@@ -685,21 +728,24 @@ module DiscourseWorkflows
end
def enqueue_downstream(node, output_index, items)
+ return if step_mode? && node.id.to_s == @step_plan.target_id
+
@snapshot
.connections_from_output_index(node, output_index)
.each do |conn|
target = @snapshot.target_node(conn)
- if target
- enqueue_target(
- target,
- conn.target_input_index,
- items,
- source: {
- "node_name" => node.name,
- "output_index" => output_index,
- },
- )
- end
+ next if target.nil?
+ next if step_mode? && !@step_plan.runnable?(target)
+
+ enqueue_target(
+ target,
+ conn.target_input_index,
+ items,
+ source: {
+ "node_name" => node.name,
+ "output_index" => output_index,
+ },
+ )
end
end
diff --git a/plugins/discourse-workflows/lib/discourse_workflows/executor/execution_options.rb b/plugins/discourse-workflows/lib/discourse_workflows/executor/execution_options.rb
index 0bb428afec9..aeeb2791132 100644
--- a/plugins/discourse-workflows/lib/discourse_workflows/executor/execution_options.rb
+++ b/plugins/discourse-workflows/lib/discourse_workflows/executor/execution_options.rb
@@ -15,6 +15,7 @@ module DiscourseWorkflows
:workflow_call_caller,
:workflow_call_run_id,
:workflow_call_child,
+ :step_node_id,
) do
def initialize(
user: nil,
@@ -27,7 +28,8 @@ module DiscourseWorkflows
workflow_call_stack: [],
workflow_call_caller: nil,
workflow_call_run_id: nil,
- workflow_call_child: false
+ workflow_call_child: false,
+ step_node_id: nil
)
super
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 aeea0d854f4..8471024f1f9 100644
--- a/plugins/discourse-workflows/lib/discourse_workflows/executor/execution_store.rb
+++ b/plugins/discourse-workflows/lib/discourse_workflows/executor/execution_store.rb
@@ -11,7 +11,7 @@ module DiscourseWorkflows
delegate :workflow, :trigger_data, to: :@execution_context
- attr_reader :trigger_node_id, :execution, :workflow_snapshot
+ attr_reader :trigger_node_id, :execution, :workflow_snapshot, :existing_run_data
def initialize(trigger_node_id:, execution_context:, execution_mode:, options:)
@trigger_node_id = trigger_node_id.to_s
@@ -38,6 +38,7 @@ module DiscourseWorkflows
)
@execution = create_execution!
reset_collaborators!
+ restore_seeded_run_data!
@execution
end
@@ -159,6 +160,25 @@ module DiscourseWorkflows
@execution_context.reset!
end
+ def restore_seeded_run_data!
+ seeded = @options.existing_execution&.execution_data&.run_data
+ return if seeded.blank?
+
+ @existing_run_data = seeded_runs_matching_snapshot(seeded)
+ restore_node_runs_from_run_data
+ end
+
+ def seeded_runs_matching_snapshot(seeded)
+ seeded.each_with_object({}) do |(node_name, runs), result|
+ node = @workflow_snapshot.find_node_by_name(node_name)
+ next if node.nil?
+
+ matching_runs =
+ Array(runs).select { |run| StepExecutionPlan.run_matches_node?(run, node) }
+ result[node_name] = matching_runs if matching_runs.any?
+ end
+ end
+
def restore_from!(execution_data)
@workflow_snapshot =
if execution_data&.workflow_data.present?
@@ -350,13 +370,11 @@ module DiscourseWorkflows
node_runs.each_with_object({}) do |(node_name, runs), result|
existing_run_count = Array(@existing_run_data[node_name]).length
- result[node_name] = Array(runs)
- .drop(existing_run_count)
- .map
- .with_index do |run, index|
- step = Array(steps_by_name[node_name])[existing_run_count + index]
- serialize_node_run(node_name, run, step, existing_run_count + index)
- end
+ new_runs = Array(runs).drop(existing_run_count)
+ node_steps = Array(steps_by_name[node_name]).last(new_runs.length)
+ result[node_name] = new_runs.map.with_index do |run, index|
+ serialize_node_run(node_name, run, node_steps[index], existing_run_count + index)
+ end
end
end
diff --git a/plugins/discourse-workflows/lib/discourse_workflows/step_execution_plan.rb b/plugins/discourse-workflows/lib/discourse_workflows/step_execution_plan.rb
new file mode 100644
index 00000000000..c554b591efd
--- /dev/null
+++ b/plugins/discourse-workflows/lib/discourse_workflows/step_execution_plan.rb
@@ -0,0 +1,194 @@
+# frozen_string_literal: true
+
+module DiscourseWorkflows
+ class StepExecutionPlan
+ COMPLETED_RUN_STATUSES = [
+ Executor::Step::SUCCESS,
+ Executor::Step::FILTERED,
+ Executor::Step::SKIPPED,
+ ].freeze
+
+ def self.run_matches_node?(run, node)
+ run_node_id = run["node_id"]
+ return false if run_node_id.present? && run_node_id.to_s != node.id.to_s
+
+ run_node_type = run["node_type"]
+ return false if run_node_type.present? && run_node_type != node.type
+
+ true
+ end
+
+ attr_reader :target
+
+ def initialize(snapshot:, target:, run_data:)
+ @snapshot = snapshot
+ @target = target
+ @run_data = run_data || {}
+ @nodes_by_id = upstream_closure
+ @classifications = @nodes_by_id.transform_values { |node| classify(node) }
+ @producible = {}
+ end
+
+ def target_id
+ @target.id.to_s
+ end
+
+ def standalone_target?
+ @snapshot.connections_to(@target).empty?
+ end
+
+ def runnable?(node)
+ @classifications[node.id.to_s] == :execute
+ end
+
+ def executable_nodes
+ @nodes_by_id.values.select { |node| runnable?(node) }
+ end
+
+ def trigger_roots_to_run
+ executable_nodes.select { |node| trigger?(node) }
+ end
+
+ def cached_frontier
+ @nodes_by_id
+ .values
+ .select { |node| @classifications[node.id.to_s] == :cached }
+ .select { |node| all_outbound_connections(node).any? { |conn| feeds_runnable?(conn) } }
+ end
+
+ def target_reachable?
+ standalone_target? || inputs_satisfiable?(@target)
+ end
+
+ def cached_outputs(node)
+ pinned_output_groups(node) || run_output_groups(node) || []
+ end
+
+ private
+
+ def upstream_closure
+ closure = { @target.id.to_s => @target }
+ queue = [@target]
+
+ while (node = queue.shift)
+ @snapshot
+ .connections_to(node)
+ .each do |connection|
+ source = @snapshot.source_node(connection)
+ next if source.nil? || closure.key?(source.id.to_s)
+
+ closure[source.id.to_s] = source
+ queue << source
+ end
+ end
+
+ closure
+ end
+
+ def classify(node)
+ return :execute if node.id.to_s == target_id
+ return :cached if cached_outputs(node).present?
+
+ return manually_triggerable?(node) ? :execute : :unavailable if trigger?(node)
+
+ @snapshot.connections_to(node).empty? ? :unavailable : :execute
+ end
+
+ def trigger?(node)
+ node.type.to_s.start_with?("trigger:")
+ end
+
+ def manually_triggerable?(node)
+ node_type_class(node)&.manually_triggerable? == true
+ end
+
+ def node_type_class(node)
+ Registry.find_node_type(node.type, version: node.type_version)
+ end
+
+ def all_outbound_connections(node)
+ @snapshot.connections.select { |conn| conn.source_node_id == node.id.to_s }
+ end
+
+ def feeds_runnable?(connection)
+ target_node = @snapshot.target_node(connection)
+ target_node.present? && runnable?(target_node)
+ end
+
+ def producible?(node)
+ node_id = node.id.to_s
+ return @producible[node_id] if @producible.key?(node_id)
+
+ # Break cycles (e.g. loop-back edges): a node cannot vouch for itself.
+ @producible[node_id] = false
+
+ @producible[node_id] = case @classifications[node_id]
+ when :cached
+ true
+ when :execute
+ trigger?(node) || standalone?(node) || inputs_satisfiable?(node)
+ else
+ false
+ end
+ end
+
+ def standalone?(node)
+ @snapshot.connections_to(node).empty?
+ end
+
+ def inputs_satisfiable?(node)
+ satisfied, unsatisfied =
+ @snapshot
+ .connections_to(node)
+ .group_by { |connection| connection.target_input_index.to_i }
+ .partition do |_index, connections|
+ connections.any? do |connection|
+ source = @snapshot.source_node(connection)
+ source.present? && producible?(source)
+ end
+ end
+
+ return true if unsatisfied.empty?
+
+ requirements = node_type_class(node)&.required_inputs(node.parameters)
+ if requirements.is_a?(Integer)
+ satisfied.length >= requirements
+ elsif requirements.present?
+ required = Array(requirements).map(&:to_i)
+ unsatisfied.none? { |index, _connections| required.include?(index) }
+ else
+ false
+ end
+ end
+
+ def pinned_output_groups(node)
+ raw_items = (@snapshot.pin_data || {})[node.name.to_s]
+ return nil if raw_items.blank?
+
+ node_type_class = node_type_class(node)
+ return nil if node_type_class.nil?
+ return nil if Array(node_type_class.outputs).length > 1
+
+ [Item.normalize_items(raw_items)]
+ rescue Item::InconsistentItemFormatError
+ nil
+ end
+
+ def run_output_groups(node)
+ run =
+ Array(@run_data[node.name.to_s]).reverse_each.find do |entry|
+ COMPLETED_RUN_STATUSES.include?(entry["status"]) &&
+ self.class.run_matches_node?(entry, node)
+ end
+ return nil if run.nil?
+
+ ports = Array(run["outputs"])
+ max_index = ports.map { |port| port["index"].to_i }.max
+ return nil if max_index.nil?
+
+ groups = Array.new(max_index + 1) { [] }
+ ports.each { |port| groups[port["index"].to_i] = Array(port["items"]) }
+ groups
+ end
+ end
+end
diff --git a/plugins/discourse-workflows/lib/discourse_workflows/trigger_runtime.rb b/plugins/discourse-workflows/lib/discourse_workflows/trigger_runtime.rb
index 58006bb86f5..f106236ce04 100644
--- a/plugins/discourse-workflows/lib/discourse_workflows/trigger_runtime.rb
+++ b/plugins/discourse-workflows/lib/discourse_workflows/trigger_runtime.rb
@@ -35,6 +35,18 @@ module DiscourseWorkflows
Webhook::Action::DeactivateWebhooks.call(workflow: workflow)
end
+ def manual_payload_for(workflow:, trigger_node:, user:)
+ return {} if trigger_node["type"] == "trigger:manual"
+
+ node_type_class = node_type_for(trigger_node)
+ if node_type_class.respond_to?(:trigger_data_for)
+ return node_type_class.trigger_data_for(TriggerNodeContext.new(trigger_node))
+ end
+ return {} unless node_type_class&.capability_enabled?(:synthesizes_manual_data)
+
+ manual_trigger_data(workflow:, trigger_node:, user:)
+ end
+
def manual_trigger_data(workflow:, trigger_node:, user:)
workflow_version = workflow.workflow_versions.find_by(version_id: workflow.version_id)
node_type_class = node_type_for(trigger_node)
diff --git a/plugins/discourse-workflows/spec/lib/discourse_workflows/executor_step_execution_spec.rb b/plugins/discourse-workflows/spec/lib/discourse_workflows/executor_step_execution_spec.rb
new file mode 100644
index 00000000000..4c9344e34a3
--- /dev/null
+++ b/plugins/discourse-workflows/spec/lib/discourse_workflows/executor_step_execution_spec.rb
@@ -0,0 +1,392 @@
+# frozen_string_literal: true
+
+RSpec.describe DiscourseWorkflows::Executor do
+ fab!(:user)
+
+ def build_chain_workflow
+ graph =
+ build_workflow_graph do |g|
+ g.node "trigger-1", "trigger:post_created", name: "Post Created"
+ g.node "set-1",
+ "action:set_fields",
+ name: "Set 1",
+ configuration: {
+ "mode" => "raw",
+ "include_other_fields" => true,
+ "json_output" => '{"a": 1}',
+ }
+ g.node "set-2",
+ "action:set_fields",
+ name: "Set 2",
+ configuration: {
+ "mode" => "raw",
+ "include_other_fields" => true,
+ "json_output" => '{"b": 2}',
+ }
+ g.node "set-3",
+ "action:set_fields",
+ name: "Set 3",
+ configuration: {
+ "mode" => "raw",
+ "include_other_fields" => true,
+ "json_output" => '{"c": 3}',
+ }
+ g.chain "trigger-1", "set-1", "set-2", "set-3"
+ end
+ Fabricate(:discourse_workflows_workflow, created_by: user, published: true, **graph)
+ end
+
+ let(:workflow) { build_chain_workflow }
+
+ let(:manual_options) do
+ DiscourseWorkflows::Executor::ExecutionOptions.new(
+ user: user,
+ execution_mode: :manual,
+ draft_execution: true,
+ )
+ end
+
+ def run_full_execution(workflow)
+ described_class.new(workflow, "trigger-1", { "seed" => true }, manual_options).run
+ end
+
+ def create_step_execution(workflow, node_id, source: nil)
+ DiscourseWorkflows::Execution.create_pending_step!(
+ workflow: workflow,
+ node_id: node_id,
+ trigger_data: source&.trigger_data || {},
+ run_data: source ? source.execution_data.run_data : {},
+ )
+ end
+
+ def run_step_execution(workflow, node_id, source: nil)
+ step_execution = create_step_execution(workflow, node_id, source: source)
+ claimed = DiscourseWorkflows::Execution.claim_pending(step_execution)
+ options =
+ DiscourseWorkflows::Executor::ExecutionOptions.new(
+ user: user,
+ execution_mode: :manual,
+ workflow_snapshot:
+ DiscourseWorkflows::WorkflowSnapshot.new(step_execution.execution_data.workflow_data),
+ existing_execution: claimed,
+ step_node_id: node_id,
+ )
+ described_class.new(workflow, node_id, claimed.trigger_data, options).run
+ end
+
+ def seeded_output(source, node_name)
+ source.execution_data.run_data[node_name].first["outputs"].first["items"]
+ end
+
+ describe "step execution over seeded run data" do
+ it "executes only the target node when driven through the manual workflow job" do
+ source = run_full_execution(workflow)
+ step_execution = create_step_execution(workflow, "set-2", source: source)
+
+ Jobs::DiscourseWorkflows::ExecuteManualWorkflow.new.execute(
+ execution_id: step_execution.id,
+ user_id: user.id,
+ step_node_id: "set-2",
+ )
+
+ step_execution.reload
+ expect(step_execution.status).to eq("success")
+ entries = step_execution.execution_data.entries
+ expect(entries.keys).to contain_exactly("set-1", "set-2")
+ expect(entries["set-1"].first.dig("metadata", "cached")).to eq(true)
+ expect(step_execution.execution_data.run_data["Set 1"].length).to eq(1)
+ expect(step_execution.execution_data.run_data["Set 3"].length).to eq(1)
+ end
+
+ it "reuses the cached frontier and executes only the target" do
+ source = run_full_execution(workflow)
+
+ execution = run_step_execution(workflow, "set-3", source: source)
+
+ entries = execution.execution_data.entries
+ expect(entries.keys).to contain_exactly("set-2", "set-3")
+ expect(entries["set-2"].first.dig("metadata", "cached")).to eq(true)
+ expect(entries["set-3"].first["input"]).to eq(seeded_output(source, "Set 2"))
+ end
+
+ it "feeds the target node the upstream output recorded in the seeded run data" do
+ source = run_full_execution(workflow)
+
+ execution = run_step_execution(workflow, "set-2", source: source)
+
+ entry = execution.execution_data.entries["set-2"].first
+ expect(entry["input"]).to eq(seeded_output(source, "Set 1"))
+
+ new_run = execution.execution_data.run_data["Set 2"].last
+ expect(new_run["inputs"].first["items"]).to eq(seeded_output(source, "Set 1"))
+ expect(new_run["inputs"].first["source"]).to eq("node_name" => "Set 1", "output_index" => 0)
+ expect(entry["output"].first["json"]).to include("seed" => true, "a" => 1, "b" => 2)
+ end
+
+ it "persists the union of the seeded runs and the new step run" do
+ source = run_full_execution(workflow)
+
+ execution = run_step_execution(workflow, "set-2", source: source)
+
+ run_data = execution.execution_data.run_data
+ expect(run_data.keys).to contain_exactly("Post Created", "Set 1", "Set 2", "Set 3")
+ expect(run_data["Post Created"].length).to eq(1)
+ expect(run_data["Set 1"].length).to eq(1)
+ expect(run_data["Set 3"].length).to eq(1)
+ expect(run_data["Set 2"].length).to eq(2)
+ expect(run_data["Set 2"].last["outputs"].first["items"].first["json"]).to include(
+ "seed" => true,
+ "a" => 1,
+ "b" => 2,
+ )
+ end
+
+ it "publishes the union of seeded and new run data over MessageBus" do
+ source = run_full_execution(workflow)
+
+ messages =
+ MessageBus.track_publish("/discourse-workflows/workflow/#{workflow.id}") do
+ run_step_execution(workflow, "set-2", source: source)
+ end
+
+ message = messages.find { |m| m.data[:type] == "execution_completed" }
+ expect(message.data[:lastExecutionRunData].keys).to contain_exactly(
+ "Post Created",
+ "Set 1",
+ "Set 2",
+ "Set 3",
+ )
+ expect(message.data[:lastExecutionRunData]["Set 2"].length).to eq(2)
+ end
+ end
+
+ describe "step execution with pin data" do
+ it "prefers pinned data on the upstream node over the seeded run output" do
+ source = run_full_execution(workflow)
+ workflow.update_node_pin_data!("Set 1", [{ "json" => { "pinned" => true } }])
+
+ execution = run_step_execution(workflow, "set-2", source: source)
+
+ entry = execution.execution_data.entries["set-2"].first
+ expect(entry["input"].map { |item| item["json"] }).to eq([{ "pinned" => true }])
+ expect(entry["output"].first["json"]).to include("pinned" => true, "b" => 2)
+ end
+
+ it "executes the target node for real even when it has its own pinned data" do
+ source = run_full_execution(workflow)
+ workflow.update_node_pin_data!("Set 2", [{ "json" => { "frozen" => true } }])
+
+ execution = run_step_execution(workflow, "set-2", source: source)
+
+ entry = execution.execution_data.entries["set-2"].first
+ expect(entry["output"].first["json"]).to include("seed" => true, "a" => 1, "b" => 2)
+ expect(entry["output"].first["json"]).not_to have_key("frozen")
+ expect(entry.dig("metadata", "pinned")).to be_nil
+ end
+ end
+
+ describe "step execution downstream of a false branch" do
+ it "feeds the target the filtered run's false-port output" do
+ graph =
+ build_workflow_graph do |g|
+ g.node "trigger-1", "trigger:post_created", name: "Post Created"
+ g.node "if-1",
+ "condition:if",
+ name: "If",
+ configuration: {
+ "conditions" => [
+ {
+ "id" => "1",
+ "leftValue" => 1,
+ "rightValue" => 2,
+ "operator" => {
+ "type" => "number",
+ "operation" => "equals",
+ },
+ },
+ ],
+ "combinator" => "and",
+ }
+ g.node "set-1",
+ "action:set_fields",
+ name: "On false",
+ configuration: {
+ "mode" => "raw",
+ "include_other_fields" => true,
+ "json_output" => '{"handled": true}',
+ }
+ g.chain "trigger-1", "if-1"
+ g.connect "if-1", "set-1", output: "false"
+ end
+ branch_workflow =
+ Fabricate(:discourse_workflows_workflow, created_by: user, published: true, **graph)
+
+ source = run_full_execution(branch_workflow)
+ if_run = source.execution_data.run_data["If"].first
+ expect(if_run["status"]).to eq("filtered")
+
+ execution = run_step_execution(branch_workflow, "set-1", source: source)
+
+ expect(execution.status).to eq("success")
+ entry = execution.execution_data.entries["set-1"].first
+ expect(entry["input"]).to eq(if_run["outputs"].last["items"])
+ expect(entry["output"].first["json"]).to include("seed" => true, "handled" => true)
+
+ new_run = execution.execution_data.run_data["On false"].last
+ expect(new_run["inputs"].first["source"]).to eq("node_name" => "If", "output_index" => 1)
+ end
+ end
+
+ describe "step execution with stale seeded run data" do
+ it "re-executes a node whose cached runs belong to a different node id" do
+ source = run_full_execution(workflow)
+ stale_run_data = source.execution_data.run_data.deep_dup
+ stale_run_data["Set 1"].each { |run| run["node_id"] = "recreated-set-1" }
+
+ step_execution =
+ DiscourseWorkflows::Execution.create_pending_step!(
+ workflow: workflow,
+ node_id: "set-2",
+ trigger_data: source.trigger_data,
+ run_data: stale_run_data,
+ )
+ claimed = DiscourseWorkflows::Execution.claim_pending(step_execution)
+ options =
+ DiscourseWorkflows::Executor::ExecutionOptions.new(
+ user: user,
+ execution_mode: :manual,
+ workflow_snapshot:
+ DiscourseWorkflows::WorkflowSnapshot.new(step_execution.execution_data.workflow_data),
+ existing_execution: claimed,
+ step_node_id: "set-2",
+ )
+ execution = described_class.new(workflow, "set-2", claimed.trigger_data, options).run
+
+ expect(execution.status).to eq("success")
+ entries = execution.execution_data.entries
+ expect(entries.keys).to contain_exactly("trigger-1", "set-1", "set-2")
+ expect(entries["trigger-1"].first.dig("metadata", "cached")).to eq(true)
+ expect(entries["set-2"].first["input"]).to eq(entries["set-1"].first["output"])
+
+ run_data = execution.execution_data.run_data
+ expect(run_data["Set 1"].length).to eq(1)
+ expect(run_data["Set 1"].first["node_id"]).to eq("set-1")
+ end
+ end
+
+ describe "step execution without cached upstream data" do
+ it "runs the un-cached upstream chain up to the target" do
+ workflow.update_node_pin_data!("Post Created", [{ "json" => { "cold" => true } }])
+
+ execution = run_step_execution(workflow, "set-2")
+
+ expect(execution.status).to eq("success")
+ entries = execution.execution_data.entries
+ expect(entries.keys).to contain_exactly("trigger-1", "set-1", "set-2")
+ expect(entries["trigger-1"].first.dig("metadata", "cached")).to eq(true)
+ expect(entries["set-2"].first["output"].first["json"]).to include(
+ "cold" => true,
+ "a" => 1,
+ "b" => 2,
+ )
+ end
+
+ it "seeds an un-cached manually triggerable trigger" do
+ graph =
+ build_workflow_graph do |g|
+ g.node "trigger-1", "trigger:manual", name: "Manual"
+ g.node "set-1",
+ "action:set_fields",
+ name: "Set 1",
+ configuration: {
+ "mode" => "raw",
+ "include_other_fields" => true,
+ "json_output" => '{"a": 1}',
+ }
+ g.chain "trigger-1", "set-1"
+ end
+ manual_workflow =
+ Fabricate(:discourse_workflows_workflow, created_by: user, published: true, **graph)
+
+ execution = run_step_execution(manual_workflow, "set-1")
+
+ expect(execution.status).to eq("success")
+ entries = execution.execution_data.entries
+ expect(entries.keys).to contain_exactly("trigger-1", "set-1")
+ expect(entries["trigger-1"].first.dig("metadata", "cached")).to be_nil
+ expect(entries["set-1"].first["input"]).to eq([{ "json" => {} }])
+ end
+ end
+
+ describe "consecutive step executions" do
+ it "feeds later step runs the latest output of earlier ones" do
+ source = run_full_execution(workflow)
+ update_workflow_node(workflow, "set-1") do |node|
+ node["parameters"] = node["parameters"].merge("json_output" => '{"a": 2}')
+ node
+ end
+
+ first = run_step_execution(workflow, "set-1", source: source)
+ first_run = first.execution_data.run_data["Set 1"].last
+ expect(first_run["status"]).to eq("success")
+ expect(first_run["node_id"]).to eq("set-1")
+
+ second = run_step_execution(workflow, "set-2", source: first)
+ expect(second.execution_data.entries["set-2"].first["input"].first["json"]).to include(
+ "a" => 2,
+ )
+ end
+ end
+
+ describe "step execution of a node with no inbound connections" do
+ it "executes with a single empty input item" do
+ graph =
+ build_workflow_graph do |g|
+ g.node "trigger-1", "trigger:post_created", name: "Post Created"
+ g.node "solo-1",
+ "action:set_fields",
+ name: "Solo",
+ configuration: {
+ "mode" => "raw",
+ "include_other_fields" => true,
+ "json_output" => '{"solo": true}',
+ }
+ end
+ standalone_workflow =
+ Fabricate(:discourse_workflows_workflow, created_by: user, published: true, **graph)
+
+ execution = run_step_execution(standalone_workflow, "solo-1")
+
+ expect(execution.status).to eq("success")
+ entry = execution.execution_data.entries["solo-1"].first
+ expect(entry["input"]).to eq([{ "json" => {} }])
+ expect(entry["output"].first["json"]).to eq("solo" => true)
+ end
+ end
+
+ describe "step execution of a node requesting a wait" do
+ it "fails the execution instead of pausing it" do
+ graph =
+ build_workflow_graph do |g|
+ g.node "trigger-1", "trigger:post_created", name: "Post Created"
+ g.node "wait-1",
+ "flow:wait",
+ name: "Wait",
+ configuration: {
+ "resume" => "time_interval",
+ "wait_amount" => 1,
+ "wait_unit" => "seconds",
+ }
+ end
+ wait_workflow =
+ Fabricate(:discourse_workflows_workflow, created_by: user, published: true, **graph)
+
+ execution = run_step_execution(wait_workflow, "wait-1")
+
+ expect(execution.status).to eq("error")
+ expect(execution.error).to eq(
+ I18n.t("discourse_workflows.errors.step_execution.wait_requested"),
+ )
+ end
+ end
+end
diff --git a/plugins/discourse-workflows/spec/lib/discourse_workflows/step_execution_plan_spec.rb b/plugins/discourse-workflows/spec/lib/discourse_workflows/step_execution_plan_spec.rb
new file mode 100644
index 00000000000..36d092696a1
--- /dev/null
+++ b/plugins/discourse-workflows/spec/lib/discourse_workflows/step_execution_plan_spec.rb
@@ -0,0 +1,210 @@
+# frozen_string_literal: true
+
+RSpec.describe DiscourseWorkflows::StepExecutionPlan do
+ def snapshot_for(graph, pin_data: {})
+ DiscourseWorkflows::WorkflowSnapshot.new(
+ "name" => "Test workflow",
+ "nodes" => graph[:nodes],
+ "connections" => graph[:connections],
+ "pinData" => pin_data,
+ )
+ end
+
+ def plan_for(snapshot, node_id, run_data = {})
+ described_class.new(snapshot: snapshot, target: snapshot.find_node(node_id), run_data: run_data)
+ end
+
+ def run_entry(node_id:, node_type:, outputs:, status: "success")
+ { "node_id" => node_id, "node_type" => node_type, "status" => status, "outputs" => outputs }
+ end
+
+ def output_port(index, items)
+ { "index" => index, "items" => items }
+ end
+
+ def source_run(items, status: "success", node_id: "set-1")
+ run_entry(
+ node_id: node_id,
+ node_type: "action:set_fields",
+ status: status,
+ outputs: [output_port(0, items)],
+ )
+ end
+
+ let(:chain_graph) do
+ build_workflow_graph do |g|
+ g.node "trigger-1", "trigger:post_created", name: "Trigger"
+ g.node "set-1", "action:set_fields", name: "Source"
+ g.node "set-2", "action:set_fields", name: "Target"
+ g.chain "trigger-1", "set-1", "set-2"
+ end
+ end
+
+ let(:chain_snapshot) { snapshot_for(chain_graph) }
+
+ it "treats a node with no inbound connections as a reachable standalone target" do
+ graph =
+ build_workflow_graph do |g|
+ g.node "trigger-1", "trigger:post_created", name: "Trigger"
+ g.node "set-1", "action:set_fields", name: "Standalone"
+ end
+
+ plan = plan_for(snapshot_for(graph), "set-1")
+
+ expect(plan).to be_standalone_target
+ expect(plan).to be_target_reachable
+ end
+
+ it "reuses cached upstream runs and only executes the target" do
+ run_data = { "Source" => [source_run([{ "json" => { "value" => 1 } }])] }
+
+ plan = plan_for(chain_snapshot, "set-2", run_data)
+
+ expect(plan.executable_nodes.map(&:id)).to contain_exactly("set-2")
+ expect(plan.cached_frontier.map(&:id)).to contain_exactly("set-1")
+ expect(plan.trigger_roots_to_run).to be_empty
+ expect(plan).to be_target_reachable
+ expect(plan.cached_outputs(chain_snapshot.find_node("set-1"))).to eq(
+ [[{ "json" => { "value" => 1 } }]],
+ )
+ end
+
+ it "always executes the target even when it has cached data" do
+ run_data = {
+ "Source" => [source_run([{ "json" => { "a" => 1 } }])],
+ "Target" => [source_run([{ "json" => { "b" => 2 } }], node_id: "set-2")],
+ }
+
+ plan = plan_for(chain_snapshot, "set-2", run_data)
+
+ expect(plan.executable_nodes.map(&:id)).to contain_exactly("set-2")
+ end
+
+ it "is unreachable when the chain is cold and the trigger cannot run manually" do
+ plan = plan_for(chain_snapshot, "set-2")
+
+ expect(plan).not_to be_target_reachable
+ end
+
+ it "executes the whole un-cached chain from a pinned trigger" do
+ snapshot =
+ snapshot_for(chain_graph, pin_data: { "Trigger" => [{ "json" => { "pinned" => true } }] })
+
+ plan = plan_for(snapshot, "set-2")
+
+ expect(plan).to be_target_reachable
+ expect(plan.executable_nodes.map(&:id)).to contain_exactly("set-1", "set-2")
+ expect(plan.cached_frontier.map(&:id)).to contain_exactly("trigger-1")
+ expect(plan.trigger_roots_to_run).to be_empty
+ end
+
+ it "runs a manually triggerable trigger when nothing is cached" do
+ graph =
+ build_workflow_graph do |g|
+ g.node "trigger-1", "trigger:manual", name: "Manual"
+ g.node "set-1", "action:set_fields", name: "Target"
+ g.chain "trigger-1", "set-1"
+ end
+
+ plan = plan_for(snapshot_for(graph), "set-1")
+
+ expect(plan).to be_target_reachable
+ expect(plan.trigger_roots_to_run.map(&:id)).to contain_exactly("trigger-1")
+ expect(plan.executable_nodes.map(&:id)).to contain_exactly("trigger-1", "set-1")
+ end
+
+ it "reuses filtered branching runs including their secondary ports" do
+ graph =
+ build_workflow_graph do |g|
+ g.node "trigger-1", "trigger:post_created", name: "Trigger"
+ g.node "if-1", "condition:if", name: "If"
+ g.node "set-1", "action:set_fields", name: "Target"
+ g.chain "trigger-1", "if-1"
+ g.connect "if-1", "set-1", output: "false"
+ end
+ items = [{ "json" => { "branched" => true } }]
+ run_data = {
+ "If" => [
+ run_entry(
+ node_id: "if-1",
+ node_type: "condition:if",
+ status: "filtered",
+ outputs: [output_port(0, []), output_port(1, items)],
+ ),
+ ],
+ }
+ snapshot = snapshot_for(graph)
+
+ plan = plan_for(snapshot, "set-1", run_data)
+
+ expect(plan.executable_nodes.map(&:id)).to contain_exactly("set-1")
+ expect(plan.cached_outputs(snapshot.find_node("if-1"))).to eq([[], items])
+ end
+
+ it "re-executes nodes whose cached runs belong to a different node identity" do
+ run_data = {
+ "Source" => [source_run([{ "json" => { "stale" => true } }], node_id: "recreated-set-1")],
+ }
+ snapshot =
+ snapshot_for(chain_graph, pin_data: { "Trigger" => [{ "json" => { "fresh" => true } }] })
+
+ plan = plan_for(snapshot, "set-2", run_data)
+
+ expect(plan.executable_nodes.map(&:id)).to contain_exactly("set-1", "set-2")
+ end
+
+ it "does not treat error runs as cache" do
+ run_data = { "Source" => [source_run([{ "json" => { "a" => 1 } }], status: "error")] }
+
+ plan = plan_for(chain_snapshot, "set-2", run_data)
+
+ expect(plan).not_to be_target_reachable
+ end
+
+ context "with a merge node requiring a minimum number of inputs" do
+ let(:merge_graph) do
+ build_workflow_graph do |g|
+ g.node "trigger-1", "trigger:post_created", name: "Trigger"
+ g.node "set-a", "action:set_fields", name: "A"
+ g.node "set-b", "action:set_fields", name: "B"
+ g.node "merge-1", "flow:merge", name: "Merge"
+ g.chain "trigger-1", "set-a"
+ g.chain "trigger-1", "set-b"
+ g.connect "set-a", "merge-1", input: "input_1"
+ g.connect "set-b", "merge-1", input: "input_2"
+ end
+ end
+
+ it "is reachable when one branch has data even though the other is dead" do
+ snapshot = snapshot_for(merge_graph, pin_data: { "A" => [{ "json" => { "a" => 1 } }] })
+
+ plan = plan_for(snapshot, "merge-1")
+
+ expect(plan).to be_target_reachable
+ expect(plan.cached_frontier.map(&:id)).to contain_exactly("set-a")
+ end
+
+ it "is unreachable when no branch can produce data" do
+ plan = plan_for(snapshot_for(merge_graph), "merge-1")
+
+ expect(plan).not_to be_target_reachable
+ end
+ end
+
+ it "terminates on graphs with cycles" do
+ graph =
+ build_workflow_graph do |g|
+ g.node "trigger-1", "trigger:post_created", name: "Trigger"
+ g.node "set-a", "action:set_fields", name: "A"
+ g.node "set-b", "action:set_fields", name: "B"
+ g.chain "trigger-1", "set-a", "set-b"
+ g.connect "set-b", "set-a"
+ end
+ snapshot = snapshot_for(graph, pin_data: { "Trigger" => [{ "json" => { "go" => true } }] })
+
+ plan = plan_for(snapshot, "set-b")
+
+ expect(plan).to be_target_reachable
+ expect(plan.executable_nodes.map(&:id)).to contain_exactly("set-a", "set-b")
+ end
+end
diff --git a/plugins/discourse-workflows/spec/requests/discourse_workflows/step_executions_controller_spec.rb b/plugins/discourse-workflows/spec/requests/discourse_workflows/step_executions_controller_spec.rb
new file mode 100644
index 00000000000..f0ce10f7c42
--- /dev/null
+++ b/plugins/discourse-workflows/spec/requests/discourse_workflows/step_executions_controller_spec.rb
@@ -0,0 +1,75 @@
+# frozen_string_literal: true
+
+RSpec.describe DiscourseWorkflows::StepExecutionsController do
+ fab!(:admin)
+ fab!(:workflow) do
+ graph =
+ build_workflow_graph do |g|
+ g.node "trigger-1", "trigger:post_created"
+ g.node "set-1",
+ "action:set_fields",
+ configuration: {
+ "mode" => "raw",
+ "include_other_fields" => true,
+ "json_output" => '{"a": 1}',
+ }
+ g.chain "trigger-1", "set-1"
+ end
+ Fabricate(:discourse_workflows_workflow, created_by: admin, published: true, **graph)
+ end
+
+ before { sign_in(admin) }
+
+ describe "POST /admin/plugins/discourse-workflows/step-executions" do
+ it "returns a pending step execution" do
+ workflow.update_node_pin_data!("Trigger-1", [{ "json" => { "post" => { "id" => 1 } } }])
+
+ post "/admin/plugins/discourse-workflows/step-executions.json",
+ params: {
+ workflow_id: workflow.id,
+ node_id: "set-1",
+ }
+
+ expect(response).to have_http_status(:created)
+ execution = DiscourseWorkflows::Execution.find(response.parsed_body.dig("execution", "id"))
+ expect(response.parsed_body["execution"]).to include(
+ "id" => execution.id,
+ "workflow_id" => workflow.id,
+ )
+ expect(execution.status).to eq("pending")
+ expect(execution.trigger_node_id).to eq("set-1")
+
+ job_args = Jobs::DiscourseWorkflows::ExecuteManualWorkflow.jobs.last["args"].first
+ expect(job_args).to include(
+ "execution_id" => execution.id,
+ "user_id" => admin.id,
+ "step_node_id" => "set-1",
+ )
+ end
+
+ it "returns 422 with an error message when the node has no input data" do
+ post "/admin/plugins/discourse-workflows/step-executions.json",
+ params: {
+ workflow_id: workflow.id,
+ node_id: "set-1",
+ }
+
+ expect(response).to have_http_status(:unprocessable_entity)
+ expect(response.parsed_body["errors"]).to include(
+ I18n.t("discourse_workflows.errors.step_execution.missing_input_data"),
+ )
+ end
+
+ it "returns 404 for non-admin users" do
+ sign_in(Fabricate(:user))
+
+ post "/admin/plugins/discourse-workflows/step-executions.json",
+ params: {
+ workflow_id: workflow.id,
+ node_id: "set-1",
+ }
+
+ expect(response).to have_http_status(:not_found)
+ end
+ end
+end
diff --git a/plugins/discourse-workflows/spec/services/discourse_workflows/workflow/execute_step_spec.rb b/plugins/discourse-workflows/spec/services/discourse_workflows/workflow/execute_step_spec.rb
new file mode 100644
index 00000000000..ba83502a949
--- /dev/null
+++ b/plugins/discourse-workflows/spec/services/discourse_workflows/workflow/execute_step_spec.rb
@@ -0,0 +1,268 @@
+# frozen_string_literal: true
+
+RSpec.describe DiscourseWorkflows::Workflow::ExecuteStep do
+ describe described_class::Contract, type: :model do
+ it { is_expected.to validate_presence_of(:node_id) }
+ end
+
+ describe ".call" do
+ subject(:result) { described_class.call(params:, **dependencies) }
+
+ fab!(:admin)
+ fab!(:workflow) do
+ graph =
+ build_workflow_graph do |g|
+ g.node "trigger-1", "trigger:post_created"
+ g.node "set-1",
+ "action:set_fields",
+ configuration: {
+ "mode" => "raw",
+ "include_other_fields" => true,
+ "json_output" => '{"a": 1}',
+ }
+ g.chain "trigger-1", "set-1"
+ end
+ Fabricate(:discourse_workflows_workflow, created_by: admin, published: true, **graph)
+ end
+
+ let(:params) { { workflow_id: workflow.id, node_id: "set-1" } }
+ let(:dependencies) { { guardian: admin.guardian } }
+
+ context "when contract is invalid" do
+ let(:params) { super().merge(node_id: nil) }
+
+ it { is_expected.to fail_a_contract }
+ end
+
+ context "when user cannot manage workflows" do
+ fab!(:user)
+
+ let(:dependencies) { { guardian: user.guardian } }
+
+ it { is_expected.to fail_a_policy(:can_manage_workflows) }
+ end
+
+ context "when workflow does not exist" do
+ let(:params) { super().merge(workflow_id: -1) }
+
+ it { is_expected.to fail_to_find_a_model(:workflow) }
+ end
+
+ context "when node does not exist" do
+ let(:params) { super().merge(node_id: "nonexistent") }
+
+ it { is_expected.to fail_to_find_a_model(:step_node) }
+ end
+
+ context "when node is a trigger" do
+ let(:params) { super().merge(node_id: "trigger-1") }
+
+ it { is_expected.to fail_a_policy(:step_node_executable) }
+ end
+
+ context "when node waits for a resume" do
+ fab!(:workflow) do
+ graph =
+ build_workflow_graph do |g|
+ g.node "trigger-1", "trigger:post_created"
+ g.node "wait-1",
+ "flow:wait",
+ configuration: {
+ "resume" => "time_interval",
+ "wait_amount" => 1,
+ "wait_unit" => "hours",
+ }
+ g.chain "trigger-1", "wait-1"
+ end
+ Fabricate(:discourse_workflows_workflow, created_by: admin, published: true, **graph)
+ end
+
+ let(:params) { super().merge(node_id: "wait-1") }
+
+ it { is_expected.to fail_a_policy(:step_node_not_waiting) }
+ end
+
+ context "when the node has a connected input but no data source" do
+ it { is_expected.to fail_a_policy(:step_data_reachable) }
+ end
+
+ context "when an un-cached upstream node waits for a resume" do
+ fab!(:workflow) do
+ graph =
+ build_workflow_graph do |g|
+ g.node "trigger-1", "trigger:post_created"
+ g.node "wait-1",
+ "flow:wait",
+ configuration: {
+ "resume" => "time_interval",
+ "wait_amount" => 1,
+ "wait_unit" => "hours",
+ }
+ g.node "set-1",
+ "action:set_fields",
+ configuration: {
+ "mode" => "raw",
+ "include_other_fields" => true,
+ "json_output" => '{"a": 1}',
+ }
+ g.chain "trigger-1", "wait-1", "set-1"
+ end
+ Fabricate(:discourse_workflows_workflow, created_by: admin, published: true, **graph)
+ end
+
+ before do
+ workflow.update_node_pin_data!("Trigger-1", [{ "json" => { "post" => { "id" => 1 } } }])
+ end
+
+ it { is_expected.to fail_a_policy(:execution_path_not_waiting) }
+ end
+
+ context "when the upstream trigger can produce manual data" do
+ fab!(:workflow) do
+ graph =
+ build_workflow_graph do |g|
+ g.node "trigger-1",
+ "trigger:schedule",
+ configuration: {
+ rule: {
+ interval: [{ field: "minutes", minutesInterval: 5 }],
+ },
+ }
+ g.node "set-1",
+ "action:set_fields",
+ configuration: {
+ "mode" => "raw",
+ "include_other_fields" => true,
+ "json_output" => '{"a": 1}',
+ }
+ g.chain "trigger-1", "set-1"
+ end
+ Fabricate(:discourse_workflows_workflow, created_by: admin, published: true, **graph)
+ end
+
+ it "computes fresh trigger data for the run" do
+ freeze_time Time.utc(2026, 3, 18, 9, 0)
+
+ expect(result).to run_successfully
+ expect(result[:execution].trigger_data).to include(
+ "timestamp" => "2026-03-18T09:00:00.000Z",
+ "hour" => "09",
+ )
+ end
+ end
+
+ context "when the upstream trigger has pinned data" do
+ before do
+ workflow.update_node_pin_data!(
+ "Trigger-1",
+ [{ "json" => { "post" => { "id" => 42, "raw" => "pinned body" } } }],
+ )
+ end
+
+ it "creates a pending step execution and enqueues the job" do
+ expect { result }.to change { DiscourseWorkflows::Execution.count }.by(1).and change {
+ Jobs::DiscourseWorkflows::ExecuteManualWorkflow.jobs.size
+ }.by(1)
+
+ expect(result).to run_successfully
+ execution = result[:execution]
+ expect(execution).to have_attributes(
+ status: "pending",
+ execution_mode: "manual",
+ trigger_node_id: "set-1",
+ )
+ expect(execution.execution_data.run_data).to eq({})
+
+ job_args = Jobs::DiscourseWorkflows::ExecuteManualWorkflow.jobs.last["args"].first
+ expect(job_args).to include(
+ "execution_id" => execution.id,
+ "user_id" => admin.id,
+ "step_node_id" => "set-1",
+ )
+ end
+ end
+
+ context "when a previous successful execution provides run data" do
+ let!(:source_execution) do
+ DiscourseWorkflows::Executor.new(
+ workflow,
+ "trigger-1",
+ { "seed" => true },
+ DiscourseWorkflows::Executor::ExecutionOptions.new(
+ user: admin,
+ execution_mode: :manual,
+ draft_execution: true,
+ ),
+ ).run
+ end
+
+ it "seeds the new execution with the source execution's run data" do
+ expect(result).to run_successfully
+
+ execution = result[:execution]
+ expect(execution.execution_data.run_data).to eq(
+ source_execution.reload.execution_data.run_data,
+ )
+ expect(execution.trigger_data).to eq(source_execution.trigger_data)
+ end
+ end
+
+ context "when a merge node has data for only one of its inputs" do
+ fab!(:workflow) do
+ graph =
+ build_workflow_graph do |g|
+ g.node "trigger-1", "trigger:post_created"
+ g.node "set-a",
+ "action:set_fields",
+ name: "A",
+ configuration: {
+ "mode" => "raw",
+ "include_other_fields" => true,
+ "json_output" => '{"a": 1}',
+ }
+ g.node "set-b",
+ "action:set_fields",
+ name: "B",
+ configuration: {
+ "mode" => "raw",
+ "include_other_fields" => true,
+ "json_output" => '{"b": 2}',
+ }
+ g.node "merge-1", "flow:merge", name: "Merge", configuration: { "mode" => "append" }
+ g.chain "trigger-1", "set-a"
+ g.chain "trigger-1", "set-b"
+ g.connect "set-a", "merge-1", input: "input_1"
+ g.connect "set-b", "merge-1", input: "input_2"
+ end
+ Fabricate(:discourse_workflows_workflow, created_by: admin, published: true, **graph)
+ end
+
+ let(:params) { super().merge(node_id: "merge-1") }
+
+ before { workflow.update_node_pin_data!("A", [{ "json" => { "pinned" => true } }]) }
+
+ it { is_expected.to run_successfully }
+ end
+
+ context "when the node has no inbound connections" do
+ fab!(:workflow) do
+ graph =
+ build_workflow_graph do |g|
+ g.node "trigger-1", "trigger:post_created"
+ g.node "solo-1",
+ "action:set_fields",
+ configuration: {
+ "mode" => "raw",
+ "include_other_fields" => true,
+ "json_output" => '{"solo": true}',
+ }
+ end
+ Fabricate(:discourse_workflows_workflow, created_by: admin, published: true, **graph)
+ end
+
+ let(:params) { super().merge(node_id: "solo-1") }
+
+ it { is_expected.to run_successfully }
+ end
+ end
+end
diff --git a/plugins/discourse-workflows/test/javascripts/integration/components/workflows/canvas/sticky-note-test.gjs b/plugins/discourse-workflows/test/javascripts/integration/components/workflows/canvas/sticky-note-test.gjs
new file mode 100644
index 00000000000..86aeadeed9e
--- /dev/null
+++ b/plugins/discourse-workflows/test/javascripts/integration/components/workflows/canvas/sticky-note-test.gjs
@@ -0,0 +1,107 @@
+import { find, render, settled } from "@ember/test-helpers";
+import { module, test } from "qunit";
+import { setupRenderingTest } from "discourse/tests/helpers/component-test";
+import StickyNote from "discourse/plugins/discourse-workflows/admin/components/workflows/canvas/sticky-note";
+
+function pointerEvent(type, options = {}) {
+ return new PointerEvent(type, {
+ bubbles: true,
+ cancelable: true,
+ ...options,
+ });
+}
+
+module(
+ "Integration | Component | Workflows | Canvas | StickyNote",
+ function (hooks) {
+ setupRenderingTest(hooks);
+
+ test("dragging only starts once the pointer passes the lenience radius", async function (assert) {
+ const moves = [];
+ const afterMutations = [];
+ const note = {
+ position: { x: 10, y: 20 },
+ size: { width: 200, height: 150 },
+ color: "yellow",
+ text: "",
+ };
+ const onMove = (position) => moves.push(position);
+ const onAfterMutation = () => afterMutations.push(true);
+
+ await render(
+ <template>
+ <StickyNote
+ @note={{note}}
+ @zoom={{1}}
+ @onMove={{onMove}}
+ @onAfterMutation={{onAfterMutation}}
+ />
+ </template>
+ );
+
+ const element = find(".workflow-sticky-note");
+ element.dispatchEvent(
+ pointerEvent("pointerdown", { clientX: 100, clientY: 100 })
+ );
+
+ document.dispatchEvent(
+ pointerEvent("pointermove", { clientX: 102, clientY: 101 })
+ );
+ assert.deepEqual(
+ moves,
+ [],
+ "sub-lenience movement does not move the note"
+ );
+
+ document.dispatchEvent(
+ pointerEvent("pointermove", { clientX: 110, clientY: 100 })
+ );
+ assert.deepEqual(
+ moves,
+ [{ x: 20, y: 20 }],
+ "past the lenience the note follows the full pointer delta"
+ );
+
+ document.dispatchEvent(
+ pointerEvent("pointerup", { clientX: 110, clientY: 100 })
+ );
+ await settled();
+ assert.strictEqual(
+ afterMutations.length,
+ 1,
+ "the drag end callback still fires"
+ );
+ });
+
+ test("a click with pointer jitter never moves the note", async function (assert) {
+ const moves = [];
+ const note = {
+ position: { x: 0, y: 0 },
+ size: { width: 200, height: 150 },
+ color: "yellow",
+ text: "",
+ };
+ const onMove = (position) => moves.push(position);
+
+ await render(
+ <template>
+ <StickyNote @note={{note}} @zoom={{1}} @onMove={{onMove}} />
+ </template>
+ );
+
+ const element = find(".workflow-sticky-note");
+ element.dispatchEvent(
+ pointerEvent("pointerdown", { clientX: 50, clientY: 50 })
+ );
+ document.dispatchEvent(
+ pointerEvent("pointermove", { clientX: 52, clientY: 49 })
+ );
+ document.dispatchEvent(
+ pointerEvent("pointerup", { clientX: 52, clientY: 49 })
+ );
+ await settled();
+
+ assert.deepEqual(moves, [], "the note position never changed");
+ });
+ }
+);
diff --git a/plugins/discourse-workflows/test/javascripts/unit/components/workflows/canvas/canvas-bridge-test.js b/plugins/discourse-workflows/test/javascripts/unit/components/workflows/canvas/canvas-bridge-test.js
index 291cb04c2a7..4211b94de87 100644
--- a/plugins/discourse-workflows/test/javascripts/unit/components/workflows/canvas/canvas-bridge-test.js
+++ b/plugins/discourse-workflows/test/javascripts/unit/components/workflows/canvas/canvas-bridge-test.js
@@ -317,6 +317,227 @@ module("Unit | Canvas Bridge", function (hooks) {
bridge.destroy();
});
+ test("pointer jitter below the drag lenience does not move a picked node", async function (assert) {
+ const dragged = [];
+ const bridge = await createReteEditor(container, {
+ callbacks: noopCallbacks({
+ onNodeDragged: (id, position) => dragged.push({ id, ...position }),
+ }),
+ nodeTypes: NODE_TYPES,
+ });
+
+ await bridge.syncState(
+ [{ clientId: "n1", type: "trigger:manual", position: { x: 0, y: 0 } }],
+ []
+ );
+
+ const view = bridge.area.nodeViews.get("n1");
+ await bridge.area.emit({ type: "nodepicked", data: { id: "n1" } });
+
+ await view.translate(2, 2);
+ assert.deepEqual(
+ view.position,
+ { x: 0, y: 0 },
+ "a sub-lenience move is swallowed"
+ );
+ assert.deepEqual(dragged, [], "no drag is reported");
+
+ await view.translate(6, 0);
+ assert.deepEqual(
+ view.position,
+ { x: 6, y: 0 },
+ "the node moves once the pointer passes the lenience radius"
+ );
+
+ await view.translate(1, 0);
+ assert.deepEqual(
+ view.position,
+ { x: 1, y: 0 },
+ "sub-lenience deltas apply normally once dragging has started"
+ );
+ assert.deepEqual(dragged, [
+ { id: "n1", x: 6, y: 0 },
+ { id: "n1", x: 1, y: 0 },
+ ]);
+
+ bridge.destroy();
+ });
+
+ test("a jittery double-click opens the node without moving it", async function (assert) {
+ const doubleClicked = [];
+ const dragged = [];
+ const bridge = await createReteEditor(container, {
+ callbacks: noopCallbacks({
+ onNodeDoubleClick: (id) => doubleClicked.push(id),
+ onNodeDragged: (id, position) => dragged.push({ id, ...position }),
+ }),
+ nodeTypes: NODE_TYPES,
+ });
+
+ await bridge.syncState(
+ [{ clientId: "n1", type: "trigger:manual", position: { x: 0, y: 0 } }],
+ []
+ );
+
+ const view = bridge.area.nodeViews.get("n1");
+ const pointerup = () =>
+ bridge.area.emit({
+ type: "pointerup",
+ data: {
+ position: { x: 0, y: 0 },
+ event: {
+ button: 0,
+ target: { closest: () => null },
+ clientX: 0,
+ clientY: 0,
+ },
+ },
+ });
+
+ await bridge.area.emit({ type: "nodepicked", data: { id: "n1" } });
+ await view.translate(2, 1);
+ await pointerup();
+ await bridge.area.emit({ type: "nodepicked", data: { id: "n1" } });
+ await pointerup();
+
+ assert.deepEqual(doubleClicked, ["n1"], "the double-click is detected");
+ assert.deepEqual(view.position, { x: 0, y: 0 }, "the node did not move");
+ assert.deepEqual(dragged, [], "no position change was reported");
+
+ bridge.destroy();
+ });
+
+ test("the drag lenience is measured in screen pixels", async function (assert) {
+ const bridge = await createReteEditor(container, {
+ callbacks: noopCallbacks(),
+ nodeTypes: NODE_TYPES,
+ });
+
+ await bridge.syncState(
+ [{ clientId: "n1", type: "trigger:manual", position: { x: 0, y: 0 } }],
+ []
+ );
+ await bridge.zoomAtViewportCenter(0.25);
+
+ const view = bridge.area.nodeViews.get("n1");
+ await bridge.area.emit({ type: "nodepicked", data: { id: "n1" } });
+
+ await view.translate(10, 0);
+ assert.deepEqual(
+ view.position,
+ { x: 0, y: 0 },
+ "10 canvas pixels is only 2.5 screen pixels when zoomed out"
+ );
+
+ await view.translate(20, 0);
+ assert.deepEqual(
+ view.position,
+ { x: 20, y: 0 },
+ "20 canvas pixels crosses the screen-space lenience"
+ );
+
+ bridge.destroy();
+ });
+
+ test("releasing the pointer stops the drag lenience from swallowing translations", async function (assert) {
+ const bridge = await createReteEditor(container, {
+ callbacks: noopCallbacks(),
+ nodeTypes: NODE_TYPES,
+ });
+
+ await bridge.syncState(
+ [{ clientId: "n1", type: "trigger:manual", position: { x: 0, y: 0 } }],
+ []
+ );
+
+ const view = bridge.area.nodeViews.get("n1");
+ await bridge.area.emit({ type: "nodepicked", data: { id: "n1" } });
+ await view.translate(2, 0);
+ assert.deepEqual(view.position, { x: 0, y: 0 });
+
+ await bridge.area.emit({
+ type: "pointerup",
+ data: {
+ position: { x: 0, y: 0 },
+ event: {
+ button: 0,
+ target: { closest: () => null },
+ clientX: 0,
+ clientY: 0,
+ },
+ },
+ });
+
+ await view.translate(2, 0);
+ assert.deepEqual(
+ view.position,
+ { x: 2, y: 0 },
+ "translations after release are not swallowed"
+ );
+
+ bridge.destroy();
+ });
+
+ test("connection dragging marks the container and the source node", async function (assert) {
+ const bridge = await createReteEditor(container, {
+ callbacks: noopCallbacks(),
+ nodeTypes: NODE_TYPES,
+ });
+
+ await bridge.syncState(
+ [
+ { clientId: "n1", type: "trigger:manual", position: { x: 0, y: 0 } },
+ {
+ clientId: "n2",
+ type: "action:http_request",
+ position: { x: 200, y: 0 },
+ },
+ ],
+ []
+ );
+
+ const socket = { nodeId: "n1", side: "output", key: "main" };
+ await bridge.connectionPlugin.emit({
+ type: "connectionpick",
+ data: { socket },
+ });
+
+ assert.true(
+ container.classList.contains("is-connection-dragging"),
+ "the canvas is marked while a connection is dragged"
+ );
+ assert.true(
+ bridge.area.nodeViews
+ .get("n1")
+ .element.classList.contains("is-connection-source"),
+ "the node the drag started from is marked"
+ );
+ assert.false(
+ bridge.area.nodeViews
+ .get("n2")
+ .element.classList.contains("is-connection-source"),
+ "other nodes are not marked"
+ );
+
+ await bridge.connectionPlugin.emit({
+ type: "connectiondrop",
+ data: { initial: socket, socket: null, created: false },
+ });
+
+ assert.false(
+ container.classList.contains("is-connection-dragging"),
+ "the canvas marker is cleared on drop"
+ );
+ assert.false(
+ bridge.area.nodeViews
+ .get("n1")
+ .element.classList.contains("is-connection-source"),
+ "the source node marker is cleared on drop"
+ );
+
+ bridge.destroy();
+ });
+
test("syncState manages connections and creates connection entries", async function (assert) {
const bridge = await createReteEditor(container, {
callbacks: noopCallbacks(),
@@ -730,6 +951,56 @@ module("Unit | Canvas Bridge", function (hooks) {
bridge.destroy();
});
+ test("autoArrange stacks branch targets in output port order", async function (assert) {
+ const nodes = [
+ {
+ clientId: "branch",
+ type: "action:data_table",
+ position: { x: 0, y: 0 },
+ },
+ {
+ clientId: "empty",
+ type: "action:http_request",
+ position: { x: 0, y: 0 },
+ },
+ {
+ clientId: "results",
+ type: "action:http_request",
+ position: { x: 0, y: 0 },
+ },
+ ];
+ const connections = [
+ {
+ sourceClientId: "branch",
+ sourceOutput: "results",
+ targetClientId: "results",
+ },
+ {
+ sourceClientId: "branch",
+ sourceOutput: "no_results",
+ targetClientId: "empty",
+ },
+ ];
+
+ // stored connection order must not matter, only output port order
+ for (const stored of [connections, [...connections].reverse()]) {
+ const bridge = await createReteEditor(container, {
+ callbacks: noopCallbacks(),
+ nodeTypes: NODE_TYPES,
+ });
+ await bridge.syncState(nodes, stored);
+
+ const positions = await bridge.autoArrange();
+
+ assert.true(
+ positions.get("results").y < positions.get("empty").y,
+ "first output's target is above second output's target"
+ );
+
+ bridge.destroy();
+ }
+ });
+
test("containerToCanvas converts coordinates based on transform", async function (assert) {
const bridge = await createReteEditor(container, {
callbacks: noopCallbacks(),
diff --git a/plugins/discourse-workflows/test/javascripts/unit/components/workflows/editor-test.js b/plugins/discourse-workflows/test/javascripts/unit/components/workflows/editor-test.js
index 43e625236af..1d7cb3942e3 100644
--- a/plugins/discourse-workflows/test/javascripts/unit/components/workflows/editor-test.js
+++ b/plugins/discourse-workflows/test/javascripts/unit/components/workflows/editor-test.js
@@ -5,16 +5,12 @@ import WorkflowsEditor, {
isNodeUnavailable,
} from "discourse/plugins/discourse-workflows/admin/components/workflows/editor";
-function buildEditor(workflow, dialog = {}) {
+function buildEditor(workflow) {
const editor = Object.create(WorkflowsEditor.prototype);
- editor.allowUnpublishedDraftTransition = false;
Object.defineProperty(editor, "args", {
value: { workflow },
});
- Object.defineProperty(editor, "dialog", {
- value: dialog,
- });
return editor;
}
@@ -158,131 +154,12 @@ module("Unit | Component | workflows editor", function () {
);
});
- test("route changes ask for confirmation when the workflow has an unpublished draft", function (assert) {
- const transition = {
- isAborted: false,
- queryParamsOnly: false,
- from: { name: "adminPlugins.show.discourse-workflows.show.index" },
- to: { name: "adminPlugins.show.discourse-workflows" },
- abort() {
- assert.step("aborted");
- },
- retry() {
- assert.step("retried");
- },
- };
- const dialog = {
- dialog({ class: dialogClass, message, buttons }) {
- assert.strictEqual(dialogClass, "workflows-unpublished-draft-dialog");
- assert.strictEqual(
- message,
- i18n("discourse_workflows.unpublished_changes_confirmation")
- );
- assert.deepEqual(
- buttons.map((button) => button.label),
- [
- i18n("discourse_workflows.leave_without_publishing"),
- i18n("discourse_workflows.keep_editing"),
- i18n("discourse_workflows.discard_changes"),
- ]
- );
- assert.true(
- buttons[2].class.includes(
- "workflows-unpublished-draft-dialog__discard-btn"
- ),
- "discard button is aligned separately"
- );
- buttons[0].action();
- },
- };
- const editor = buildEditor(
- {
- activeVersionId: "published-version",
- hasUnpublishedChanges: true,
- },
- dialog
- );
-
- editor.confirmUnpublishedDraftTransition(transition);
-
- assert.true(editor.allowUnpublishedDraftTransition);
- assert.verifySteps(["aborted", "retried"]);
- });
-
- test("route changes can discard changes before retrying", async function (assert) {
- const transition = {
- isAborted: false,
- queryParamsOnly: false,
- from: { name: "adminPlugins.show.discourse-workflows.show.index" },
- to: { name: "adminPlugins.show.discourse-workflows" },
- abort() {
- assert.step("aborted");
- },
- retry() {
- assert.step("retried");
- },
- };
- let discardAction;
- const dialog = {
- dialog({ buttons }) {
- discardAction = buttons[2].action;
- },
- confirm({ message, confirmButtonLabel, cancelButtonLabel }) {
- assert.strictEqual(
- message,
- i18n("discourse_workflows.discard_changes_confirmation")
- );
- assert.strictEqual(
- confirmButtonLabel,
- "discourse_workflows.discard_changes"
- );
- assert.strictEqual(
- cancelButtonLabel,
- "discourse_workflows.keep_editing"
- );
- assert.step("confirmed discard");
- return true;
- },
- };
- const editor = buildEditor(
- {
- activeVersionId: "published-version",
- hasUnpublishedChanges: true,
- },
- dialog
- );
- editor.discardWorkflowDraft = async () => assert.step("discarded");
-
- editor.confirmUnpublishedDraftTransition(transition);
- await discardAction();
-
- assert.true(editor.allowUnpublishedDraftTransition);
- assert.verifySteps([
- "aborted",
- "confirmed discard",
- "discarded",
- "retried",
- ]);
- });
-
- test("browseTemplates skips draft confirmation for an empty workflow", function (assert) {
- const editor = buildEditor({ id: 12, hasUnpublishedChanges: true });
- setFormApi(editor, { nodes: [], stickyNotes: [] });
- setRouter(editor, assert);
-
- editor.browseTemplates();
-
- assert.true(editor.allowUnpublishedDraftTransition);
- });
-
- test("browseTemplates keeps draft confirmation for non-empty workflows", function (assert) {
+ test("browseTemplates navigates to the templates route", function (assert) {
const editor = buildEditor({ id: 12, hasUnpublishedChanges: true });
setFormApi(editor, { nodes: [{ id: "n1" }], stickyNotes: [] });
setRouter(editor, assert);
editor.browseTemplates();
-
- assert.false(editor.allowUnpublishedDraftTransition);
});
test("node panel hides triggers when adding after a trigger", function (assert) {
diff --git a/plugins/discourse-workflows/test/javascripts/unit/components/workflows/workflow-node-test.gjs b/plugins/discourse-workflows/test/javascripts/unit/components/workflows/workflow-node-test.gjs
index 5bb30a1d031..dd5040b2532 100644
--- a/plugins/discourse-workflows/test/javascripts/unit/components/workflows/workflow-node-test.gjs
+++ b/plugins/discourse-workflows/test/javascripts/unit/components/workflows/workflow-node-test.gjs
@@ -1,6 +1,7 @@
import { module, test } from "qunit";
import {
shouldEnableManualTrigger,
+ shouldShowExecuteStep,
shouldShowManualTrigger,
} from "discourse/plugins/discourse-workflows/admin/components/workflows/canvas/workflow-node";
@@ -53,6 +54,33 @@ module("Unit | Component | Workflows | Canvas | WorkflowNode", function () {
);
});
+ test("shows execute step only for non-trigger nodes", function (assert) {
+ assert.true(
+ shouldShowExecuteStep({
+ name: "HTTP request",
+ type: "action:http_request",
+ typeVersion: "1.0",
+ })
+ );
+ assert.true(
+ shouldShowExecuteStep({
+ name: "If",
+ type: "condition:if",
+ typeVersion: "1.0",
+ })
+ );
+
+ assert.false(
+ shouldShowExecuteStep({
+ name: "Post created",
+ type: "trigger:post_created",
+ typeVersion: "1.0",
+ })
+ );
+ assert.false(shouldShowExecuteStep({ name: "No type" }));
+ assert.false(shouldShowExecuteStep(undefined));
+ });
+
test("does not show or enable manual trigger for action nodes with pinned data", function (assert) {
assert.false(
shouldShowManualTrigger({
diff --git a/plugins/discourse-workflows/test/javascripts/unit/lib/workflows-run-data-test.js b/plugins/discourse-workflows/test/javascripts/unit/lib/workflows-run-data-test.js
index a8b47128d91..4c4862822b7 100644
--- a/plugins/discourse-workflows/test/javascripts/unit/lib/workflows-run-data-test.js
+++ b/plugins/discourse-workflows/test/javascripts/unit/lib/workflows-run-data-test.js
@@ -1,10 +1,33 @@
import { module, test } from "qunit";
import {
inputForRun,
+ latestRunWithOutput,
outputForRun,
} from "discourse/plugins/discourse-workflows/admin/lib/workflows/run-data";
module("Unit | lib | discourse-workflows | run-data", function () {
+ test("latestRunWithOutput includes filtered and skipped runs", function (assert) {
+ const filteredRun = {
+ status: "filtered",
+ outputs: [
+ { index: 0, items: [] },
+ { index: 1, items: [{ json: { branched: true } }] },
+ ],
+ };
+ const runData = {
+ If: [{ status: "success", outputs: [] }, filteredRun],
+ Skipped: [{ status: "skipped", outputs: [{ index: 0, items: [] }] }],
+ Failed: [{ status: "error", outputs: [] }],
+ };
+
+ assert.strictEqual(latestRunWithOutput(runData, "If"), filteredRun);
+ assert.strictEqual(
+ latestRunWithOutput(runData, "Skipped"),
+ runData.Skipped[0]
+ );
+ assert.strictEqual(latestRunWithOutput(runData, "Failed"), null);
+ });
+
test("outputForRun keeps output indexes positional", function (assert) {
const run = {
outputs: [{ index: 0, items: [{ json: { primary: true } }] }],