Skip to content

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

FEATURE: Resolve workflow editor output schemas on the server (#44559)

Régis Hanol28b3d9831d7e
diff --git a/.skills/discourse-workflow-nodes/SKILL.md b/.skills/discourse-workflow-nodes/SKILL.md
index 17eb33fb139..e90d28459d5 100644
--- a/.skills/discourse-workflow-nodes/SKILL.md
+++ b/.skills/discourse-workflow-nodes/SKILL.md
@@ -63,8 +63,16 @@ Renaming or removing an output key, or changing its meaning, breaks saved workfl
- Actions that mutate a topic also return `topic`.
- Cap user lists with a named constant (e.g. `PostEventScoping::MAX_GOING_USERNAMES`).
+## Secrets
+
+- Never put credential values in output. Password credential fields serialize as `Credential::REDACTED_VALUE`.
+- `WebhookRequest` masks `FILTERED_HEADERS` (`authorization`, `cookie`, `proxy-authorization`) with `FILTERED_VALUE`; `AuthenticateNode` masks the matched `header_auth` header.
+- http_request logs headers through `redact_headers`.
+
## Output contracts
+Every node declares its output with `output_contracts` in `description`, or derives it from config by overriding `self.output_schemas` (see summarize, data_table, trigger:form, action:form). The editor fetches resolved schemas from the server (`POST /output-schemas`), so there is no JS counterpart.
+
`node_output_contracts_spec` has a `user_defined_output` opt-out list. A node belongs there only if the user writes its output shape (code, sql, set_fields, workflow_call, manual). If the shape can be derived from config, override `self.output_schemas` instead.
- Use `"type": [..., "null"]` for keys that are always emitted but may be nil.
diff --git a/plugins/discourse-ai/admin/assets/javascripts/admin/lib/workflows/output-schemas/ai-agent.js b/plugins/discourse-ai/admin/assets/javascripts/admin/lib/workflows/output-schemas/ai-agent.js
deleted file mode 100644
index 73d3943e04c..00000000000
--- a/plugins/discourse-ai/admin/assets/javascripts/admin/lib/workflows/output-schemas/ai-agent.js
+++ /dev/null
@@ -1,32 +0,0 @@
-const DRAFT_URI = "https://json-schema.org/draft/2020-12/schema";
-
-function schemaTypeFor(field) {
- if (field.type !== "array") {
- return { type: field.type };
- }
-
- const schema = {
- type: "array",
- items: { type: field.array_type || "string" },
- };
- if (Number.isInteger(field.max_items) && field.max_items >= 0) {
- schema.maxItems = field.max_items;
- }
-
- return schema;
-}
-
-export default function aiAgentOutputSchemas(configuration = {}) {
- const properties = { result: { type: "string" } };
- const fields = Array.isArray(configuration.agent_response_format)
- ? configuration.agent_response_format
- : [];
-
- for (const field of fields) {
- if (field?.key) {
- properties[field.key] = schemaTypeFor(field);
- }
- }
-
- return [{ $schema: DRAFT_URI, type: "object", properties }];
-}
diff --git a/plugins/discourse-ai/discourse_workflows/nodes/ai_agent/v1.rb b/plugins/discourse-ai/discourse_workflows/nodes/ai_agent/v1.rb
index 7abff6c9b4f..01f8ff89568 100644
--- a/plugins/discourse-ai/discourse_workflows/nodes/ai_agent/v1.rb
+++ b/plugins/discourse-ai/discourse_workflows/nodes/ai_agent/v1.rb
@@ -20,7 +20,6 @@ if defined?(DiscourseWorkflows)
available: -> { SiteSetting.discourse_ai_enabled },
unavailable_reason_key: "discourse_workflows.node_unavailable.requires_ai",
i18n_prefix: "discourse_ai.discourse_workflows",
- output_schema_resolver: "ai-agent",
capabilities: {
run_scope: {
parameter: "mode",
diff --git a/plugins/discourse-ai/discourse_workflows/nodes/classify/v1.rb b/plugins/discourse-ai/discourse_workflows/nodes/classify/v1.rb
index b88399443a8..67d2b39a490 100644
--- a/plugins/discourse-ai/discourse_workflows/nodes/classify/v1.rb
+++ b/plugins/discourse-ai/discourse_workflows/nodes/classify/v1.rb
@@ -19,7 +19,6 @@ if defined?(DiscourseWorkflows)
available: -> { SiteSetting.discourse_ai_enabled && ::DecisionModel.exists? },
unavailable_reason_key: "discourse_workflows.node_unavailable.requires_decision_model",
i18n_prefix: "discourse_ai.discourse_workflows",
- output_schema_resolver: "classify",
capabilities: {
run_scope: "per_item",
},
diff --git a/plugins/discourse-ai/test/javascripts/unit/lib/ai-agent-output-schemas-test.js b/plugins/discourse-ai/test/javascripts/unit/lib/ai-agent-output-schemas-test.js
deleted file mode 100644
index 2b4f7b4d271..00000000000
--- a/plugins/discourse-ai/test/javascripts/unit/lib/ai-agent-output-schemas-test.js
+++ /dev/null
@@ -1,35 +0,0 @@
-import { module, test } from "qunit";
-import aiAgentOutputSchemas from "discourse/plugins/discourse-ai/admin/lib/workflows/output-schemas/ai-agent";
-
-module("Unit | lib | discourse-ai | AI agent output schemas", function () {
- test("declares the response format fields next to the raw result", function (assert) {
- const [schema] = aiAgentOutputSchemas({
- agent_response_format: [
- { key: "verdict", type: "string" },
- { key: "confident", type: "boolean" },
- { key: "reasons", type: "array", array_type: "string", max_items: 2 },
- ],
- });
-
- assert.deepEqual(schema.properties, {
- result: { type: "string" },
- verdict: { type: "string" },
- confident: { type: "boolean" },
- reasons: { type: "array", items: { type: "string" }, maxItems: 2 },
- });
- });
-
- test("declares only the raw result without usable fields", function (assert) {
- for (const configuration of [
- undefined,
- { agent_response_format: "" },
- { agent_response_format: [{ type: "string" }] },
- ]) {
- assert.deepEqual(
- Object.keys(aiAgentOutputSchemas(configuration)[0].properties),
- ["result"],
- `only result for ${JSON.stringify(configuration)}`
- );
- }
- });
-});
diff --git a/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/configurators/condition-builder.gjs b/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/configurators/condition-builder.gjs
index 2a42a8fe0f0..cff7ffa3d7f 100644
--- a/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/configurators/condition-builder.gjs
+++ b/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/configurators/condition-builder.gjs
@@ -21,7 +21,6 @@ import {
import {
inputConnectionsForNode,
previousNodeForConnection,
- resolveDeclaredOutputSchemas,
} from "../../../lib/workflows/schema-graph.js";
import Collection from "./collection.gjs";
import Field from "./field.gjs";
@@ -169,10 +168,9 @@ export default class ConditionBuilder extends Component {
const graph = {
nodes: this.args.nodes || [],
connections: this.args.connections || [],
- nodeTypes: this.args.nodeTypes || [],
};
const runData = this.args.session?.lastExecutionRunData || {};
- const declaredOutputSchemas = resolveDeclaredOutputSchemas(graph);
+ const declaredOutputSchemas = this.args.session?.outputSchemas;
const inputConnections = inputConnectionsForNode(this.args.node, graph);
const primaryConnection = inputConnections[0] || null;
@@ -197,7 +195,6 @@ export default class ConditionBuilder extends Component {
sourceNode: previousNode,
outputIndex,
prefix,
- graph,
pinnedItems,
declaredOutputSchemas,
});
diff --git a/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/configurators/expression-input.gjs b/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/configurators/expression-input.gjs
index dc53fa39065..35fc0785636 100644
--- a/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/configurators/expression-input.gjs
+++ b/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/configurators/expression-input.gjs
@@ -2,6 +2,7 @@ import Component from "@glimmer/component";
import { tracked } from "@glimmer/tracking";
import { action } from "@ember/object";
import didInsert from "@ember/render-modifiers/modifiers/did-insert";
+import didUpdate from "@ember/render-modifiers/modifiers/did-update";
import { cancel } from "@ember/runloop";
import { service } from "@ember/service";
import discourseLater from "discourse/lib/later";
@@ -9,6 +10,7 @@ import {
schemaFieldsForNodeInput,
schemaFieldsForNodeOutput,
} from "../../../lib/workflows/data-preview.js";
+import { buildScope } from "../../../lib/workflows/expression-context.js";
import buildExpressionExtensions from "../../../lib/workflows/expression-extensions/index.js";
import {
inputIndexForConnection,
@@ -20,7 +22,6 @@ import {
ancestorOutputNodes,
inputConnectionsForNode,
previousNodeForConnection,
- resolveDeclaredOutputSchemas,
} from "../../../lib/workflows/schema-graph.js";
import ExpressionPreview from "../variable/expression-preview.gjs";
import VariableInput from "../variable/input.gjs";
@@ -36,10 +37,17 @@ export default class ExpressionInput extends Component {
@tracked isFocused = false;
@tracked segments = [];
wrapperElement = null;
+ #editorView = null;
#focusOutTimer = null;
+ #liveScope = new Proxy(Object.create(null), {
+ get: (_, key) => this.#currentScope()[key],
+ has: (_, key) => key in this.#currentScope(),
+ });
#pickerDismiss = null;
#pickerEditorElement = null;
#pickerTrigger = null;
+ #scope = null;
+ #scopeOutputSchemas = null;
willDestroy() {
super.willDestroy(...arguments);
@@ -64,77 +72,12 @@ export default class ExpressionInput extends Component {
@action
buildExtensions(cmParams) {
- const session = this.args.session;
- const node = session?.editingNode;
- const graph = {
- nodes: session?.graphNodes || [],
- connections: session?.graphConnections || [],
- nodeTypes: this.workflowsNodeTypes.nodeTypes || [],
- };
- const itemPrefix =
- this.workflowsNodeTypes.expressionContext.item_prefix || "$json";
- const runData = session?.lastExecutionRunData || {};
- const declaredOutputSchemas = resolveDeclaredOutputSchemas(graph);
- const previousConnection = node
- ? inputConnectionsForNode(node, graph)[0]
- : null;
- const previousNode = previousNodeForConnection(previousConnection, graph);
- const currentInputIndex = previousConnection
- ? inputIndexForConnection(previousConnection)
- : 0;
- const previousOutputIndex = previousConnection
- ? outputIndexForConnection(previousConnection)
- : 0;
- const pinnedInputItems =
- previousOutputIndex === 0
- ? session?.pinnedItemsForNode(previousNode?.name)
- : undefined;
- const inputFields = node
- ? schemaFieldsForNodeInput(runData, node.name, {
- inputIndex: currentInputIndex,
- node,
- sourceNode: previousNode,
- outputIndex: previousOutputIndex,
- prefix: itemPrefix,
- graph,
- pinnedItems: pinnedInputItems,
- declaredOutputSchemas,
- })
- : [];
- // Pinned sample data, falling back to the last run.
- const ancestorNodes = node
- ? ancestorOutputNodes(node, graph).map((ancestor) => {
- const pinnedItems =
- ancestor.outputIndex === 0
- ? session?.pinnedItemsForNode(ancestor.node.name)
- : undefined;
- const prefix = nodeOutputJsonPath(runData, ancestor.node.name, {
- outputIndex: ancestor.outputIndex,
- node: ancestor.node,
- itemCount: pinnedItems?.length,
- });
- return {
- node: ancestor.node,
- fields:
- pinnedItems === undefined
- ? schemaFieldsForNodeOutput(runData, ancestor.node.name, {
- outputIndex: ancestor.outputIndex,
- node: ancestor.node,
- prefix,
- graph,
- declaredOutputSchemas,
- })
- : schemaFieldsForItems(pinnedItems, { prefix }),
- };
- })
- : [];
+ const { graph, itemPrefix, node, session, ancestorNodes } =
+ this.#scopeOptions();
return buildExpressionExtensions(cmParams, {
- inputFields,
+ scope: this.#liveScope,
ancestorNodes,
- siteSettings: this.siteSettings,
- globalVars: this.workflowsNodeTypes.workflowVars,
- workflowVariables: session?.variables,
nodes: graph.nodes,
itemPrefix,
workflowId: session?.workflowId,
@@ -144,6 +87,11 @@ export default class ExpressionInput extends Component {
});
}
+ @action
+ refreshScope() {
+ this.#editorView?.dispatch({ selection: this.#editorView.state.selection });
+ }
+
@action
openReferencePicker({ trigger, properties, current, onSelect, onEdit }) {
// Re-triggering on the same pill toggles the dropdown shut rather than
@@ -220,6 +168,7 @@ export default class ExpressionInput extends Component {
@action
labelEditor(view) {
+ this.#editorView = view;
if (this.args.inputId) {
view.contentDOM.id = this.args.inputId;
}
@@ -233,6 +182,93 @@ export default class ExpressionInput extends Component {
this.wrapperElement = element;
}
+ #currentScope() {
+ const outputSchemas = this.args.session?.outputSchemas;
+ if (!this.#scope || this.#scopeOutputSchemas !== outputSchemas) {
+ this.#scopeOutputSchemas = outputSchemas;
+ this.#scope = buildScope(this.#scopeOptions());
+ }
+
+ return this.#scope;
+ }
+
+ #scopeOptions() {
+ const session = this.args.session;
+ const node = session?.editingNode;
+ const graph = {
+ nodes: session?.graphNodes || [],
+ connections: session?.graphConnections || [],
+ };
+ const itemPrefix =
+ this.workflowsNodeTypes.expressionContext.item_prefix || "$json";
+ const runData = session?.lastExecutionRunData || {};
+ const declaredOutputSchemas = session?.outputSchemas;
+ const previousConnection = node
+ ? inputConnectionsForNode(node, graph)[0]
+ : null;
+ const previousNode = previousNodeForConnection(previousConnection, graph);
+ const currentInputIndex = previousConnection
+ ? inputIndexForConnection(previousConnection)
+ : 0;
+ const previousOutputIndex = previousConnection
+ ? outputIndexForConnection(previousConnection)
+ : 0;
+ const pinnedInputItems =
+ previousOutputIndex === 0
+ ? session?.pinnedItemsForNode(previousNode?.name)
+ : undefined;
+ const inputFields = node
+ ? schemaFieldsForNodeInput(runData, node.name, {
+ inputIndex: currentInputIndex,
+ node,
+ sourceNode: previousNode,
+ outputIndex: previousOutputIndex,
+ prefix: itemPrefix,
+ pinnedItems: pinnedInputItems,
+ declaredOutputSchemas,
+ })
+ : [];
+ // Pinned sample data, falling back to the last run.
+ const ancestorNodes = node
+ ? ancestorOutputNodes(node, graph).map((ancestor) => {
+ const pinnedItems =
+ ancestor.outputIndex === 0
+ ? session?.pinnedItemsForNode(ancestor.node.name)
+ : undefined;
+ const prefix = nodeOutputJsonPath(runData, ancestor.node.name, {
+ outputIndex: ancestor.outputIndex,
+ node: ancestor.node,
+ itemCount: pinnedItems?.length,
+ });
+ return {
+ node: ancestor.node,
+ fields:
+ pinnedItems === undefined
+ ? schemaFieldsForNodeOutput(runData, ancestor.node.name, {
+ outputIndex: ancestor.outputIndex,
+ node: ancestor.node,
+ prefix,
+ declaredOutputSchemas,
+ })
+ : schemaFieldsForItems(pinnedItems, { prefix }),
+ };
+ })
+ : [];
+
+ return {
+ graph,
+ itemPrefix,
+ node,
+ session,
+ inputFields,
+ ancestorNodes,
+ siteSettings: this.siteSettings,
+ globalVars: this.workflowsNodeTypes.workflowVars,
+ workflowVariables: session?.variables,
+ nodes: graph.nodes,
+ };
+ }
+
// CodeMirror swallows pointerdowns before float-kit's outside-click detector
// sees them, so dismiss on a capture listener instead.
#armPickerDismiss() {
@@ -279,7 +315,10 @@ export default class ExpressionInput extends Component {
}
<template>
- <div {{didInsert this.registerWrapper}}>
+ <div
+ {{didInsert this.registerWrapper}}
+ {{didUpdate this.refreshScope @session.outputSchemas}}
+ >
<VariableInput
@extensions={{this.buildExtensions}}
@onChange={{this.handleChange}}
diff --git a/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/configurators/field-path-control.gjs b/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/configurators/field-path-control.gjs
index abbc4e8ea29..ed2b8072cb0 100644
--- a/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/configurators/field-path-control.gjs
+++ b/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/configurators/field-path-control.gjs
@@ -26,7 +26,6 @@ export default class FieldPathControl extends Component {
return inputFieldPathsForNode(this.args.node, {
nodes: this.args.nodes,
connections: this.args.connections,
- nodeTypes: this.args.nodeTypes,
session: this.args.session,
});
}
diff --git a/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/configurators/field.gjs b/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/configurators/field.gjs
index 2a188c48f9a..169d3c4cc95 100644
--- a/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/configurators/field.gjs
+++ b/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/configurators/field.gjs
@@ -176,6 +176,7 @@ export default class Field extends Component {
@nodes={{@nodes}}
@nodeTypes={{@nodeTypes}}
@onBeforeStartTestSession={{@onBeforeStartTestSession}}
+ @onChange={{@onChange}}
@onSet={{@onSet}}
@schema={{@schema}}
@session={{@session}}
diff --git a/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/configurators/property-engine.gjs b/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/configurators/property-engine.gjs
index 093d91c2255..aa659a07e73 100644
--- a/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/configurators/property-engine.gjs
+++ b/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/configurators/property-engine.gjs
@@ -115,6 +115,7 @@ export default class PropertyEngineConfigurator extends Component {
@nodeType={{this.nodeType}}
@nodeTypes={{@nodeTypes}}
@onBeforeStartTestSession={{@onBeforeStartTestSession}}
+ @onChange={{@onChange}}
@schema={{field}}
@session={{@session}}
/>
diff --git a/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/configurators/summarize-aggregations.gjs b/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/configurators/summarize-aggregations.gjs
index afc462fd1a3..144f82f4363 100644
--- a/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/configurators/summarize-aggregations.gjs
+++ b/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/configurators/summarize-aggregations.gjs
@@ -8,10 +8,6 @@ import {
propertyLabel,
propertyOptionLabel,
} from "../../../lib/workflows/property-engine.js";
-import {
- summarizeOutputKey,
- summarizeOutputKeyIsDerived,
-} from "../../../lib/workflows/summarize-output-key.js";
import FieldPathControl from "./field-path-control.gjs";
import FixedCollection from "./fixed-collection.gjs";
@@ -20,16 +16,7 @@ function isVisible(field, item) {
}
function isDerived(item) {
- return summarizeOutputKeyIsDerived(item || {});
-}
-
-function derivedPlaceholder(item, configuration, fieldName) {
- return summarizeOutputKeyIsDerived(item || {})
- ? summarizeOutputKey(
- item || {},
- fixedCollectionRows(configuration?.[fieldName])
- )
- : "";
+ return !String(item?.output_field_name ?? "").trim();
}
export default class SummarizeAggregations extends Component {
@@ -41,6 +28,22 @@ export default class SummarizeAggregations extends Component {
return propertyLabel(this.args.nodeDefinition, name);
};
+ derivedPlaceholder = (item, index) => {
+ return isDerived(item) ? (this.rowOutputKeys[index] ?? "") : "";
+ };
+
+ get rowOutputKeys() {
+ const rowCount = fixedCollectionRows(
+ this.args.configuration?.[this.args.fieldName]
+ ).length;
+ const keys = Object.keys(
+ this.args.session?.outputSchemas?.[this.args.node?.clientId]?.[0]
+ ?.properties || {}
+ );
+
+ return keys.length < rowCount ? [] : keys.slice(keys.length - rowCount);
+ }
+
get rowFields() {
const group = (this.args.schema?.options || [])[0] || { values: {} };
return normalizeSchema(group.values || {});
@@ -86,6 +89,7 @@ export default class SummarizeAggregations extends Component {
@nodes={{@nodes}}
@nodeType={{@nodeType}}
@nodeTypes={{@nodeTypes}}
+ @onChange={{@onChange}}
@schema={{@schema}}
@session={{@session}}
@showLabel={{false}}
@@ -98,15 +102,16 @@ export default class SummarizeAggregations extends Component {
@name="aggregation"
@showTitle={{false}}
@title={{this.fieldTitle "aggregation"}}
+ @type="select"
as |field|
>
- <field.Select @includeNone={{false}} as |select|>
+ <field.Control @includeNone={{false}} as |select|>
{{#each this.aggregationOptions key="value" as |choice|}}
<select.Option @value={{choice.value}}>
{{choice.label}}
</select.Option>
{{/each}}
- </field.Select>
+ </field.Control>
</row.object.Field>
{{#if (isVisible (this.fieldSchema "field") row.item)}}
@@ -115,17 +120,19 @@ export default class SummarizeAggregations extends Component {
@name="field"
@showTitle={{false}}
@title={{this.fieldTitle "field"}}
+ @type="custom"
as |field|
>
- <FieldPathControl
- @connections={{@connections}}
- @field={{field}}
- @node={{@node}}
- @nodes={{@nodes}}
- @nodeTypes={{@nodeTypes}}
- @schema={{this.fieldSchema "field"}}
- @session={{@session}}
- />
+ <field.Control>
+ <FieldPathControl
+ @connections={{@connections}}
+ @field={{field}}
+ @node={{@node}}
+ @nodes={{@nodes}}
+ @schema={{this.fieldSchema "field"}}
+ @session={{@session}}
+ />
+ </field.Control>
</row.object.Field>
{{/if}}
</div>
@@ -143,15 +150,16 @@ export default class SummarizeAggregations extends Component {
@name="separate_by"
@showTitle={{false}}
@title={{this.fieldTitle "separate_by"}}
+ @type="select"
as |field|
>
- <field.Select @includeNone={{false}} as |select|>
+ <field.Control @includeNone={{false}} as |select|>
{{#each this.separatorOptions key="value" as |choice|}}
<select.Option @value={{choice.value}}>
{{choice.label}}
</select.Option>
{{/each}}
- </field.Select>
+ </field.Control>
</row.object.Field>
</div>
{{/if}}
@@ -169,9 +177,10 @@ export default class SummarizeAggregations extends Component {
@name="custom_separator"
@showTitle={{false}}
@title={{this.fieldTitle "custom_separator"}}
+ @type="input"
as |field|
>
- <field.Input />
+ <field.Control />
</row.object.Field>
</div>
{{/if}}
@@ -190,16 +199,13 @@ export default class SummarizeAggregations extends Component {
'workflows-summarize-row__control--derived'
}}"
@name="output_field_name"
- @placeholder={{derivedPlaceholder
- row.item
- @configuration
- @fieldName
- }}
+ @placeholder={{this.derivedPlaceholder row.item row.index}}
@showTitle={{false}}
@title={{this.fieldTitle "output_field_name"}}
+ @type="input"
as |field|
>
- <field.Input />
+ <field.Control />
</row.object.Field>
</div>
</div>
diff --git a/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/context/input.gjs b/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/context/input.gjs
index 049944ae3df..74172d0c5fa 100644
--- a/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/context/input.gjs
+++ b/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/context/input.gjs
@@ -26,7 +26,6 @@ import {
ancestorOutputNodes,
inputConnectionsForNode,
previousNodeForConnection,
- resolveDeclaredOutputSchemas,
} from "../../../lib/workflows/schema-graph.js";
import DragDropHint from "./drag-drop-hint.gjs";
import SchemaField from "./schema-field.gjs";
@@ -142,15 +141,9 @@ export default class InputContext extends Component {
return {
nodes: this.args.nodes || [],
connections: this.args.connections || [],
- nodeTypes: this.args.nodeTypes || [],
};
}
- @cached
- get declaredOutputSchemas() {
- return resolveDeclaredOutputSchemas(this.graph);
- }
-
@cached
get inputConnections() {
return inputConnectionsForNode(this.args.node, this.graph);
@@ -200,9 +193,8 @@ export default class InputContext extends Component {
prefix: inputFieldPrefixForConnection(connection, previousNode, {
primaryConnection: this.primaryInputConnection,
}),
- graph: this.graph,
pinnedItems,
- declaredOutputSchemas: this.declaredOutputSchemas,
+ declaredOutputSchemas: this.args.session?.outputSchemas,
}
);
@@ -250,8 +242,7 @@ export default class InputContext extends Component {
outputIndex: ancestor.outputIndex,
node: ancestor.node,
prefix,
- graph: this.graph,
- declaredOutputSchemas: this.declaredOutputSchemas,
+ declaredOutputSchemas: this.args.session?.outputSchemas,
});
const summary = pinnedItems
? { itemCount: pinnedItems.length, truncated: false }
diff --git a/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/context/output.gjs b/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/context/output.gjs
index 3f3860626a7..289f7ec2b26 100644
--- a/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/context/output.gjs
+++ b/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/context/output.gjs
@@ -89,7 +89,6 @@ export default class OutputContext extends Component {
return {
nodes: this.args.nodes || [],
connections: this.args.connections || [],
- nodeTypes: this.args.nodeTypes || [],
};
}
@@ -102,8 +101,7 @@ export default class OutputContext extends Component {
{
pinnedItems: this.pinnedItems,
node: currentNode,
- graph: this.graph,
- configuration: this.args.configuration,
+ declaredOutputSchemas: this.args.session?.outputSchemas,
}
);
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 d89e93d7728..13280a94d1b 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
@@ -390,6 +390,7 @@ export default class NodeConfigurator extends Component {
this.isSaveStatusFading = false;
}
+ this.args.model.session?.scheduleOutputSchemas(...this.#draftGraph());
cancel(this.autosaveTimer);
this.autosaveTimer = later(() => {
this.#saveConfiguration({ throwOnError: true }).catch(() => {
@@ -443,6 +444,21 @@ export default class NodeConfigurator extends Component {
this.nodeTypes = await this.workflowsNodeTypes.load();
applySchemaDefaults(this.propertySchema, this.initialConfiguration);
this.#setSavedBaseline(this.configuration, this.initialNodeName);
+ this.args.model.session?.loadOutputSchemas(...this.#draftGraph());
+ }
+
+ #draftGraph() {
+ const { node, nodes, connections } = this.args.model;
+ const configuration = this.persistedConfiguration;
+
+ return [
+ nodes.map((candidate) =>
+ candidate.clientId === node.clientId
+ ? { ...candidate, configuration }
+ : candidate
+ ),
+ connections,
+ ];
}
#cancelTimers() {
@@ -628,7 +644,6 @@ export default class NodeConfigurator extends Component {
@hasConfiguration={{this.hasConfiguration}}
@node={{@model.node}}
@nodes={{@model.nodes}}
- @nodeTypes={{this.nodeTypes}}
@session={{@model.session}}
@triggerType={{@model.triggerType}}
/>
@@ -804,7 +819,6 @@ export default class NodeConfigurator extends Component {
@connections={{@model.connections}}
@node={{@model.node}}
@nodes={{@model.nodes}}
- @nodeTypes={{this.nodeTypes}}
@session={{@model.session}}
@triggerType={{@model.triggerType}}
/>
diff --git a/plugins/discourse-workflows/admin/assets/javascripts/admin/lib/workflows/data-preview.js b/plugins/discourse-workflows/admin/assets/javascripts/admin/lib/workflows/data-preview.js
index 96830ab297c..6488a88cf78 100644
--- a/plugins/discourse-workflows/admin/assets/javascripts/admin/lib/workflows/data-preview.js
+++ b/plugins/discourse-workflows/admin/assets/javascripts/admin/lib/workflows/data-preview.js
@@ -4,24 +4,13 @@ import {
outputForRun,
} from "./run-data.js";
import { fieldsForSchema, schemaFieldsForItems } from "./schema-fields.js";
-import { outputSchemaForNode } from "./schema-graph.js";
function declaredFieldsForNodeOutput(
node,
- graph,
- {
- outputIndex = 0,
- prefix = "$json",
- configuration,
- declaredOutputSchemas,
- } = {}
+ { outputIndex = 0, prefix = "$json", declaredOutputSchemas = {} } = {}
) {
return fieldsForSchema(
- outputSchemaForNode(node, graph, {
- configuration,
- outputIndex,
- outputSchemas: declaredOutputSchemas,
- }),
+ declaredOutputSchemas[node?.clientId]?.[outputIndex] || {},
{ prefix }
);
}
@@ -37,31 +26,14 @@ function portWasFullyCompacted(port) {
export function schemaFieldsForNodeOutput(
runData,
nodeName,
- {
- outputIndex = 0,
- prefix = "$json",
- node,
- graph,
- configuration,
- declaredOutputSchemas,
- } = {}
+ { outputIndex = 0, prefix = "$json", node, declaredOutputSchemas } = {}
) {
const run = latestRunWithOutput(runData, nodeName, { node });
- if (!run) {
- return declaredFieldsForNodeOutput(node, graph, {
+ const output = run && outputForRun(run, outputIndex);
+ if (!run || portWasFullyCompacted(output)) {
+ return declaredFieldsForNodeOutput(node, {
outputIndex,
prefix,
- configuration,
- declaredOutputSchemas,
- });
- }
-
- const output = outputForRun(run, outputIndex);
- if (portWasFullyCompacted(output)) {
- return declaredFieldsForNodeOutput(node, graph, {
- outputIndex,
- prefix,
- configuration,
declaredOutputSchemas,
});
}
@@ -78,7 +50,6 @@ export function schemaFieldsForNodeInput(
node,
sourceNode,
outputIndex = 0,
- graph,
pinnedItems,
declaredOutputSchemas,
} = {}
@@ -90,27 +61,19 @@ export function schemaFieldsForNodeInput(
outputIndex,
pinnedItems,
});
- if (!port) {
- if (latestRunWithOutput(runData, nodeName, { node })) {
- return [];
- }
-
- return declaredFieldsForNodeOutput(sourceNode, graph, {
- outputIndex,
- prefix,
- declaredOutputSchemas,
- });
+ if (!port && latestRunWithOutput(runData, nodeName, { node })) {
+ return [];
}
- if (portWasFullyCompacted(port)) {
- return declaredFieldsForNodeOutput(sourceNode, graph, {
+ if (!port || portWasFullyCompacted(port)) {
+ return declaredFieldsForNodeOutput(sourceNode, {
outputIndex,
prefix,
declaredOutputSchemas,
});
}
- return schemaFieldsForItems(port?.items || [], { prefix });
+ return schemaFieldsForItems(port.items || [], { prefix });
}
function portSummary(port, indexKey) {
@@ -187,7 +150,7 @@ function outputPreviewItemCount(outputs, items) {
export function outputPreviewForNode(
runData,
nodeName,
- { pinnedItems, node, graph, configuration, declaredOutputSchemas } = {}
+ { pinnedItems, node, declaredOutputSchemas } = {}
) {
if (Array.isArray(pinnedItems) && pinnedItems.length > 0) {
return {
@@ -204,8 +167,7 @@ export function outputPreviewForNode(
if (!run) {
return {
summary: null,
- fields: declaredFieldsForNodeOutput(node, graph, {
- configuration,
+ fields: declaredFieldsForNodeOutput(node, {
declaredOutputSchemas,
}),
};
@@ -215,8 +177,7 @@ export function outputPreviewForNode(
const items = outputPreviewItems(outputs);
const fields =
items.length === 0 && outputs.some(portWasFullyCompacted)
- ? declaredFieldsForNodeOutput(node, graph, {
- configuration,
+ ? declaredFieldsForNodeOutput(node, {
declaredOutputSchemas,
})
: schemaFieldsForItems(items, { prefix: "$json" });
diff --git a/plugins/discourse-workflows/admin/assets/javascripts/admin/lib/workflows/editor-session.js b/plugins/discourse-workflows/admin/assets/javascripts/admin/lib/workflows/editor-session.js
index 3ccb4035bc6..0bd16f463bc 100644
--- a/plugins/discourse-workflows/admin/assets/javascripts/admin/lib/workflows/editor-session.js
+++ b/plugins/discourse-workflows/admin/assets/javascripts/admin/lib/workflows/editor-session.js
@@ -1,5 +1,10 @@
import { tracked } from "@glimmer/tracking";
+import { cancel } from "@ember/runloop";
import { ajax } from "discourse/lib/ajax";
+import discourseDebounce from "discourse/lib/debounce";
+import { deepEqual } from "discourse/lib/object";
+import { serializeConnections } from "../../models/workflow-connection.js";
+import WorkflowNode from "../../models/workflow-node.js";
import {
normalizeSourceOutputIndex,
normalizeTargetInputIndex,
@@ -11,6 +16,8 @@ import {
outputForRun,
} from "./run-data.js";
+const OUTPUT_SCHEMAS_DEBOUNCE_MS = 300;
+
function compactObject(object) {
return Object.fromEntries(
Object.entries(object).filter(([, value]) => value !== undefined)
@@ -35,6 +42,11 @@ export default class WorkflowEditorSession {
@tracked pinData = {};
@tracked webhookTestListeners = {};
@tracked variables = [];
+ @tracked outputSchemas = {};
+
+ #outputSchemasData = null;
+ #outputSchemasRequest = 0;
+ #outputSchemasTimer = null;
constructor({
workflowId = null,
@@ -58,6 +70,59 @@ export default class WorkflowEditorSession {
this.editingNode = null;
this.graphNodes = null;
this.graphConnections = null;
+ this.outputSchemas = {};
+ this.#outputSchemasData = null;
+ this.#outputSchemasRequest++;
+ cancel(this.#outputSchemasTimer);
+ }
+
+ scheduleOutputSchemas(nodes, connections) {
+ this.#outputSchemasTimer = discourseDebounce(
+ this,
+ this.loadOutputSchemas,
+ nodes,
+ connections,
+ OUTPUT_SCHEMAS_DEBOUNCE_MS
+ );
+ }
+
+ async loadOutputSchemas(nodes, connections) {
+ if (!this.editingNode) {
+ return;
+ }
+
+ const data = JSON.stringify({
+ nodes: nodes.map((node) => {
+ const { type, typeVersion, name, parameters } =
+ WorkflowNode.serialize(node);
+ return { id: node.clientId, type, typeVersion, name, parameters };
+ }),
+ connections: serializeConnections(connections, nodes),
+ });
+ if (data === this.#outputSchemasData) {
+ return;
+ }
+
+ this.#outputSchemasData = data;
+ const request = ++this.#outputSchemasRequest;
+ let result;
+
+ try {
+ result = await ajax(
+ "/admin/plugins/discourse-workflows/output-schemas.json",
+ { type: "POST", contentType: "application/json", data }
+ );
+ } catch {
+ this.#outputSchemasData = null;
+ return;
+ }
+
+ if (
+ request === this.#outputSchemasRequest &&
+ !deepEqual(this.outputSchemas, result.output_schemas)
+ ) {
+ this.outputSchemas = result.output_schemas;
+ }
}
nodeParameterOptionsContext(context = {}) {
diff --git a/plugins/discourse-workflows/admin/assets/javascripts/admin/lib/workflows/expression-extensions/index.js b/plugins/discourse-workflows/admin/assets/javascripts/admin/lib/workflows/expression-extensions/index.js
index 4affa71fadd..00ec9d95268 100644
--- a/plugins/discourse-workflows/admin/assets/javascripts/admin/lib/workflows/expression-extensions/index.js
+++ b/plugins/discourse-workflows/admin/assets/javascripts/admin/lib/workflows/expression-extensions/index.js
@@ -19,7 +19,7 @@ export default function buildExpressionExtensions(cmParams, domainOpts = {}) {
);
const sections = { ...cmParams.utils.sections, nodes: SECTION_NODES };
- const scope = buildScope(domainOpts);
+ const scope = domainOpts.scope ?? buildScope(domainOpts);
const ancestorNodes = domainOpts.ancestorNodes || [];
const completionOpts = { scope, ancestorNodes, sections };
const onOpenReferencePicker = domainOpts.onOpenReferencePicker;
diff --git a/plugins/discourse-workflows/admin/assets/javascripts/admin/lib/workflows/input-fields.js b/plugins/discourse-workflows/admin/assets/javascripts/admin/lib/workflows/input-fields.js
index 643e43e0270..270dffc2156 100644
--- a/plugins/discourse-workflows/admin/assets/javascripts/admin/lib/workflows/input-fields.js
+++ b/plugins/discourse-workflows/admin/assets/javascripts/admin/lib/workflows/input-fields.js
@@ -4,7 +4,6 @@ import { schemaFieldsForItems } from "./schema-fields.js";
import {
inputConnectionsForNode,
previousNodeForConnection,
- resolveDeclaredOutputSchemas,
} from "./schema-graph.js";
function flattenPaths(fields, prefix = "") {
@@ -34,7 +33,7 @@ function flattenPaths(fields, prefix = "") {
* node declares no schema.
*
* @param {object} node - the node being configured
- * @param {object} context - { nodes, connections, nodeTypes, session }
+ * @param {object} context - { nodes, connections, session }
* @returns {Array<{path: string, type: string}>} deduplicated, in declaration order
*/
export function inputFieldPathsForNode(node, context = {}) {
@@ -45,11 +44,10 @@ export function inputFieldPathsForNode(node, context = {}) {
const graph = {
nodes: context.nodes || [],
connections: context.connections || [],
- nodeTypes: context.nodeTypes || [],
};
const session = context.session;
const runData = session?.lastExecutionRunData || {};
- const declaredOutputSchemas = resolveDeclaredOutputSchemas(graph);
+ const declaredOutputSchemas = session?.outputSchemas;
const seen = new Set();
const paths = [];
@@ -71,8 +69,6 @@ export function inputFieldPathsForNode(node, context = {}) {
node: previousNode,
outputIndex,
prefix: "",
- graph,
- configuration: previousNode.parameters,
declaredOutputSchemas,
});
diff --git a/plugins/discourse-workflows/admin/assets/javascripts/admin/lib/workflows/node-output-schemas.js b/plugins/discourse-workflows/admin/assets/javascripts/admin/lib/workflows/node-output-schemas.js
deleted file mode 100644
index 052f9b21425..00000000000
--- a/plugins/discourse-workflows/admin/assets/javascripts/admin/lib/workflows/node-output-schemas.js
+++ /dev/null
@@ -1,14 +0,0 @@
-import classify from "./output-schemas/classify.js";
-import summarize from "./output-schemas/summarize.js";
-
-// Nodes whose output keys come from what the author typed cannot declare them as a contract, so
-// they compute them in Ruby and name an editor-side counterpart through `output_schema_resolver`.
-const RESOLVERS = { classify, summarize };
-
-export function outputSchemasFromResolver(resolver, configuration = {}) {
- if (!resolver) {
- return null;
- }
-
- return RESOLVERS[resolver]?.(configuration || {}) || null;
-}
diff --git a/plugins/discourse-workflows/admin/assets/javascripts/admin/lib/workflows/output-schemas/classify.js b/plugins/discourse-workflows/admin/assets/javascripts/admin/lib/workflows/output-schemas/classify.js
deleted file mode 100644
index e7095ff03b4..00000000000
--- a/plugins/discourse-workflows/admin/assets/javascripts/admin/lib/workflows/output-schemas/classify.js
+++ /dev/null
@@ -1,50 +0,0 @@
-import { fixedCollectionRows } from "../property-engine.js";
-
-function answerSchema(type) {
- const properties = {
- type: { type: "string" },
- reason: { type: ["string", "null"] },
- };
-
- if (type === "yes_no") {
- properties.probability = { type: "number" };
- } else if (type === "choice" || type === "score") {
- properties.probabilities = { type: "object" };
- properties.confidence = { type: ["number", "null"] };
- if (type === "choice") {
- properties.choice = { type: "string" };
- } else {
- properties.score = { type: "number" };
- properties.level = { type: "string" };
- }
- }
-
- return { type: "object", properties };
-}
-
-export default function classifyOutputSchemas(configuration = {}) {
- const answers = new Map();
- for (const row of fixedCollectionRows(configuration.questions)) {
- if (!row || typeof row !== "object" || Array.isArray(row)) {
- continue;
- }
-
- const name = String(row.name ?? "").trim();
- if (name) {
- answers.set(name, answerSchema(row.type));
- }
- }
-
- return [
- {
- $schema: "https://json-schema.org/draft/2020-12/schema",
- type: "object",
- properties: {
- classification: {
- type: "object",
- properties: Object.fromEntries(answers),
- },
- },
- },
- ];
-}
diff --git a/plugins/discourse-workflows/admin/assets/javascripts/admin/lib/workflows/output-schemas/summarize.js b/plugins/discourse-workflows/admin/assets/javascripts/admin/lib/workflows/output-schemas/summarize.js
deleted file mode 100644
index a189f1e0216..00000000000
--- a/plugins/discourse-workflows/admin/assets/javascripts/admin/lib/workflows/output-schemas/summarize.js
+++ /dev/null
@@ -1,51 +0,0 @@
-import { fixedCollectionRows } from "../property-engine.js";
-import { fieldKey, summarizeOutputKey } from "../summarize-output-key.js";
-
-const DRAFT_URI = "https://json-schema.org/draft/2020-12/schema";
-const NUMBER_TYPE = { type: ["number", "null"] };
-const INTEGER_TYPE = { type: "integer" };
-const STRING_TYPE = { type: "string" };
-const ARRAY_TYPE = { type: "array" };
-const ANY_TYPE = {};
-
-function schemaTypeFor(row = {}) {
- switch (String(row.aggregation ?? "")) {
- case "count":
- case "count_unique":
- return INTEGER_TYPE;
- case "sum":
- case "average":
- return NUMBER_TYPE;
- case "concatenate":
- return STRING_TYPE;
- case "append":
- case "collect":
- case "unique":
- return ARRAY_TYPE;
- default:
- return ANY_TYPE;
- }
-}
-
-function splitFieldList(value) {
- return String(value ?? "")
- .split(",")
- .map((field) => field.trim())
- .filter(Boolean);
-}
-
-export default function summarizeOutputSchemas(configuration = {}) {
- const properties = {};
-
- const splitFields = splitFieldList(configuration.fields_to_split_by);
- const rows = fixedCollectionRows(configuration.fields_to_summarize);
-
- for (const field of splitFields) {
- properties[fieldKey(field, splitFields)] = ANY_TYPE;
- }
- for (const row of rows) {
- properties[summarizeOutputKey(row, rows)] = schemaTypeFor(row);
- }
-
- return [{ $schema: DRAFT_URI, type: "object", properties }];
-}
diff --git a/plugins/discourse-workflows/admin/assets/javascripts/admin/lib/workflows/schema-graph.js b/plugins/discourse-workflows/admin/assets/javascripts/admin/lib/workflows/schema-graph.js
index db08b819e34..13d3d775486 100644
--- a/plugins/discourse-workflows/admin/assets/javascripts/admin/lib/workflows/schema-graph.js
+++ b/plugins/discourse-workflows/admin/assets/javascripts/admin/lib/workflows/schema-graph.js
@@ -2,265 +2,6 @@ import {
normalizeSourceOutputIndex,
normalizeTargetInputIndex,
} from "./graph-constants.js";
-import { outputSchemasFromResolver } from "./node-output-schemas.js";
-import { resolveNodeTypeVersion, typeVersionForNode } from "./node-types.js";
-import { fieldDisplayState, fieldVisible } from "./property-engine.js";
-
-const DRAFT_URI = "https://json-schema.org/draft/2020-12/schema";
-
-function isUnknown(schema) {
- return !schema || !Object.keys(schema).length;
-}
-
-function isAnyOfWrapper(schema) {
- const keys = Object.keys(schema).filter((key) => key !== "$schema");
- return keys.length === 1 && keys[0] === "anyOf";
-}
-
-function anyOfBranches(schema) {
- return isAnyOfWrapper(schema) ? schema.anyOf : [schema];
-}
-
-function schemasEqual(left, right) {
- return JSON.stringify(left) === JSON.stringify(right);
-}
-
-function unionSchemas(schemas) {
- if (!schemas.length || schemas.some(isUnknown)) {
- return {};
- }
-
- const branches = [];
- for (const schema of schemas) {
- for (const branch of anyOfBranches(schema)) {
- if (!branches.some((existing) => schemasEqual(existing, branch))) {
- branches.push(branch);
- }
- }
- }
-
- return branches.length === 1
- ? branches[0]
- : { $schema: DRAFT_URI, anyOf: branches };
-}
-
-function isObjectSchema(schema) {
- const types = Array.isArray(schema.type)
- ? schema.type
- : schema.type
- ? [schema.type]
- : [];
- return types.includes("object");
-}
-
-function overlaySchemas(inputSchema, declaredSchema) {
- if (isUnknown(inputSchema)) {
- return declaredSchema;
- }
-
- if (isUnknown(declaredSchema)) {
- return inputSchema;
- }
-
- if (isAnyOfWrapper(inputSchema)) {
- return unionSchemas(
- inputSchema.anyOf.map((branch) => overlaySchemas(branch, declaredSchema))
- );
- }
-
- const merged = { ...inputSchema, ...declaredSchema };
- if (isObjectSchema(inputSchema) && isObjectSchema(declaredSchema)) {
- merged.properties = {
- ...(inputSchema.properties || {}),
- ...(declaredSchema.properties || {}),
- };
-
- const required = [
- ...new Set([
- ...(inputSchema.required || []),
- ...(declaredSchema.required || []),
- ]),
- ];
- if (required.length) {
- merged.required = required;
- } else {
- delete merged.required;
- }
- }
-
- return merged;
-}
-
-function mergeSchemaPair(left, right) {
- const merged = { ...left, ...right };
- if (!isObjectSchema(left) || !isObjectSchema(right)) {
- return merged;
- }
-
- const properties = { ...(left.properties || {}) };
- for (const [name, value] of Object.entries(right.properties || {})) {
- const existing = properties[name];
- properties[name] =
- existing && isObjectSchema(existing) && isObjectSchema(value)
- ? mergeSchemaPair(existing, value)
- : value;
- }
- merged.properties = properties;
-
- const required = [
- ...new Set([...(left.required || []), ...(right.required || [])]),
- ];
- if (required.length) {
- merged.required = required;
- } else {
- delete merged.required;
- }
-
- return merged;
-}
-
-function augmentSchema(schema, extensions) {
- const usable = extensions.filter((extension) => !isUnknown(extension));
- if (!usable.length) {
- return schema;
- }
-
- if (isAnyOfWrapper(schema)) {
- return unionSchemas(
- schema.anyOf.map((branch) => augmentSchema(branch, usable))
- );
- }
-
- return usable.reduce(mergeSchemaPair, schema);
-}
-
-function activeOutputExtensions(contract, configuration) {
- return (contract.extensions || [])
- .filter((extension) =>
- fieldVisible(
- { display_options: extension.display_options },
- configuration
- )
- )
- .map((extension) => extension.schema || {});
-}
-
-function resolvedOutputSchema(contract, inputSchema = {}) {
- switch (contract.mode) {
- case "passthrough":
- return inputSchema;
- case "union":
- return unionSchemas([inputSchema, contract.schema]);
- case "merge":
- return overlaySchemas(inputSchema, contract.schema);
- default:
- return contract.schema;
- }
-}
-
-function contractDefinition(contract = {}) {
- return {
- mode: contract.mode ?? "replace",
- schema:
- contract.schema &&
- typeof contract.schema === "object" &&
- !Array.isArray(contract.schema)
- ? contract.schema
- : {},
- };
-}
-
-function activeOutputContracts(contract, configuration) {
- const candidates = [];
-
- for (const variant of contract.variants || []) {
- const state = fieldDisplayState(
- { display_options: variant.display_options },
- configuration
- );
- if (state === "hidden") {
- continue;
- }
-
- candidates.push(contractDefinition(variant));
- // Nothing after a definite match can be picked at runtime.
- if (state === "visible") {
- return candidates;
- }
- }
-
- if (
- fieldVisible({ display_options: contract.display_options }, configuration)
- ) {
- candidates.push(contractDefinition(contract));
- }
-
- // An unknown schema absorbs the union of everything it contends with, so drop
- // it rather than let it erase what the others declare.
- const contenders = candidates.filter(
- ({ mode, schema }) => !(mode === "replace" && isUnknown(schema))
- );
-
- return contenders.length ? contenders : [contractDefinition({})];
-}
-
-function nodeTypeDefinitionForNode(node, graph) {
- const definition = (graph?.nodeTypes || []).find(
- (candidate) =>
- candidate.name === node?.type || candidate.identifier === node?.type
- );
- if (!definition) {
- return null;
- }
-
- return resolveNodeTypeVersion(definition, typeVersionForNode(node));
-}
-
-function ownOutputResolution(node, graph, configuration) {
- const definition = nodeTypeDefinitionForNode(node, graph);
- if (!definition) {
- return { contracts: [[{ mode: "replace", schema: {} }]], extensions: [[]] };
- }
-
- const currentConfiguration = configuration ?? node.configuration ?? {};
- const resolved = outputSchemasFromResolver(
- definition.output_schema_resolver,
- currentConfiguration
- );
- if (resolved) {
- return {
- contracts: resolved.map((schema, index) => [
- {
- mode: definition.output_contracts?.[index]?.mode || "replace",
- schema,
- },
- ]),
- extensions: resolved.map(() => []),
- };
- }
-
- const serializedContracts = definition.output_contracts;
- const declarations = Array.isArray(serializedContracts)
- ? serializedContracts
- : [];
- const outputCount =
- declarations.length ||
- (definition.outputs || definition.ports || [null]).length;
-
- const contracts = [];
- const extensions = [];
- for (let index = 0; index < outputCount; index++) {
- const declaration = declarations[index] || {};
- contracts.push(activeOutputContracts(declaration, currentConfiguration));
- extensions.push(activeOutputExtensions(declaration, currentConfiguration));
- }
-
- return { contracts, extensions };
-}
-
-function nodeKey(node) {
- return node?.clientId ?? node?.id ?? node;
-}
function connectionOrder(left, right) {
return (
@@ -270,167 +11,6 @@ function connectionOrder(left, right) {
);
}
-export function resolveDeclaredOutputSchemas(
- graph,
- { configurationOverrides = new Map(), visited = new Set() } = {}
-) {
- const nodes = (graph?.nodes || []).filter(
- (candidate) => !visited.has(nodeKey(candidate))
- );
- const nodesById = new Map(
- nodes.map((candidate) => [nodeKey(candidate), candidate])
- );
-
- const incomingByTarget = new Map();
- for (const connection of graph?.connections || []) {
- if (
- connection.sourceClientId === connection.targetClientId ||
- visited.has(connection.sourceClientId) ||
- !nodesById.has(connection.sourceClientId) ||
- !nodesById.has(connection.targetClientId)
- ) {
- continue;
- }
-
- const incoming = incomingByTarget.get(connection.targetClientId) || [];
- incoming.push(connection);
- incomingByTarget.set(connection.targetClientId, incoming);
- }
- for (const incoming of incomingByTarget.values()) {
- incoming.sort(connectionOrder);
- }
-
- const resolutionByKey = new Map(
- nodes.map((candidate) => [
- nodeKey(candidate),
- ownOutputResolution(
- candidate,
- graph,
- configurationOverrides.get(nodeKey(candidate))
- ),
- ])
- );
-
- const outputSchemas = new Map();
-
- function inputSchemaFor(key) {
- const connections = incomingByTarget.get(key) || [];
- if (!connections.length) {
- return {};
- }
-
- const schemas = [];
- for (const connection of connections) {
- const sourceOutputs = outputSchemas.get(connection.sourceClientId);
- if (!sourceOutputs) {
- continue;
- }
-
- schemas.push(sourceOutputs[normalizeSourceOutputIndex(connection)] || {});
- }
-
- return schemas.length ? unionSchemas(schemas) : undefined;
- }
-
- function sweepUntilStable() {
- let changed = true;
- let sweeps = 0;
-
- while (changed) {
- if (++sweeps > nodes.length + 2) {
- throw new Error("Output schema graph did not converge");
- }
-
- changed = false;
- for (const candidate of nodes) {
- const key = nodeKey(candidate);
- const { contracts, extensions } = resolutionByKey.get(key);
- let inputSchema = {};
-
- if (
- contracts.some((port) => port.some(({ mode }) => mode !== "replace"))
- ) {
- inputSchema = inputSchemaFor(key);
- if (inputSchema === undefined) {
- continue;
- }
- }
-
- const resolved = contracts.map((port, index) =>
- augmentSchema(
- unionSchemas(
- port.map((contract) =>
- resolvedOutputSchema(contract, inputSchema)
- )
- ),
- extensions[index] || []
- )
- );
- if (
- !outputSchemas.has(key) ||
- !schemasEqual(outputSchemas.get(key), resolved)
- ) {
- changed = true;
- outputSchemas.set(key, resolved);
- }
- }
- }
- }
-
- sweepUntilStable();
-
- let promoted = false;
- for (const candidate of nodes) {
- const key = nodeKey(candidate);
- if (!outputSchemas.has(key)) {
- promoted = true;
- outputSchemas.set(
- key,
- resolutionByKey.get(key).contracts.map(() => ({}))
- );
- }
- }
- if (promoted) {
- sweepUntilStable();
- }
-
- return outputSchemas;
-}
-
-export function outputSchemaForNode(
- node,
- graph,
- { configuration, outputIndex = 0, outputSchemas, visited = new Set() } = {}
-) {
- if (!node) {
- return {};
- }
-
- const targetNodeKey = nodeKey(node);
- if (visited.has(targetNodeKey)) {
- return {};
- }
-
- if (!outputSchemas) {
- const nodes = graph?.nodes || [];
- const resolutionGraph = nodes.some(
- (candidate) => nodeKey(candidate) === targetNodeKey
- )
- ? graph
- : { ...graph, nodes: [...nodes, node] };
- const configurationOverrides = new Map();
- if (configuration !== undefined) {
- configurationOverrides.set(targetNodeKey, configuration);
- }
- outputSchemas = resolveDeclaredOutputSchemas(resolutionGraph, {
- configurationOverrides,
- visited,
- });
- }
-
- return outputSchemas.get(targetNodeKey)?.[outputIndex] || {};
-}
-
export function inputConnectionsForNode(node, graph, visited = new Set()) {
if (!node) {
return [];
diff --git a/plugins/discourse-workflows/admin/assets/javascripts/admin/lib/workflows/summarize-output-key.js b/plugins/discourse-workflows/admin/assets/javascripts/admin/lib/workflows/summarize-output-key.js
deleted file mode 100644
index adf11ab4818..00000000000
--- a/plugins/discourse-workflows/admin/assets/javascripts/admin/lib/workflows/summarize-output-key.js
+++ /dev/null
@@ -1,69 +0,0 @@
-// Mirrors DiscourseWorkflows::Nodes::Summarize::V1.output_key so the editor can show
-// which field an aggregation will write to before the workflow runs.
-const OUTPUT_PREFIXES = {
- append: "appended_",
- average: "average_",
- collect: "collected_",
- concatenate: "concatenated_",
- count: "count_",
- count_unique: "unique_count_",
- first: "first_",
- last: "last_",
- max: "max_",
- min: "min_",
- sum: "sum_",
- unique: "unique_",
-};
-
-function leafName(field) {
- return field.includes(".") ? field.split(".").pop() : field;
-}
-
-function sanitizeKey(name) {
- return String(name)
- .replace(/["[\]]/g, "")
- .replace(/[ .]/g, "_");
-}
-
-export function fieldKey(field, fields) {
- const leaf = leafName(field);
- if (fields.filter((other) => leafName(other) === leaf).length < 2) {
- return leaf;
- }
-
- return sanitizeKey(field);
-}
-
-function derivedFields(rows, aggregation) {
- return rows
- .filter(
- (row) =>
- String(row.aggregation ?? "") === aggregation &&
- summarizeOutputKeyIsDerived(row)
- )
- .map((row) => String(row.field ?? "").trim())
- .filter(Boolean);
-}
-
-export function summarizeOutputKey(row = {}, rows = [row]) {
- const explicit = String(row.output_field_name ?? "").trim();
- if (explicit) {
- return explicit;
- }
-
- const aggregation = String(row.aggregation ?? "");
- const prefix = OUTPUT_PREFIXES[aggregation] ?? "";
- const field = String(row.field ?? "").trim();
-
- if (!field) {
- return prefix.replace(/_$/, "");
- }
-
- return `${prefix}${sanitizeKey(
- fieldKey(field, derivedFields(rows, aggregation))
- )}`;
-}
-
-export function summarizeOutputKeyIsDerived(row = {}) {
- return !String(row.output_field_name ?? "").trim();
-}
diff --git a/plugins/discourse-workflows/app/controllers/discourse_workflows/output_schemas_controller.rb b/plugins/discourse-workflows/app/controllers/discourse_workflows/output_schemas_controller.rb
new file mode 100644
index 00000000000..01d07c983c1
--- /dev/null
+++ b/plugins/discourse-workflows/app/controllers/discourse_workflows/output_schemas_controller.rb
@@ -0,0 +1,40 @@
+# frozen_string_literal: true
+
+module DiscourseWorkflows
+ class OutputSchemasController < ::Admin::AdminController
+ requires_plugin DiscourseWorkflows::PLUGIN_NAME
+
+ RATE_LIMIT = 240
+ RATE_PERIOD = 60
+
+ before_action :rate_limit_resolution, only: :create
+
+ def create
+ Workflow::ResolveOutputSchemas.call(service_params) do
+ on_success { |output_schemas:| render json: { output_schemas: } }
+ on_failed_policy(:can_manage_workflows) { raise Discourse::InvalidAccess }
+ on_exceptions(Schema::GraphResolver::NotConverged) do
+ render(json: failed_json, status: :unprocessable_entity)
+ end
+ on_failed_contract do |contract|
+ render(
+ json: failed_json.merge(errors: contract.errors.full_messages),
+ status: :bad_request,
+ )
+ end
+ end
+ end
+
+ private
+
+ def rate_limit_resolution
+ RateLimiter.new(
+ current_user,
+ "workflow-output-schemas",
+ RATE_LIMIT,
+ RATE_PERIOD,
+ apply_limit_to_staff: true,
+ ).performed!
+ end
+ end
+end
diff --git a/plugins/discourse-workflows/app/services/discourse_workflows/workflow/resolve_output_schemas.rb b/plugins/discourse-workflows/app/services/discourse_workflows/workflow/resolve_output_schemas.rb
new file mode 100644
index 00000000000..999c99bbe0e
--- /dev/null
+++ b/plugins/discourse-workflows/app/services/discourse_workflows/workflow/resolve_output_schemas.rb
@@ -0,0 +1,40 @@
+# frozen_string_literal: true
+
+module DiscourseWorkflows
+ class Workflow::ResolveOutputSchemas
+ include Service::Base
+
+ params do
+ attribute :nodes
+ attribute :connections
+
+ validates :nodes, presence: true, length: { maximum: WorkflowGraphValidator::MAX_NODES }
+ validate :nodes_are_hashes
+ validate :connections_is_a_hash
+
+ private
+
+ def nodes_are_hashes
+ errors.add(:nodes, :invalid) unless nodes.is_a?(Array) && nodes.all?(Hash)
+ end
+
+ def connections_is_a_hash
+ errors.add(:connections, :invalid) unless connections.nil? || connections.is_a?(Hash)
+ end
+ end
+
+ policy :can_manage_workflows, class_name: Policy::CanManageWorkflows
+ try(Schema::GraphResolver::NotConverged) { step :resolve }
+
+ private
+
+ def resolve(params:)
+ context[:output_schemas] = Schema.resolve_graph(
+ params.nodes.map(&:deep_stringify_keys),
+ params.connections.to_h.deep_stringify_keys,
+ )[
+ :output_schemas
+ ]
+ end
+ end
+end
diff --git a/plugins/discourse-workflows/config/routes.rb b/plugins/discourse-workflows/config/routes.rb
index f0fa0baa4bf..4a8a0214b06 100644
--- a/plugins/discourse-workflows/config/routes.rb
+++ b/plugins/discourse-workflows/config/routes.rb
@@ -79,6 +79,7 @@ DiscourseWorkflows::Engine.routes.draw do
get "/stats/:workflow_id" => "stats#index"
post "/expressions/evaluate" => "expressions#evaluate"
post "/node-previews" => "node_previews#create"
+ post "/output-schemas" => "output_schemas#create"
get "/variables" => "variables#index"
post "/variables" => "variables#create"
put "/variables/:id" => "variables#update"
diff --git a/plugins/discourse-workflows/lib/discourse_workflows/node_type.rb b/plugins/discourse-workflows/lib/discourse_workflows/node_type.rb
index b573ca3e071..91fcfe8140a 100644
--- a/plugins/discourse-workflows/lib/discourse_workflows/node_type.rb
+++ b/plugins/discourse-workflows/lib/discourse_workflows/node_type.rb
@@ -92,7 +92,6 @@ module DiscourseWorkflows
capabilities: {
},
output_contracts: [],
- output_schema_resolver: nil,
palette_visible: true,
available: true,
previewable: false,
@@ -219,10 +218,6 @@ module DiscourseWorkflows
end
end
- def self.output_schema_resolver
- description_value(:output_schema_resolver)
- end
-
def self.output_contracts
@output_contracts ||=
begin
diff --git a/plugins/discourse-workflows/lib/discourse_workflows/node_type_serializer.rb b/plugins/discourse-workflows/lib/discourse_workflows/node_type_serializer.rb
index b337aac297e..421eeaa9b5e 100644
--- a/plugins/discourse-workflows/lib/discourse_workflows/node_type_serializer.rb
+++ b/plugins/discourse-workflows/lib/discourse_workflows/node_type_serializer.rb
@@ -36,16 +36,19 @@ module DiscourseWorkflows
webhooks = serializable_webhooks(klass)
metadata = load_options_metadata(klass, properties)
description =
- klass.description.merge(
- displayName: klass.label_key,
- descriptionKey: klass.description_key,
- name: @identifier,
- version: version,
- inputs: klass.input_ports,
- outputs: klass.ports,
- properties: properties,
- webhooks: webhooks,
- )
+ klass
+ .description
+ .except(:output_contracts)
+ .merge(
+ displayName: klass.label_key,
+ descriptionKey: klass.description_key,
+ name: @identifier,
+ version: version,
+ inputs: klass.input_ports,
+ outputs: klass.ports,
+ properties: properties,
+ webhooks: webhooks,
+ )
{
displayName: description[:displayName],
@@ -64,8 +67,6 @@ module DiscourseWorkflows
capabilities: klass.capabilities,
ports: klass.ports,
operations: klass.operations,
- output_contracts: serializable_output_contracts(klass),
- output_schema_resolver: klass.output_schema_resolver,
palette_visible: klass.palette_visible?,
deprecation: klass.deprecation,
previewable: klass.previewable?,
@@ -79,31 +80,6 @@ module DiscourseWorkflows
klass.webhooks.map { |webhook| webhook.except(:handler) }
end
- def serializable_output_contracts(klass)
- contracts = klass.output_contracts
- if contracts.all? { |contract|
- contract[:schema].empty? && contract[:mode] == :replace && contract[:variants].empty? &&
- contract[:extensions].empty?
- }
- return
- end
-
- contracts.map { |contract| serializable_output_contract(contract) }
- end
-
- def serializable_output_contract(contract)
- contract.slice(:schema, :mode, :display_options).merge(
- variants:
- contract
- .fetch(:variants)
- .map { |variant| variant.slice(:schema, :mode, :display_options) },
- extensions:
- contract
- .fetch(:extensions)
- .map { |extension| extension.slice(:schema, :display_options) },
- )
- end
-
def load_options_metadata(klass, properties)
return {} unless klass.respond_to?(:load_options_context)
diff --git a/plugins/discourse-workflows/lib/discourse_workflows/nodes/data_table/v1.rb b/plugins/discourse-workflows/lib/discourse_workflows/nodes/data_table/v1.rb
index 2e76d90535f..aa6c7af3d8f 100644
--- a/plugins/discourse-workflows/lib/discourse_workflows/nodes/data_table/v1.rb
+++ b/plugins/discourse-workflows/lib/discourse_workflows/nodes/data_table/v1.rb
@@ -5,6 +5,21 @@ module DiscourseWorkflows
module DataTable
class V1 < NodeType
OPERATIONS = %w[insert get update delete upsert row_exists row_not_exists].freeze
+ PASSTHROUGH_OPERATIONS = %w[row_exists row_not_exists].freeze
+ COLUMN_SCHEMAS = {
+ "string" => {
+ "type" => %w[string null],
+ },
+ "number" => {
+ "type" => %w[number null],
+ },
+ "boolean" => {
+ "type" => %w[boolean null],
+ },
+ "date" => {
+ "type" => %w[string null],
+ },
+ }.freeze
MAPPING_MODES = %w[manual auto].freeze
DEFAULT_LIMIT = DiscourseWorkflows::DataTables::Facade::MAX_LIMIT
CONDITION_OVERRIDES =
@@ -47,6 +62,20 @@ module DiscourseWorkflows
},
group: "data",
i18n_scope: "data_table_node",
+ output_contracts: [
+ {
+ variants: [
+ {
+ mode: :passthrough,
+ display_options: {
+ show: {
+ operation: PASSTHROUGH_OPERATIONS,
+ },
+ },
+ },
+ ],
+ },
+ ],
capabilities: {
run_scope: "per_item",
},
@@ -178,6 +207,19 @@ module DiscourseWorkflows
},
)
+ def self.output_schemas(configuration = {}, input_schemas: [])
+ config = (configuration || {}).deep_stringify_keys
+ return super if PASSTHROUGH_OPERATIONS.include?(config["operation"])
+
+ columns = DiscourseWorkflows::DataTable.find_by(id: config["data_table_id"])&.columns.to_a
+ types =
+ DataTables::Types::SYSTEM_COLUMN_TYPE_MAP.merge(
+ columns.to_h { |column| [column["name"], column["type"]] },
+ )
+
+ [Schema.document(types.transform_values { |type| COLUMN_SCHEMAS.fetch(type) })]
+ end
+
def self.load_options_context(context)
case context.method_name
when "data_tables"
diff --git a/plugins/discourse-workflows/lib/discourse_workflows/nodes/form/v1.rb b/plugins/discourse-workflows/lib/discourse_workflows/nodes/form/v1.rb
index 11ca326b613..4aff2be279f 100644
--- a/plugins/discourse-workflows/lib/discourse_workflows/nodes/form/v1.rb
+++ b/plugins/discourse-workflows/lib/discourse_workflows/nodes/form/v1.rb
@@ -4,6 +4,8 @@ module DiscourseWorkflows
module Nodes
module Form
class V1 < NodeType
+ COMPLETION_PAGE_TYPE = "completion"
+
description(
name: "action:form",
version: "1.0",
@@ -12,6 +14,7 @@ module DiscourseWorkflows
color: "blue",
},
group: "human_review",
+ output_contracts: [{ mode: :passthrough }],
properties: {
page_type: {
type: :options,
@@ -125,10 +128,18 @@ module DiscourseWorkflows
],
)
+ def self.output_schemas(configuration = {}, input_schemas: [])
+ if (configuration || {}).deep_stringify_keys["page_type"] == COMPLETION_PAGE_TYPE
+ return super
+ end
+
+ FormTrigger::V1.output_schemas(configuration)
+ end
+
def execute(exec_ctx)
page_type = exec_ctx.get_node_parameter("page_type", 0, default: "page")
- return [exec_ctx.input_items] if page_type == "completion"
+ return [exec_ctx.input_items] if page_type == COMPLETION_PAGE_TYPE
exec_ctx.put_execution_to_wait(nil)
[exec_ctx.input_items]
diff --git a/plugins/discourse-workflows/lib/discourse_workflows/nodes/form_trigger/v1.rb b/plugins/discourse-workflows/lib/discourse_workflows/nodes/form_trigger/v1.rb
index a75a0448bd1..83ee356d873 100644
--- a/plugins/discourse-workflows/lib/discourse_workflows/nodes/form_trigger/v1.rb
+++ b/plugins/discourse-workflows/lib/discourse_workflows/nodes/form_trigger/v1.rb
@@ -4,6 +4,28 @@ module DiscourseWorkflows
module Nodes
module FormTrigger
class V1 < NodeType
+ TEXT_FIELD_SCHEMA = { "type" => %w[string null] }.freeze
+ FIELD_SCHEMAS = {
+ "number" => {
+ "type" => %w[number null],
+ },
+ "checkbox" => {
+ "type" => %w[boolean null],
+ },
+ }.freeze
+ METADATA_PROPERTIES = {
+ "submitted_at" => {
+ "type" => "string",
+ },
+ "form_mode" => {
+ "type" => "string",
+ },
+ "form_query_parameters" => {
+ "type" => "object",
+ "x-optional" => true,
+ },
+ }.freeze
+
description(
name: NodeDataShape::FORM_TRIGGER_TYPE,
version: "1.0",
@@ -53,6 +75,25 @@ module DiscourseWorkflows
],
)
+ def self.output_schemas(configuration = {}, input_schemas: [])
+ fields =
+ Schemas::FormFields.with_keys(
+ CollectionParameters.rows(configuration || {}, "form_fields"),
+ )
+ properties =
+ fields
+ .reject do |field|
+ field["field_type"] == Schemas::FormFields::DISPLAY_ONLY_FIELD_TYPE
+ end
+ .to_h { |field| [field["key"], field_schema(field["field_type"])] }
+
+ [Schema.document(properties.merge(METADATA_PROPERTIES))]
+ end
+
+ def self.field_schema(field_type)
+ FIELD_SCHEMAS.fetch(field_type) { expression_value?(field_type) ? {} : TEXT_FIELD_SCHEMA }
+ end
+
def initialize(
form_data:,
submitted_at: Time.current.utc.iso8601(3),
diff --git a/plugins/discourse-workflows/lib/discourse_workflows/nodes/summarize/v1.rb b/plugins/discourse-workflows/lib/discourse_workflows/nodes/summarize/v1.rb
index 0e23948acd6..8ca3a22c695 100644
--- a/plugins/discourse-workflows/lib/discourse_workflows/nodes/summarize/v1.rb
+++ b/plugins/discourse-workflows/lib/discourse_workflows/nodes/summarize/v1.rb
@@ -58,7 +58,6 @@ module DiscourseWorkflows
},
group: "data",
previewable: true,
- output_schema_resolver: "summarize",
capabilities: {
run_scope: "all_items",
},
diff --git a/plugins/discourse-workflows/lib/discourse_workflows/schema/graph_resolver.rb b/plugins/discourse-workflows/lib/discourse_workflows/schema/graph_resolver.rb
index c902e54ab1d..8c1726ec6a2 100644
--- a/plugins/discourse-workflows/lib/discourse_workflows/schema/graph_resolver.rb
+++ b/plugins/discourse-workflows/lib/discourse_workflows/schema/graph_resolver.rb
@@ -3,6 +3,9 @@
module DiscourseWorkflows
module Schema
class GraphResolver
+ class NotConverged < StandardError
+ end
+
def self.call(nodes, connections)
new(nodes, connections).call
end
@@ -33,6 +36,7 @@ module DiscourseWorkflows
end
@input_schemas = {}
@output_schemas = {}
+ @resolved_output_schemas = {}
end
def call
@@ -54,9 +58,7 @@ module DiscourseWorkflows
sweeps = 0
while changed
- if (sweeps += 1) > @nodes.length + 2
- raise ArgumentError, "Output schema graph did not converge"
- end
+ raise NotConverged if (sweeps += 1) > @nodes.length + 2
changed = false
@nodes_by_id.each_key do |node_id|
@@ -89,7 +91,7 @@ module DiscourseWorkflows
node_class = @node_classes[node_id]
return [{}] unless node_class
- node_class.output_schemas(
+ @resolved_output_schemas[[node_id, input_schemas]] ||= node_class.output_schemas(
NodeData.parameters(@nodes_by_id.fetch(node_id)),
input_schemas: input_schemas,
)
diff --git a/plugins/discourse-workflows/lib/discourse_workflows/schemas/form_fields.rb b/plugins/discourse-workflows/lib/discourse_workflows/schemas/form_fields.rb
index 20c422ce8fe..8b440341805 100644
--- a/plugins/discourse-workflows/lib/discourse_workflows/schemas/form_fields.rb
+++ b/plugins/discourse-workflows/lib/discourse_workflows/schemas/form_fields.rb
@@ -5,6 +5,7 @@ module DiscourseWorkflows
module FormFields
MAX_FIELD_VALUE_LENGTH = 10_000
EMAIL_REGEX = URI::MailTo::EMAIL_REGEXP
+ DISPLAY_ONLY_FIELD_TYPE = "html"
ValidationResult =
Struct.new(:errors, :data, keyword_init: true) do
@@ -153,7 +154,7 @@ module DiscourseWorkflows
next field if field["field_value"].present?
field.merge("field_value" => normalized_query_parameters[key])
- when "password", "html"
+ when "password", DISPLAY_ONLY_FIELD_TYPE
field
else
field.merge("default_value" => normalized_query_parameters[key])
@@ -181,7 +182,7 @@ module DiscourseWorkflows
data = {}
with_keys(fields).each do |field|
- next if field["field_type"] == "html"
+ next if field["field_type"] == DISPLAY_ONLY_FIELD_TYPE
key = field["key"]
@@ -216,7 +217,7 @@ module DiscourseWorkflows
return false unless field["required"]
return false if field["field_type"] == "checkbox"
return false if field["field_type"] == "hiddenField"
- return false if field["field_type"] == "html"
+ return false if field["field_type"] == DISPLAY_ONLY_FIELD_TYPE
value.blank?
end
diff --git a/plugins/discourse-workflows/lib/discourse_workflows/workflow_document.rb b/plugins/discourse-workflows/lib/discourse_workflows/workflow_document.rb
index 1ab5d2d010c..e6c66258cc9 100644
--- a/plugins/discourse-workflows/lib/discourse_workflows/workflow_document.rb
+++ b/plugins/discourse-workflows/lib/discourse_workflows/workflow_document.rb
@@ -3,6 +3,7 @@
module DiscourseWorkflows
module WorkflowDocument
DEFAULT_CONNECTION_TYPE = "main"
+ MAX_INPUT_INDEX = 99
module_function
@@ -137,10 +138,14 @@ module DiscourseWorkflows
target_name = target_connection["node"].to_s
next if target_name.blank? || !node_names.include?(target_name)
+ index = target_connection["index"]
+ index = index.to_i if index.respond_to?(:to_i)
+ next unless index.is_a?(Integer) && index.between?(0, MAX_INPUT_INDEX)
+
{
"node" => target_name,
"type" => target_connection["type"].presence || DEFAULT_CONNECTION_TYPE,
- "index" => target_connection["index"].to_i,
+ "index" => index,
}
end
diff --git a/plugins/discourse-workflows/spec/lib/discourse_workflows/node_output_contracts_spec.rb b/plugins/discourse-workflows/spec/lib/discourse_workflows/node_output_contracts_spec.rb
index b9bf4f3f939..920dfe70a28 100644
--- a/plugins/discourse-workflows/spec/lib/discourse_workflows/node_output_contracts_spec.rb
+++ b/plugins/discourse-workflows/spec/lib/discourse_workflows/node_output_contracts_spec.rb
@@ -13,28 +13,15 @@ RSpec.describe DiscourseWorkflows::NodeType do
}
end
- it "requires nodes that override output_schemas to name an editor-side resolver" do
- overriding =
- DiscourseWorkflows::NodeType.registered_nodes.select do |node_class|
- node_class.singleton_class.instance_methods(false).include?(:output_schemas)
- end
-
- expect(overriding).to be_present
- expect(overriding.reject(&:output_schema_resolver)).to be_empty
- end
-
it "requires every node without a user-defined output to declare it" do
user_defined_output = %w[
action:code
- action:data_table
- action:form
action:modal
action:set_fields
action:split_out
action:sql
action:workflow_call
flow:sticky_note
- trigger:form
trigger:manual
trigger:workflow_call
]
diff --git a/plugins/discourse-workflows/spec/lib/discourse_workflows/node_type_serializer_spec.rb b/plugins/discourse-workflows/spec/lib/discourse_workflows/node_type_serializer_spec.rb
index 922628e9574..093d4a4517f 100644
--- a/plugins/discourse-workflows/spec/lib/discourse_workflows/node_type_serializer_spec.rb
+++ b/plugins/discourse-workflows/spec/lib/discourse_workflows/node_type_serializer_spec.rb
@@ -2,97 +2,15 @@
RSpec.describe DiscourseWorkflows::NodeTypeSerializer do
describe "#to_h" do
- it "serializes output contract schemas by version", :aggregate_failures do
- serializer = described_class.new(identifier: "action:group", available_versions: ["1.0"])
-
- version = serializer.to_h.dig(:versions, "1.0")
-
- expect(version.dig(:output_contracts, 0, :schema)).to eq({})
- expect(version.dig(:output_contracts, 0, :mode)).to eq(:replace)
- expect(version.dig(:output_contracts, 0, :variants)).to eq(
- [
- {
- schema: DiscourseWorkflows::Nodes::Group::V1::GROUP_ACTION_SCHEMA,
- mode: :replace,
- display_options: {
- show: {
- operation: %w[add remove],
- },
- },
- },
- {
- schema: DiscourseWorkflows::Schema::GROUP_SCHEMA,
- mode: :replace,
- display_options: {
- show: {
- operation: ["get"],
- },
- },
- },
- {
- schema: DiscourseWorkflows::Schema::GROUP_MEMBERSHIP_SCHEMA,
- mode: :merge,
- display_options: {
- show: {
- operation: ["check_membership"],
- },
- },
- },
- ],
- )
- end
-
- it "omits empty and default declaration fields", :aggregate_failures do
- serializer = described_class.new(identifier: "trigger:manual", available_versions: ["1.0"])
-
- version = serializer.to_h.dig(:versions, "1.0")
+ it "does not serialize output contracts" do
+ version =
+ described_class
+ .new(identifier: "action:group", available_versions: ["1.0"])
+ .to_h
+ .dig(:versions, "1.0")
expect(version).not_to have_key(:output_contracts)
- end
-
- it "serializes a non-default mode without an output schema" do
- serializer = described_class.new(identifier: "action:limit", available_versions: ["1.0"])
-
- version = serializer.to_h.dig(:versions, "1.0")
-
- expect(version[:output_contracts]).to contain_exactly(
- schema: {
- },
- mode: :passthrough,
- display_options: {
- },
- variants: [],
- extensions: [],
- )
- end
-
- it "serializes configuration-aware output variants" do
- serializer = described_class.new(identifier: "flow:wait", available_versions: ["1.0"])
-
- version = serializer.to_h.dig(:versions, "1.0")
-
- expect(version.dig(:output_contracts, 0, :variants)).to contain_exactly(
- {
- schema: DiscourseWorkflows::Schema::WEBHOOK_REQUEST_SCHEMA,
- mode: :union,
- display_options: {
- show: {
- resume: ["webhook"],
- limit_wait_time: [true],
- timeout_amount: [{ condition: { exists: true } }],
- },
- },
- },
- {
- schema: DiscourseWorkflows::Schema::WEBHOOK_REQUEST_SCHEMA,
- mode: :replace,
- display_options: {
- show: {
- resume: ["webhook"],
- },
- },
- },
- )
+ expect(version[:description]).not_to have_key(:output_contracts)
end
it "marks hidden executable definitions for client-side palette filtering" do
@@ -102,7 +20,6 @@ RSpec.describe DiscourseWorkflows::NodeTypeSerializer do
version = serializer.to_h.dig(:versions, "1.0")
expect(version[:palette_visible]).to eq(false)
- expect(version[:output_contracts].pluck(:mode)).to eq(%i[passthrough passthrough])
end
it "serializes the deprecation of superseded versions" do
diff --git a/plugins/discourse-workflows/spec/lib/discourse_workflows/nodes/data_table_spec.rb b/plugins/discourse-workflows/spec/lib/discourse_workflows/nodes/data_table_spec.rb
index d67b2a4b7a2..67e6e919c2e 100644
--- a/plugins/discourse-workflows/spec/lib/discourse_workflows/nodes/data_table_spec.rb
+++ b/plugins/discourse-workflows/spec/lib/discourse_workflows/nodes/data_table_spec.rb
@@ -649,4 +649,56 @@ RSpec.describe DiscourseWorkflows::Nodes::DataTable::V1 do
expect(count_data_table_rows(data_table)).to eq(1)
end
end
+
+ describe ".output_schemas" do
+ let(:input_schema) { DiscourseWorkflows::Schema.document("marker" => { "type" => "string" }) }
+
+ it "declares the system and configured table columns" do
+ schema =
+ described_class.output_schemas(
+ { "operation" => "get", "data_table_id" => data_table.id.to_s },
+ ).first
+
+ expect(schema["properties"].keys).to eq(%w[id created_at updated_at email score])
+ end
+
+ it "declares only the system columns without a known table" do
+ schema = described_class.output_schemas({ "operation" => "insert" }).first
+
+ expect(schema["properties"].keys).to eq(%w[id created_at updated_at])
+ end
+
+ it "passes the input through for existence checks" do
+ expect(
+ described_class.output_schemas(
+ { "operation" => "row_exists", "data_table_id" => data_table.id.to_s },
+ input_schemas: [input_schema],
+ ),
+ ).to eq([input_schema])
+ end
+
+ it "matches every row returning operation" do
+ insert_data_table_row(data_table, "email" => "[email protected]", "score" => 1)
+ filter = [filter_condition("email", "equals", value: "[email protected]")]
+
+ [
+ { "operation" => "insert", "columns" => { "email" => "[email protected]", "score" => "2" } },
+ { "operation" => "get", "filter" => filter },
+ { "operation" => "update", "filter" => filter, "columns" => { "score" => "3" } },
+ { "operation" => "upsert", "filter" => filter, "columns" => { "score" => "4" } },
+ { "operation" => "delete", "filter" => filter },
+ ].each do |config|
+ configuration = config.merge("data_table_id" => data_table.id.to_s)
+ items = execute_data_table(configuration)
+
+ expect(items).to be_present
+ items.each do |item|
+ expect(item["json"]).to match_node_output_schema(
+ described_class,
+ configuration: configuration,
+ )
+ end
+ end
+ end
+ end
end
diff --git a/plugins/discourse-workflows/spec/lib/discourse_workflows/nodes/form_spec.rb b/plugins/discourse-workflows/spec/lib/discourse_workflows/nodes/form_spec.rb
index 3eac2465d67..fbb29a6c734 100644
--- a/plugins/discourse-workflows/spec/lib/discourse_workflows/nodes/form_spec.rb
+++ b/plugins/discourse-workflows/spec/lib/discourse_workflows/nodes/form_spec.rb
@@ -47,4 +47,35 @@ RSpec.describe DiscourseWorkflows::Nodes::Form::V1 do
end
end
end
+
+ describe ".output_schemas" do
+ let(:configuration) do
+ {
+ "form_fields" => {
+ "values" => [
+ { "field_label" => "Reason", "field_type" => "text" },
+ { "field_label" => "Approved", "field_type" => "checkbox" },
+ { "field_label" => "Intro", "field_type" => "html", "html" => "<p>Hi</p>" },
+ ],
+ },
+ }
+ end
+
+ it "derives the schema from the configured form fields like the form trigger" do
+ expect(described_class.output_schemas(configuration)).to eq(
+ DiscourseWorkflows::Nodes::FormTrigger::V1.output_schemas(configuration),
+ )
+ end
+
+ it "passes the input schema through for a completion page" do
+ input_schema = DiscourseWorkflows::Schema.document("source" => { "type" => "string" })
+
+ expect(
+ described_class.output_schemas(
+ configuration.merge("page_type" => "completion"),
+ input_schemas: [input_schema],
+ ),
+ ).to eq([input_schema])
+ end
+ end
end
diff --git a/plugins/discourse-workflows/spec/lib/discourse_workflows/nodes/form_trigger_spec.rb b/plugins/discourse-workflows/spec/lib/discourse_workflows/nodes/form_trigger_spec.rb
index 26ac56d86e0..23f9c502509 100644
--- a/plugins/discourse-workflows/spec/lib/discourse_workflows/nodes/form_trigger_spec.rb
+++ b/plugins/discourse-workflows/spec/lib/discourse_workflows/nodes/form_trigger_spec.rb
@@ -24,4 +24,44 @@ RSpec.describe DiscourseWorkflows::Nodes::FormTrigger::V1 do
)
end
end
+
+ describe ".output_schemas" do
+ let(:configuration) do
+ {
+ "form_fields" => {
+ "values" => [
+ { "field_label" => "Full name", "field_type" => "text" },
+ { "field_label" => "Age", "field_type" => "number" },
+ { "field_label" => "Agree", "field_type" => "checkbox" },
+ { "field_label" => "Source", "field_name" => "src", "field_type" => "hiddenField" },
+ { "field_label" => "Intro", "field_type" => "html", "html" => "<p>Hi</p>" },
+ { "field_label" => "Dynamic", "field_type" => "={{ $json.type }}" },
+ ],
+ },
+ }
+ end
+
+ it "derives properties from the configured form fields" do
+ schema = described_class.output_schemas(configuration).first
+
+ expect(schema["properties"].keys).to eq(
+ %w[full_name age agree src dynamic submitted_at form_mode form_query_parameters],
+ )
+ expect(schema.dig("properties", "dynamic")).to eq({})
+ end
+
+ it "matches the output of a validated submission" do
+ fields = DiscourseWorkflows::CollectionParameters.rows(configuration, "form_fields")
+ result =
+ DiscourseWorkflows::Schemas::FormFields.validate_submission(
+ fields,
+ { "full_name" => "Jane", "age" => "42", "agree" => "true", "dynamic" => "x" },
+ )
+
+ expect(described_class.new(form_data: result.data).output).to match_node_output_schema(
+ described_class,
+ configuration: configuration,
+ )
+ end
+ end
end
diff --git a/plugins/discourse-workflows/spec/lib/discourse_workflows/nodes/summarize_spec.rb b/plugins/discourse-workflows/spec/lib/discourse_workflows/nodes/summarize_spec.rb
index 1fc37989600..5bd2b9e35f5 100644
--- a/plugins/discourse-workflows/spec/lib/discourse_workflows/nodes/summarize_spec.rb
+++ b/plugins/discourse-workflows/spec/lib/discourse_workflows/nodes/summarize_spec.rb
@@ -359,10 +359,6 @@ RSpec.describe DiscourseWorkflows::Nodes::Summarize::V1 do
end
describe ".output_schemas" do
- it "names the editor-side resolver so both sides derive the same keys" do
- expect(described_class.output_schema_resolver).to eq("summarize")
- end
-
it "derives properties from the configured aggregations and group keys" do
schema =
described_class.output_schemas(
diff --git a/plugins/discourse-workflows/spec/lib/discourse_workflows/schema_spec.rb b/plugins/discourse-workflows/spec/lib/discourse_workflows/schema_spec.rb
index 05d9d23bced..0da41a00202 100644
--- a/plugins/discourse-workflows/spec/lib/discourse_workflows/schema_spec.rb
+++ b/plugins/discourse-workflows/spec/lib/discourse_workflows/schema_spec.rb
@@ -478,6 +478,26 @@ RSpec.describe DiscourseWorkflows::Schema do
unregister_workflow_nodes(v1_class, v2_class)
end
+ it "resolves each node once per distinct input" do
+ data_table = Fabricate(:discourse_workflows_data_table)
+ graph =
+ build_workflow_graph do |builder|
+ builder.node "trigger", "trigger:manual"
+ builder.node "table",
+ "action:data_table",
+ parameters: {
+ "operation" => "get",
+ "data_table_id" => data_table.id,
+ }
+ builder.connect "trigger", "table"
+ end
+ allow(DiscourseWorkflows::DataTable).to receive(:find_by).and_call_original
+
+ described_class.resolve_graph(graph[:nodes], graph[:connections])
+
+ expect(DiscourseWorkflows::DataTable).to have_received(:find_by).once
+ end
+
it "selects the source schema by output position" do
schemas =
%w[kept rejected].map { |field| described_class.document(field => { "type" => "boolean" }) }
@@ -750,8 +770,7 @@ RSpec.describe DiscourseWorkflows::Schema do
end
expect { described_class.resolve_graph(graph[:nodes], graph[:connections]) }.to raise_error(
- ArgumentError,
- "Output schema graph did not converge",
+ DiscourseWorkflows::Schema::GraphResolver::NotConverged,
)
end
diff --git a/plugins/discourse-workflows/spec/requests/discourse_workflows/node_types_controller_spec.rb b/plugins/discourse-workflows/spec/requests/discourse_workflows/node_types_controller_spec.rb
index dc134ee7076..9e60d4f063f 100644
--- a/plugins/discourse-workflows/spec/requests/discourse_workflows/node_types_controller_spec.rb
+++ b/plugins/discourse-workflows/spec/requests/discourse_workflows/node_types_controller_spec.rb
@@ -63,10 +63,6 @@ RSpec.describe DiscourseWorkflows::NodeTypesController do
expect(option_ids).to include("site_description")
expect(option_ids).not_to include(SiteSetting.secret_settings.first.to_s)
expect(option_ids).not_to include(SiteSetting.hidden_settings.first.to_s)
- expect(node.dig("output_contracts", 0, "schema", "properties")).to include(
- "name" => include("type" => "string"),
- "changed" => include("type" => "boolean"),
- )
end
end
end
diff --git a/plugins/discourse-workflows/spec/requests/discourse_workflows/output_schemas_controller_spec.rb b/plugins/discourse-workflows/spec/requests/discourse_workflows/output_schemas_controller_spec.rb
new file mode 100644
index 00000000000..e295bf66f1f
--- /dev/null
+++ b/plugins/discourse-workflows/spec/requests/discourse_workflows/output_schemas_controller_spec.rb
@@ -0,0 +1,128 @@
+# frozen_string_literal: true
+
+RSpec.describe DiscourseWorkflows::OutputSchemasController do
+ fab!(:admin)
+ fab!(:user)
+ fab!(:data_table) do
+ Fabricate(
+ :discourse_workflows_data_table,
+ name: "zzz",
+ columns: [{ "name" => "email", "type" => "string" }],
+ )
+ end
+
+ let(:nodes) do
+ [
+ {
+ "id" => "form",
+ "type" => "trigger:form",
+ "typeVersion" => "1.0",
+ "name" => "Form",
+ "parameters" => {
+ "form_fields" => {
+ "values" => [{ "field_label" => "Größe", "field_type" => "text" }],
+ },
+ },
+ },
+ {
+ "id" => "table",
+ "type" => "action:data_table",
+ "typeVersion" => "1.0",
+ "name" => "Table",
+ "parameters" => {
+ "operation" => "get",
+ "data_table_id" => data_table.id,
+ },
+ },
+ ]
+ end
+
+ let(:connections) do
+ { "Form" => { "main" => [[{ "node" => "Table", "type" => "main", "index" => 0 }]] } }
+ end
+
+ def resolve(payload)
+ post "/admin/plugins/discourse-workflows/output-schemas.json", params: payload, as: :json
+ end
+
+ context "when logged in as an admin" do
+ before { sign_in(admin) }
+
+ it "returns each node's output schemas resolved on the server" do
+ resolve(nodes:, connections:)
+
+ expect(response.status).to eq(200)
+ schemas = response.parsed_body["output_schemas"]
+ expect(schemas.dig("form", 0, "properties").keys).to include("grosse")
+ expect(schemas.dig("table", 0, "properties").keys).to include("id", "email")
+ end
+
+ it "rejects a payload without nodes" do
+ resolve(nodes: [], connections:)
+
+ expect(response.status).to eq(400)
+ end
+
+ it "fails when the graph does not converge" do
+ allow(DiscourseWorkflows::Schema).to receive(:resolve_graph).and_raise(
+ DiscourseWorkflows::Schema::GraphResolver::NotConverged,
+ )
+
+ resolve(nodes:, connections:)
+
+ expect(response.status).to eq(422)
+ end
+
+ it "does not hide node schema errors behind a 422" do
+ allow(DiscourseWorkflows::Nodes::DataTable::V1).to receive(:output_schemas).and_raise(
+ ArgumentError,
+ )
+
+ resolve(nodes:, connections:)
+
+ expect(response.status).to eq(500)
+ end
+
+ it "ignores connections with a malformed input index" do
+ resolve(
+ nodes:,
+ connections: {
+ "Form" => {
+ "main" => [
+ [
+ { "node" => "Table", "type" => "main", "index" => {} },
+ { "node" => "Table", "type" => "main", "index" => 10**9 },
+ ],
+ ],
+ },
+ },
+ )
+
+ expect(response.status).to eq(200)
+ expect(response.parsed_body.dig("output_schemas", "table", 0, "properties").keys).to include(
+ "email",
+ )
+ end
+
+ it "is rate limited" do
+ RateLimiter.enable
+ stub_const(described_class, "RATE_LIMIT", 1) do
+ resolve(nodes:, connections:)
+ expect(response.status).to eq(200)
+
+ resolve(nodes:, connections:)
+ expect(response.status).to eq(429)
+ end
+ ensure
+ RateLimiter.disable
+ end
+ end
+
+ it "is forbidden for non-admins" do
+ sign_in(user)
+
+ resolve(nodes:, connections:)
+
+ expect(response.status).to eq(404)
+ end
+end
diff --git a/plugins/discourse-workflows/spec/requests/discourse_workflows/workflows_controller_spec.rb b/plugins/discourse-workflows/spec/requests/discourse_workflows/workflows_controller_spec.rb
index 390c85d6ebb..7acbe3adbf8 100644
--- a/plugins/discourse-workflows/spec/requests/discourse_workflows/workflows_controller_spec.rb
+++ b/plugins/discourse-workflows/spec/requests/discourse_workflows/workflows_controller_spec.rb
@@ -224,6 +224,29 @@ RSpec.describe DiscourseWorkflows::WorkflowsController do
expect(response.parsed_body["workflow"]["active_version_id"]).to be_nil
end
+ it "drops connections with a malformed input index" do
+ workflow = Fabricate(:discourse_workflows_workflow, created_by: admin)
+
+ put "/admin/plugins/discourse-workflows/workflows/#{workflow.id}.json",
+ params: {
+ workflow: {
+ nodes: [
+ { id: "t1", type: "trigger:topic_closed", name: "Topic Closed" },
+ { id: "a1", type: "action:log", name: "Log" },
+ ],
+ connections: {
+ "Topic Closed" => {
+ "main" => [[{ "node" => "Log", "type" => "main", "index" => {} }]],
+ },
+ },
+ },
+ },
+ as: :json
+
+ expect(response).to have_http_status(:ok)
+ expect(workflow.reload.connections).to eq({})
+ end
+
it "updates the workflow tags" do
workflow = Fabricate(:discourse_workflows_workflow, created_by: admin)
diff --git a/plugins/discourse-workflows/spec/services/discourse_workflows/node_type/list_spec.rb b/plugins/discourse-workflows/spec/services/discourse_workflows/node_type/list_spec.rb
index d2ec84bed0c..26757894118 100644
--- a/plugins/discourse-workflows/spec/services/discourse_workflows/node_type/list_spec.rb
+++ b/plugins/discourse-workflows/spec/services/discourse_workflows/node_type/list_spec.rb
@@ -184,7 +184,6 @@ RSpec.describe DiscourseWorkflows::NodeType::List do
loop_node = result[:node_types].find { |nt| nt[:identifier] == "flow:loop_over_items" }
expect(loop_node[:palette_visible]).to eq(false)
- expect(loop_node[:output_contracts].pluck(:mode)).to eq(%i[passthrough passthrough])
end
it "includes manually_triggerable for triggers that support it" do
diff --git a/plugins/discourse-workflows/spec/services/discourse_workflows/workflow/resolve_output_schemas_spec.rb b/plugins/discourse-workflows/spec/services/discourse_workflows/workflow/resolve_output_schemas_spec.rb
new file mode 100644
index 00000000000..591e32d188b
--- /dev/null
+++ b/plugins/discourse-workflows/spec/services/discourse_workflows/workflow/resolve_output_schemas_spec.rb
@@ -0,0 +1,56 @@
+# frozen_string_literal: true
+
+RSpec.describe DiscourseWorkflows::Workflow::ResolveOutputSchemas do
+ describe ".call" do
+ subject(:result) { described_class.call(params:, **dependencies) }
+
+ fab!(:admin)
+
+ let(:node) do
+ { "id" => "manual", "type" => "trigger:manual", "typeVersion" => "1.0", "name" => "Manual" }
+ end
+ let(:params) { { nodes: [node], connections: {} } }
+ let(:dependencies) { { guardian: admin.guardian } }
+
+ context "when nodes are not hashes" do
+ let(:params) { { nodes: ["x"], connections: {} } }
+
+ it { is_expected.to fail_a_contract }
+ end
+
+ context "when nodes is not an array" do
+ let(:params) { { nodes: "x", connections: {} } }
+
+ it { is_expected.to fail_a_contract }
+ end
+
+ context "when connections is not a hash" do
+ let(:params) { { nodes: [node], connections: [] } }
+
+ it { is_expected.to fail_a_contract }
+ end
+
+ context "when there are too many nodes" do
+ let(:params) do
+ { nodes: Array.new(DiscourseWorkflows::WorkflowGraphValidator::MAX_NODES + 1) { node } }
+ end
+
+ 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 everything is valid" do
+ it "resolves the output schemas per node" do
+ expect(result).to run_successfully
+ expect(result[:output_schemas]).to have_key("manual")
+ end
+ end
+ end
+end
diff --git a/plugins/discourse-workflows/test/javascripts/integration/components/workflows/context-input-test.gjs b/plugins/discourse-workflows/test/javascripts/integration/components/workflows/context-input-test.gjs
index 51f16af614a..a9c4305b44b 100644
--- a/plugins/discourse-workflows/test/javascripts/integration/components/workflows/context-input-test.gjs
+++ b/plugins/discourse-workflows/test/javascripts/integration/components/workflows/context-input-test.gjs
@@ -88,7 +88,6 @@ module(
@connections={{(Array)}}
@node={{node}}
@nodes={{nodes}}
- @nodeTypes={{(Array)}}
@session={{this.session}}
/>
</template>
@@ -128,7 +127,6 @@ module(
@connections={{(Array)}}
@node={{actionNode}}
@nodes={{nodes}}
- @nodeTypes={{(Array)}}
@session={{this.session}}
/>
</template>
@@ -167,7 +165,6 @@ module(
@connections={{(Array)}}
@node={{node}}
@nodes={{nodes}}
- @nodeTypes={{(Array)}}
@session={{this.session}}
/>
</template>
@@ -212,7 +209,6 @@ module(
@connections={{(Array)}}
@node={{actionNode}}
@nodes={{nodes}}
- @nodeTypes={{(Array)}}
@session={{this.session}}
/>
</template>
@@ -345,7 +341,6 @@ module(
@connections={{connections}}
@node={{currentNode}}
@nodes={{nodes}}
- @nodeTypes={{(Array)}}
@session={{this.session}}
/>
</template>
@@ -391,45 +386,20 @@ module(
{ sourceClientId: "trigger", targetClientId: "step" },
{ sourceClientId: "step", targetClientId: "current" },
];
- const nodeTypes = [
- {
- name: "trigger:sample",
- versions: {
- "1.0": {
- output_contracts: [
- {
- schema: {
- type: "object",
- properties: {
- trigger: {
- type: "object",
- description: "Trigger payload",
- properties: { id: { type: "integer" } },
- },
- },
- },
- },
- ],
- },
- },
- },
- {
- name: "action:step",
- versions: {
- "1.0": {
- output_contracts: [
- {
- mode: "merge",
- schema: {
- type: "object",
- properties: { result: { type: "string" } },
- },
- },
- ],
- },
+ const trigger = {
+ type: "object",
+ description: "Trigger payload",
+ properties: { id: { type: "integer" } },
+ };
+ this.session.outputSchemas = {
+ trigger: [{ type: "object", properties: { trigger } }],
+ step: [
+ {
+ type: "object",
+ properties: { trigger, result: { type: "string" } },
},
- },
- ];
+ ],
+ };
await render(
<template>
@@ -437,7 +407,6 @@ module(
@connections={{connections}}
@node={{currentNode}}
@nodes={{nodes}}
- @nodeTypes={{nodeTypes}}
@session={{this.session}}
/>
</template>
@@ -503,80 +472,6 @@ module(
);
});
- test("reuses one declared schema resolution across ancestor sections", async function (assert) {
- let declarationReads = 0;
- const triggerNode = {
- clientId: "trigger",
- type: "trigger:sample",
- typeVersion: "1.0",
- name: "Trigger",
- };
- const stepNodes = Array.from({ length: 8 }, (_, index) => ({
- clientId: `step-${index}`,
- type: "action:passthrough",
- typeVersion: "1.0",
- name: `Step ${index}`,
- }));
- const currentNode = {
- clientId: "current",
- type: "action:current",
- name: "Current",
- };
- const nodes = [triggerNode, ...stepNodes, currentNode];
- const connections = nodes.slice(1).map((node, index) => ({
- sourceClientId: nodes[index].clientId,
- targetClientId: node.clientId,
- }));
- const passthroughVersion = {
- get output_contracts() {
- declarationReads++;
- return [{ mode: "passthrough" }];
- },
- };
- const nodeTypes = [
- {
- name: "trigger:sample",
- versions: {
- "1.0": {
- output_contracts: [
- {
- schema: {
- type: "object",
- properties: { id: { type: "integer" } },
- },
- },
- ],
- },
- },
- },
- {
- name: "action:passthrough",
- versions: { "1.0": passthroughVersion },
- },
- ];
-
- await render(
- <template>
- <InputContext
- @connections={{connections}}
- @node={{currentNode}}
- @nodes={{nodes}}
- @nodeTypes={{nodeTypes}}
- @session={{this.session}}
- />
- </template>
- );
-
- assert.strictEqual(
- declarationReads,
- stepNodes.length,
- "all direct and ancestor sections share one graph-level resolution"
- );
- assert
- .dom(".workflows-schema-field__key-title")
- .includesText("id", "the propagated declaration remains visible");
- });
-
test("shows an empty input state when the input has no JSON fields", async function (assert) {
const previousNode = {
clientId: "previous-1",
@@ -614,7 +509,6 @@ module(
@connections={{connections}}
@node={{currentNode}}
@nodes={{nodes}}
- @nodeTypes={{(Array)}}
@session={{this.session}}
/>
</template>
@@ -647,7 +541,6 @@ module(
@connections={{connections}}
@node={{currentNode}}
@nodes={{nodes}}
- @nodeTypes={{(Array)}}
@session={{this.session}}
/>
</template>
@@ -731,7 +624,6 @@ module(
@connections={{connections}}
@node={{currentNode}}
@nodes={{nodes}}
- @nodeTypes={{(Array)}}
@session={{this.session}}
/>
</template>
@@ -825,7 +717,6 @@ module(
@connections={{connections}}
@node={{currentNode}}
@nodes={{nodes}}
- @nodeTypes={{(Array)}}
@session={{this.session}}
/>
</template>
@@ -899,7 +790,6 @@ module(
@connections={{connections}}
@node={{logNode}}
@nodes={{nodes}}
- @nodeTypes={{(Array)}}
@session={{this.session}}
/>
</template>
@@ -937,7 +827,6 @@ module(
@connections={{(Array)}}
@node={{node}}
@nodes={{nodes}}
- @nodeTypes={{(Array)}}
@session={{this.session}}
/>
</template>
@@ -1071,7 +960,6 @@ module(
@connections={{(Array)}}
@node={{node}}
@nodes={{Array node}}
- @nodeTypes={{(Array)}}
@session={{this.session}}
/>
</template>
diff --git a/plugins/discourse-workflows/test/javascripts/integration/components/workflows/context-output-test.gjs b/plugins/discourse-workflows/test/javascripts/integration/components/workflows/context-output-test.gjs
index 4558c798844..63517ee521c 100644
--- a/plugins/discourse-workflows/test/javascripts/integration/components/workflows/context-output-test.gjs
+++ b/plugins/discourse-workflows/test/javascripts/integration/components/workflows/context-output-test.gjs
@@ -50,7 +50,6 @@ module(
@connections={{(Array)}}
@node={{node}}
@nodes={{nodes}}
- @nodeTypes={{(Array)}}
@session={{this.session}}
/>
</template>
@@ -84,7 +83,6 @@ module(
@connections={{(Array)}}
@node={{node}}
@nodes={{Array node}}
- @nodeTypes={{(Array)}}
@session={{this.session}}
/>
</template>
@@ -99,51 +97,35 @@ module(
.hasText(/Add sample data/);
});
- test("renders a configuration-aware declaration before the first run", async function (assert) {
+ test("renders server-resolved output schemas before the first run", async function (assert) {
const node = {
clientId: "n1",
name: "Group",
type: "action:group",
typeVersion: "1.0",
- configuration: { operation: "add" },
+ configuration: { operation: "check_membership" },
};
- const nodeTypes = [
- {
- name: "action:group",
- versions: {
- "1.0": {
- output_contracts: [
- {
- mode: "merge",
- schema: {
- type: "object",
- properties: {
- group_membership: {
- type: "object",
- description: "Group membership result",
- properties: { in_group: { type: "boolean" } },
- },
- },
- },
- display_options: {
- show: { operation: ["check_membership"] },
- },
- },
- ],
+ this.session.outputSchemas = {
+ n1: [
+ {
+ type: "object",
+ properties: {
+ group_membership: {
+ type: "object",
+ description: "Group membership result",
+ properties: { in_group: { type: "boolean" } },
+ },
},
},
- },
- ];
- const configuration = { operation: "check_membership" };
+ ],
+ };
await render(
<template>
<OutputContext
- @configuration={{configuration}}
@connections={{(Array)}}
@node={{node}}
@nodes={{Array node}}
- @nodeTypes={{nodeTypes}}
@session={{this.session}}
/>
</template>
@@ -203,7 +185,6 @@ module(
@connections={{(Array)}}
@node={{node}}
@nodes={{Array node}}
- @nodeTypes={{(Array)}}
@session={{session}}
/>
</template>
@@ -236,7 +217,6 @@ module(
@connections={{(Array)}}
@node={{node}}
@nodes={{Array node}}
- @nodeTypes={{(Array)}}
@session={{this.session}}
/>
</template>
@@ -274,7 +254,6 @@ module(
@connections={{(Array)}}
@node={{node}}
@nodes={{Array node}}
- @nodeTypes={{(Array)}}
@session={{this.session}}
/>
</template>
@@ -313,7 +292,6 @@ module(
@connections={{(Array)}}
@node={{node}}
@nodes={{Array node}}
- @nodeTypes={{(Array)}}
@session={{this.session}}
/>
</template>
@@ -357,7 +335,6 @@ module(
@connections={{(Array)}}
@node={{node}}
@nodes={{Array node}}
- @nodeTypes={{(Array)}}
@session={{this.session}}
/>
</template>
@@ -411,7 +388,6 @@ module(
@connections={{(Array)}}
@node={{node}}
@nodes={{Array node}}
- @nodeTypes={{(Array)}}
@session={{this.session}}
/>
</template>
diff --git a/plugins/discourse-workflows/test/javascripts/integration/components/workflows/expression-input-test.gjs b/plugins/discourse-workflows/test/javascripts/integration/components/workflows/expression-input-test.gjs
new file mode 100644
index 00000000000..c008066cd81
--- /dev/null
+++ b/plugins/discourse-workflows/test/javascripts/integration/components/workflows/expression-input-test.gjs
@@ -0,0 +1,62 @@
+import { render, settled, waitFor } from "@ember/test-helpers";
+import { module, test } from "qunit";
+import { setupRenderingTest } from "discourse/tests/helpers/component-test";
+import pretender, { response } from "discourse/tests/helpers/create-pretender";
+import ExpressionInput from "discourse/plugins/discourse-workflows/admin/components/workflows/configurators/expression-input";
+import WorkflowEditorSession from "discourse/plugins/discourse-workflows/admin/lib/workflows/editor-session";
+
+module(
+ "Integration | Component | Workflows | expression input",
+ function (hooks) {
+ setupRenderingTest(hooks);
+
+ hooks.beforeEach(function () {
+ pretender.get("/admin/plugins/discourse-workflows/variables.json", () =>
+ response(200, { variables: [] })
+ );
+ });
+
+ test("refreshes the $json scope when output schemas load", async function (assert) {
+ const trigger = {
+ clientId: "trigger",
+ name: "Trigger",
+ type: "trigger:manual",
+ };
+ const action = {
+ clientId: "action",
+ name: "Action",
+ type: "action:topic",
+ };
+ const session = new WorkflowEditorSession();
+ session.setEditingContext(
+ action,
+ [trigger, action],
+ [{ sourceClientId: "trigger", targetClientId: "action" }]
+ );
+ const field = { value: "={{ $json.post.raw }}", set() {} };
+
+ await render(
+ <template>
+ <ExpressionInput @field={{field}} @session={{session}} />
+ </template>
+ );
+ await waitFor(".cm-wf-reference-pill");
+
+ assert.dom(".cm-wf-reference-pill").hasClass("--invalid");
+
+ session.outputSchemas = {
+ trigger: [
+ {
+ type: "object",
+ properties: {
+ post: { type: "object", properties: { raw: { type: "string" } } },
+ },
+ },
+ ],
+ };
+ await settled();
+
+ assert.dom(".cm-wf-reference-pill").hasClass("--value");
+ });
+ }
+);
diff --git a/plugins/discourse-workflows/test/javascripts/integration/components/workflows/property-engine-test.gjs b/plugins/discourse-workflows/test/javascripts/integration/components/workflows/property-engine-test.gjs
index 2090f108def..c53cddd52b5 100644
--- a/plugins/discourse-workflows/test/javascripts/integration/components/workflows/property-engine-test.gjs
+++ b/plugins/discourse-workflows/test/javascripts/integration/components/workflows/property-engine-test.gjs
@@ -1344,6 +1344,23 @@ module("Integration | Component | workflows property engine", function (hooks) {
});
test("condition builder supports declared integer and array fields", async function (assert) {
+ this.session.outputSchemas = {
+ trigger: [
+ {
+ type: "object",
+ properties: {
+ post: {
+ type: "object",
+ properties: {
+ id: { type: "integer" },
+ mixed: { type: ["integer", "string"] },
+ tags: { type: "array", items: { type: "string" } },
+ },
+ },
+ },
+ },
+ ],
+ };
this.setProperties({
configuration: { conditions: [] },
formApi: null,
@@ -1371,35 +1388,6 @@ module("Integration | Component | workflows property engine", function (hooks) {
targetClientId: "branch",
},
],
- nodeTypes: [
- {
- name: "trigger:sample",
- versions: {
- "1.0": {
- output_contracts: [
- {
- schema: {
- type: "object",
- properties: {
- post: {
- type: "object",
- properties: {
- id: { type: "integer" },
- mixed: { type: ["integer", "string"] },
- tags: {
- type: "array",
- items: { type: "string" },
- },
- },
- },
- },
- },
- },
- ],
- },
- },
- },
- ],
nodeType: "condition:if",
schema: {
conditions: {
@@ -1466,6 +1454,69 @@ module("Integration | Component | workflows property engine", function (hooks) {
.includesText("/workflows/webhooks/my-hook");
});
+ test("summarize placeholders use server output keys and add/remove notify changes", async function (assert) {
+ this.session.outputSchemas = {
+ "summarize-1": [
+ {
+ type: "object",
+ properties: { region: {}, sum_a_total: {}, sum_b_total: {} },
+ },
+ ],
+ };
+ this.setProperties({
+ configuration: {
+ fields_to_summarize: {
+ values: [
+ { aggregation: "sum", field: "a.total", output_field_name: "" },
+ { aggregation: "sum", field: "b.total", output_field_name: "" },
+ ],
+ },
+ },
+ node: { clientId: "summarize-1", type: "action:summarize" },
+ nodeType: "action:summarize",
+ onChange: sinon.spy(),
+ schema: {
+ fields_to_summarize: {
+ type: "fixed_collection",
+ ui: { control: "summarize_aggregations" },
+ type_options: { multiple_values: true },
+ options: [
+ {
+ name: "values",
+ values: {
+ aggregation: {
+ type: "options",
+ options: ["sum"],
+ no_data_expression: true,
+ },
+ field: { type: "string", no_data_expression: true },
+ output_field_name: {
+ type: "string",
+ no_data_expression: true,
+ },
+ },
+ },
+ ],
+ },
+ },
+ });
+
+ await renderEngine(this);
+
+ assert.deepEqual(
+ findAll(".workflows-summarize-row__control--derived input").map(
+ (input) => input.placeholder
+ ),
+ ["sum_a_total", "sum_b_total"]
+ );
+
+ await click(".workflows-property-engine__collection-delete");
+ assert.true(this.onChange.calledOnce);
+
+ await click("button.btn-default:has(.d-icon-plus)");
+ assert.true(this.onChange.calledTwice);
+ });
+
test("renders form trigger test and production URL controls", async function (assert) {
sinon.stub(window, "open");
pretender.post(
diff --git a/plugins/discourse-workflows/test/javascripts/unit/lib/workflows-data-preview-test.js b/plugins/discourse-workflows/test/javascripts/unit/lib/workflows-data-preview-test.js
index 56ced5e32e5..24f294a0762 100644
--- a/plugins/discourse-workflows/test/javascripts/unit/lib/workflows-data-preview-test.js
+++ b/plugins/discourse-workflows/test/javascripts/unit/lib/workflows-data-preview-test.js
@@ -7,23 +7,10 @@ import {
schemaFieldsForNodeOutput,
} from "discourse/plugins/discourse-workflows/admin/lib/workflows/data-preview";
-function declaredType(name) {
- return {
- name,
- versions: {
- "1.0": {
- output_contracts: [
- {
- schema: {
- type: "object",
- properties: { declared: { type: "string" } },
- },
- },
- ],
- },
- },
- };
-}
+const DECLARED_SCHEMA = {
+ type: "object",
+ properties: { declared: { type: "string" } },
+};
function typedNode(clientId, name, type) {
return { clientId, name, type, typeVersion: "1.0" };
@@ -31,23 +18,17 @@ function typedNode(clientId, name, type) {
function sampleGraph() {
const node = typedNode("sample", "Sample", "action:sample");
- const graph = {
- nodes: [node],
- connections: [],
- nodeTypes: [declaredType("action:sample")],
- };
- return { node, graph };
+ return { node, declaredOutputSchemas: { sample: [DECLARED_SCHEMA] } };
}
function sourceCurrentGraph() {
const sourceNode = typedNode("source", "Source", "trigger:source");
const currentNode = typedNode("current", "Current", "action:current");
- const graph = {
- nodes: [sourceNode, currentNode],
- connections: [{ sourceClientId: "source", targetClientId: "current" }],
- nodeTypes: [declaredType("trigger:source")],
+ return {
+ sourceNode,
+ currentNode,
+ declaredOutputSchemas: { source: [DECLARED_SCHEMA] },
};
- return { sourceNode, currentNode, graph };
}
function successRun(attrs) {
@@ -111,15 +92,17 @@ module("Unit | lib | discourse-workflows | data-preview", function () {
});
test("output declarations fill in before a run and after full compaction", function (assert) {
- const { node, graph } = sampleGraph();
+ const { node, declaredOutputSchemas } = sampleGraph();
assert.deepEqual(
- keys(schemaFieldsForNodeOutput({}, "Sample", { node, graph })),
+ keys(
+ schemaFieldsForNodeOutput({}, "Sample", { node, declaredOutputSchemas })
+ ),
["declared"],
"uses declared fields before the first run"
);
assert.deepEqual(
- outputPreviewForNode({}, "Sample", { node, graph }),
+ outputPreviewForNode({}, "Sample", { node, declaredOutputSchemas }),
{
summary: null,
fields: [{ key: "declared", id: "$json.declared", type: "string" }],
@@ -129,7 +112,10 @@ module("Unit | lib | discourse-workflows | data-preview", function () {
const emptyRun = { Sample: [successRun({ outputs: [port(0, [])] })] };
assert.deepEqual(
- schemaFieldsForNodeOutput(emptyRun, "Sample", { node, graph }),
+ schemaFieldsForNodeOutput(emptyRun, "Sample", {
+ node,
+ declaredOutputSchemas,
+ }),
[],
"a successful empty output takes precedence over the declaration"
);
@@ -142,11 +128,19 @@ module("Unit | lib | discourse-workflows | data-preview", function () {
],
};
assert.deepEqual(
- keys(schemaFieldsForNodeOutput(compacted, "Sample", { node, graph })),
+ keys(
+ schemaFieldsForNodeOutput(compacted, "Sample", {
+ node,
+ declaredOutputSchemas,
+ })
+ ),
["declared"],
"recovers declarations when persistence removed every output sample"
);
- const preview = outputPreviewForNode(compacted, "Sample", { node, graph });
+ const preview = outputPreviewForNode(compacted, "Sample", {
+ node,
+ declaredOutputSchemas,
+ });
assert.deepEqual(
preview.summary,
{ itemCount: 24, truncated: true },
@@ -259,7 +253,8 @@ module("Unit | lib | discourse-workflows | data-preview", function () {
});
test("a successful run with a stale recorded source yields no input preview", function (assert) {
- const { sourceNode, currentNode, graph } = sourceCurrentGraph();
+ const { sourceNode, currentNode, declaredOutputSchemas } =
+ sourceCurrentGraph();
const runData = {
Source: [
successRun({
@@ -285,7 +280,7 @@ module("Unit | lib | discourse-workflows | data-preview", function () {
schemaFieldsForNodeInput(runData, "Current", {
node: currentNode,
sourceNode,
- graph,
+ declaredOutputSchemas,
outputIndex: 0,
}),
[],
@@ -303,7 +298,8 @@ module("Unit | lib | discourse-workflows | data-preview", function () {
});
test("schemaFieldsForNodeInput recovers declarations from a fully compacted port", function (assert) {
- const { sourceNode, currentNode, graph } = sourceCurrentGraph();
+ const { sourceNode, currentNode, declaredOutputSchemas } =
+ sourceCurrentGraph();
const runData = {
Current: [
successRun({
@@ -323,7 +319,7 @@ module("Unit | lib | discourse-workflows | data-preview", function () {
schemaFieldsForNodeInput(runData, "Current", {
node: currentNode,
sourceNode,
- graph,
+ declaredOutputSchemas,
})
),
["declared"],
@@ -340,7 +336,8 @@ module("Unit | lib | discourse-workflows | data-preview", function () {
});
test("schemaFieldsForNodeInput prefers recorded and pinned items over declarations", function (assert) {
- const { sourceNode, currentNode, graph } = sourceCurrentGraph();
+ const { sourceNode, currentNode, declaredOutputSchemas } =
+ sourceCurrentGraph();
const pinnedItems = [
{ json: { pinned: true } },
{ json: { pinned: false } },
@@ -351,7 +348,7 @@ module("Unit | lib | discourse-workflows | data-preview", function () {
schemaFieldsForNodeInput({}, "Current", {
node: currentNode,
sourceNode,
- graph,
+ declaredOutputSchemas,
pinnedItems,
})
),
@@ -384,7 +381,7 @@ module("Unit | lib | discourse-workflows | data-preview", function () {
schemaFieldsForNodeInput(runData, "Current", {
node: currentNode,
sourceNode,
- graph,
+ declaredOutputSchemas,
pinnedItems,
})
),
diff --git a/plugins/discourse-workflows/test/javascripts/unit/lib/workflows-editor-session-test.js b/plugins/discourse-workflows/test/javascripts/unit/lib/workflows-editor-session-test.js
new file mode 100644
index 00000000000..4034e3f6d4f
--- /dev/null
+++ b/plugins/discourse-workflows/test/javascripts/unit/lib/workflows-editor-session-test.js
@@ -0,0 +1,153 @@
+import { settled } from "@ember/test-helpers";
+import { setupTest } from "ember-qunit";
+import { module, test } from "qunit";
+import pretender, { response } from "discourse/tests/helpers/create-pretender";
+import WorkflowEditorSession from "discourse/plugins/discourse-workflows/admin/lib/workflows/editor-session";
+import WorkflowConnection from "discourse/plugins/discourse-workflows/admin/models/workflow-connection";
+import WorkflowNode from "discourse/plugins/discourse-workflows/admin/models/workflow-node";
+
+const OUTPUT_SCHEMAS_PATH =
+ "/admin/plugins/discourse-workflows/output-schemas.json";
+const SCHEMAS = {
+ "client-form": [{ type: "object", properties: { grosse: {} } }],
+};
+
+function graph() {
+ const nodes = [
+ WorkflowNode.create({
+ id: "42",
+ clientId: "client-form",
+ type: "trigger:form",
+ name: "Form",
+ parameters: { form_fields: { values: [{ field_label: "Größe" }] } },
+ }),
+ WorkflowNode.create({
+ clientId: "client-log",
+ type: "action:log",
+ name: "Log",
+ }),
+ ];
+ const connections = [
+ WorkflowConnection.create({
+ sourceClientId: "client-form",
+ targetClientId: "client-log",
+ }),
+ ];
+ return { nodes, connections };
+}
+
+module("Unit | lib | discourse-workflows | editor-session", function (hooks) {
+ setupTest(hooks);
+
+ test("loadOutputSchemas posts the draft graph keyed by client id", async function (assert) {
+ let body;
+ pretender.post(OUTPUT_SCHEMAS_PATH, (request) => {
+ body = JSON.parse(request.requestBody);
+ return response(200, { output_schemas: SCHEMAS });
+ });
+ const { nodes, connections } = graph();
+ const session = new WorkflowEditorSession();
+ session.setEditingContext(nodes[1], nodes, connections);
+
+ await session.loadOutputSchemas(nodes, connections);
+
+ assert.deepEqual(
+ body.nodes.map((node) => node.id),
+ ["client-form", "client-log"]
+ );
+ assert.deepEqual(body.nodes[0].parameters, nodes[0].parameters);
+ assert.deepEqual(body.connections, {
+ Form: { main: [[{ node: "Log", type: "main", index: 0 }]] },
+ });
+ assert.deepEqual(session.outputSchemas, SCHEMAS);
+ });
+
+ test("loadOutputSchemas drops responses that arrive after the context closed", async function (assert) {
+ pretender.post(OUTPUT_SCHEMAS_PATH, () =>
+ response(200, { output_schemas: SCHEMAS })
+ );
+ const { nodes, connections } = graph();
+ const session = new WorkflowEditorSession();
+ session.setEditingContext(nodes[1], nodes, connections);
+
+ const loading = session.loadOutputSchemas(nodes, connections);
+ session.clearEditingContext();
+ await loading;
+
+ assert.deepEqual(session.outputSchemas, {});
+ });
+
+ test("loadOutputSchemas falls back to no schemas when the request fails", async function (assert) {
+ pretender.post(OUTPUT_SCHEMAS_PATH, () => response(422, {}));
+ const { nodes, connections } = graph();
+ const session = new WorkflowEditorSession();
+ session.setEditingContext(nodes[1], nodes, connections);
+
+ await session.loadOutputSchemas(nodes, connections);
+
+ assert.deepEqual(session.outputSchemas, {});
+ });
+
+ test("loadOutputSchemas skips the request once the context closed", async function (assert) {
+ let requested = false;
+ pretender.post(OUTPUT_SCHEMAS_PATH, () => {
+ requested = true;
+ return response(200, { output_schemas: SCHEMAS });
+ });
+ const { nodes, connections } = graph();
+ const session = new WorkflowEditorSession();
+ session.setEditingContext(nodes[1], nodes, connections);
+ session.clearEditingContext();
+
+ await session.loadOutputSchemas(nodes, connections);
+
+ assert.false(requested);
+ assert.deepEqual(session.outputSchemas, {});
+ });
+
+ test("scheduleOutputSchemas sends only the latest graph once settled", async function (assert) {
+ const bodies = [];
+ pretender.post(OUTPUT_SCHEMAS_PATH, (request) => {
+ bodies.push(JSON.parse(request.requestBody));
+ return response(200, { output_schemas: SCHEMAS });
+ });
+ const { nodes, connections } = graph();
+ const session = new WorkflowEditorSession();
+ session.setEditingContext(nodes[1], nodes, connections);
+
+ session.scheduleOutputSchemas(nodes, connections);
+ session.scheduleOutputSchemas(nodes.slice(0, 1), connections);
+ await settled();
+
+ assert.strictEqual(bodies.length, 1);
+ assert.deepEqual(
+ bodies[0].nodes.map((node) => node.id),
+ ["client-form"]
+ );
+ assert.deepEqual(session.outputSchemas, SCHEMAS);
+ });
+
+ test("loadOutputSchemas skips unchanged graphs and keeps equal schemas", async function (assert) {
+ let requests = 0;
+ pretender.post(OUTPUT_SCHEMAS_PATH, () => {
+ requests++;
+ return response(200, { output_schemas: SCHEMAS });
+ });
+ const { nodes, connections } = graph();
+ const session = new WorkflowEditorSession();
+ session.setEditingContext(nodes[1], nodes, connections);
+
+ await session.loadOutputSchemas(nodes, connections);
+ const loaded = session.outputSchemas;
+ nodes[1].position = { x: 10, y: 10 };
+ await session.loadOutputSchemas(nodes, connections);
+
+ assert.strictEqual(requests, 1);
+
+ nodes[0].configuration = { form_fields: { values: [] } };
+ await session.loadOutputSchemas(nodes, connections);
+
+ assert.strictEqual(requests, 2);
+ assert.strictEqual(session.outputSchemas, loaded);
+ });
+});
diff --git a/plugins/discourse-workflows/test/javascripts/unit/lib/workflows-schema-graph-test.js b/plugins/discourse-workflows/test/javascripts/unit/lib/workflows-schema-graph-test.js
index 0d8f1e901a6..4fe965b04e2 100644
--- a/plugins/discourse-workflows/test/javascripts/unit/lib/workflows-schema-graph-test.js
+++ b/plugins/discourse-workflows/test/javascripts/unit/lib/workflows-schema-graph-test.js
@@ -2,674 +2,14 @@ import { module, test } from "qunit";
import {
ancestorOutputNodes,
inputConnectionsForNode,
- outputSchemaForNode,
previousNodeForConnection,
- resolveDeclaredOutputSchemas,
} from "discourse/plugins/discourse-workflows/admin/lib/workflows/schema-graph";
-const DRAFT_URI = "https://json-schema.org/draft/2020-12/schema";
-
-function objectSchema(properties, extra = {}) {
- return { type: "object", properties, ...extra };
-}
-
-function prop(name, type) {
- return objectSchema({ [name]: { type } });
-}
-
-function node(clientId, type, extra = {}) {
- return { clientId, type, typeVersion: "1.0", ...extra };
-}
-
function conn(sourceClientId, targetClientId, extra = {}) {
return { sourceClientId, targetClientId, ...extra };
}
-function nodeType(name, contracts) {
- return { name, versions: { "1.0": { output_contracts: contracts } } };
-}
-
-function triggerType(name, schema) {
- return nodeType(name, [{ schema }]);
-}
-
-const PASSTHROUGH_TYPE = nodeType("flow:passthrough", [
- { mode: "passthrough" },
-]);
-const UNKNOWN_TRIGGER_TYPE = {
- name: "trigger:unknown",
- versions: { "1.0": {} },
-};
-
module("Unit | lib | discourse-workflows | schema-graph", function () {
- test("output positions, visited nodes and out-of-graph nodes", function (assert) {
- const kept = prop("kept", "boolean");
- const rejected = prop("rejected", "boolean");
- const source = node("source", "condition:branch");
- const nodeTypes = [
- nodeType("condition:branch", [{ schema: kept }, { schema: rejected }]),
- PASSTHROUGH_TYPE,
- ];
- const graph = {
- nodes: [source, node("target", "flow:passthrough")],
- connections: [
- conn("source", "target", { sourceOutputIndex: 1, targetInputIndex: 1 }),
- ],
- nodeTypes,
- };
- const out = (n, opts) => outputSchemaForNode(n, graph, opts);
-
- assert.deepEqual(
- resolveDeclaredOutputSchemas(graph).get("source"),
- [kept, rejected],
- "each output port resolves its own schema"
- );
- assert.deepEqual(
- out(source, { outputIndex: 1 }),
- rejected,
- "outputIndex selects the port on the resolved node"
- );
- assert.deepEqual(out(graph.nodes[1]), rejected, "routes the source port");
-
- const resolved = resolveDeclaredOutputSchemas(graph, {
- visited: new Set(["source"]),
- });
- assert.false(resolved.has("source"), "visited nodes are not resolved");
- assert.deepEqual(resolved.get("target"), [{}], "visited links ignored");
- assert.deepEqual(
- out(source, { visited: new Set(["source"]) }),
- {},
- "a visited node resolves to unknown"
- );
- assert.deepEqual(out(null), {}, "a missing node resolves to unknown");
-
- const detached = node("detached", "flow:passthrough");
- const partial = {
- nodes: [source],
- connections: [conn("source", "detached")],
- nodeTypes,
- };
- assert.deepEqual(
- outputSchemaForNode(detached, partial),
- kept,
- "a node missing from the graph is appended to the resolution graph"
- );
- assert.strictEqual(partial.nodes.length, 1, "the graph is left untouched");
- });
-
- test("merge contracts resolve saved versions and overlay shallowly", function (assert) {
- const input = objectSchema(
- { root: { type: "string" }, shared: prop("left", "string") },
- { required: ["shared"] }
- );
- const declared = objectSchema(
- { shared: prop("own", "boolean"), extra: { type: "integer" } },
- { required: ["extra"] }
- );
- const v1 = { version: "1.0", output_contracts: [{ schema: input }] };
- const v2 = {
- version: "2.0",
- output_contracts: [{ schema: prop("latest", "boolean") }],
- };
- const staleLatest = {
- version: "2.0",
- output_contracts: [{ mode: "merge", schema: prop("latest", "boolean") }],
- };
- const merge = node("merge", "action:merge");
- const stale = node("stale", "action:versioned");
- const noOverlay = node("no-overlay", "action:no-overlay");
- const overlayOnly = node("overlay-only", "action:merge");
- const graph = {
- nodes: [
- node("source", "trigger:versioned"),
- node("unknown-source", "trigger:unknown"),
- merge,
- stale,
- noOverlay,
- overlayOnly,
- ],
- connections: [
- conn("source", "merge"),
- conn("source", "stale"),
- conn("source", "no-overlay"),
- conn("unknown-source", "overlay-only"),
- ],
- nodeTypes: [
- {
- name: "trigger:versioned",
- latest: v2,
- versions: { "1.0": v1, "2.0": v2 },
- },
- {
- name: "action:versioned",
- ...staleLatest,
- latest: staleLatest,
- versions: { "1.0": { version: "1.0" }, "2.0": staleLatest },
- },
- nodeType("action:merge", [{ mode: "merge", schema: declared }]),
- nodeType("action:no-overlay", [{ mode: "merge" }]),
- UNKNOWN_TRIGGER_TYPE,
- ],
- };
- const out = (n) => outputSchemaForNode(n, graph);
-
- assert.deepEqual(
- out(merge),
- objectSchema(
- {
- root: { type: "string" },
- shared: prop("own", "boolean"),
- extra: { type: "integer" },
- },
- { required: ["shared", "extra"] }
- ),
- "the saved trigger version feeds the merge, which keeps input root properties, replaces a colliding property wholesale and unions required"
- );
- assert.deepEqual(out(stale), {}, "saved versions do not inherit latest");
- assert.deepEqual(out(noOverlay), input, "empty declarations keep input");
- assert.deepEqual(out(overlayOnly), declared, "declared replaces unknown");
- });
-
- test("unregistered and missing type versions resolve like the server", function (assert) {
- const v1Schema = prop("from_v1", "string");
- const v2Schema = prop("from_v2", "string");
- const legacy = { clientId: "legacy", type: "trigger:versioned" };
- const stale = node("stale", "trigger:versioned", { typeVersion: "9.0" });
- const current = node("current", "trigger:versioned");
- const join = node("join", "flow:passthrough");
- const graph = {
- nodes: [legacy, stale, current, join],
- connections: [conn("current", "join"), conn("stale", "join")],
- nodeTypes: [
- {
- name: "trigger:versioned",
- latest: { version: "2.0", output_contracts: [{ schema: v2Schema }] },
- versions: {
- "1.0": { version: "1.0", output_contracts: [{ schema: v1Schema }] },
- "2.0": { version: "2.0", output_contracts: [{ schema: v2Schema }] },
- },
- },
- PASSTHROUGH_TYPE,
- ],
- };
- const out = (n) => outputSchemaForNode(n, graph);
-
- assert.deepEqual(
- out(current),
- v1Schema,
- "a registered typeVersion resolves its own declaration"
- );
- assert.deepEqual(
- out(stale),
- {},
- "an unregistered typeVersion resolves to unknown instead of latest"
- );
- assert.deepEqual(
- out(legacy),
- v1Schema,
- "a missing typeVersion resolves the default version, not latest"
- );
- assert.deepEqual(
- out(join),
- {},
- "an unknown version keeps downstream unions unknown"
- );
- });
-
- test("contract selection applies variants, display rules and overrides", function (assert) {
- const src = prop("source", "string");
- const hook = prop("body", "object");
- const base = prop("base", "string");
- const variant = prop("variant", "integer");
- const wait = node("wait", "flow:wait", {
- configuration: { resume: "time" },
- });
- const chooser = node("chooser", "action:chooser");
- const blender = node("blender", "flow:blender");
- const graph = {
- nodes: [node("source", "trigger:source"), wait, chooser, blender],
- connections: [
- conn("source", "wait"),
- conn("source", "chooser"),
- conn("source", "blender"),
- ],
- nodeTypes: [
- triggerType("trigger:source", src),
- nodeType("flow:wait", [
- {
- variants: [
- {
- mode: "passthrough",
- display_options: { show: { resume: ["time"] } },
- },
- {
- schema: hook,
- mode: "replace",
- display_options: { show: { resume: ["webhook"] } },
- },
- ],
- },
- ]),
- nodeType("action:chooser", [
- {
- schema: base,
- display_options: { show: { mode: ["base"] } },
- variants: [
- {
- schema: variant,
- display_options: { show: { mode: ["variant"] } },
- },
- ],
- },
- ]),
- nodeType("flow:blender", [
- {
- mode: "passthrough",
- variants: [{ display_options: { show: { mode: ["combine"] } } }],
- },
- ]),
- ],
- };
- const out = (n, opts) => outputSchemaForNode(n, graph, opts);
-
- assert.deepEqual(out(wait), src, "stored config picks passthrough");
- assert.deepEqual(
- out(wait, { configuration: { resume: "webhook" } }),
- hook,
- "a current configuration override selects the replacement variant"
- );
- assert.deepEqual(
- resolveDeclaredOutputSchemas(graph, {
- configurationOverrides: new Map([["wait", { resume: "webhook" }]]),
- }).get("wait"),
- [hook],
- "graph-level configuration overrides select the same variant"
- );
- assert.deepEqual(
- out(chooser, { configuration: { mode: "variant" } }),
- variant,
- "a matching variant wins over the base contract"
- );
- assert.deepEqual(
- out(chooser, { configuration: { mode: "base" } }),
- base,
- "the base contract applies when only its display options match and replace ignores the connected input"
- );
- assert.deepEqual(
- out(chooser, { configuration: { mode: "other" } }),
- {},
- "no matching contract resolves to unknown without passing the input through"
- );
-
- assert.deepEqual(
- out(wait, { configuration: { resume: "={{ $json.kind }}" } }),
- { $schema: DRAFT_URI, anyOf: [src, hook] },
- "an expression-valued controlling parameter unions the variants in contention, leaving out an empty-replace fallback"
- );
- assert.deepEqual(
- out(chooser, { configuration: { mode: "={{ $json.mode }}" } }),
- { $schema: DRAFT_URI, anyOf: [variant, base] },
- "the declared fallback contract stays in contention alongside indeterminate variants"
- );
- assert.deepEqual(
- out(blender, { configuration: { mode: "={{ $json.mode }}" } }),
- src,
- "a schema-less variant leaves contention rather than collapsing the union"
- );
- assert.deepEqual(
- out(blender, { configuration: { mode: "combine" } }),
- {},
- "a schema-less variant that definitely matches still resolves to unknown"
- );
- });
-
- test("extensions compose onto the contract per selected value", function (assert) {
- const base = objectSchema({
- user: objectSchema({ id: { type: "integer" } }),
- });
- const extension = (name) => ({
- type: "object",
- properties: {
- user: objectSchema({ [name]: { type: "string" } }),
- },
- });
- const picker = node("picker", "action:picker");
- const graph = {
- nodes: [picker],
- nodeTypes: [
- nodeType("action:picker", [
- {
- schema: base,
- extensions: [
- {
- schema: extension("email"),
- display_options: { show: { include: ["emails"] } },
- },
- {
- schema: extension("ip"),
- display_options: { show: { include: ["ips"] } },
- },
- ],
- },
- ]),
- ],
- connections: [],
- };
- const keys = (configuration) =>
- Object.keys(
- outputSchemaForNode(picker, graph, { configuration }).properties.user
- .properties
- );
-
- assert.deepEqual(keys({}), ["id"], "nothing is added without a selection");
- assert.deepEqual(
- keys({ include: ["emails"] }),
- ["id", "email"],
- "a selected extension merges into the base contract"
- );
- assert.deepEqual(
- keys({ include: ["ips", "emails"] }),
- ["id", "email", "ip"],
- "every selected extension composes, unlike variants which are exclusive"
- );
- assert.deepEqual(
- keys({ include: "={{ $json.include }}" }),
- ["id", "email", "ip"],
- "an expression leaves every extension in contention"
- );
- });
-
- test("nodes with author-defined output keys resolve from their configuration", function (assert) {
- const summarize = node("summarize", "action:summarize");
- const graph = {
- nodes: [node("source", "trigger:source"), summarize],
- connections: [conn("source", "summarize")],
- nodeTypes: [
- triggerType("trigger:source", prop("source", "string")),
- {
- name: "action:summarize",
- versions: { "1.0": { output_schema_resolver: "summarize" } },
- },
- ],
- };
- const keys = (configuration) =>
- Object.keys(
- outputSchemaForNode(summarize, graph, { configuration }).properties
- );
-
- assert.deepEqual(
- keys({
- fields_to_split_by: "topic_id",
- fields_to_summarize: {
- values: [
- { aggregation: "sum", field: "likes" },
- { aggregation: "count", output_field_name: "posts" },
- ],
- },
- }),
- ["topic_id", "sum_likes", "posts"],
- "the node's declared resolver derives keys from the configuration"
- );
- assert.deepEqual(
- keys({}),
- [],
- "an unconfigured node resolves to an empty shape rather than the input"
- );
- });
-
- test("classification answers resolve their types while preserving input fields", function (assert) {
- const classify = node("classify", "action:classify");
- const graph = {
- nodes: [node("source", "trigger:source"), classify],
- connections: [conn("source", "classify")],
- nodeTypes: [
- triggerType("trigger:source", prop("post", "object")),
- {
- name: "action:classify",
- versions: {
- "1.0": {
- output_schema_resolver: "classify",
- output_contracts: [{ mode: "merge" }],
- },
- },
- },
- ],
- };
- const common = {
- type: { type: "string" },
- reason: { type: ["string", "null"] },
- };
- const distribution = {
- probabilities: { type: "object" },
- confidence: { type: ["number", "null"] },
- };
- const configuration = {
- questions: {
- values: [
- { name: " urgent ", type: "yes_no" },
- { name: "team", type: "choice" },
- { name: "severity", type: "score" },
- { name: "__proto__", type: "yes_no" },
- { name: "draft", type: "" },
- { name: " " },
- null,
- "invalid",
- ],
- },
- };
-
- assert.deepEqual(
- outputSchemaForNode(classify, graph, { configuration }).properties,
- {
- post: { type: "object" },
- classification: objectSchema({
- urgent: objectSchema({ ...common, probability: { type: "number" } }),
- team: objectSchema({
- ...common,
- ...distribution,
- choice: { type: "string" },
- }),
- severity: objectSchema({
- ...common,
- ...distribution,
- score: { type: "number" },
- level: { type: "string" },
- }),
- ["__proto__"]: objectSchema({
- ...common,
- probability: { type: "number" },
- }),
- draft: objectSchema(common),
- }),
- },
- "downstream expressions can select each answer and the original input"
- );
- assert.deepEqual(
- outputSchemaForNode(classify, graph, { configuration: {} }).properties,
- { post: { type: "object" }, classification: objectSchema({}) },
- "an unconfigured classifier still preserves the input"
- );
- });
-
- test("joins, union contracts and cycles resolve across the graph", function (assert) {
- const str = prop("v", "string");
- const num = prop("v", "integer");
- const third = prop("t", "boolean");
- const join = node("join", "flow:passthrough");
- const dedup = node("dedup", "flow:passthrough");
- const pjoin = node("pjoin", "flow:passthrough");
- const extend = node("extend", "union:extend");
- const same = node("same", "union:same");
- const chain = node("chain", "union:chain");
- const punion = node("punion", "union:extend");
- const seededA = node("seeded-a", "flow:passthrough");
- const loopA = node("loop-a", "flow:passthrough");
- const cjoin = node("cjoin", "flow:passthrough");
- const graph = {
- nodes: [
- node("string-source", "trigger:string"),
- node("number-source", "trigger:number"),
- node("string-twin", "trigger:string"),
- node("unknown-source", "trigger:unknown"),
- node("seeded-b", "flow:passthrough"),
- node("loop-b", "flow:passthrough"),
- join,
- dedup,
- pjoin,
- extend,
- same,
- chain,
- punion,
- seededA,
- loopA,
- cjoin,
- ],
- connections: [
- conn("string-source", "join"),
- conn("number-source", "join"),
- conn("string-source", "dedup"),
- conn("string-twin", "dedup"),
- conn("string-source", "pjoin"),
- conn("unknown-source", "pjoin"),
- conn("string-source", "extend"),
- conn("string-source", "same"),
- conn("extend", "chain"),
- conn("unknown-source", "punion"),
- conn("string-source", "seeded-a"),
- conn("seeded-a", "seeded-b"),
- conn("seeded-b", "seeded-a"),
- conn("loop-a", "loop-b"),
- conn("loop-b", "loop-a"),
- conn("string-source", "cjoin"),
- conn("loop-a", "cjoin"),
- ],
- nodeTypes: [
- triggerType("trigger:string", str),
- triggerType("trigger:number", num),
- UNKNOWN_TRIGGER_TYPE,
- PASSTHROUGH_TYPE,
- nodeType("union:extend", [{ mode: "union", schema: num }]),
- nodeType("union:same", [{ mode: "union", schema: str }]),
- nodeType("union:chain", [{ mode: "union", schema: third }]),
- ],
- };
- const out = (n) => outputSchemaForNode(n, graph);
-
- assert.deepEqual(
- out(join),
- { $schema: DRAFT_URI, anyOf: [num, str] },
- "branch joins keep every incoming schema in canonical connection order"
- );
- assert.deepEqual(out(dedup), str, "identical branches collapse into one");
- assert.deepEqual(out(pjoin), {}, "an unknown branch poisons the join");
- assert.deepEqual(
- out(extend),
- { $schema: DRAFT_URI, anyOf: [str, num] },
- "the declared union schema becomes an extra anyOf alternative"
- );
- assert.deepEqual(out(same), str, "identical declared alternatives dedup");
- assert.deepEqual(
- out(chain),
- { $schema: DRAFT_URI, anyOf: [str, num, third] },
- "nested anyOf branches are flattened"
- );
- assert.deepEqual(out(punion), {}, "an unknown input poisons the union");
- assert.deepEqual(out(seededA), str, "a seeded cycle propagates the seed");
- assert.deepEqual(out(loopA), {}, "an unseeded cycle resolves to unknown");
- assert.deepEqual(out(cjoin), {}, "an unseeded cycle poisons joins");
- });
-
- test("merge contracts converge inside cycles by distributing over anyOf", function (assert) {
- const graph = {
- nodes: [
- node("seed", "trigger:seed"),
- node("first", "m:a"),
- node("second", "m:b"),
- ],
- connections: [
- conn("seed", "first"),
- conn("first", "second"),
- conn("second", "first"),
- ],
- nodeTypes: [
- triggerType("trigger:seed", prop("seed", "string")),
- nodeType("m:a", [{ mode: "merge", schema: prop("a", "string") }]),
- nodeType("m:b", [{ mode: "merge", schema: prop("b", "string") }]),
- ],
- };
-
- const resolved = resolveDeclaredOutputSchemas(graph);
- assert.deepEqual(
- resolved.get("second"),
- [
- objectSchema({
- seed: { type: "string" },
- a: { type: "string" },
- b: { type: "string" },
- }),
- ],
- "the loop-back merge accumulates every declared property exactly once"
- );
- assert.deepEqual(
- resolved.get("first")[0].anyOf?.length,
- 2,
- "the merge inside the cycle keeps flat, bounded alternatives"
- );
- });
-
- test("resolution reads each declaration once and is reusable per node", function (assert) {
- const src = prop("source", "string");
- const source = node("source", "trigger:source");
- const nodes = [source];
- const connections = [];
- let previousLayer = [source];
- let reads = 0;
-
- for (let layer = 0; layer < 20; layer++) {
- const currentLayer = ["left", "right"].map((side) =>
- node(`${side}-${layer}`, "flow:passthrough")
- );
- nodes.push(...currentLayer);
- for (const previous of previousLayer) {
- for (const current of currentLayer) {
- connections.push(conn(previous.clientId, current.clientId));
- }
- }
- previousLayer = currentLayer;
- }
-
- const graph = {
- nodes: [...nodes].reverse(),
- connections,
- nodeTypes: [
- triggerType("trigger:source", src),
- {
- name: "flow:passthrough",
- versions: {
- "1.0": {
- get output_contracts() {
- reads++;
- return [{ mode: "passthrough" }];
- },
- },
- },
- },
- ],
- };
-
- assert.deepEqual(
- outputSchemaForNode(previousLayer[0], graph),
- src,
- "the declaration reaches the end of a reverse-ordered reconverging graph"
- );
- assert.strictEqual(reads, nodes.length - 1, "reads scale with node count");
-
- const outputSchemas = resolveDeclaredOutputSchemas(graph);
- const readsAfter = reads;
- outputSchemaForNode(nodes[5], graph, { outputSchemas });
- assert.strictEqual(reads, readsAfter, "lookups reuse the resolution");
- });
-
test("ancestorOutputNodes deduplicates output ports and survives cycles", function (assert) {
const trigger = { clientId: "t" };
const branch = { clientId: "b" };
diff --git a/plugins/discourse-workflows/test/javascripts/unit/lib/workflows-summarize-output-key-test.js b/plugins/discourse-workflows/test/javascripts/unit/lib/workflows-summarize-output-key-test.js
deleted file mode 100644
index d0afae30654..00000000000
--- a/plugins/discourse-workflows/test/javascripts/unit/lib/workflows-summarize-output-key-test.js
+++ /dev/null
@@ -1,96 +0,0 @@
-import { module, test } from "qunit";
-import {
- summarizeOutputKey,
- summarizeOutputKeyIsDerived,
-} from "discourse/plugins/discourse-workflows/admin/lib/workflows/summarize-output-key";
-
-module("Unit | lib | discourse-workflows | summarizeOutputKey", function () {
- test("prefers an explicit output field name", function (assert) {
- assert.strictEqual(
- summarizeOutputKey({
- aggregation: "sum",
- field: "like_count",
- output_field_name: "post_likes",
- }),
- "post_likes"
- );
- });
-
- test("derives a name from the aggregation and field", function (assert) {
- assert.strictEqual(
- summarizeOutputKey({ aggregation: "sum", field: "like_count" }),
- "sum_like_count"
- );
- assert.strictEqual(
- summarizeOutputKey({ aggregation: "count_unique", field: "topic_id" }),
- "unique_count_topic_id"
- );
- assert.strictEqual(
- summarizeOutputKey({ aggregation: "unique", field: "tags" }),
- "unique_tags"
- );
- });
-
- test("uses the leaf of a dotted field", function (assert) {
- assert.strictEqual(
- summarizeOutputKey({ aggregation: "sum", field: "post.like_count" }),
- "sum_like_count"
- );
- });
-
- test("uses the full path when derived leaves collide", function (assert) {
- const rows = [
- { aggregation: "count", field: "topic.id" },
- { aggregation: "count", field: "user.id" },
- { aggregation: "sum", field: "post.id" },
- ];
-
- assert.strictEqual(summarizeOutputKey(rows[0], rows), "count_topic_id");
- assert.strictEqual(summarizeOutputKey(rows[1], rows), "count_user_id");
- assert.strictEqual(summarizeOutputKey(rows[2], rows), "sum_id");
- });
-
- test("ignores rows with explicit names when checking collisions", function (assert) {
- const rows = [
- { aggregation: "count", field: "topic.id" },
- { aggregation: "count", field: "user.id", output_field_name: "users" },
- ];
-
- assert.strictEqual(summarizeOutputKey(rows[0], rows), "count_id");
- });
-
- test("drops the trailing underscore when there is no field", function (assert) {
- assert.strictEqual(summarizeOutputKey({ aggregation: "count" }), "count");
- assert.strictEqual(
- summarizeOutputKey({ aggregation: "collect" }),
- "collected"
- );
- });
-
- test("sanitizes characters that cannot appear in a key", function (assert) {
- assert.strictEqual(
- summarizeOutputKey({ aggregation: "sum", field: 'a["b c"]' }),
- "sum_ab_c"
- );
- });
-
- test("ignores whitespace-only explicit names", function (assert) {
- assert.strictEqual(
- summarizeOutputKey({
- aggregation: "count",
- output_field_name: " ",
- }),
- "count"
- );
- });
-
- test("reports whether the key was derived", function (assert) {
- assert.true(summarizeOutputKeyIsDerived({ aggregation: "count" }));
- assert.false(
- summarizeOutputKeyIsDerived({
- aggregation: "count",
- output_field_name: "rows",
- })
- );
- });
-});
diff --git a/plugins/discourse-workflows/test/javascripts/unit/lib/workflows-summarize-output-schemas-test.js b/plugins/discourse-workflows/test/javascripts/unit/lib/workflows-summarize-output-schemas-test.js
deleted file mode 100644
index cd91cbee997..00000000000
--- a/plugins/discourse-workflows/test/javascripts/unit/lib/workflows-summarize-output-schemas-test.js
+++ /dev/null
@@ -1,64 +0,0 @@
-import { module, test } from "qunit";
-import summarizeOutputSchemas from "discourse/plugins/discourse-workflows/admin/lib/workflows/output-schemas/summarize";
-
-module(
- "Unit | lib | discourse-workflows | summarize output schemas",
- function () {
- test("derives properties from group keys and aggregations", function (assert) {
- const [schema] = summarizeOutputSchemas({
- fields_to_split_by: "topic_id",
- fields_to_summarize: {
- values: [
- {
- aggregation: "sum",
- field: "likes",
- output_field_name: "post_likes",
- },
- { aggregation: "count" },
- ],
- },
- });
-
- assert.deepEqual(Object.keys(schema.properties), [
- "topic_id",
- "post_likes",
- "count",
- ]);
- assert.strictEqual(schema.properties.count.type, "integer");
- assert.deepEqual(schema.properties.post_likes.type, ["number", "null"]);
- });
-
- test("takes the leaf of a dotted group key", function (assert) {
- const [schema] = summarizeOutputSchemas({
- fields_to_split_by: "post.topic_id, tags",
- });
-
- assert.deepEqual(Object.keys(schema.properties), ["topic_id", "tags"]);
- });
-
- test("uses the full path when group key leaves collide", function (assert) {
- const [schema] = summarizeOutputSchemas({
- fields_to_split_by: "topic.id, user.id",
- fields_to_summarize: {
- values: [
- { aggregation: "count", field: "topic.id" },
- { aggregation: "count", field: "user.id" },
- ],
- },
- });
-
- assert.deepEqual(Object.keys(schema.properties), [
- "topic_id",
- "user_id",
- "count_topic_id",
- "count_user_id",
- ]);
- });
-
- test("resolves an empty shape without configuration", function (assert) {
- const [schema] = summarizeOutputSchemas();
-
- assert.deepEqual(schema.properties, {});
- });
- }
-);