Skip to content

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

FEATURE: Add AI authoring to Discourse Workflows (#40504)

Sam65024326dd7a
diff --git a/db/structure.sql b/db/structure.sql
index 6f0a6ef5d60..148f34b1e09 100644
--- a/db/structure.sql
+++ b/db/structure.sql
@@ -4310,6 +4310,47 @@ CREATE SEQUENCE public.discourse_templates_usage_count_id_seq
ALTER SEQUENCE public.discourse_templates_usage_count_id_seq OWNED BY public.discourse_templates_usage_count.id;
+--
+-- Name: discourse_workflows_ai_authoring_sessions; Type: TABLE; Schema: public; Owner: -
+--
+
+CREATE TABLE public.discourse_workflows_ai_authoring_sessions (
+ id bigint NOT NULL,
+ workflow_id bigint,
+ user_id integer NOT NULL,
+ status character varying(40) DEFAULT 'drafting'::character varying NOT NULL,
+ messages jsonb DEFAULT '[]'::jsonb NOT NULL,
+ latest_request text,
+ latest_response jsonb DEFAULT '{}'::jsonb NOT NULL,
+ proposed_patch jsonb DEFAULT '{}'::jsonb NOT NULL,
+ base_workflow_version_id character varying(36),
+ base_graph_digest character varying(64),
+ risk_level character varying(20),
+ applied_at timestamp(6) without time zone,
+ created_at timestamp(6) without time zone NOT NULL,
+ updated_at timestamp(6) without time zone NOT NULL
+);
+
+
+--
+-- Name: discourse_workflows_ai_authoring_sessions_id_seq; Type: SEQUENCE; Schema: public; Owner: -
+--
+
+CREATE SEQUENCE public.discourse_workflows_ai_authoring_sessions_id_seq
+ START WITH 1
+ INCREMENT BY 1
+ NO MINVALUE
+ NO MAXVALUE
+ CACHE 1;
+
+
+--
+-- Name: discourse_workflows_ai_authoring_sessions_id_seq; Type: SEQUENCE OWNED BY; Schema: public; Owner: -
+--
+
+ALTER SEQUENCE public.discourse_workflows_ai_authoring_sessions_id_seq OWNED BY public.discourse_workflows_ai_authoring_sessions.id;
+
+
--
-- Name: discourse_workflows_credentials; Type: TABLE; Schema: public; Owner: -
--
@@ -12618,6 +12659,13 @@ ALTER TABLE ONLY public.discourse_subscriptions_subscriptions ALTER COLUMN id SE
ALTER TABLE ONLY public.discourse_templates_usage_count ALTER COLUMN id SET DEFAULT nextval('public.discourse_templates_usage_count_id_seq'::regclass);
+--
+-- Name: discourse_workflows_ai_authoring_sessions id; Type: DEFAULT; Schema: public; Owner: -
+--
+
+ALTER TABLE ONLY public.discourse_workflows_ai_authoring_sessions ALTER COLUMN id SET DEFAULT nextval('public.discourse_workflows_ai_authoring_sessions_id_seq'::regclass);
+
+
--
-- Name: discourse_workflows_credentials id; Type: DEFAULT; Schema: public; Owner: -
--
@@ -14882,6 +14930,14 @@ ALTER TABLE ONLY public.discourse_templates_usage_count
ADD CONSTRAINT discourse_templates_usage_count_pkey PRIMARY KEY (id);
+--
+-- Name: discourse_workflows_ai_authoring_sessions discourse_workflows_ai_authoring_sessions_pkey; Type: CONSTRAINT; Schema: public; Owner: -
+--
+
+ALTER TABLE ONLY public.discourse_workflows_ai_authoring_sessions
+ ADD CONSTRAINT discourse_workflows_ai_authoring_sessions_pkey PRIMARY KEY (id);
+
+
--
-- Name: discourse_workflows_credentials discourse_workflows_credentials_pkey; Type: CONSTRAINT; Schema: public; Owner: -
--
@@ -16776,6 +16832,27 @@ CREATE UNIQUE INDEX idx_discourse_automation_user_global_notices ON public.disco
CREATE UNIQUE INDEX idx_discourse_calendar_post_event_dates_event_id_starts_at_uniq ON public.discourse_calendar_post_event_dates USING btree (event_id, starts_at);
+--
+-- Name: idx_dwf_ai_sessions_on_status_updated_at; Type: INDEX; Schema: public; Owner: -
+--
+
+CREATE INDEX idx_dwf_ai_sessions_on_status_updated_at ON public.discourse_workflows_ai_authoring_sessions USING btree (status, updated_at);
+
+
+--
+-- Name: idx_dwf_ai_sessions_on_user_id; Type: INDEX; Schema: public; Owner: -
+--
+
+CREATE INDEX idx_dwf_ai_sessions_on_user_id ON public.discourse_workflows_ai_authoring_sessions USING btree (user_id);
+
+
+--
+-- Name: idx_dwf_ai_sessions_on_workflow_id; Type: INDEX; Schema: public; Owner: -
+--
+
+CREATE INDEX idx_dwf_ai_sessions_on_workflow_id ON public.discourse_workflows_ai_authoring_sessions USING btree (workflow_id);
+
+
--
-- Name: idx_dwf_credentials_on_created_by_id; Type: INDEX; Schema: public; Owner: -
--
@@ -21991,6 +22068,7 @@ INSERT INTO "schema_migrations" (version) VALUES
('20260603115200'),
('20260603013342'),
('20260602104726'),
+('20260601063855'),
('20260601043020'),
('20260528074731'),
('20260528074719'),
diff --git a/plugins/discourse-ai/db/fixtures/agents/603_ai_agents.rb b/plugins/discourse-ai/db/fixtures/agents/603_ai_agents.rb
index 3f652fbbd32..2f1d15aeb73 100644
--- a/plugins/discourse-ai/db/fixtures/agents/603_ai_agents.rb
+++ b/plugins/discourse-ai/db/fixtures/agents/603_ai_agents.rb
@@ -98,6 +98,14 @@ DiscourseAi::Agents::Agent.system_agents.each do |agent_class, id|
forced_tool_names = instance.force_tool_use.map { |tool| tool.to_s.split("::").last }
agent.tools = tools.map { |name, value| [name, value, forced_tool_names.include?(name)] }
agent.forced_tool_count = instance.forced_tool_count
+ agent.execution_mode = agent_class.execution_mode
+ agent.max_turn_tokens = agent_class.max_turn_tokens
+ agent.compression_threshold =
+ if agent.execution_mode == "agentic"
+ agent_class.compression_threshold || 85
+ else
+ agent_class.compression_threshold
+ end
agent.response_format = instance.response_format
agent.examples = instance.examples
diff --git a/plugins/discourse-ai/lib/agents/agent.rb b/plugins/discourse-ai/lib/agents/agent.rb
index ffbdf7989d9..4bf13182e2b 100644
--- a/plugins/discourse-ai/lib/agents/agent.rb
+++ b/plugins/discourse-ai/lib/agents/agent.rb
@@ -163,7 +163,9 @@ module DiscourseAi
def sync_external_registry!
configs = external_feature_configs
signature = configs.hash
- return if @external_registry_signature == signature
+ if @external_registry_signature == signature && @external_tools_by_name && @system_agents
+ return
+ end
@external_registry_signature = signature
external_agents = {}
diff --git a/plugins/discourse-ai/lib/completions/anthropic_message_processor.rb b/plugins/discourse-ai/lib/completions/anthropic_message_processor.rb
index 7e4788b32b3..7b481495b8d 100644
--- a/plugins/discourse-ai/lib/completions/anthropic_message_processor.rb
+++ b/plugins/discourse-ai/lib/completions/anthropic_message_processor.rb
@@ -36,8 +36,7 @@ class DiscourseAi::Completions::AnthropicMessageProcessor
end
def to_tool_call
- parameters = {}
- parameters = JSON.parse(raw_json, symbolize_names: true) if raw_json.present?
+ parameters = DiscourseAi::Completions::ToolArgumentsParser.parse(raw_json)
# we dupe to avoid poisoning the original tool call
@tool_call = @tool_call.dup
@tool_call.partial = false
diff --git a/plugins/discourse-ai/lib/completions/converse_message_processor.rb b/plugins/discourse-ai/lib/completions/converse_message_processor.rb
index a144d01c9b8..347a15c3630 100644
--- a/plugins/discourse-ai/lib/completions/converse_message_processor.rb
+++ b/plugins/discourse-ai/lib/completions/converse_message_processor.rb
@@ -36,8 +36,7 @@ class DiscourseAi::Completions::ConverseMessageProcessor
end
def to_tool_call
- parameters = {}
- parameters = JSON.parse(raw_json, symbolize_names: true) if raw_json.present?
+ parameters = DiscourseAi::Completions::ToolArgumentsParser.parse(raw_json)
@tool_call = @tool_call.dup
@tool_call.partial = false
@tool_call.parameters = parameters
diff --git a/plugins/discourse-ai/lib/completions/nova_message_processor.rb b/plugins/discourse-ai/lib/completions/nova_message_processor.rb
index b31f46b478b..fe409f9c946 100644
--- a/plugins/discourse-ai/lib/completions/nova_message_processor.rb
+++ b/plugins/discourse-ai/lib/completions/nova_message_processor.rb
@@ -34,7 +34,7 @@ class DiscourseAi::Completions::NovaMessageProcessor
end
def to_tool_call
- parameters = JSON.parse(raw_json, symbolize_names: true)
+ parameters = DiscourseAi::Completions::ToolArgumentsParser.parse(raw_json)
# we dupe to avoid poisoning the original tool call
@tool_call = @tool_call.dup
@tool_call.partial = false
diff --git a/plugins/discourse-ai/lib/completions/open_ai_message_processor.rb b/plugins/discourse-ai/lib/completions/open_ai_message_processor.rb
index 15a9e5ac8f8..59fa91f6b25 100644
--- a/plugins/discourse-ai/lib/completions/open_ai_message_processor.rb
+++ b/plugins/discourse-ai/lib/completions/open_ai_message_processor.rb
@@ -24,7 +24,7 @@ module DiscourseAi::Completions
id = tool_call.dig(:id)
name = tool_call.dig(:function, :name)
arguments = tool_call.dig(:function, :arguments)
- parameters = arguments.present? ? JSON.parse(arguments, symbolize_names: true) : {}
+ parameters = ToolArgumentsParser.parse(arguments)
result << ToolCall.new(id: id, name: name, parameters: parameters)
end
end
@@ -67,7 +67,7 @@ module DiscourseAi::Completions
@streaming_parser << arguments.to_s if @streaming_parser && !arguments.to_s.empty?
rval = current_tool_progress if !rval
elsif finished_tools && @tool
- parsed_args = JSON.parse(@tool_arguments, symbolize_names: true)
+ parsed_args = ToolArgumentsParser.parse(@tool_arguments)
@tool.parameters = parsed_args
@tool.partial = false
rval = @tool
@@ -115,7 +115,7 @@ module DiscourseAi::Completions
def process_arguments
if @tool_arguments.present?
- parsed_args = JSON.parse(@tool_arguments, symbolize_names: true)
+ parsed_args = ToolArgumentsParser.parse(@tool_arguments)
@tool.parameters = parsed_args
@tool_arguments = nil
end
diff --git a/plugins/discourse-ai/lib/completions/open_ai_responses_message_processor.rb b/plugins/discourse-ai/lib/completions/open_ai_responses_message_processor.rb
index 9bc8cc8dace..419a046380f 100644
--- a/plugins/discourse-ai/lib/completions/open_ai_responses_message_processor.rb
+++ b/plugins/discourse-ai/lib/completions/open_ai_responses_message_processor.rb
@@ -172,7 +172,7 @@ module DiscourseAi::Completions
item_id = item[:id]
name = item[:name]
arguments = item[:arguments] || ""
- params = arguments.empty? ? {} : JSON.parse(arguments, symbolize_names: true)
+ params = ToolArgumentsParser.parse(arguments)
ToolCall.new(
id: call_id,
@@ -272,7 +272,7 @@ module DiscourseAi::Completions
# Parse accumulated @tool_arguments once we have a complete JSON blob
def process_arguments
return if @tool_arguments.to_s.empty?
- parsed = JSON.parse(@tool_arguments, symbolize_names: true)
+ parsed = ToolArgumentsParser.parse(@tool_arguments)
@tool.parameters = parsed
@tool.partial = false
@tool_arguments = nil
diff --git a/plugins/discourse-ai/lib/completions/tool_arguments_parser.rb b/plugins/discourse-ai/lib/completions/tool_arguments_parser.rb
new file mode 100644
index 00000000000..e1ac1c97d2b
--- /dev/null
+++ b/plugins/discourse-ai/lib/completions/tool_arguments_parser.rb
@@ -0,0 +1,86 @@
+# frozen_string_literal: true
+
+module DiscourseAi
+ module Completions
+ class ToolArgumentsParser
+ class << self
+ def parse(arguments)
+ return arguments.deep_symbolize_keys if arguments.is_a?(Hash)
+
+ normalized_arguments = arguments.to_s.strip
+ return {} if normalized_arguments.blank?
+
+ JSON.parse(normalized_arguments, symbolize_names: true)
+ rescue JSON::ParserError => error
+ repaired_arguments(normalized_arguments).each do |repaired_arguments|
+ next if repaired_arguments == normalized_arguments
+
+ begin
+ return JSON.parse(repaired_arguments, symbolize_names: true)
+ rescue JSON::ParserError
+ next
+ end
+ end
+
+ raise error
+ end
+
+ private
+
+ def repaired_arguments(arguments)
+ missing_opening_brace = repair_missing_opening_brace(arguments)
+ candidates = [missing_opening_brace, repair_missing_closing_braces(arguments)]
+
+ if missing_opening_brace != arguments
+ candidates << repair_missing_closing_braces(missing_opening_brace)
+ end
+
+ candidates.uniq
+ end
+
+ def repair_missing_opening_brace(arguments)
+ return arguments if arguments.start_with?("{") || !arguments.include?(":")
+
+ if arguments.start_with?("\"")
+ "{#{arguments}"
+ elsif arguments.match?(/\A[a-zA-Z_][a-zA-Z0-9_]*"\s*:/)
+ "{\"#{arguments}"
+ else
+ arguments
+ end
+ end
+
+ def repair_missing_closing_braces(arguments)
+ return arguments if !arguments.start_with?("{")
+
+ unclosed_braces = unclosed_object_brace_count(arguments)
+ return arguments if unclosed_braces <= 0
+
+ arguments + ("}" * unclosed_braces)
+ end
+
+ def unclosed_object_brace_count(arguments)
+ unclosed_braces = 0
+ escaped = false
+ in_string = false
+
+ arguments.each_char do |character|
+ if escaped
+ escaped = false
+ elsif character == "\\" && in_string
+ escaped = true
+ elsif character == '"'
+ in_string = !in_string
+ elsif !in_string && character == "{"
+ unclosed_braces += 1
+ elsif !in_string && character == "}"
+ unclosed_braces -= 1
+ end
+ end
+
+ unclosed_braces
+ end
+ end
+ end
+ end
+end
diff --git a/plugins/discourse-ai/spec/lib/agents/agent_spec.rb b/plugins/discourse-ai/spec/lib/agents/agent_spec.rb
index ae5d7382796..7903ff428f2 100644
--- a/plugins/discourse-ai/spec/lib/agents/agent_spec.rb
+++ b/plugins/discourse-ai/spec/lib/agents/agent_spec.rb
@@ -376,6 +376,20 @@ RSpec.describe DiscourseAi::Agents::Agent do
)
end
+ it "rebuilds external tool lookup when the cache is partially reset" do
+ register_fake_feature
+
+ expect(described_class.external_tool_by_name("FakeExternalTool")).to eq(
+ FakeExternalPlugin::FakeExternalTool,
+ )
+
+ described_class.instance_variable_set(:@external_tools_by_name, nil)
+
+ expect(described_class.external_tool_by_name("FakeExternalTool")).to eq(
+ FakeExternalPlugin::FakeExternalTool,
+ )
+ end
+
it "includes external tools in the agent's available_tools" do
register_fake_feature
diff --git a/plugins/discourse-ai/spec/lib/completions/open_ai_message_processor_spec.rb b/plugins/discourse-ai/spec/lib/completions/open_ai_message_processor_spec.rb
index cc21103ef29..b6995a42fdc 100644
--- a/plugins/discourse-ai/spec/lib/completions/open_ai_message_processor_spec.rb
+++ b/plugins/discourse-ai/spec/lib/completions/open_ai_message_processor_spec.rb
@@ -74,4 +74,74 @@ RSpec.describe DiscourseAi::Completions::OpenAiMessageProcessor do
expect(final_tool.parameters).to eq({ title: "Pack", time: "18:00" })
expect(final_tool.partial?).to eq(false)
end
+
+ it "parses streamed arguments with padding" do
+ processor = described_class.new
+
+ processor.process_streamed_message(
+ chunk(
+ delta: {
+ tool_calls: [
+ { index: 0, id: "call_group", function: { name: "resolve", arguments: " {\"kind" } },
+ ],
+ },
+ ),
+ )
+ processor.process_streamed_message(
+ chunk(
+ delta: {
+ tool_calls: [
+ { index: 0, function: { arguments: "\":\"group\",\"query\":\"friend\"} " } },
+ ],
+ },
+ ),
+ )
+
+ tool = processor.process_streamed_message(chunk(delta: {}, finish_reason: "tool_calls"))
+
+ expect(tool.parameters).to eq({ kind: "group", query: "friend" })
+ end
+
+ it "repairs a missing opening delimiter" do
+ processor = described_class.new
+
+ processor.process_streamed_message(
+ chunk(
+ delta: {
+ tool_calls: [
+ {
+ index: 0,
+ id: "call_group",
+ function: {
+ name: "resolve",
+ arguments: "kind\": \"group\", \"query\": \"friend\"} ",
+ },
+ },
+ ],
+ },
+ ),
+ )
+
+ tool = processor.process_streamed_message(chunk(delta: {}, finish_reason: "tool_calls"))
+
+ expect(tool.parameters).to eq({ kind: "group", query: "friend" })
+ end
+
+ it "raises on invalid tool arguments" do
+ processor = described_class.new
+
+ processor.process_streamed_message(
+ chunk(
+ delta: {
+ tool_calls: [
+ { index: 0, id: "call_group", function: { name: "resolve", arguments: "not-json" } },
+ ],
+ },
+ ),
+ )
+
+ expect {
+ processor.process_streamed_message(chunk(delta: {}, finish_reason: "tool_calls"))
+ }.to raise_error(JSON::ParserError)
+ end
end
diff --git a/plugins/discourse-ai/spec/lib/completions/tool_arguments_parser_spec.rb b/plugins/discourse-ai/spec/lib/completions/tool_arguments_parser_spec.rb
new file mode 100644
index 00000000000..58c94c58a31
--- /dev/null
+++ b/plugins/discourse-ai/spec/lib/completions/tool_arguments_parser_spec.rb
@@ -0,0 +1,35 @@
+# frozen_string_literal: true
+
+RSpec.describe DiscourseAi::Completions::ToolArgumentsParser do
+ before { enable_current_plugin }
+
+ it "returns hash arguments with symbolized keys" do
+ expect(described_class.parse("kind" => "group", "options" => { "notify" => true })).to eq(
+ { kind: "group", options: { notify: true } },
+ )
+ end
+
+ it "parses blank arguments as an empty hash" do
+ expect(described_class.parse(" ")).to eq({})
+ end
+
+ it "parses arguments with padding" do
+ expect(described_class.parse(" {\"kind\":\"group\",\"query\":\"friend\"} ")).to eq(
+ { kind: "group", query: "friend" },
+ )
+ end
+
+ it "repairs an omitted opening delimiter" do
+ expect(described_class.parse("kind\": \"group\", \"query\": \"friend\"} ")).to eq(
+ { kind: "group", query: "friend" },
+ )
+ end
+
+ it "repairs omitted closing delimiters" do
+ expect(described_class.parse('{"outer":{"inner":"value"')).to eq({ outer: { inner: "value" } })
+ end
+
+ it "raises on invalid arguments" do
+ expect { described_class.parse("not-json") }.to raise_error(JSON::ParserError)
+ end
+end
diff --git a/plugins/discourse-workflows/USE_CASES.md b/plugins/discourse-workflows/USE_CASES.md
new file mode 100644
index 00000000000..724cbb84ff4
--- /dev/null
+++ b/plugins/discourse-workflows/USE_CASES.md
@@ -0,0 +1,67 @@
+# Workflow AI authoring use cases
+
+Purpose: maintain a durable set of prompts for evaluating the Workflow AI authoring loop as schemas, tools, and prompting change.
+
+## How to run a dev eval
+
+Use the synchronous dev runner so the latest local code and tools are used:
+
+```bash
+bin/rails runner /tmp/workflow_ai_dev_run.rb '<prompt>' 'AI dev eval <id>' > /tmp/workflow_ai_<id>.json
+```
+
+For each run, record:
+
+- Session/workflow IDs and status
+- Tool calls used
+- Proposal shape
+- Whether Code nodes were avoided when declarative nodes are sufficient
+- Whether `workflow_validate_patch` was used and final `expression_errors` is empty
+- Token/time totals
+- Any optimization applied
+
+## Core regression prompts
+
+| ID | Prompt | Expected shape | Key checks |
+| --- | --- | --- | --- |
+| `tl1-cake-chat` | `if a tl1 posts a post with the word cake make a post in the general chat channel linking to it` | `trigger:post_created -> condition:filter -> action:send_chat_message` | Uses `$json.user.trust_level` (trust level lives on the user object, not the post), `$json.post.raw`, `$json.post.post_url`; no Code node; chat template starts with `=`. |
+| `support-tag-reply` | `when a new topic is created in Support, tag it needs-review and reply with Thanks for contacting support. Our team will review this soon.` | `trigger:topic_created -> action:topic_tags -> action:post (create)` | Resolves category/tag; after `action:topic_tags`, downstream reply uses `$json.topic_id`; no Code node. |
+| `closed-support-wait-archive-chat` | `30 days after a topic in Support is closed, archive it and post a message in General chat linking to the topic` | `trigger:topic_closed -> flow:wait -> action:topic (archive) -> action:send_chat_message` | Uses `flow:wait`; no unnecessary forum search/read; topic link template starts with `=`. |
+| `manual-maintenance-chat` | `create a manual workflow that sends a message to General chat saying Maintenance window is starting now` | `trigger:manual -> action:send_chat_message` | Static message does not need expression syntax; validates without expression errors. |
+| `closed-general-tl1-chat` | `when a topic by a tl1 or lower is closed in the general category message the general channel with a link to the post` | `trigger:topic_closed -> action:topic (get) -> action:group (check_membership) -> condition:if -> action:send_chat_message` | Uses `action:topic` get to hydrate first-post fields (the topic payload has no `trust_level`). Resolves the `trust_level_2` automatic group and uses `action:group` with `operation: check_membership`, resolved `group_id`, and `username: ={{ $json.post.username }}`, then continues on the condition false branch (`group_membership.in_group == false`) for TL1-or-lower because `trust_level_N` is cumulative for TL >= N. Uses `$json.post.post_url`; no Code node; no clarification needed. |
+| `friend-group-post-dm-admin` | `when anyone in the friend group posts send admin a dm with a link to the post` | `trigger:post_created -> action:group (check_membership) -> condition:if -> action:send_personal_message` | Resolves the `friend` group and `admin` user; sets resolved `group_id`, uses `$json.post.username` for membership, branches on `$json.group_membership.in_group`, and uses `$json.post.post_url` in a leading-`=` personal message body; no Code node. |
+
+## Additional prompts to rotate into evals
+
+| ID | Prompt | Expected shape | Key checks |
+| --- | --- | --- | --- |
+| `post-staff-exclusion` | `when a non-staff user posts in General and the post contains urgent, send a message to General chat with a link to the post` | `trigger:post_created -> condition:filter -> action:send_chat_message` | Uses boolean filter on `$json.post.staff` plus string contains on `$json.post.raw`; no Code node. |
+| `topic-created-category-chat` | `when a new topic is created in Support by a TL0 user, message General chat with the topic title and post link` | `trigger:topic_created -> condition:filter -> action:send_chat_message` | Uses `$json.post.trust_level == 0`, `$json.topic.title`, `$json.post.post_url`. |
+| `closed-topic-no-author-filter` | `when any topic in General is closed, message General chat with a link to the topic` | `trigger:topic_closed -> action:send_chat_message` or `trigger:topic_closed -> action:topic (get) -> action:send_chat_message` | If only topic link is needed, no author lookup is required; if post link is requested, use `action:topic` get. |
+| `wait-chat-reminder` | `when a topic in Support is closed, wait 7 days and message General chat with the topic title` | `trigger:topic_closed -> flow:wait -> action:send_chat_message` | Wait parameters are `wait_amount: 7`, `wait_unit: days`; dynamic chat template starts with `=`. |
+| `tag-only` | `when a new topic is created in Support, add the needs-review tag` | `trigger:topic_created -> action:topic_tags` | Resolves category/tag; no reply; no Code node. |
+| `reply-only` | `when a new topic is created in Support, reply Thanks, we will review this shortly.` | `trigger:topic_created -> action:post (create)` | Uses `$json.topic.id`; no unnecessary tag lookup. |
+| `post-created-category-filter` | `when a post is created in Support by a TL1 user, message General chat with the post link` | `trigger:post_created -> condition:filter -> action:send_chat_message` | Trigger category scoping or category filter is correct; uses `$json.post.trust_level`. |
+| `archive-closed-topic` | `when a topic in Support is closed, wait 30 days and archive it` | `trigger:topic_closed -> flow:wait -> action:topic (archive)` | Uses archive operation, no chat lookup. |
+| `manual-topic-create` | `create a manual workflow that creates a topic in General titled Maintenance update with body Maintenance is complete.` | `trigger:manual -> action:topic (create)` | Resolves category; create operation includes title/raw/category; no Code node. |
+| `manual-log` | `create a manual workflow that writes a log entry saying Manual workflow ran` | `trigger:manual -> action:log` | No external discovery needed; no Code node. |
+| `topic-admin-button-chat` | `add a topic admin button workflow that sends the current topic link to General chat` | `trigger:topic_admin_button -> action:send_chat_message` | Uses topic-only schema; dynamic template starts with `=`. |
+| `tag-changed-chat` | `when a topic in Support gets the needs-review tag, message General chat with the topic title` | `trigger:topic_tag_changed -> condition:filter? -> action:send_chat_message` | Uses tag-changed schema for `added_tags`/`new_tags` if available; should query catalog first. |
+| `category-changed-chat` | `when a topic is moved into Support, message General chat with a link to the topic` | `trigger:topic_category_changed -> action:send_chat_message` | Should query catalog for old/new category fields before drafting. |
+| `badge-grant` | `when a TL1 user posts in General with the word helpful, grant them the Basic badge` | `trigger:post_created -> condition:filter -> action:badge` | Uses declarative filter; resolves badge; no Code node. |
+| `group-add` | `when a TL1 user creates a topic in Support, add them to the helpers group` | `trigger:topic_created -> condition:filter -> action:group` | Uses `$json.post.username`; resolves group; no Code node. |
+| `http-request-warning` | `when a new topic is created in Support, send the topic title to https://example.com/webhook` | `trigger:topic_created -> action:http_request` | Includes external HTTP risk; validates URL/method/body; no Code unless necessary. |
+
+## Known edge cases to keep testing
+
+- Topic-only triggers that need author/post fields should use `action:topic` get before filtering or messaging.
+- Generic prompts like "when someone posts" should use `trigger:post_created` for all regular posts; do not ask whether to include replies unless the prompt explicitly narrows the scope.
+- Actions that replace item JSON require downstream nodes to use the action output schema, not the original trigger schema.
+- Dynamic strings containing `{{ }}` must start with `=`.
+- Simple trust/text/category/staff checks should use `condition:filter`, not Code nodes. `condition:if` is for separate true/false branches.
+- Trust level is only exposed as `$json.user.trust_level` on triggers with a user object (e.g. `trigger:post_created`); the post/topic payloads have no `trust_level`. When a trust-level check is needed but no `trust_level` field is in scope (topic-only triggers), resolve the cumulative `trust_level_N` automatic group and use `action:group` with `operation: check_membership` plus resolved `group_id` -- do not ask for clarification or add a Code node.
+- Condition builder entries must use `leftValue` and `rightValue`; `left`/`right` will not execute correctly.
+- Connections leaving `condition:filter` or `condition:if` should use `connection_type: "true"` for the passing branch, not `main`.
+- Group membership checks should use `action:group` with `operation: check_membership` and the resolved `group_id` instead of Code nodes. Branch with `condition:if` on `$json.group_membership.in_group` when different member and non-member paths are needed.
+- DM/personal-message notifications should use `action:send_personal_message` instead of chat or topic reply nodes.
+- Forum `search`/`read` should not be used for node/schema discovery; use `workflow_node_catalog` and `workflow_validate_patch`.
diff --git a/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/build-with-ai-modal.gjs b/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/build-with-ai-modal.gjs
new file mode 100644
index 00000000000..dc37e09c459
--- /dev/null
+++ b/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/build-with-ai-modal.gjs
@@ -0,0 +1,949 @@
+import Component from "@glimmer/component";
+import { tracked } from "@glimmer/tracking";
+import { fn } from "@ember/helper";
+import { on } from "@ember/modifier";
+import { action } from "@ember/object";
+import { service } from "@ember/service";
+import { ajax } from "discourse/lib/ajax";
+import DButton from "discourse/ui-kit/d-button";
+import DTextarea from "discourse/ui-kit/d-textarea";
+import dConcatClass from "discourse/ui-kit/helpers/d-concat-class";
+import { i18n } from "discourse-i18n";
+
+export default class BuildWithAiModal extends Component {
+ @service messageBus;
+ @service toasts;
+
+ @tracked aiPrompt = "";
+ @tracked aiGenerating = false;
+ @tracked aiProgressEvents = [];
+ @tracked aiResponse = null;
+ @tracked aiSessionId = null;
+ @tracked aiGenerationId = null;
+ @tracked aiClarificationAnswers = {};
+ @tracked aiClarificationQuestionIndex = 0;
+ @tracked aiError = null;
+
+ willDestroy() {
+ super.willDestroy();
+ this.unsubscribeFromAiAuthoring();
+ }
+
+ get aiSubmitDisabled() {
+ return this.aiGenerating || !this.aiPrompt.trim();
+ }
+
+ get aiProposal() {
+ if (this.aiResponseStatus !== "proposed_patch") {
+ return null;
+ }
+
+ const proposal = this.aiResponse?.response?.proposal;
+ return proposal?.operations?.length ? proposal : null;
+ }
+
+ get aiResponseMessage() {
+ if (
+ ["error", "needs_clarification"].includes(this.aiResponseStatus) ||
+ this.aiProposal
+ ) {
+ return null;
+ }
+
+ return this.aiResponse?.response?.message;
+ }
+
+ get aiResponseStatus() {
+ return this.aiResponse?.status;
+ }
+
+ get aiNeedsClarification() {
+ return this.aiResponseStatus === "needs_clarification";
+ }
+
+ get aiResponseError() {
+ return (
+ this.aiError ||
+ this.aiResponse?.error ||
+ this.aiResponse?.response?.error ||
+ (this.aiResponseStatus === "error"
+ ? this.aiResponse?.response?.message
+ : null)
+ );
+ }
+
+ get aiStatusLabel() {
+ if (this.aiGenerating) {
+ return i18n("discourse_workflows.ai.status_working");
+ }
+
+ if (this.aiResponseError || this.aiNeedsClarification) {
+ return i18n("discourse_workflows.ai.status_error");
+ }
+
+ if (this.aiProposal) {
+ return i18n("discourse_workflows.ai.status_ready");
+ }
+
+ return i18n("discourse_workflows.ai.status_idle");
+ }
+
+ get aiStatusClass() {
+ if (this.aiGenerating) {
+ return "is-working";
+ }
+
+ if (this.aiResponseError || this.aiNeedsClarification) {
+ return "is-error";
+ }
+
+ if (this.aiProposal) {
+ return "is-ready";
+ }
+
+ return "is-idle";
+ }
+
+ get aiQuestions() {
+ return this.aiResponse?.response?.questions || [];
+ }
+
+ get aiShowingClarification() {
+ return this.aiNeedsClarification && this.aiQuestions.length;
+ }
+
+ get aiCurrentQuestionIndex() {
+ return Math.min(
+ this.aiClarificationQuestionIndex,
+ Math.max(this.aiQuestions.length - 1, 0)
+ );
+ }
+
+ get aiCurrentQuestion() {
+ return this.aiQuestions[this.aiCurrentQuestionIndex];
+ }
+
+ get aiCurrentQuestionNumber() {
+ return this.aiCurrentQuestionIndex + 1;
+ }
+
+ get aiFirstClarificationQuestion() {
+ return this.aiCurrentQuestionIndex === 0;
+ }
+
+ get aiLastClarificationQuestion() {
+ return this.aiCurrentQuestionIndex >= this.aiQuestions.length - 1;
+ }
+
+ get aiClarificationContinueLabel() {
+ return this.aiLastClarificationQuestion
+ ? i18n("discourse_workflows.ai.continue")
+ : i18n("discourse_workflows.ai.next_question");
+ }
+
+ get aiClarificationCurrentQuestionDisabled() {
+ if (this.aiGenerating || !this.aiCurrentQuestion) {
+ return true;
+ }
+
+ const answer = this.#aiClarificationAnswer(
+ this.aiCurrentQuestion,
+ this.aiCurrentQuestionIndex
+ );
+ return !answer.selected.length && !answer.custom.trim();
+ }
+
+ get aiShowingProposalReview() {
+ return Boolean(this.aiProposal);
+ }
+
+ get aiShowingPromptComposer() {
+ return !this.aiShowingClarification && !this.aiShowingProposalReview;
+ }
+
+ get aiCanReturnToPrompt() {
+ return Boolean(
+ this.aiResponse ||
+ this.aiError ||
+ this.aiSessionId ||
+ this.aiGenerationId ||
+ this.aiProgressEvents?.length ||
+ Object.keys(this.aiClarificationAnswers || {}).length ||
+ this.aiClarificationQuestionIndex
+ );
+ }
+
+ get aiNeedsClarificationFallback() {
+ return this.aiNeedsClarification && !this.aiShowingClarification;
+ }
+
+ get aiClarificationSubmitDisabled() {
+ return (
+ this.aiGenerating ||
+ !this.aiQuestions.every((question, index) => {
+ const answer = this.#aiClarificationAnswer(question, index);
+ return answer.selected.length || answer.custom.trim();
+ })
+ );
+ }
+
+ @action
+ aiQuestionText(question) {
+ if (typeof question === "string") {
+ return question;
+ }
+
+ return question?.question || question?.text || question?.label || "";
+ }
+
+ @action
+ aiQuestionOptions(question) {
+ if (!question || typeof question === "string") {
+ return [];
+ }
+
+ return question.options || [];
+ }
+
+ @action
+ aiQuestionHasOptions(question) {
+ return this.aiQuestionOptions(question).length > 0;
+ }
+
+ @action
+ aiQuestionMultiSelect(question) {
+ return Boolean(question?.multi_select || question?.multiSelect);
+ }
+
+ @action
+ aiQuestionCustomAllowed(question) {
+ return question?.custom_allowed ?? question?.customAllowed ?? true;
+ }
+
+ @action
+ aiClarificationOptionLabel(option) {
+ return typeof option === "string"
+ ? option
+ : option?.label || option?.value || "";
+ }
+
+ @action
+ aiClarificationOptionDescription(option) {
+ return typeof option === "string" ? "" : option?.description || "";
+ }
+
+ @action
+ aiClarificationOptionSelected(question, index, option) {
+ return this.#aiClarificationAnswer(question, index).selected.includes(
+ this.aiClarificationOptionLabel(option)
+ );
+ }
+
+ @action
+ aiClarificationCustomValue(question, index) {
+ return this.#aiClarificationAnswer(question, index).custom;
+ }
+
+ get aiCodePreviews() {
+ return (this.aiProposal?.operations || [])
+ .map((operation, index) =>
+ this.#codePreviewForOperation(operation, index)
+ )
+ .filter(Boolean);
+ }
+
+ get aiCreatedAgentResources() {
+ const resources = this.aiProposal?.created_resources || [];
+ const resourcesByClientId = new Map(
+ resources
+ .filter(
+ (resource) => resource?.type === "ai_agent" && resource.client_id
+ )
+ .map((resource) => [resource.client_id, resource])
+ );
+
+ return (this.aiProposal?.operations || [])
+ .filter((operation) => operation?.op === "create_ai_agent")
+ .map((operation, index) => {
+ const agent = operation.agent || operation.ai_agent || {};
+ const resource = resourcesByClientId.get(operation.client_id) || {};
+ const name = resource.name || agent.name;
+
+ if (!name) {
+ return null;
+ }
+
+ return {
+ key: `${operation.client_id || index}-${name}`,
+ name,
+ description: resource.description || agent.description,
+ systemPrompt: resource.system_prompt || agent.system_prompt,
+ };
+ })
+ .filter(Boolean);
+ }
+
+ get aiShowingProgress() {
+ return this.aiGenerating && this.aiProgressEvents.length > 0;
+ }
+
+ aiProgressMessage(event) {
+ return (
+ event.message || i18n(`discourse_workflows.ai.progress.${event.stage}`)
+ );
+ }
+
+ #codePreviewForOperation(operation, index) {
+ if (
+ operation?.op === "add_node" &&
+ operation.node?.type === "action:code"
+ ) {
+ return this.#buildCodePreview(
+ index,
+ operation.node.name,
+ operation.node.parameters || {}
+ );
+ }
+
+ if (
+ operation?.op === "update_node_parameters" &&
+ Object.prototype.hasOwnProperty.call(operation.parameters || {}, "code")
+ ) {
+ return this.#buildCodePreview(
+ index,
+ operation.node_name || operation.node_id,
+ operation.parameters || {}
+ );
+ }
+ }
+
+ #buildCodePreview(operationIndex, nodeName, parameters) {
+ return {
+ key: `${operationIndex}-${nodeName || "code"}`,
+ nodeName: nodeName || i18n("discourse_workflows.ai.code_node"),
+ mode: parameters.mode || "runOnceForAllItems",
+ code: parameters.code || "",
+ validation: this.#scriptValidationFor(operationIndex, nodeName),
+ };
+ }
+
+ #scriptValidationFor(operationIndex, nodeName) {
+ return (this.aiProposal?.script_validations || []).find((validation) => {
+ const validationOperationIndex =
+ validation.operation_index ?? validation.operationIndex;
+ const validationNodeName = validation.node_name ?? validation.nodeName;
+ return (
+ validationOperationIndex === operationIndex ||
+ (nodeName && validationNodeName === nodeName)
+ );
+ });
+ }
+
+ #ajaxErrorMessage(error) {
+ const status = error?.jqXHR?.status ?? error?.status;
+ if (status >= 500) {
+ return i18n("discourse_workflows.ai.unexpected_error");
+ }
+
+ return (
+ error?.jqXHR?.responseJSON?.errors?.join("\n") ||
+ error?.jqXHR?.responseJSON?.error ||
+ error?.jqXHR?.responseText ||
+ i18n("discourse_workflows.ai.unexpected_error")
+ );
+ }
+
+ #aiClarificationKey(question, index) {
+ return (
+ question?.id ||
+ question?.key ||
+ this.aiQuestionText(question) ||
+ index
+ )
+ .toString()
+ .trim();
+ }
+
+ #aiClarificationAnswer(question, index) {
+ const key = this.#aiClarificationKey(question, index);
+ const answer = this.aiClarificationAnswers[key] || {};
+
+ return {
+ selected: answer.selected || [],
+ custom: answer.custom || "",
+ };
+ }
+
+ #setAiClarificationAnswer(question, index, answer) {
+ this.aiClarificationAnswers = {
+ ...this.aiClarificationAnswers,
+ [this.#aiClarificationKey(question, index)]: answer,
+ };
+ }
+
+ #aiClarificationPayload() {
+ return {
+ type: "workflow_ask_questions_result",
+ answers: this.aiQuestions.map((question, index) => {
+ const answer = this.#aiClarificationAnswer(question, index);
+
+ return {
+ id: this.#aiClarificationKey(question, index),
+ question: this.aiQuestionText(question),
+ selected_options: answer.selected,
+ custom_answer: answer.custom.trim(),
+ };
+ }),
+ };
+ }
+
+ #aiClarificationMessage() {
+ return JSON.stringify(this.#aiClarificationPayload());
+ }
+
+ async #submitAiMessage(message) {
+ this.unsubscribeFromAiAuthoring();
+ this.aiGenerating = true;
+ this.aiProgressEvents = [
+ {
+ status: "progress",
+ stage: "queued",
+ message: i18n("discourse_workflows.ai.progress.queued"),
+ },
+ ];
+ this.aiResponse = null;
+ this.aiClarificationAnswers = {};
+ this.aiClarificationQuestionIndex = 0;
+ this.aiError = null;
+
+ try {
+ const response = await ajax(
+ `/admin/plugins/discourse-workflows/workflows/${this.args.workflowId}/ai/author.json`,
+ {
+ type: "POST",
+ data: {
+ session_id: this.aiSessionId || undefined,
+ message,
+ mode: "edit",
+ },
+ }
+ );
+
+ this.aiSessionId = response.session_id;
+ this.aiGenerationId = response.generation_id;
+ this.#subscribeToAiAuthoring(response.generation_id);
+ } catch (error) {
+ this.aiGenerating = false;
+ this.aiProgressEvents = [];
+ this.aiError = this.#ajaxErrorMessage(error);
+ }
+ }
+
+ @action
+ updateAiPrompt(event) {
+ this.aiPrompt = event.target.value;
+ }
+
+ @action
+ returnToAiPrompt() {
+ this.unsubscribeFromAiAuthoring();
+ this.aiGenerating = false;
+ this.aiProgressEvents = [];
+ this.aiResponse = null;
+ this.aiSessionId = null;
+ this.aiGenerationId = null;
+ this.aiClarificationAnswers = {};
+ this.aiClarificationQuestionIndex = 0;
+ this.aiError = null;
+ }
+
+ @action
+ async submitAiPrompt() {
+ if (this.aiSubmitDisabled) {
+ return;
+ }
+
+ await this.#submitAiMessage(this.aiPrompt.trim());
+ }
+
+ @action
+ selectAiClarificationOption(question, index, option) {
+ const label = this.aiClarificationOptionLabel(option);
+ if (!label) {
+ return;
+ }
+
+ const answer = this.#aiClarificationAnswer(question, index);
+ let selected;
+
+ if (this.aiQuestionMultiSelect(question)) {
+ selected = answer.selected.includes(label)
+ ? answer.selected.filter((value) => value !== label)
+ : [...answer.selected, label];
+ } else {
+ selected = [label];
+ }
+
+ this.#setAiClarificationAnswer(question, index, {
+ ...answer,
+ selected,
+ });
+ }
+
+ @action
+ updateAiClarificationCustom(question, index, event) {
+ const answer = this.#aiClarificationAnswer(question, index);
+
+ this.#setAiClarificationAnswer(question, index, {
+ ...answer,
+ custom: event.target.value,
+ });
+ }
+
+ @action
+ previousAiClarificationQuestion() {
+ if (this.aiGenerating) {
+ return;
+ }
+
+ this.aiClarificationQuestionIndex = Math.max(
+ this.aiCurrentQuestionIndex - 1,
+ 0
+ );
+ }
+
+ @action
+ async continueAiClarificationQuestion() {
+ if (this.aiClarificationCurrentQuestionDisabled) {
+ return;
+ }
+
+ if (this.aiLastClarificationQuestion) {
+ await this.submitAiClarification();
+ return;
+ }
+
+ this.aiClarificationQuestionIndex = this.aiCurrentQuestionIndex + 1;
+ }
+
+ @action
+ async submitAiClarification() {
+ if (this.aiClarificationSubmitDisabled) {
+ return;
+ }
+
+ await this.#submitAiMessage(this.#aiClarificationMessage());
+ }
+
+ @action
+ async applyAiProposal() {
+ if (!this.aiSessionId || !this.aiProposal) {
+ return;
+ }
+
+ try {
+ const response = await ajax(
+ `/admin/plugins/discourse-workflows/workflows/${this.args.workflowId}/ai/apply.json`,
+ {
+ type: "POST",
+ data: {
+ session_id: this.aiSessionId,
+ },
+ }
+ );
+ this.args.onApply?.(response.workflow);
+ this.returnToAiPrompt();
+ this.aiPrompt = "";
+ this.args.onClose?.();
+ this.toasts.success({
+ data: { message: i18n("discourse_workflows.ai.applied") },
+ });
+ } catch (error) {
+ this.aiError = this.#ajaxErrorMessage(error);
+ }
+ }
+
+ #subscribeToAiAuthoring(generationId) {
+ const channel = `/discourse-workflows/ai-authoring/${generationId}`;
+ const handler = (message) => {
+ if (message.generation_id !== generationId) {
+ return;
+ }
+
+ if (message.status === "progress") {
+ this.aiProgressEvents = [...this.aiProgressEvents, message];
+ return;
+ }
+
+ this.aiGenerating = false;
+ this.aiProgressEvents = [];
+ this.aiResponse = message;
+ if (message.status === "needs_clarification") {
+ this.aiClarificationAnswers = {};
+ this.aiClarificationQuestionIndex = 0;
+ }
+ this.aiError = message.status === "error" ? message.error : null;
+ this.unsubscribeFromAiAuthoring();
+ };
+
+ this.aiAuthoringChannel = channel;
+ this.aiAuthoringHandler = handler;
+ this.messageBus.subscribe(channel, handler, -1);
+ }
+
+ unsubscribeFromAiAuthoring() {
+ if (this.aiAuthoringChannel && this.aiAuthoringHandler) {
+ this.messageBus.unsubscribe(
+ this.aiAuthoringChannel,
+ this.aiAuthoringHandler
+ );
+ }
+ this.aiAuthoringChannel = null;
+ this.aiAuthoringHandler = null;
+ }
+
+ <template>
+ {{#if @open}}
+ <div class="workflows-canvas__ai-panel-shell">
+ {{#if this.aiShowingProgress}}
+ <aside
+ class="workflows-canvas__ai-progress-panel"
+ aria-label={{i18n "discourse_workflows.ai.progress_title"}}
+ >
+ <h4 class="workflows-canvas__ai-progress-title">
+ {{i18n "discourse_workflows.ai.progress_title"}}
+ </h4>
+ <ol
+ class={{dConcatClass
+ "workflows-canvas__ai-progress"
+ (if this.aiGenerating "is-working")
+ }}
+ >
+ {{#each this.aiProgressEvents as |event|}}
+ <li>
+ <span class="workflows-canvas__ai-progress-marker"></span>
+ <span>{{this.aiProgressMessage event}}</span>
+ </li>
+ {{/each}}
+ </ol>
+ </aside>
+ {{/if}}
+
+ <aside
+ class={{dConcatClass
+ "workflows-canvas__ai-panel"
+ (if this.aiShowingProposalReview "is-reviewing")
+ }}
+ role="dialog"
+ aria-labelledby="workflow-ai-panel-title"
+ >
+ <div class="workflows-canvas__ai-panel-header">
+ <div class="workflows-canvas__ai-title-row">
+ <div class="workflows-canvas__ai-title">
+ <h3 id="workflow-ai-panel-title">
+ {{i18n "discourse_workflows.ai.title"}}
+ </h3>
+ <span
+ class={{dConcatClass
+ "workflows-canvas__ai-status"
+ this.aiStatusClass
+ }}
+ >
+ {{this.aiStatusLabel}}
+ </span>
+
+ </div>
+ <p>{{i18n "discourse_workflows.ai.subtitle"}}</p>
+ </div>
+ <DButton
+ @action={{@onClose}}
+ @icon="xmark"
+ @title="discourse_workflows.ai.close"
+ class="btn-transparent workflows-canvas__ai-close"
+ />
+ </div>
+
+ {{#if this.aiShowingClarification}}
+ <div class="workflows-canvas__ai-clarification">
+ <div class="workflows-canvas__ai-clarification-header">
+ <h4>{{i18n "discourse_workflows.ai.questions"}}</h4>
+ <p>{{i18n "discourse_workflows.ai.clarification_intro"}}</p>
+ <div class="workflows-canvas__ai-question-progress">
+ <span>
+ {{i18n
+ "discourse_workflows.ai.question_progress"
+ current=this.aiCurrentQuestionNumber
+ total=this.aiQuestions.length
+ }}
+ </span>
+ <progress
+ class="workflows-canvas__ai-question-progress-bar"
+ value={{this.aiCurrentQuestionNumber}}
+ max={{this.aiQuestions.length}}
+ ></progress>
+ </div>
+ </div>
+
+ {{#let
+ this.aiCurrentQuestion this.aiCurrentQuestionIndex
+ as |question index|
+ }}
+ <section class="workflows-canvas__ai-question-card">
+ <h5>{{this.aiQuestionText question}}</h5>
+
+ {{#if (this.aiQuestionHasOptions question)}}
+ <div class="workflows-canvas__ai-question-options">
+ {{#each (this.aiQuestionOptions question) as |option|}}
+ <button
+ type="button"
+ aria-pressed={{this.aiClarificationOptionSelected
+ question
+ index
+ option
+ }}
+ class={{dConcatClass
+ "workflows-canvas__ai-question-option"
+ (if
+ (this.aiClarificationOptionSelected
+ question index option
+ )
+ "is-selected"
+ )
+ }}
+ {{on
+ "click"
+ (fn
+ this.selectAiClarificationOption
+ question
+ index
+ option
+ )
+ }}
+ >
+ <span>{{this.aiClarificationOptionLabel
+ option
+ }}</span>
+ {{#if (this.aiClarificationOptionDescription option)}}
+ <small>{{this.aiClarificationOptionDescription
+ option
+ }}</small>
+ {{/if}}
+ </button>
+ {{/each}}
+ </div>
+ {{/if}}
+
+ {{#if (this.aiQuestionCustomAllowed question)}}
+ <label class="workflows-canvas__ai-custom-answer">
+ <span>{{i18n
+ "discourse_workflows.ai.custom_answer"
+ }}</span>
+ <DTextarea
+ @value={{this.aiClarificationCustomValue
+ question
+ index
+ }}
+ {{on
+ "input"
+ (fn this.updateAiClarificationCustom question index)
+ }}
+ placeholder={{i18n
+ "discourse_workflows.ai.custom_answer_placeholder"
+ }}
+ disabled={{this.aiGenerating}}
+ class="workflows-canvas__ai-custom-answer-input"
+ />
+ </label>
+ {{/if}}
+ </section>
+ {{/let}}
+
+ <div class="workflows-canvas__ai-panel-actions">
+ <DButton
+ @action={{this.returnToAiPrompt}}
+ @translatedLabel={{i18n "discourse_workflows.ai.start_over"}}
+ @disabled={{this.aiGenerating}}
+ class="btn-default workflows-canvas__ai-start-over-btn"
+ />
+
+ {{#unless this.aiFirstClarificationQuestion}}
+ <DButton
+ @action={{this.previousAiClarificationQuestion}}
+ @icon="arrow-left"
+ @translatedLabel={{i18n
+ "discourse_workflows.ai.previous_question"
+ }}
+ @disabled={{this.aiGenerating}}
+ class="btn-default"
+ />
+ {{/unless}}
+
+ <DButton
+ @action={{this.continueAiClarificationQuestion}}
+ @translatedLabel={{this.aiClarificationContinueLabel}}
+ @isLoading={{this.aiGenerating}}
+ @disabled={{this.aiClarificationCurrentQuestionDisabled}}
+ class="btn-primary"
+ />
+ </div>
+ </div>
+ {{else if this.aiShowingProposalReview}}
+ <div class="workflows-canvas__ai-review-step">
+ <div class="workflows-canvas__ai-review-actions">
+ <DButton
+ @action={{this.returnToAiPrompt}}
+ @icon="arrow-left"
+ @translatedLabel={{i18n
+ "discourse_workflows.ai.back_to_prompt"
+ }}
+ class="btn-transparent"
+ />
+ </div>
+
+ <div class="workflows-canvas__ai-proposal">
+ <h4>{{this.aiProposal.title}}</h4>
+ <p>{{this.aiProposal.summary}}</p>
+
+ {{#if this.aiCreatedAgentResources.length}}
+ <section class="workflows-canvas__ai-created-agents">
+ <h5>{{i18n "discourse_workflows.ai.created_agents"}}</h5>
+ <ul>
+ {{#each this.aiCreatedAgentResources as |agent|}}
+ <li class="workflows-canvas__ai-created-agent">
+ <strong>{{agent.name}}</strong>
+ {{#if agent.description}}
+ <p>{{agent.description}}</p>
+ {{/if}}
+ {{#if agent.systemPrompt}}
+ <details>
+ <summary>{{i18n
+ "discourse_workflows.ai.created_agent_system_prompt"
+ }}</summary>
+ <pre><code>{{agent.systemPrompt}}</code></pre>
+ </details>
+ {{/if}}
+ </li>
+ {{/each}}
+ </ul>
+ </section>
+ {{/if}}
+
+ {{#if this.aiCodePreviews.length}}
+ <div class="workflows-canvas__ai-code-previews">
+ <h5>{{i18n "discourse_workflows.ai.script_preview"}}</h5>
+ {{#each this.aiCodePreviews as |preview|}}
+ <section class="workflows-canvas__ai-code-preview">
+ <div class="workflows-canvas__ai-code-preview-header">
+ <span>{{preview.nodeName}}</span>
+ <span>{{i18n
+ "discourse_workflows.ai.script_mode"
+ mode=preview.mode
+ }}</span>
+ </div>
+ <pre><code>{{preview.code}}</code></pre>
+ {{#if preview.validation}}
+ {{#if preview.validation.valid}}
+ <p
+ class="workflows-canvas__ai-validation workflows-canvas__ai-validation--passed"
+ >
+ {{i18n
+ "discourse_workflows.ai.script_validation_passed"
+ }}
+ </p>
+ {{else}}
+ <div
+ class="workflows-canvas__ai-validation workflows-canvas__ai-validation--failed"
+ >
+ <p>{{i18n
+ "discourse_workflows.ai.script_validation_failed"
+ }}</p>
+ <ul>
+ {{#each preview.validation.errors as |error|}}
+ <li>{{error}}</li>
+ {{/each}}
+ </ul>
+ </div>
+ {{/if}}
+ {{/if}}
+ </section>
+ {{/each}}
+ </div>
+ {{/if}}
+
+ {{#if this.aiProposal.risks}}
+ <h5>{{i18n "discourse_workflows.ai.risks"}}</h5>
+ <ul>
+ {{#each this.aiProposal.risks as |risk|}}
+ <li>{{risk}}</li>
+ {{/each}}
+ </ul>
+ {{/if}}
+ </div>
+
+ <div class="workflows-canvas__ai-review-footer">
+ <DButton
+ @action={{this.applyAiProposal}}
+ @translatedLabel={{i18n "discourse_workflows.ai.apply"}}
+ class="btn-primary"
+ />
+ </div>
+ </div>
+ {{else}}
+ <div class="workflows-canvas__ai-prompt-wrap">
+ <label for="workflow-ai-prompt">
+ {{i18n "discourse_workflows.ai.prompt_label"}}
+ </label>
+ <DTextarea
+ id="workflow-ai-prompt"
+ @value={{this.aiPrompt}}
+ {{on "input" this.updateAiPrompt}}
+ placeholder={{i18n "discourse_workflows.ai.prompt_placeholder"}}
+ disabled={{this.aiGenerating}}
+ class="workflows-canvas__ai-prompt"
+ />
+ </div>
+
+ <div class="workflows-canvas__ai-panel-actions">
+ {{#if this.aiCanReturnToPrompt}}
+ <DButton
+ @action={{this.returnToAiPrompt}}
+ @translatedLabel={{i18n "discourse_workflows.ai.start_over"}}
+ @disabled={{this.aiGenerating}}
+ class="btn-default workflows-canvas__ai-start-over-btn"
+ />
+ {{/if}}
+
+ <DButton
+ @action={{this.submitAiPrompt}}
+ @translatedLabel={{i18n "discourse_workflows.ai.generate"}}
+ @isLoading={{this.aiGenerating}}
+ @disabled={{this.aiSubmitDisabled}}
+ class="btn-primary"
+ />
+ </div>
+ {{/if}}
+
+ {{#if this.aiResponseError}}
+ <div
+ class="workflows-canvas__ai-response workflows-canvas__ai-response--error"
+ >
+ <p>{{this.aiResponseError}}</p>
+ </div>
+ {{/if}}
+
+ {{#if this.aiResponseMessage}}
+ <div class="workflows-canvas__ai-response">
+ <p>{{this.aiResponseMessage}}</p>
+ </div>
+ {{/if}}
+
+ {{#if this.aiNeedsClarificationFallback}}
+ <div class="workflows-canvas__ai-response">
+ {{i18n "discourse_workflows.ai.needs_clarification"}}
+ </div>
+ {{/if}}
+ </aside>
+ </div>
+ {{/if}}
+ </template>
+}
diff --git a/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/canvas/index.gjs b/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/canvas/index.gjs
index 9c4115ece7b..3da5ada7cea 100644
--- a/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/canvas/index.gjs
+++ b/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/canvas/index.gjs
@@ -14,6 +14,7 @@ import DButton from "discourse/ui-kit/d-button";
import DDropdownMenu from "discourse/ui-kit/d-dropdown-menu";
import dIcon from "discourse/ui-kit/helpers/d-icon";
import { i18n } from "discourse-i18n";
+import BuildWithAiModal from "../build-with-ai-modal";
import CanvasContextMenu from "./canvas-context-menu";
import { exportWorkflowToFile, parseWorkflowImport } from "./canvas-file-io";
import { setupCanvasKeyboard } from "./canvas-keyboard";
@@ -36,6 +37,7 @@ export default class WorkflowCanvas extends Component {
@service router;
@service workflowsNodeTypes;
@service toasts;
+ @service siteSettings;
@tracked isLoading = true;
@tracked rete = null;
@@ -43,6 +45,7 @@ export default class WorkflowCanvas extends Component {
@tracked workflowPublishedOverride = null;
@tracked hasUnpublishedChangesOverride = null;
@tracked selectionVersion = 0;
+ @tracked aiPanelOpen = false;
copiedEntities = { nodes: [], stickyNotes: [] };
pasteOffset = 0;
isFirstSync = true;
@@ -98,6 +101,23 @@ export default class WorkflowCanvas extends Component {
return this.workflowPublished && this.hasUnpublishedChanges;
}
+ get aiAuthoringAvailable() {
+ return (
+ this.siteSettings.discourse_workflows_ai_authoring_enabled &&
+ this.args.workflowId
+ );
+ }
+
+ @action
+ openAiPanel() {
+ this.aiPanelOpen = true;
+ }
+
+ @action
+ closeAiPanel() {
+ this.aiPanelOpen = false;
+ }
+
@action
isStickyNoteSelected(clientId) {
this.selectionVersion;
@@ -809,114 +829,137 @@ export default class WorkflowCanvas extends Component {
/>
{{#if @onOpenNodePanel}}
- {{#if this.showUnpublishedChangesMessage}}
- <div class="workflows-canvas__publish-status">
- <span class="workflows-canvas__publish-status-body" role="status">
- <span class="workflows-canvas__publish-status-icon">
- {{dIcon "triangle-exclamation"}}
- </span>
- <span class="workflows-canvas__publish-status-text">
- <span class="workflows-canvas__publish-status-title">
- {{i18n "discourse_workflows.unpublished_changes_message"}}
+ <div class="workflows-canvas__top-bar">
+ {{#if this.showUnpublishedChangesMessage}}
+ <div class="workflows-canvas__publish-status">
+ <span
+ class="workflows-canvas__publish-status-body"
+ role="status"
+ >
+ <span class="workflows-canvas__publish-status-icon">
+ {{dIcon "triangle-exclamation"}}
</span>
- <span class="workflows-canvas__publish-status-detail">
- {{i18n
- "discourse_workflows.unpublished_changes_message_detail"
- }}
+ <span class="workflows-canvas__publish-status-text">
+ <span class="workflows-canvas__publish-status-title">
+ {{i18n "discourse_workflows.unpublished_changes_message"}}
+ </span>
+ <span class="workflows-canvas__publish-status-detail">
+ {{i18n
+ "discourse_workflows.unpublished_changes_message_detail"
+ }}
+ </span>
</span>
</span>
- </span>
- <span class="workflows-canvas__publish-status-actions">
+ <span class="workflows-canvas__publish-status-actions">
+ <DButton
+ @action={{this.publishWorkflow}}
+ @translatedLabel={{i18n "discourse_workflows.publish"}}
+ class="btn-primary btn-small workflows-canvas__publish-status-btn"
+ />
+
+ {{#if this.showDiscardChangesButton}}
+ <DButton
+ @action={{this.discardWorkflow}}
+ @translatedLabel={{i18n
+ "discourse_workflows.discard_changes"
+ }}
+ class="btn-default btn-small workflows-canvas__publish-status-btn"
+ />
+ {{/if}}
+ </span>
+ </div>
+ {{/if}}
+
+ <div class="workflows-canvas__toolbar-top-right">
+ {{#if this.showToolbarPublishButton}}
<DButton
@action={{this.publishWorkflow}}
@translatedLabel={{i18n "discourse_workflows.publish"}}
- class="btn-primary btn-small workflows-canvas__publish-status-btn"
+ class="btn-primary workflows-canvas__publish-btn"
/>
+ {{/if}}
- {{#if this.showDiscardChangesButton}}
- <DButton
- @action={{this.discardWorkflow}}
- @translatedLabel={{i18n
- "discourse_workflows.discard_changes"
- }}
- class="btn-default btn-small workflows-canvas__publish-status-btn"
- />
- {{/if}}
- </span>
- </div>
- {{/if}}
+ {{#if this.aiAuthoringAvailable}}
+ <DButton
+ @action={{this.openAiPanel}}
+ @icon="discourse-sparkles"
+ @translatedLabel={{i18n "discourse_workflows.ai.button"}}
+ class="btn-default workflows-canvas__ai-btn"
+ />
+ {{/if}}
- <div class="workflows-canvas__toolbar-top-right">
- {{#if this.showToolbarPublishButton}}
<DButton
- @action={{this.publishWorkflow}}
- @translatedLabel={{i18n "discourse_workflows.publish"}}
- class="btn-primary workflows-canvas__publish-btn"
+ @action={{this.openNodePanelAtCenter}}
+ @icon="plus"
+ class="btn-default workflows-canvas__add-node-btn"
/>
- {{/if}}
-
- <DButton
- @action={{this.openNodePanelAtCenter}}
- @icon="plus"
- class="btn-default workflows-canvas__add-node-btn"
- />
- <DMenu
- @identifier="workflows-canvas-menu"
- @icon="ellipsis-vertical"
- class="btn-default workflows-canvas__menu-btn"
- >
- <:content as |args|>
- <DDropdownMenu as |dropdown|>
- {{#if this.workflowPublished}}
+ <DMenu
+ @identifier="workflows-canvas-menu"
+ @icon="ellipsis-vertical"
+ class="btn-default workflows-canvas__menu-btn"
+ >
+ <:content as |args|>
+ <DDropdownMenu as |dropdown|>
+ {{#if this.workflowPublished}}
+ <dropdown.item>
+ <DButton
+ @action={{fn this.unpublishWorkflow args.close}}
+ @translatedLabel={{i18n
+ "discourse_workflows.unpublish"
+ }}
+ class="btn-transparent"
+ />
+ </dropdown.item>
+ {{/if}}
<dropdown.item>
<DButton
- @action={{fn this.unpublishWorkflow args.close}}
+ @action={{fn this.addStickyNoteAtCenter args.close}}
+ @icon="note-sticky"
@translatedLabel={{i18n
- "discourse_workflows.unpublish"
+ "discourse_workflows.sticky_note.add"
}}
class="btn-transparent"
/>
</dropdown.item>
- {{/if}}
- <dropdown.item>
- <DButton
- @action={{fn this.addStickyNoteAtCenter args.close}}
- @icon="note-sticky"
- @translatedLabel={{i18n
- "discourse_workflows.sticky_note.add"
- }}
- class="btn-transparent"
- />
- </dropdown.item>
- <dropdown.item>
- <DButton
- @action={{fn this.exportWorkflow args.close}}
- @icon="download"
- @translatedLabel={{i18n
- "discourse_workflows.canvas.export_nodes"
- }}
- @disabled={{this.showEmptyState}}
- class="btn-transparent"
- />
- </dropdown.item>
- <dropdown.item>
- <DButton
- @action={{fn this.openImportDialog args.close}}
- @icon="upload"
- @translatedLabel={{i18n
- "discourse_workflows.canvas.import_nodes"
- }}
- class="btn-transparent"
- />
- </dropdown.item>
- </DDropdownMenu>
- </:content>
- </DMenu>
+ <dropdown.item>
+ <DButton
+ @action={{fn this.exportWorkflow args.close}}
+ @icon="download"
+ @translatedLabel={{i18n
+ "discourse_workflows.canvas.export_nodes"
+ }}
+ @disabled={{this.showEmptyState}}
+ class="btn-transparent"
+ />
+ </dropdown.item>
+ <dropdown.item>
+ <DButton
+ @action={{fn this.openImportDialog args.close}}
+ @icon="upload"
+ @translatedLabel={{i18n
+ "discourse_workflows.canvas.import_nodes"
+ }}
+ class="btn-transparent"
+ />
+ </dropdown.item>
+ </DDropdownMenu>
+ </:content>
+ </DMenu>
+ </div>
</div>
{{/if}}
+ {{#if this.aiAuthoringAvailable}}
+ <BuildWithAiModal
+ @open={{this.aiPanelOpen}}
+ @workflowId={{@workflowId}}
+ @onApply={{@onWorkflowUpdated}}
+ @onClose={{this.closeAiPanel}}
+ />
+ {{/if}}
+
<CanvasContextMenu
@canvasElement={{this.canvasElement}}
@containerElement={{this.containerElement}}
diff --git a/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/canvas/workflow-node.gjs b/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/canvas/workflow-node.gjs
index 8c81a0f1039..6f64e584f3d 100644
--- a/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/canvas/workflow-node.gjs
+++ b/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/canvas/workflow-node.gjs
@@ -5,6 +5,7 @@ import { action } from "@ember/object";
import didInsert from "@ember/render-modifiers/modifiers/did-insert";
import { service } from "@ember/service";
import { trustHTML } from "@ember/template";
+import { modifier } from "ember-modifier";
import DTooltip from "discourse/float-kit/components/d-tooltip";
import { eq } from "discourse/truth-helpers";
import dConcatClass from "discourse/ui-kit/helpers/d-concat-class";
@@ -33,6 +34,22 @@ function resolveType(workflowsNodeTypes, node) {
return resolveNodeTypeVersion(nodeType, node.typeVersion);
}
+const highlightOnInsert = modifier((element) => {
+ if (window.matchMedia?.("(prefers-reduced-motion: reduce)").matches) {
+ return;
+ }
+
+ const removeHighlight = () => element.classList.remove("is-highlighted");
+
+ element.classList.add("is-highlighted");
+ element.addEventListener("animationend", removeHighlight, { once: true });
+
+ return () => {
+ element.removeEventListener("animationend", removeHighlight);
+ removeHighlight();
+ };
+});
+
export function shouldShowManualTrigger(node) {
return Boolean(node?.type?.startsWith("trigger:"));
}
@@ -210,6 +227,7 @@ export default class WorkflowNode extends Component {
style={{this.dimensionsStyle}}
data-client-id={{this.data.clientId}}
data-unavailable={{if this.isUnavailable "true" "false"}}
+ {{highlightOnInsert}}
>
{{#if @node.selected}}
{{#if this.runScopeLabel}}
diff --git a/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/configurators/actor-control.gjs b/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/configurators/actor-control.gjs
index 86875aecde3..2be40e3fa77 100644
--- a/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/configurators/actor-control.gjs
+++ b/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/configurators/actor-control.gjs
@@ -57,6 +57,7 @@ export default class ActorControl extends Component {
<template>
<ExpressionWrapper
@field={{@field}}
+ @schema={{@schema}}
@supportsExpression={{@supportsExpression}}
@placeholder={{@placeholder}}
@dynamicValueHint={{@dynamicValueHint}}
diff --git a/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/configurators/boolean-control.gjs b/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/configurators/boolean-control.gjs
index 2a6afd78643..fc447c8f659 100644
--- a/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/configurators/boolean-control.gjs
+++ b/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/configurators/boolean-control.gjs
@@ -116,6 +116,7 @@ export default class BooleanControl extends Component {
<ExpressionWrapper
@expressionMode={{true}}
@field={{field}}
+ @schema={{@schema}}
@placeholder={{this.placeholder}}
@supportsExpression={{this.supportsExpression}}
@dynamicValueHint={{@dynamicValueHint}}
diff --git a/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/configurators/category-control.gjs b/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/configurators/category-control.gjs
index 3e6f35d5a6f..367d126e1ee 100644
--- a/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/configurators/category-control.gjs
+++ b/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/configurators/category-control.gjs
@@ -17,6 +17,7 @@ export default class CategoryControl extends Component {
<template>
<ExpressionWrapper
@field={{@field}}
+ @schema={{@schema}}
@supportsExpression={{@supportsExpression}}
@placeholder={{@placeholder}}
@dynamicValueHint={{@dynamicValueHint}}
diff --git a/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/configurators/combo-box.gjs b/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/configurators/combo-box.gjs
index 299191d0721..412c73aaf99 100644
--- a/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/configurators/combo-box.gjs
+++ b/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/configurators/combo-box.gjs
@@ -220,13 +220,17 @@ export default class ComboBoxField extends Component {
const selectedOption =
selectedItem ||
- this.options.find((option) => String(option.id) === String(value));
+ this.options.find((option) => String(option.id) === String(value)) ||
+ null;
for (const [fieldName, propertyName] of Object.entries(
this.setFromOption
)) {
- const selectedOptionValue = selectedOption?.original?.[propertyName];
- this.args.formApi?.set(fieldName, selectedOptionValue ?? "");
+ const selectedOptionValue =
+ selectedOption?.original?.[propertyName] ??
+ selectedOption?.[propertyName] ??
+ "";
+ this.args.formApi?.set(fieldName, selectedOptionValue);
}
const schema = this.args.nodeDefinition?.properties || {};
@@ -250,6 +254,7 @@ export default class ComboBoxField extends Component {
<template>
<ExpressionWrapper
@field={{@field}}
+ @schema={{@schema}}
@supportsExpression={{@supportsExpression}}
@placeholder={{@placeholder}}
@dynamicValueHint={{@dynamicValueHint}}
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 96c4d4eb02f..b2c462c4a8f 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
@@ -46,6 +46,11 @@ function leafKey(fieldPath) {
}
let path = fieldPath;
+ if (typeof path === "object") {
+ path = path.value ?? path.id ?? path.label ?? "";
+ }
+ path = String(path);
+
const exprMatch = path.match(/^=\{\{\s*(.*?)\s*\}\}$/);
if (exprMatch) {
path = exprMatch[1];
diff --git a/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/configurators/credential.gjs b/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/configurators/credential.gjs
index cce1bd17180..66c66448032 100644
--- a/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/configurators/credential.gjs
+++ b/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/configurators/credential.gjs
@@ -102,6 +102,7 @@ export default class Credential extends Component {
<template>
<ExpressionWrapper
@field={{if @field @field (hash value=this.value)}}
+ @schema={{@schema}}
@supportsExpression={{@supportsExpression}}
@placeholder={{@placeholder}}
@dynamicValueHint={{@dynamicValueHint}}
diff --git a/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/configurators/data-table-column-select.gjs b/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/configurators/data-table-column-select.gjs
index 582da06c392..07f431e5c94 100644
--- a/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/configurators/data-table-column-select.gjs
+++ b/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/configurators/data-table-column-select.gjs
@@ -65,6 +65,7 @@ export default class DataTableColumnSelect extends Component {
<template>
<ExpressionWrapper
@field={{@field}}
+ @schema={{@schema}}
@supportsExpression={{@supportsExpression}}
@placeholder={{@placeholder}}
@dynamicValueHint={{@dynamicValueHint}}
diff --git a/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/configurators/data-table-select.gjs b/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/configurators/data-table-select.gjs
index 06e20b6df5a..d045fb6a8e9 100644
--- a/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/configurators/data-table-select.gjs
+++ b/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/configurators/data-table-select.gjs
@@ -18,6 +18,7 @@ export default class DataTableSelect extends ComboBoxField {
<template>
<ExpressionWrapper
@field={{@field}}
+ @schema={{@schema}}
@supportsExpression={{@supportsExpression}}
@placeholder={{@placeholder}}
@dynamicValueHint={{@dynamicValueHint}}
diff --git a/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/configurators/default-input-control.gjs b/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/configurators/default-input-control.gjs
index 61f5d65cee3..9215e16bfcf 100644
--- a/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/configurators/default-input-control.gjs
+++ b/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/configurators/default-input-control.gjs
@@ -3,6 +3,7 @@ import ExpressionWrapper from "./expression-wrapper";
<template>
<ExpressionWrapper
@field={{@field}}
+ @schema={{@schema}}
@supportsExpression={{@supportsExpression}}
@placeholder={{@placeholder}}
@dynamicValueHint={{@dynamicValueHint}}
diff --git a/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/configurators/expression-wrapper.gjs b/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/configurators/expression-wrapper.gjs
index fe4f9de074c..2536f119463 100644
--- a/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/configurators/expression-wrapper.gjs
+++ b/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/configurators/expression-wrapper.gjs
@@ -10,7 +10,10 @@ import {
resolveVariableId,
WORKFLOW_VARIABLE_MIME,
} from "../../../lib/workflows/expression-context";
-import { isExpression } from "../../../lib/workflows/property-engine";
+import {
+ fieldType,
+ isExpression,
+} from "../../../lib/workflows/property-engine";
import ExpressionInput from "./expression-input";
const MODE_ITEMS = [
@@ -26,7 +29,7 @@ const MODE_ITEMS = [
},
];
-function plainValueForModeToggle(value) {
+function plainTextValue(value) {
if (value === null || value === undefined) {
return "";
}
@@ -42,6 +45,99 @@ function plainValueForModeToggle(value) {
return String(value);
}
+function schemaType(schema) {
+ return fieldType(schema);
+}
+
+function wholeExpressionBody(value) {
+ const expressionBody = value.slice(1).trim();
+ const match = expressionBody.match(/^\{\{\s*([\s\S]*?)\s*\}\}$/);
+
+ return match?.[1]?.trim() || null;
+}
+
+function parseJsonLiteral(value) {
+ try {
+ return JSON.parse(value);
+ } catch {
+ return undefined;
+ }
+}
+
+function splitListValue(value) {
+ return String(value)
+ .split(",")
+ .map((entry) => entry.trim())
+ .filter(Boolean);
+}
+
+function arrayLiteralValue(value) {
+ if (Array.isArray(value)) {
+ return value;
+ }
+
+ if (value === null || value === undefined || value === "") {
+ return [];
+ }
+
+ return splitListValue(value);
+}
+
+function dynamicValueForModeToggle(value, schema = {}) {
+ if (typeof value === "string" && value.startsWith("=")) {
+ return value;
+ }
+
+ if (schemaType(schema) === "array" || Array.isArray(value)) {
+ return `={{ ${JSON.stringify(arrayLiteralValue(value))} }}`;
+ }
+
+ return `=${plainTextValue(value)}`;
+}
+
+function plainArrayValueForModeToggle(expressionValue) {
+ const parsedLiteral = parseJsonLiteral(
+ wholeExpressionBody(expressionValue) || ""
+ );
+
+ if (Array.isArray(parsedLiteral)) {
+ return parsedLiteral;
+ }
+
+ if (typeof parsedLiteral === "string") {
+ return splitListValue(parsedLiteral);
+ }
+
+ const rawExpression = expressionValue.slice(1).trim();
+ if (!rawExpression.includes("{{") && !rawExpression.includes("}}")) {
+ return splitListValue(rawExpression);
+ }
+
+ return [];
+}
+
+function plainValueForModeToggle(value, schema = {}) {
+ if (!(typeof value === "string" && value.startsWith("="))) {
+ return value;
+ }
+
+ const type = schemaType(schema);
+
+ if (type === "array") {
+ return plainArrayValueForModeToggle(value);
+ }
+
+ const body = wholeExpressionBody(value);
+ if (body) {
+ const parsedLiteral = parseJsonLiteral(body);
+ if (parsedLiteral !== undefined && typeof parsedLiteral !== "object") {
+ return parsedLiteral;
+ }
+ }
+
+ return value.slice(1);
+}
+
export default class ExpressionWrapper extends Component {
@service workflowsNodeTypes;
@@ -80,15 +176,13 @@ export default class ExpressionWrapper extends Component {
return;
}
- const currentValue = plainValueForModeToggle(this.args.field.value);
-
if (wantsDynamic) {
this.args.field.set(
- currentValue.startsWith("=") ? currentValue : `=${currentValue}`
+ dynamicValueForModeToggle(this.args.field.value, this.args.schema)
);
} else {
this.args.field.set(
- currentValue.startsWith("=") ? currentValue.slice(1) : currentValue
+ plainValueForModeToggle(this.args.field.value, this.args.schema)
);
}
}
diff --git a/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/configurators/filter-query.gjs b/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/configurators/filter-query.gjs
index 0a45aa2d4e0..ce7917f7823 100644
--- a/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/configurators/filter-query.gjs
+++ b/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/configurators/filter-query.gjs
@@ -46,6 +46,7 @@ export default class FilterQuery extends Component {
<template>
<ExpressionWrapper
@field={{@field}}
+ @schema={{@schema}}
@supportsExpression={{@supportsExpression}}
@placeholder={{@placeholder}}
@dynamicValueHint={{@dynamicValueHint}}
diff --git a/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/configurators/group-select.gjs b/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/configurators/group-select.gjs
index af691748a33..00be735e4ef 100644
--- a/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/configurators/group-select.gjs
+++ b/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/configurators/group-select.gjs
@@ -1,46 +1,130 @@
+import { tracked } from "@glimmer/tracking";
import { hash } from "@ember/helper";
import { action } from "@ember/object";
import { service } from "@ember/service";
+import { makeArray } from "discourse/lib/helpers";
+import GroupChooser from "discourse/select-kit/components/group-chooser";
import DButton from "discourse/ui-kit/d-button";
import ComboBoxField, { DynamicOptionsComboBox } from "./combo-box";
import ExpressionWrapper from "./expression-wrapper";
+export class DynamicOptionsGroupChooser extends GroupChooser {
+ search(filter) {
+ if (this.loadOptions) {
+ return Promise.resolve(this.loadOptions(filter)).then((options) => {
+ const selectedValues = new Set(
+ makeArray(this.selectedContent).map((item) =>
+ String(this.getValue(item))
+ )
+ );
+
+ return options.filter(
+ (option) => !selectedValues.has(String(this.getValue(option)))
+ );
+ });
+ }
+
+ return super.search(filter);
+ }
+}
+
+function groupValuesFromValue(value) {
+ return Array.isArray(value) ? value : [];
+}
+
export default class GroupSelect extends ComboBoxField {
@service router;
+ @tracked selectedOptions = [];
+
+ get multiple() {
+ return Boolean(this.args.schema?.ui?.multiple);
+ }
+
get clearable() {
return !this.args.schema?.required;
}
+ get hasValue() {
+ if (this.multiple) {
+ return this.value.length > 0;
+ }
+
+ const value = this.args.field.value;
+ return value !== null && value !== undefined && value !== "";
+ }
+
+ get value() {
+ return this.multiple
+ ? groupValuesFromValue(this.args.field.value)
+ : this.args.field.value;
+ }
+
+ get contentOptions() {
+ if (!this.usesRemoteOptions) {
+ return this.options;
+ }
+
+ const optionsByValue = new Map(
+ [
+ ...this.formatOptions(this.metadataOptions || []),
+ ...this.selectedOptions,
+ ].map((option) => [String(option.id), option])
+ );
+
+ return this.value.map(
+ (value) => optionsByValue.get(String(value)) || { id: value, name: value }
+ );
+ }
+
@action
manageGroups() {
this.router.transitionTo("groups");
}
+ @action
+ handleMultiChange(value, selectedOptions) {
+ this.selectedOptions = makeArray(selectedOptions);
+ this.args.field.set(value || []);
+ }
+
<template>
<ExpressionWrapper
@field={{@field}}
+ @schema={{@schema}}
@supportsExpression={{@supportsExpression}}
@placeholder={{@placeholder}}
@dynamicValueHint={{@dynamicValueHint}}
@session={{@session}}
>
<div class="workflows-property-engine__select-with-action">
- <DynamicOptionsComboBox
- @content={{this.options}}
- @loadOptions={{if this.usesRemoteOptions this.loadRemoteOptions}}
- @nameProperty="name"
- @value={{@field.value}}
- @valueProperty="id"
- @onChange={{this.handleChange}}
- @options={{hash
- filterable=this.filterable
- none=this.none
- castInteger=this.castInteger
- clearable=this.clearable
- }}
- />
- {{#unless @field.value}}
+ {{#if this.multiple}}
+ <DynamicOptionsGroupChooser
+ @content={{this.contentOptions}}
+ @loadOptions={{if this.usesRemoteOptions this.loadRemoteOptions}}
+ @nameProperty="name"
+ @value={{this.value}}
+ @valueProperty="id"
+ @onChange={{this.handleMultiChange}}
+ @options={{hash filterable=this.filterable none=this.none}}
+ />
+ {{else}}
+ <DynamicOptionsComboBox
+ @content={{this.options}}
+ @loadOptions={{if this.usesRemoteOptions this.loadRemoteOptions}}
+ @nameProperty="name"
+ @value={{@field.value}}
+ @valueProperty="id"
+ @onChange={{this.handleChange}}
+ @options={{hash
+ filterable=this.filterable
+ none=this.none
+ castInteger=this.castInteger
+ clearable=this.clearable
+ }}
+ />
+ {{/if}}
+ {{#unless this.hasValue}}
<DButton
@action={{this.manageGroups}}
@label="discourse_workflows.group.manage_groups"
diff --git a/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/configurators/icon-control.gjs b/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/configurators/icon-control.gjs
index d3a4afd2c06..589d82115bd 100644
--- a/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/configurators/icon-control.gjs
+++ b/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/configurators/icon-control.gjs
@@ -3,6 +3,7 @@ import ExpressionWrapper from "./expression-wrapper";
<template>
<ExpressionWrapper
@field={{@field}}
+ @schema={{@schema}}
@supportsExpression={{@supportsExpression}}
@placeholder={{@placeholder}}
@dynamicValueHint={{@dynamicValueHint}}
diff --git a/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/configurators/multi-combo-box.gjs b/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/configurators/multi-combo-box.gjs
index 11269250ed1..99245257374 100644
--- a/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/configurators/multi-combo-box.gjs
+++ b/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/configurators/multi-combo-box.gjs
@@ -206,6 +206,7 @@ export default class MultiComboBox extends Component {
<template>
<ExpressionWrapper
@field={{@field}}
+ @schema={{@schema}}
@supportsExpression={{@supportsExpression}}
@placeholder={{@placeholder}}
@dynamicValueHint={{@dynamicValueHint}}
diff --git a/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/configurators/select-control.gjs b/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/configurators/select-control.gjs
index 5251bc6943f..54e7cd13a95 100644
--- a/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/configurators/select-control.gjs
+++ b/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/configurators/select-control.gjs
@@ -20,6 +20,7 @@ export default class SelectControl extends Component {
<template>
<ExpressionWrapper
@field={{@field}}
+ @schema={{@schema}}
@supportsExpression={{@supportsExpression}}
@placeholder={{@placeholder}}
@dynamicValueHint={{@dynamicValueHint}}
diff --git a/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/configurators/tags-control.gjs b/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/configurators/tags-control.gjs
index 8f8db86e3a5..292705c10b0 100644
--- a/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/configurators/tags-control.gjs
+++ b/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/configurators/tags-control.gjs
@@ -25,6 +25,7 @@ export default class TagsControl extends Component {
<template>
<ExpressionWrapper
@field={{@field}}
+ @schema={{@schema}}
@supportsExpression={{@supportsExpression}}
@placeholder={{@placeholder}}
@dynamicValueHint={{@dynamicValueHint}}
diff --git a/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/configurators/url-preview.gjs b/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/configurators/url-preview.gjs
index abfa48a57b4..3f475f90631 100644
--- a/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/configurators/url-preview.gjs
+++ b/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/configurators/url-preview.gjs
@@ -260,6 +260,7 @@ export default class UrlPreview extends Component {
<template>
<ExpressionWrapper
@field={{@field}}
+ @schema={{@schema}}
@supportsExpression={{@supportsExpression}}
@placeholder={{@placeholder}}
@dynamicValueHint={{@dynamicValueHint}}
diff --git a/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/configurators/user-control.gjs b/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/configurators/user-control.gjs
index 997aaa7ac89..1c7304de4d8 100644
--- a/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/configurators/user-control.gjs
+++ b/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/configurators/user-control.gjs
@@ -4,24 +4,50 @@ import { action } from "@ember/object";
import UserChooser from "discourse/select-kit/components/user-chooser";
import ExpressionWrapper from "./expression-wrapper";
+function usernamesFromValue(value) {
+ if (Array.isArray(value)) {
+ return value;
+ }
+
+ if (typeof value === "string" && value.length > 0) {
+ return [value];
+ }
+
+ return [];
+}
+
export default class UserControl extends Component {
+ get multiple() {
+ return Boolean(this.args.schema?.ui?.multiple);
+ }
+
+ get value() {
+ const usernames = usernamesFromValue(this.args.field.value);
+ return this.multiple ? usernames : usernames[0] || null;
+ }
+
+ get maximum() {
+ return this.multiple ? null : 1;
+ }
+
@action
handleChange(usernames) {
- this.args.field.set(usernames[0] || "");
+ this.args.field.set(this.multiple ? usernames || [] : usernames[0] || "");
}
<template>
<ExpressionWrapper
@field={{@field}}
+ @schema={{@schema}}
@supportsExpression={{@supportsExpression}}
@placeholder={{@placeholder}}
@dynamicValueHint={{@dynamicValueHint}}
@session={{@session}}
>
<UserChooser
- @value={{if @field.value @field.value null}}
+ @value={{this.value}}
@onChange={{this.handleChange}}
- @options={{hash maximum=1 excludeCurrentUser=false}}
+ @options={{hash maximum=this.maximum excludeCurrentUser=false}}
/>
</ExpressionWrapper>
</template>
diff --git a/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/configurators/user-or-group-control.gjs b/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/configurators/user-or-group-control.gjs
index ddaccc33db4..67a14fe47cb 100644
--- a/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/configurators/user-or-group-control.gjs
+++ b/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/configurators/user-or-group-control.gjs
@@ -13,6 +13,7 @@ export default class UserOrGroupControl extends Component {
<template>
<ExpressionWrapper
@field={{@field}}
+ @schema={{@schema}}
@supportsExpression={{@supportsExpression}}
@placeholder={{@placeholder}}
@dynamicValueHint={{@dynamicValueHint}}
diff --git a/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/editor/index.gjs b/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/editor/index.gjs
index 0c298bcdc57..f770da8f87f 100644
--- a/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/editor/index.gjs
+++ b/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/editor/index.gjs
@@ -1358,7 +1358,7 @@ export default class WorkflowsEditor extends Component {
}
@action
- handleWorkflowDiscarded(workflow) {
+ replaceWorkflow(workflow) {
this.pendingSave = false;
this.pendingGraphSnapshot = null;
this.pendingSaveOptions = null;
@@ -1393,7 +1393,7 @@ export default class WorkflowsEditor extends Component {
}
);
- this.handleWorkflowDiscarded(response.workflow);
+ this.replaceWorkflow(response.workflow);
} catch (e) {
popupAjaxError(e);
throw e;
@@ -1530,7 +1530,8 @@ export default class WorkflowsEditor extends Component {
@onOpenNodePanel={{this.openNodePanel}}
@onCloseNodePanel={{this.closeNodePanel}}
@onBrowseTemplates={{this.browseTemplates}}
- @onDiscardWorkflow={{this.handleWorkflowDiscarded}}
+ @onDiscardWorkflow={{this.replaceWorkflow}}
+ @onWorkflowUpdated={{this.replaceWorkflow}}
@onImportNodes={{this.importNodes}}
@onAddStickyNote={{this.addStickyNote}}
@onStickyNoteBeforeMutation={{this.stickyNoteBeforeMutation}}
diff --git a/plugins/discourse-workflows/admin/assets/javascripts/admin/lib/workflows/property-engine.js b/plugins/discourse-workflows/admin/assets/javascripts/admin/lib/workflows/property-engine.js
index 5d0f3793c06..e9c91a309b1 100644
--- a/plugins/discourse-workflows/admin/assets/javascripts/admin/lib/workflows/property-engine.js
+++ b/plugins/discourse-workflows/admin/assets/javascripts/admin/lib/workflows/property-engine.js
@@ -134,11 +134,13 @@ function dynamicValueKey(schema = {}, fieldName) {
case "data_table_select":
return "data_table_id";
case "group_select":
- return "group_id";
+ return schema.control_options?.value_property === "name"
+ ? "group_names"
+ : "group_id";
case "tags":
return "tag_names";
case "user":
- return "username";
+ return ui.multiple ? "usernames" : "username";
case "user_or_group":
return "user_or_group_name";
case "select":
diff --git a/plugins/discourse-workflows/app/controllers/discourse_workflows/ai_authoring_controller.rb b/plugins/discourse-workflows/app/controllers/discourse_workflows/ai_authoring_controller.rb
new file mode 100644
index 00000000000..be9c5c26c87
--- /dev/null
+++ b/plugins/discourse-workflows/app/controllers/discourse_workflows/ai_authoring_controller.rb
@@ -0,0 +1,94 @@
+# frozen_string_literal: true
+
+module DiscourseWorkflows
+ class AiAuthoringController < ::Admin::AdminController
+ requires_plugin DiscourseWorkflows::PLUGIN_NAME
+
+ def create
+ rate_limit! if DiscourseWorkflows::AiAuthoringEnqueuer.enabled?
+
+ DiscourseWorkflows::AiAuthoring::Start.call(ai_authoring_service_params) do |result|
+ on_success do |session:, generation_id:|
+ render json: {
+ session_id: session.id,
+ generation_id: generation_id,
+ status: "generating",
+ }
+ end
+ on_failed_contract { |contract| render_failed_contract(contract) }
+ on_failed_policy(:ai_authoring_enabled) { raise Discourse::NotFound }
+ on_failed_policy(:can_manage_workflows) { raise Discourse::InvalidAccess }
+ on_failed_policy(:workflow_exists_when_requested) { raise Discourse::NotFound }
+ on_model_not_found(:session) { raise Discourse::NotFound }
+ on_failure { render(json: failed_json, status: :unprocessable_entity) }
+ end
+ end
+
+ def apply
+ DiscourseWorkflows::AiAuthoring::Apply.call(ai_authoring_service_params) do |result|
+ on_success do |workflow:|
+ render_serialized(
+ workflow.reload,
+ DiscourseWorkflows::WorkflowSerializer,
+ root: "workflow",
+ )
+ end
+ on_failed_contract { |contract| render_failed_contract(contract) }
+ on_failed_policy(:ai_authoring_enabled) { raise Discourse::NotFound }
+ on_failed_policy(:can_manage_workflows) { raise Discourse::InvalidAccess }
+ on_failed_policy(:proposal_ready) do
+ render(
+ json:
+ failed_json.merge(
+ errors: [I18n.t("discourse_workflows.ai.error_proposal_not_ready")],
+ ),
+ status: :unprocessable_entity,
+ )
+ end
+ on_failed_policy(:proposal_current) do
+ render(
+ json:
+ failed_json.merge(errors: [I18n.t("discourse_workflows.ai.error_stale_proposal")]),
+ status: :conflict,
+ )
+ end
+ on_failed_policy(:patch_valid) do |_policy, patch_result:|
+ render json: failed_json.merge(errors: patch_result[:errors]),
+ status: :unprocessable_entity
+ end
+ on_model_not_found(:session) { raise Discourse::NotFound }
+ on_model_not_found(:workflow) { raise Discourse::NotFound }
+ on_model_not_found(:operations) do
+ raise Discourse::InvalidParameters.new(
+ I18n.t("discourse_workflows.ai.error_no_operations"),
+ )
+ end
+ on_failure { render(json: failed_json, status: :unprocessable_entity) }
+ end
+ end
+
+ private
+
+ def rate_limit!
+ RateLimiter.new(
+ current_user,
+ "discourse-workflows-ai-authoring",
+ SiteSetting.discourse_workflows_ai_authoring_rate_limit_per_minute,
+ 1.minute,
+ apply_limit_to_staff: true,
+ ).performed!
+ end
+
+ def workflow_id
+ params[:workflow_id].presence || params[:id].presence
+ end
+
+ def ai_authoring_service_params
+ service_params.deep_merge(params: { workflow_id: workflow_id })
+ end
+
+ def render_failed_contract(contract)
+ render(json: failed_json.merge(errors: contract.errors.full_messages), status: :bad_request)
+ end
+ end
+end
diff --git a/plugins/discourse-workflows/app/jobs/regular/discourse_workflows/author_with_ai.rb b/plugins/discourse-workflows/app/jobs/regular/discourse_workflows/author_with_ai.rb
new file mode 100644
index 00000000000..e4da3f3890b
--- /dev/null
+++ b/plugins/discourse-workflows/app/jobs/regular/discourse_workflows/author_with_ai.rb
@@ -0,0 +1,660 @@
+# frozen_string_literal: true
+
+module Jobs
+ module DiscourseWorkflows
+ class AuthorWithAi < ::Jobs::Base
+ sidekiq_options retry: false
+
+ AI_RESPONSE_STATUSES = %w[needs_clarification proposed_patch explanation error].freeze
+ TRIGGER_AUTHOR_FIELD_FACTS = [
+ "trigger:topic_created exposes the topic creator/first-post author under post.* and does not expose a top-level user object. Use exact paths such as post.username for the username, post.user_id for the user ID, and post.post_url for a link to the post.",
+ "trigger:post_created exposes the created post under post.* and the post author under user.*. Use exact paths such as user.trust_level for trust-level checks, user.username for the username, user.id for the user ID, user.admin/user.moderator/user.staff for staff checks, and post.post_url for a link to the post.",
+ "For generic requests like 'when someone posts' or 'when anyone posts', trigger:post_created covers all regular posts, including first posts and replies. Do not ask to distinguish replies from topic starters unless the request explicitly says replies only or new topics only.",
+ "trigger:topic_closed exposes only the closed topic under topic.*. When a closed-topic workflow needs a first-post link, add action:topic with operation get and topic_id ={{ $json.topic.id }} immediately after the trigger. Use the exact fields returned by workflow_validate_patch for any first-post author data; do not assume post.trust_level is available.",
+ "Do not ask whether trust level is available for trigger:post_created or trigger:post_edited; it is available as user.trust_level.",
+ "Do not generate fallback chains for undocumented author aliases; use the exact post.* fields from the node catalog output_schema.",
+ "For named group membership checks, use workflow_resolve_entity to resolve the group, then use action:group with operation check_membership, group_id set to the resolved group id, and username ={{ $json.user.username }} when the input schema includes user.username, otherwise use the exact username field from the current input schema. It adds group_membership.in_group while preserving the original item fields. Do not use a Code node for simple group membership.",
+ "For personal messages, private messages, DMs, direct messages, or PM notifications, use action:send_personal_message with recipient_usernames or recipient_group_names as arrays, title, raw, and sender_username. Resolve named users with workflow_resolve_entity(kind: user), and named groups with workflow_resolve_entity(kind: group).",
+ ].freeze
+
+ def execute(args)
+ @generation_id = args[:generation_id]
+ @session = ::DiscourseWorkflows::AiAuthoringSession.find_by(id: args[:session_id])
+ @user = User.find_by(id: args[:user_id])
+ return if @session.blank? || @user.blank?
+ if !::DiscourseWorkflows::AiAuthoringEnqueuer.enabled?
+ return publish_error(I18n.t("discourse_workflows.ai.error_not_enabled"))
+ end
+
+ publish_progress(:loading_context)
+ agent_record = find_agent_record
+ if agent_record.blank?
+ return publish_error(I18n.t("discourse_workflows.ai.error_agent_not_configured"))
+ end
+
+ publish_progress(:planning)
+ parsed = run_agent(agent_record)
+
+ if proposed_patch_response?(parsed) && code_scripts_present?(parsed)
+ publish_progress(:writing_scripts)
+ publish_progress(:validating_scripts)
+ parsed = validate_script_proposals(parsed)
+ end
+
+ if proposed_patch_response?(parsed)
+ publish_progress(:validating_patch)
+ parsed = validate_patch_proposal(parsed)
+ end
+
+ publish_progress(:summarizing)
+ persist_response(parsed)
+ publish_terminal(parsed)
+ rescue => e
+ publish_error(e.message)
+ end
+
+ private
+
+ def find_agent_record
+ configured_agent_id = SiteSetting.discourse_workflows_workflow_authoring_agent.to_i
+ default_agent_id =
+ ::DiscourseAi::Agents::Agent.external_agent_id(::DiscourseWorkflows::AiWorkflowAuthor)
+
+ AiAgent.find_by(id: configured_agent_id) || AiAgent.find_by(id: default_agent_id)
+ end
+
+ def run_agent(agent_record)
+ agent_klass = agent_record.class_instance
+ bot = ::DiscourseAi::Agents::Bot.as(Discourse.system_user, agent: agent_klass.new)
+ context =
+ ::DiscourseAi::Agents::BotContext.new(
+ messages: normalized_session_messages,
+ user: @user,
+ feature_name: "discourse_workflows_workflow_authoring",
+ custom_instructions: authoring_context_instructions,
+ bypass_response_format: true,
+ )
+
+ result = +""
+ raw_context =
+ bot.reply(context) do |partial, raw, type|
+ publish_agent_stream_progress(partial, raw, type)
+
+ result << partial if type.blank? && partial.is_a?(String)
+ end
+ append_raw_context_text(result, raw_context)
+
+ parse_response(result, raw_context)
+ end
+
+ def append_raw_context_text(result, raw_context)
+ return if result.present? || raw_context.blank?
+
+ raw_context.each do |entry|
+ next if !entry.is_a?(Array) || !entry.first.is_a?(String)
+ next if entry[2].present?
+
+ result << entry.first
+ end
+ end
+
+ def normalized_session_messages
+ @session.messages.map do |message|
+ normalized_message = message.symbolize_keys.slice(:type, :content)
+ normalized_message[:type] = normalized_message[:type].to_sym if normalized_message[:type]
+ normalized_message
+ end
+ end
+
+ def authoring_context_instructions
+ context_tools = {
+ workflow_node_catalog:
+ "Call this with targeted queries for node parameters, output schemas, capabilities, and examples.",
+ workflow_ai_agent_catalog:
+ "Call this before adding action:ai_agent nodes to find existing enabled AI agents to reuse. If none fit, propose create_ai_agent with name, description, and system_prompt.",
+ workflow_graph_context:
+ "Call this with workflow_id when you need the current graph nodes and connections.",
+ workflow_validate_patch:
+ "Call this to dry-run candidate operations and inspect inferred node_schemas.",
+ workflow_script_context:
+ "Call this before writing Code node JavaScript to inspect the runtime API and mode rules.",
+ workflow_validate_script:
+ "Call this with exact Code node mode and code; repair any errors before returning a proposal.",
+ workflow_authoring_result:
+ "Call this exactly once when authoring is complete; it is the final response.",
+ }
+ if ::DiscourseWorkflows::Ai::Tools::SearchChatChannels.available?
+ context_tools[
+ :search_chat_channels
+ ] = "Call this before asking the admin to choose a chat channel or before setting action:send_chat_message channel_id. Use returned matches; never invent channel names or IDs."
+ end
+
+ payload = {
+ workflow: workflow_summary,
+ trigger_author_field_facts: TRIGGER_AUTHOR_FIELD_FACTS,
+ context_tools: context_tools,
+ }
+
+ <<~TEXT
+ Important workflow field facts:
+ #{TRIGGER_AUTHOR_FIELD_FACTS.map { |fact| "- #{fact}" }.join("\n")}
+
+ Compact workflow authoring context. Full graph and node catalog are intentionally not preloaded; use workflow_graph_context and workflow_node_catalog tools for details:
+ #{JSON.generate(payload)}
+ TEXT
+ end
+
+ def workflow_summary
+ workflow = @session.workflow
+ return nil if workflow.blank?
+
+ nodes = workflow.nodes || []
+ connection_count =
+ ::DiscourseWorkflows::WorkflowDocument.connection_records(
+ nodes,
+ workflow.connections || {},
+ ).length
+
+ {
+ id: workflow.id,
+ name: workflow.name,
+ node_count: nodes.length,
+ connection_count: connection_count,
+ published: workflow.published?,
+ has_unpublished_changes: workflow.has_unpublished_changes?,
+ version_id: workflow.version_id,
+ active_version_id: workflow.active_version_id,
+ graph_digest: ::DiscourseWorkflows::Ai::GraphDigest.call(workflow),
+ }
+ end
+
+ def parse_response(text, raw_context = [])
+ parsed = parse_tool_call_response(raw_context)
+ return parsed if parsed.present?
+
+ invalid_response(text)
+ end
+
+ def parse_json_hash(candidate)
+ parsed = JSON.parse(candidate)
+ parsed if parsed.is_a?(Hash)
+ rescue JSON::ParserError, Oj::ParseError
+ nil
+ end
+
+ def parse_tool_call_response(raw_context)
+ parse_authoring_result_tool_response(raw_context) ||
+ parse_ask_questions_tool_response(raw_context) ||
+ parse_validate_patch_tool_response(raw_context)
+ end
+
+ def parse_authoring_result_tool_response(raw_context)
+ Array
+ .wrap(raw_context)
+ .reverse_each do |entry|
+ next if !workflow_authoring_result_tool_entry?(entry)
+
+ parsed = authoring_result_from_tool_entry(entry)
+ next if parsed.blank?
+
+ parsed = normalize_ai_response(parsed)
+ return parsed if meaningful_ai_response?(parsed)
+ end
+
+ nil
+ end
+
+ def authoring_result_from_tool_entry(entry)
+ content = parse_json_hash(entry.first.to_s)
+ if entry[2].to_s == "tool_call"
+ normalized_hash(content&.fetch("arguments", nil))
+ else
+ normalized_hash(content)
+ end
+ end
+
+ def workflow_authoring_result_tool_entry?(entry)
+ entry.is_a?(Array) && %w[tool_call tool].include?(entry[2].to_s) &&
+ entry[3].to_s == ::DiscourseWorkflows::Ai::Tools::WorkflowAuthoringResult.name
+ end
+
+ def parse_ask_questions_tool_response(raw_context)
+ Array
+ .wrap(raw_context)
+ .reverse_each do |entry|
+ next if !workflow_ask_questions_tool_entry?(entry)
+
+ content = parse_json_hash(entry.first.to_s)
+ questions = ask_questions_from_tool_entry(entry, content)
+ next if questions.blank?
+
+ return(
+ {
+ "status" => "needs_clarification",
+ "message" => I18n.t("discourse_workflows.ai.clarification_message"),
+ "questions" => json_safe(questions),
+ "proposal" => {
+ },
+ }
+ )
+ end
+
+ nil
+ end
+
+ def ask_questions_from_tool_entry(entry, content)
+ if entry[2].to_s == "tool_call"
+ normalized_hash(content&.fetch("arguments", nil))[:questions]
+ else
+ normalized_hash(content)[:questions]
+ end
+ end
+
+ def workflow_ask_questions_tool_entry?(entry)
+ entry.is_a?(Array) && %w[tool_call tool].include?(entry[2].to_s) &&
+ entry[3].to_s == ::DiscourseWorkflows::Ai::Tools::WorkflowAskQuestions.name
+ end
+
+ def parse_validate_patch_tool_response(raw_context)
+ Array
+ .wrap(raw_context)
+ .reverse_each do |entry|
+ next if !workflow_validate_patch_tool_call?(entry)
+
+ content = parse_json_hash(entry.first.to_s)
+ arguments = normalized_hash(content&.fetch("arguments", nil))
+ operations = Array.wrap(arguments[:operations])
+ next if operations.blank?
+
+ return tool_call_proposal_response(arguments, operations)
+ end
+
+ nil
+ end
+
+ def workflow_validate_patch_tool_call?(entry)
+ entry.is_a?(Array) && entry[2].to_s == "tool_call" &&
+ entry[3].to_s == ::DiscourseWorkflows::Ai::Tools::WorkflowValidatePatch.name
+ end
+
+ def tool_call_proposal_response(arguments, operations)
+ operations = normalized_patch_operations(operations)
+ title =
+ arguments[:workflow_name].presence ||
+ @session.latest_request.to_s.truncate(80).presence ||
+ I18n.t("discourse_workflows.ai.tool_call_proposal_title")
+
+ {
+ "status" => "proposed_patch",
+ "message" => I18n.t("discourse_workflows.ai.tool_call_proposal_message"),
+ "questions" => [],
+ "proposal" => {
+ "title" => title,
+ "summary" =>
+ I18n.t("discourse_workflows.ai.tool_call_proposal_summary", count: operations.size),
+ "risk_level" => arguments[:risk_level].presence || "medium",
+ "operations" => json_safe(operations),
+ },
+ }
+ end
+
+ def normalize_ai_response(parsed)
+ parsed = normalized_hash(parsed)
+ proposal = normalized_hash(parsed[:proposal])
+ status = parsed[:status].to_s
+ status = "proposed_patch" if status.blank? && proposal[:operations].present?
+
+ {
+ "status" => status,
+ "message" => parsed[:message].presence || parsed[:error].presence,
+ "questions" => Array.wrap(parsed[:questions]),
+ "proposal" => proposal,
+ }
+ end
+
+ def meaningful_ai_response?(parsed)
+ parsed = normalized_hash(parsed)
+ proposal = normalized_hash(parsed[:proposal])
+
+ status = parsed[:status].to_s
+ if status == "proposed_patch"
+ proposal[:operations].present?
+ else
+ AI_RESPONSE_STATUSES.include?(status) || proposal[:operations].present?
+ end
+ end
+
+ def invalid_response(text)
+ {
+ "status" => "error",
+ "message" => text.presence || I18n.t("discourse_workflows.ai.error_invalid_response"),
+ }
+ end
+
+ def proposed_patch_response?(parsed)
+ parsed["status"].to_s == "proposed_patch"
+ end
+
+ def validate_script_proposals(parsed)
+ proposal = proposal_for(parsed)
+ operations = normalized_patch_operations(proposal[:operations])
+ proposal["operations"] = operations
+ validations = code_script_validations(operations)
+ proposal["script_validations"] = validations if validations.present?
+
+ if validations.any? { |validation| !validation["valid"] }
+ return(
+ parsed.merge(
+ "status" => "error",
+ "message" => invalid_script_message(validations),
+ "proposal" => json_safe(proposal),
+ )
+ )
+ end
+
+ parsed.merge("proposal" => json_safe(proposal))
+ end
+
+ def validate_patch_proposal(parsed)
+ proposal = proposal_for(parsed)
+ operations = normalized_patch_operations(proposal[:operations])
+ proposal["operations"] = operations
+
+ if operations.blank?
+ return(
+ parsed.merge(
+ "status" => "error",
+ "message" => I18n.t("discourse_workflows.ai.error_no_operations"),
+ "proposal" => json_safe(proposal),
+ )
+ )
+ end
+
+ validation = validate_patch_operations(proposal, operations)
+ proposal["patch_validation"] = validation
+ proposal["created_resources"] = validation["created_resources"] if validation[
+ "created_resources"
+ ].present?
+
+ if !validation["valid"]
+ return(
+ parsed.merge(
+ "status" => "error",
+ "message" =>
+ I18n.t(
+ "discourse_workflows.ai.error_invalid_patch",
+ errors: validation["errors"].join(", "),
+ ),
+ "proposal" => json_safe(proposal),
+ )
+ )
+ end
+
+ parsed.merge("proposal" => json_safe(proposal))
+ end
+
+ def code_scripts_present?(parsed)
+ operations = normalized_patch_operations(proposal_for(parsed)[:operations])
+ operations.any? do |operation|
+ code_script_for_operation(normalized_hash(operation)).present?
+ end
+ end
+
+ def invalid_script_message(validations)
+ details =
+ validations
+ .select { |validation| !validation["valid"] }
+ .flat_map do |validation|
+ node_name =
+ validation["node_name"].presence ||
+ I18n.t("discourse_workflows.ai.default_code_node_name")
+ Array.wrap(validation["errors"]).map { |error| "#{node_name}: #{error}" }
+ end
+ .join("; ")
+
+ if details.present?
+ I18n.t("discourse_workflows.ai.error_invalid_script_with_errors", errors: details)
+ else
+ I18n.t("discourse_workflows.ai.error_invalid_script")
+ end
+ end
+
+ def code_script_validations(operations)
+ operations.each_with_index.filter_map do |operation, index|
+ script = code_script_for_operation(normalized_hash(operation))
+ next if script.blank?
+
+ result = validate_code_script(script)
+ {
+ "operation_index" => index,
+ "node_name" => script[:node_name],
+ "mode" => script[:mode],
+ "valid" => result[:valid],
+ "errors" => result[:errors] || [],
+ "warnings" => result[:warnings] || [],
+ }
+ end
+ end
+
+ def code_script_for_operation(operation)
+ case operation[:op].to_s
+ when "add_node"
+ code_script_for_added_node(operation)
+ when "update_node_parameters"
+ code_script_for_parameter_update(operation)
+ end
+ end
+
+ def code_script_for_added_node(operation)
+ node = normalized_hash(operation[:node])
+ return if node[:type].to_s != "action:code"
+
+ parameters = normalized_hash(node[:parameters])
+ {
+ node_name:
+ node[:name].presence || I18n.t("discourse_workflows.ai.default_code_node_name"),
+ mode: code_mode(parameters),
+ code: parameters[:code].to_s,
+ }
+ end
+
+ def code_script_for_parameter_update(operation)
+ parameters = normalized_hash(operation[:parameters])
+ return if !parameters.key?(:code) && !parameters.key?(:mode)
+
+ node = @session.workflow&.find_node(operation[:node_id] || operation[:client_id])
+ return if node.blank? && !parameters.key?(:code)
+ return if node.present? && node["type"] != "action:code" && !parameters.key?(:code)
+
+ existing_parameters = node ? ::DiscourseWorkflows::NodeData.parameters(node) : {}
+ {
+ node_name:
+ node&.dig("name").presence || I18n.t("discourse_workflows.ai.default_code_node_name"),
+ mode: code_mode(parameters, existing_parameters),
+ code: (parameters.key?(:code) ? parameters[:code] : existing_parameters["code"]).to_s,
+ }
+ end
+
+ def validate_code_script(script)
+ context = ::DiscourseAi::Agents::BotContext.new(messages: [], user: @user)
+ ::DiscourseWorkflows::Ai::Tools::WorkflowValidateScript.new(
+ { mode: script[:mode], code: script[:code] },
+ bot_user: Discourse.system_user,
+ llm: nil,
+ context: context,
+ ).invoke
+ end
+
+ def code_mode(parameters, existing_parameters = {})
+ (
+ parameters[:mode].presence || existing_parameters["mode"].presence ||
+ ::DiscourseWorkflows::Ai::Tools::WorkflowValidateScript::RUN_ONCE_FOR_ALL_ITEMS
+ ).to_s
+ end
+
+ def validate_patch_operations(proposal, operations)
+ result =
+ ::DiscourseWorkflows::Ai::Tools::WorkflowValidatePatch.new(
+ {
+ workflow_id: @session.workflow_id,
+ workflow_name:
+ proposal[:workflow_name].presence || @session.workflow&.name ||
+ @session.latest_request.to_s.truncate(100),
+ operations: operations,
+ }.compact,
+ bot_user: Discourse.system_user,
+ llm: nil,
+ context: ::DiscourseAi::Agents::BotContext.new(messages: [], user: @user),
+ ).invoke
+
+ {
+ "valid" => result[:valid],
+ "errors" => Array.wrap(result[:errors]),
+ "graph_errors" => Array.wrap(result[:graph_errors]),
+ "expression_errors" => Array.wrap(result[:expression_errors]),
+ "diff" => result[:diff],
+ "created_resources" => Array.wrap(result[:created_resources]),
+ }
+ end
+
+ def proposal_for(parsed)
+ proposal = parsed["proposal"]
+ proposal.is_a?(Hash) ? proposal.with_indifferent_access : {}.with_indifferent_access
+ end
+
+ def normalized_patch_operations(operations)
+ Array
+ .wrap(operations)
+ .map do |operation|
+ if operation.is_a?(String)
+ parse_json_hash(operation.strip) || operation
+ else
+ operation
+ end
+ end
+ end
+
+ def normalized_hash(value)
+ value.respond_to?(:to_h) ? value.to_h.with_indifferent_access : {}.with_indifferent_access
+ end
+
+ def persist_response(parsed)
+ status = parsed["status"].to_s
+ session_status =
+ case status
+ when "needs_clarification"
+ "needs_clarification"
+ when "proposed_patch"
+ "proposal_ready"
+ when "error"
+ "error"
+ else
+ "drafting"
+ end
+
+ @session.update!(
+ status: session_status,
+ latest_response: parsed,
+ proposed_patch: parsed["proposal"] || {},
+ risk_level: proposal_for(parsed)["risk_level"],
+ )
+ end
+
+ def publish_terminal(parsed)
+ status = parsed["status"].presence || "error"
+ ::DiscourseWorkflows::Ai::ProgressPublisher.publish(
+ generation_id: @generation_id,
+ user: @user,
+ status: status,
+ session_id: @session.id,
+ response: parsed,
+ )
+ end
+
+ def publish_progress(stage, details = {})
+ ::DiscourseWorkflows::Ai::ProgressPublisher.publish(
+ generation_id: @generation_id,
+ user: @user,
+ status: "progress",
+ stage: stage.to_s,
+ message: I18n.t("discourse_workflows.ai.progress.#{stage}"),
+ details: details,
+ )
+ end
+
+ def publish_agent_stream_progress(partial, raw, type)
+ case type
+ when :thinking
+ publish_tool_progress(partial, raw)
+ when :structured_output
+ publish_agent_progress_once(
+ :drafting_response,
+ I18n.t("discourse_workflows.ai.progress.drafting_response"),
+ )
+ when nil
+ if partial.is_a?(String) && partial.present?
+ publish_agent_progress_once(
+ :writing_response,
+ I18n.t("discourse_workflows.ai.progress.writing_response"),
+ )
+ end
+ end
+ end
+
+ def publish_tool_progress(partial, raw)
+ tool_label = tool_label_from_placeholder(raw.presence || partial)
+ return if tool_label.blank?
+
+ phase = raw.present? ? :using_tool : :tool_finished
+ publish_agent_progress_once(
+ "#{phase}:#{tool_label}",
+ I18n.t("discourse_workflows.ai.progress.#{phase}", tool: tool_label),
+ tool: tool_label,
+ )
+ end
+
+ def tool_label_from_placeholder(value)
+ first_line = value.to_s.lines.map(&:strip).find(&:present?)
+ return if first_line.blank? || !first_line.start_with?("**") || !first_line.end_with?("**")
+
+ first_line.delete_prefix("**").delete_suffix("**").gsub(/<[^>]*>/, "").strip
+ end
+
+ def publish_agent_progress_once(key, message, details = {})
+ @published_agent_progress_keys ||= {}
+ return if @published_agent_progress_keys[key]
+
+ @published_agent_progress_keys[key] = true
+ ::DiscourseWorkflows::Ai::ProgressPublisher.publish(
+ generation_id: @generation_id,
+ user: @user,
+ status: "progress",
+ stage: "agent_update",
+ message: message,
+ details: details.merge(key: key.to_s),
+ )
+ end
+
+ def publish_error(message)
+ @session&.update!(
+ status: "error",
+ latest_response: {
+ "status" => "error",
+ "message" => message,
+ },
+ )
+ ::DiscourseWorkflows::Ai::ProgressPublisher.publish(
+ generation_id: @generation_id,
+ user: @user,
+ status: "error",
+ session_id: @session&.id,
+ error: message,
+ )
+ end
+
+ def json_safe(value)
+ JSON.parse(JSON.generate(value))
+ end
+ end
+ end
+end
diff --git a/plugins/discourse-workflows/app/models/discourse_workflows/ai_authoring_session.rb b/plugins/discourse-workflows/app/models/discourse_workflows/ai_authoring_session.rb
new file mode 100644
index 00000000000..b9fd2c816c5
--- /dev/null
+++ b/plugins/discourse-workflows/app/models/discourse_workflows/ai_authoring_session.rb
@@ -0,0 +1,73 @@
+# frozen_string_literal: true
+
+module DiscourseWorkflows
+ class AiAuthoringSession < ActiveRecord::Base
+ self.table_name = "discourse_workflows_ai_authoring_sessions"
+
+ STATUSES = %w[
+ drafting
+ generating
+ needs_clarification
+ proposal_ready
+ applied
+ error
+ cancelled
+ ].freeze
+
+ RISK_LEVELS = %w[low medium high].freeze
+
+ belongs_to :workflow,
+ class_name: "DiscourseWorkflows::Workflow",
+ foreign_key: "workflow_id",
+ optional: true
+ belongs_to :user
+
+ validates :status, presence: true, inclusion: { in: STATUSES }
+ validates :risk_level, inclusion: { in: RISK_LEVELS }, allow_nil: true
+ validate :json_fields_have_expected_shape
+
+ scope :expired_applied_or_inactive,
+ -> { where(status: %w[applied error cancelled]).where("updated_at < ?", 30.days.ago) }
+ scope :expired_unapplied_proposals,
+ -> { where(status: "proposal_ready").where("updated_at < ?", 7.days.ago) }
+
+ def append_message!(type:, content:)
+ self.messages = messages + [{ "type" => type.to_s, "content" => content.to_s }]
+ save!
+ end
+
+ private
+
+ def json_fields_have_expected_shape
+ errors.add(:messages, :invalid) if !messages.is_a?(Array)
+ errors.add(:latest_response, :invalid) if !latest_response.is_a?(Hash)
+ errors.add(:proposed_patch, :invalid) if !proposed_patch.is_a?(Hash)
+ end
+ end
+end
+
+# == Schema Information
+#
+# Table name: discourse_workflows_ai_authoring_sessions
+#
+# id :bigint not null, primary key
+# applied_at :datetime
+# base_graph_digest :string(64)
+# latest_request :text
+# latest_response :jsonb not null
+# messages :jsonb not null
+# proposed_patch :jsonb not null
+# risk_level :string(20)
+# status :string(40) default("drafting"), not null
+# created_at :datetime not null
+# updated_at :datetime not null
+# base_workflow_version_id :string(36)
+# user_id :integer not null
+# workflow_id :bigint
+#
+# Indexes
+#
+# idx_dwf_ai_sessions_on_status_updated_at (status,updated_at)
+# idx_dwf_ai_sessions_on_user_id (user_id)
+# idx_dwf_ai_sessions_on_workflow_id (workflow_id)
+#
diff --git a/plugins/discourse-workflows/app/models/discourse_workflows/workflow.rb b/plugins/discourse-workflows/app/models/discourse_workflows/workflow.rb
index e97d344a3d8..1eee654f611 100644
--- a/plugins/discourse-workflows/app/models/discourse_workflows/workflow.rb
+++ b/plugins/discourse-workflows/app/models/discourse_workflows/workflow.rb
@@ -29,6 +29,10 @@ module DiscourseWorkflows
class_name: "DiscourseWorkflows::WorkflowPublishHistory",
foreign_key: "workflow_id",
dependent: :delete_all
+ has_many :ai_authoring_sessions,
+ class_name: "DiscourseWorkflows::AiAuthoringSession",
+ foreign_key: "workflow_id",
+ dependent: :delete_all
belongs_to :created_by, class_name: "User", foreign_key: "created_by_id"
belongs_to :updated_by, class_name: "User", foreign_key: "updated_by_id", optional: true
diff --git a/plugins/discourse-workflows/app/serializers/discourse_workflows/user_serializer.rb b/plugins/discourse-workflows/app/serializers/discourse_workflows/user_serializer.rb
new file mode 100644
index 00000000000..1f288e5f430
--- /dev/null
+++ b/plugins/discourse-workflows/app/serializers/discourse_workflows/user_serializer.rb
@@ -0,0 +1,15 @@
+# frozen_string_literal: true
+
+module DiscourseWorkflows
+ class UserSerializer < ApplicationSerializer
+ attributes :id, :username, :name, :trust_level, :trust_level_name, :admin, :moderator, :staff
+
+ def trust_level_name
+ TrustLevel.name(object.trust_level)
+ end
+
+ def staff
+ object.staff?
+ end
+ end
+end
diff --git a/plugins/discourse-workflows/app/services/discourse_workflows/ai_authoring/apply.rb b/plugins/discourse-workflows/app/services/discourse_workflows/ai_authoring/apply.rb
new file mode 100644
index 00000000000..8ce49fa091e
--- /dev/null
+++ b/plugins/discourse-workflows/app/services/discourse_workflows/ai_authoring/apply.rb
@@ -0,0 +1,77 @@
+# frozen_string_literal: true
+
+module DiscourseWorkflows
+ module AiAuthoring
+ class Apply
+ include Service::Base
+
+ policy :ai_authoring_enabled
+
+ params do
+ attribute :session_id, :integer
+ attribute :workflow_id, :integer
+
+ validates :session_id, :workflow_id, presence: true
+ end
+
+ policy :can_manage_workflows, class_name: Policy::CanManageWorkflows
+ model :session
+ model :workflow
+ policy :proposal_ready
+ model :operations, :extract_operations
+ policy :proposal_current
+ model :patch_result, :apply_patch
+ policy :patch_valid
+ step :mark_proposal_applied
+
+ private
+
+ def ai_authoring_enabled
+ DiscourseWorkflows::AiAuthoringEnqueuer.enabled?
+ end
+
+ def fetch_session(params:, guardian:)
+ DiscourseWorkflows::AiAuthoringSession.find_by(
+ id: params.session_id,
+ user_id: guardian.user.id,
+ workflow_id: params.workflow_id,
+ )
+ end
+
+ def fetch_workflow(session:)
+ session.workflow
+ end
+
+ def proposal_ready(session:)
+ session.status == "proposal_ready"
+ end
+
+ def extract_operations(session:)
+ proposal = session.proposed_patch || {}
+ proposal["operations"] || proposal[:operations]
+ end
+
+ def proposal_current(session:, workflow:)
+ session.base_graph_digest.blank? ||
+ DiscourseWorkflows::Ai::GraphDigest.call(workflow) == session.base_graph_digest
+ end
+
+ def apply_patch(workflow:, operations:, guardian:)
+ DiscourseWorkflows::Workflow::Action::ApplyPatch.call(
+ workflow: workflow,
+ operations: operations,
+ persist: true,
+ user: guardian.user,
+ )
+ end
+
+ def patch_valid(patch_result:)
+ patch_result[:valid]
+ end
+
+ def mark_proposal_applied(session:)
+ session.update!(status: "applied", applied_at: Time.current)
+ end
+ end
+ end
+end
diff --git a/plugins/discourse-workflows/app/services/discourse_workflows/ai_authoring/start.rb b/plugins/discourse-workflows/app/services/discourse_workflows/ai_authoring/start.rb
new file mode 100644
index 00000000000..44a666ebbeb
--- /dev/null
+++ b/plugins/discourse-workflows/app/services/discourse_workflows/ai_authoring/start.rb
@@ -0,0 +1,139 @@
+# frozen_string_literal: true
+
+module DiscourseWorkflows
+ module AiAuthoring
+ class Start
+ include Service::Base
+
+ MODES = %w[create edit explain debug].freeze
+
+ policy :ai_authoring_enabled
+
+ params do
+ attribute :message, :string
+ attribute :mode, :string
+ attribute :workflow_id, :integer
+ attribute :session_id, :integer
+
+ before_validation :normalize_message
+
+ validate :message_is_present
+ validate :message_length_is_valid
+ validate :mode_is_supported
+
+ def effective_mode
+ mode.presence || (workflow_id.present? ? "edit" : "create")
+ end
+
+ def user_message
+ JSON.pretty_generate(
+ { mode: effective_mode, message: message, workflow_id: workflow_id }.compact,
+ )
+ end
+
+ private
+
+ def normalize_message
+ self.message = message.to_s.strip
+ end
+
+ def message_is_present
+ if message.blank?
+ errors.add(:base, I18n.t("discourse_workflows.ai.error_message_required"))
+ end
+ end
+
+ def message_length_is_valid
+ return if message.length <= SiteSetting.discourse_workflows_ai_authoring_max_prompt_length
+
+ errors.add(:base, I18n.t("discourse_workflows.ai.error_message_too_long"))
+ end
+
+ def mode_is_supported
+ return if DiscourseWorkflows::AiAuthoring::Start::MODES.include?(effective_mode)
+
+ errors.add(:base, I18n.t("discourse_workflows.ai.error_invalid_mode"))
+ end
+ end
+
+ policy :can_manage_workflows, class_name: Policy::CanManageWorkflows
+ model :workflow, optional: true
+ policy :workflow_exists_when_requested
+
+ only_if(:existing_session_requested) { model :session, :find_existing_session }
+ only_if(:new_session_requested) { model :session, :create_session }
+ only_if(:session_has_workflow) { step :refresh_session_base_graph }
+ step :record_authoring_request
+
+ model :generation_id, :generate_generation_id
+ step :enqueue_authoring
+
+ private
+
+ def ai_authoring_enabled
+ DiscourseWorkflows::AiAuthoringEnqueuer.enabled?
+ end
+
+ def fetch_workflow(params:)
+ DiscourseWorkflows::Workflow.find_by(id: params.workflow_id) if params.workflow_id.present?
+ end
+
+ def workflow_exists_when_requested(params:, workflow:)
+ params.workflow_id.blank? || workflow.present?
+ end
+
+ def existing_session_requested(params:)
+ params.session_id.present?
+ end
+
+ def new_session_requested(params:)
+ params.session_id.blank?
+ end
+
+ def find_existing_session(params:, guardian:)
+ DiscourseWorkflows::AiAuthoringSession.find_by(
+ id: params.session_id,
+ user_id: guardian.user.id,
+ workflow_id: params.workflow_id,
+ )
+ end
+
+ def create_session(guardian:, workflow:)
+ DiscourseWorkflows::AiAuthoringSession.create(
+ workflow: workflow,
+ user: guardian.user,
+ status: "drafting",
+ messages: [],
+ base_workflow_version_id: workflow&.version_id,
+ base_graph_digest: workflow ? DiscourseWorkflows::Ai::GraphDigest.call(workflow) : nil,
+ )
+ end
+
+ def session_has_workflow(session:)
+ session.workflow.present?
+ end
+
+ def refresh_session_base_graph(session:)
+ session.base_workflow_version_id = session.workflow.version_id
+ session.base_graph_digest = DiscourseWorkflows::Ai::GraphDigest.call(session.workflow)
+ end
+
+ def record_authoring_request(session:, params:)
+ session.latest_request = params.message
+ session.append_message!(type: :user, content: params.user_message)
+ end
+
+ def generate_generation_id
+ SecureRandom.hex
+ end
+
+ def enqueue_authoring(session:, generation_id:, guardian:)
+ DiscourseWorkflows::AiAuthoringEnqueuer.enqueue(
+ session: session,
+ generation_id: generation_id,
+ user: guardian.user,
+ )
+ end
+ end
+ end
+end
diff --git a/plugins/discourse-workflows/app/services/discourse_workflows/workflow/action/apply_patch.rb b/plugins/discourse-workflows/app/services/discourse_workflows/workflow/action/apply_patch.rb
new file mode 100644
index 00000000000..330fdcbad59
--- /dev/null
+++ b/plugins/discourse-workflows/app/services/discourse_workflows/workflow/action/apply_patch.rb
@@ -0,0 +1,424 @@
+# frozen_string_literal: true
+
+module DiscourseWorkflows
+ class Workflow::Action::ApplyPatch < Service::ActionBase
+ AI_AGENT_NODE_TYPE = "action:ai_agent"
+ AI_AGENT_REF_KEY = "$ref"
+ AI_AGENT_REF_PREFIX = "$agent:"
+ CREATE_AI_AGENT_OPERATION = "create_ai_agent"
+ AI_AGENT_ALLOWED_KEYS = %w[name description system_prompt].freeze
+
+ option :workflow
+ option :operations
+ option :persist, default: -> { false }
+ option :user, optional: true
+
+ def call
+ result = build_candidate
+ return result if !result[:valid]
+
+ return result if !persist
+
+ workflow_version = nil
+ created_ai_agents_by_client_id = {}
+ workflow.transaction do
+ created_ai_agents_by_client_id = create_ai_agents!(result[:ai_agent_definitions])
+ rewrite_ai_agent_references!(result[:nodes], created_ai_agents_by_client_id)
+ workflow.update!(nodes: result[:nodes], connections: result[:connections], updated_by: user)
+ workflow_version =
+ workflow.snapshot!(user: user || workflow.updated_by || workflow.created_by)
+ WorkflowDependencyIndexer.call(workflow.reload, version: workflow_version)
+ end
+ Workflow::Action::ExpireCaches.call
+ result[:created_resources] = created_ai_agent_resources(created_ai_agents_by_client_id)
+ result
+ end
+
+ private
+
+ def build_candidate
+ state = initial_state
+ Array
+ .wrap(operations)
+ .each { |operation| apply_operation!(state, normalize_operation!(operation)) }
+ validate_ai_agent_node_references!(state)
+ validate_state(state)
+ rescue PatchError => e
+ invalid_result([e.message])
+ end
+
+ def initial_state
+ nodes = deep_copy(workflow.nodes || [])
+ {
+ nodes: nodes,
+ node_ids_by_client_id: {
+ },
+ connection_records:
+ DiscourseWorkflows::WorkflowDocument.connection_records(
+ nodes,
+ deep_copy(workflow.connections || {}),
+ ),
+ ai_agent_definitions: {
+ },
+ }
+ end
+
+ def normalize_operation!(operation)
+ normalize_hash!(operation, "Patch operation must be an object")
+ end
+
+ def normalize_hash!(value, message)
+ raise PatchError, message if !value.respond_to?(:to_h)
+
+ value.to_h.with_indifferent_access
+ rescue TypeError
+ raise PatchError, message
+ end
+
+ def apply_operation!(state, operation)
+ case operation[:op].to_s
+ when "add_node"
+ add_node!(state, operation)
+ when "update_node_parameters"
+ update_node_parameters!(state, operation)
+ when "rename_node"
+ rename_node!(state, operation)
+ when "remove_node"
+ remove_node!(state, operation)
+ when "add_connection"
+ add_connection!(state, operation)
+ when "remove_connection"
+ remove_connection!(state, operation)
+ when CREATE_AI_AGENT_OPERATION
+ create_ai_agent_definition!(state, operation)
+ else
+ raise PatchError, "Unsupported patch operation: #{operation[:op]}"
+ end
+ end
+
+ def add_node!(state, operation)
+ node_data = normalize_hash!(operation[:node], "Node payload must be an object")
+ node_type = node_data[:type].presence || raise(PatchError, "Node type is required")
+ name = node_data[:name].presence || raise(PatchError, "Node name is required")
+ node_id = SecureRandom.uuid
+ client_id = operation[:client_id].presence
+ state[:node_ids_by_client_id][client_id] = node_id if client_id
+
+ state[:nodes] << {
+ "id" => node_id,
+ "type" => node_type,
+ "typeVersion" => node_type_version(node_data[:typeVersion], node_type),
+ "name" => name,
+ "parameters" => node_data[:parameters] || {},
+ "credentials" => node_credentials(node_data[:credentials]),
+ "webhookId" => node_data[:webhookId],
+ "position" => node_position(node_data[:position]),
+ }
+ end
+
+ def node_position(position)
+ return { "x" => 0, "y" => 0 } if position.blank?
+
+ return { "x" => position[0].to_f, "y" => position[1].to_f } if position.is_a?(Array)
+
+ normalize_hash!(position, "Node position must be an object or [x, y] array")
+ end
+
+ def node_credentials(credentials)
+ return {} if credentials.blank?
+
+ normalize_hash!(credentials, "Credentials must be an object")
+ end
+
+ def node_type_version(type_version, node_type)
+ version = type_version.presence || latest_version(node_type)
+ version = version.to_s
+ version.include?(".") ? version : "#{version}.0"
+ end
+
+ def update_node_parameters!(state, operation)
+ node = find_node!(state, operation)
+ parameters = normalize_hash!(operation[:parameters], "Parameters must be an object")
+ node["parameters"] = (node["parameters"] || {}).merge(parameters)
+ end
+
+ def rename_node!(state, operation)
+ node = find_node!(state, operation)
+ node["name"] = operation[:name].presence || raise(PatchError, "Node name is required")
+ end
+
+ def remove_node!(state, operation)
+ node = find_node!(state, operation)
+ state[:nodes].delete(node)
+ state[:connection_records].reject! do |connection|
+ connection["source_node_id"] == node["id"] || connection["target_node_id"] == node["id"]
+ end
+ end
+
+ def add_connection!(state, operation)
+ source_node_id = resolve_node_ref!(state, operation[:from] || operation[:from_node_id])
+ target_node_id = resolve_node_ref!(state, operation[:to] || operation[:to_node_id])
+ state[:connection_records] << {
+ "source_node_id" => source_node_id,
+ "source_output_index" => operation[:output_index].to_i,
+ "target_node_id" => target_node_id,
+ "target_input_index" => operation[:input_index].to_i,
+ "connection_type" => operation[:connection_type].presence || "main",
+ }
+ end
+
+ def remove_connection!(state, operation)
+ source_node_id = resolve_node_ref!(state, operation[:from] || operation[:from_node_id])
+ target_node_id = resolve_node_ref!(state, operation[:to] || operation[:to_node_id])
+ state[:connection_records].reject! do |connection|
+ connection["source_node_id"] == source_node_id &&
+ connection["target_node_id"] == target_node_id &&
+ (
+ operation[:output_index].blank? ||
+ connection["source_output_index"] == operation[:output_index].to_i
+ ) &&
+ (
+ operation[:input_index].blank? ||
+ connection["target_input_index"] == operation[:input_index].to_i
+ )
+ end
+ end
+
+ def create_ai_agent_definition!(state, operation)
+ ensure_ai_agent_available!
+
+ client_id =
+ operation[:client_id].presence || raise(PatchError, "AI agent client_id is required")
+ if state[:ai_agent_definitions].key?(client_id)
+ raise PatchError, "Duplicate AI agent client_id: #{client_id}"
+ end
+
+ agent_data =
+ normalize_hash!(
+ operation[:agent] || operation[:ai_agent],
+ "AI agent payload must be an object",
+ )
+ unsupported_keys = agent_data.keys.map(&:to_s) - AI_AGENT_ALLOWED_KEYS
+ if unsupported_keys.present?
+ raise PatchError,
+ "AI agent payload includes unsupported fields: #{unsupported_keys.join(", ")}"
+ end
+
+ attributes = ai_agent_attributes(agent_data)
+ validate_unique_ai_agent_name!(state, attributes)
+ validate_ai_agent_attributes!(client_id, attributes)
+ state[:ai_agent_definitions][client_id] = attributes
+ end
+
+ def validate_unique_ai_agent_name!(state, attributes)
+ duplicate =
+ state[:ai_agent_definitions].values.find do |existing_attributes|
+ existing_attributes["name"].casecmp?(attributes["name"])
+ end
+ return if duplicate.blank?
+
+ raise PatchError, "Duplicate proposed AI agent name: #{attributes["name"]}"
+ end
+
+ def ai_agent_attributes(agent_data)
+ {
+ "name" => agent_data[:name].to_s.strip,
+ "description" => agent_data[:description].to_s.strip,
+ "system_prompt" => agent_data[:system_prompt].to_s.strip,
+ "enabled" => true,
+ "tools" => [],
+ "allowed_group_ids" => [],
+ "show_thinking" => false,
+ }
+ end
+
+ def validate_ai_agent_attributes!(client_id, attributes)
+ agent = ::AiAgent.new(attributes.merge("created_by" => ai_agent_creator))
+ return if agent.valid?
+
+ raise PatchError,
+ "AI agent #{client_id.inspect} is invalid: #{agent.errors.full_messages.join(", ")}"
+ end
+
+ def validate_ai_agent_node_references!(state)
+ state[:nodes].each do |node|
+ next if node["type"] != AI_AGENT_NODE_TYPE
+
+ parameters = node["parameters"] || {}
+ agent_id = parameters["agent_id"] || parameters[:agent_id]
+ agent_ref = ai_agent_ref(agent_id)
+
+ if agent_ref.present?
+ validate_ai_agent_ref!(node, parameters, state[:ai_agent_definitions], agent_ref)
+ else
+ validate_existing_ai_agent!(node, parameters, agent_id)
+ end
+ end
+ end
+
+ def validate_ai_agent_ref!(node, parameters, definitions, agent_ref)
+ definition = definitions[agent_ref]
+ if definition.blank?
+ raise PatchError,
+ "#{node_label(node)} references unknown AI agent client_id #{agent_ref.inspect}"
+ end
+
+ parameters["agent_name"] ||= definition["name"]
+ end
+
+ def validate_existing_ai_agent!(node, parameters, agent_id)
+ if agent_id.blank?
+ raise PatchError,
+ "#{node_label(node)} must set agent_id to an existing AI agent ID or a proposed AI agent reference"
+ end
+
+ ensure_ai_agent_available!
+ agent = ::AiAgent.find_by(id: agent_id.to_i)
+ if agent.blank?
+ raise PatchError, "#{node_label(node)} references missing AI agent ID #{agent_id.inspect}"
+ end
+ if !agent.enabled?
+ raise PatchError, "#{node_label(node)} references disabled AI agent #{agent.name.inspect}"
+ end
+
+ parameters["agent_name"] ||= agent.name
+ end
+
+ def ai_agent_ref(value)
+ if value.respond_to?(:to_h)
+ value.to_h[AI_AGENT_REF_KEY].presence
+ elsif value.is_a?(String) && value.start_with?(AI_AGENT_REF_PREFIX)
+ value.delete_prefix(AI_AGENT_REF_PREFIX).presence
+ end
+ end
+
+ def ensure_ai_agent_available!
+ return if defined?(::AiAgent)
+
+ raise PatchError, "AI agent operations require Discourse AI"
+ end
+
+ def node_label(node)
+ node["name"].presence || node["id"].presence || node["type"]
+ end
+
+ def validate_state(state)
+ connections =
+ DiscourseWorkflows::WorkflowDocument.connections_from_records(
+ state[:nodes],
+ state[:connection_records],
+ )
+ candidate = workflow.dup
+ candidate.nodes = state[:nodes]
+ candidate.connections = connections
+ validator =
+ DiscourseWorkflows::WorkflowGraphValidator.new(
+ workflow: candidate,
+ nodes_data: state[:nodes],
+ connections_data: connections,
+ )
+
+ return invalid_result(candidate.errors.full_messages) if !validator.valid?
+
+ {
+ valid: true,
+ errors: [],
+ nodes: validator.nodes,
+ connections: validator.connections,
+ diff: diff_summary,
+ ai_agent_definitions: state[:ai_agent_definitions],
+ created_resources: created_ai_agent_definition_resources(state[:ai_agent_definitions]),
+ }
+ end
+
+ def diff_summary
+ counts =
+ Array.wrap(operations).map { |operation| operation.to_h["op"] || operation.to_h[:op] }.tally
+ { operation_counts: counts, operation_count: counts.values.sum }
+ end
+
+ def invalid_result(errors)
+ { valid: false, errors: Array.wrap(errors), nodes: nil, connections: nil, diff: nil }
+ end
+
+ def create_ai_agents!(definitions)
+ definitions.each_with_object({}) do |(client_id, attributes), created_agents|
+ created_agents[client_id] = ::AiAgent.create!(
+ attributes.merge("created_by" => ai_agent_creator),
+ )
+ end
+ end
+
+ def ai_agent_creator
+ user || Discourse.system_user
+ end
+
+ def rewrite_ai_agent_references!(nodes, created_ai_agents_by_client_id)
+ return if created_ai_agents_by_client_id.blank?
+
+ nodes.each do |node|
+ next if node["type"] != AI_AGENT_NODE_TYPE
+
+ parameters = node["parameters"] || {}
+ agent_ref = ai_agent_ref(parameters["agent_id"] || parameters[:agent_id])
+ next if agent_ref.blank?
+
+ agent = created_ai_agents_by_client_id[agent_ref]
+ next if agent.blank?
+
+ parameters["agent_id"] = agent.id
+ parameters["agent_name"] = agent.name
+ end
+ end
+
+ def created_ai_agent_definition_resources(definitions)
+ definitions.map do |client_id, attributes|
+ {
+ "type" => "ai_agent",
+ "client_id" => client_id,
+ "name" => attributes["name"],
+ "description" => attributes["description"],
+ "system_prompt" => attributes["system_prompt"],
+ }
+ end
+ end
+
+ def created_ai_agent_resources(created_ai_agents_by_client_id)
+ created_ai_agents_by_client_id.map do |client_id, agent|
+ {
+ "type" => "ai_agent",
+ "client_id" => client_id,
+ "id" => agent.id,
+ "name" => agent.name,
+ "description" => agent.description,
+ "system_prompt" => agent.system_prompt,
+ }
+ end
+ end
+
+ def find_node!(state, operation)
+ node_id = resolve_node_ref!(state, operation[:node_id] || operation[:client_id])
+ state[:nodes].find { |node| node["id"].to_s == node_id.to_s } ||
+ raise(PatchError, "Node not found: #{node_id}")
+ end
+
+ def resolve_node_ref!(state, ref)
+ ref = ref.to_s
+ raise PatchError, "Node reference is required" if ref.blank?
+
+ state[:node_ids_by_client_id][ref] || ref
+ end
+
+ def latest_version(node_type)
+ DiscourseWorkflows::Registry.latest_version(node_type) ||
+ DiscourseWorkflows::Registry::DEFAULT_VERSION
+ end
+
+ def deep_copy(value)
+ JSON.parse(JSON.generate(value))
+ end
+
+ class PatchError < StandardError
+ end
+ end
+end
diff --git a/plugins/discourse-workflows/assets/stylesheets/common/canvas/ai-build-tool.scss b/plugins/discourse-workflows/assets/stylesheets/common/canvas/ai-build-tool.scss
new file mode 100644
index 00000000000..b22810ffe81
--- /dev/null
+++ b/plugins/discourse-workflows/assets/stylesheets/common/canvas/ai-build-tool.scss
@@ -0,0 +1,511 @@
+.workflows-canvas {
+ --workflows-canvas-ai-panel-top: calc(var(--space-2) + 3rem);
+ --workflows-canvas-ai-panel-viewport-offset: 18rem;
+
+ &__ai-btn {
+ background: var(--secondary);
+ border: 1px solid var(--primary-low-mid);
+ box-shadow: 0 2px 8px rgb(0, 0, 0, 0.1);
+ }
+
+ &__ai-panel-shell {
+ --workflows-canvas-ai-panel-available-height: min(
+ calc(100% - var(--workflows-canvas-ai-panel-top) - var(--space-2)),
+ calc(100dvh - var(--workflows-canvas-ai-panel-viewport-offset))
+ );
+ position: absolute;
+ top: var(--workflows-canvas-ai-panel-top);
+ right: var(--space-2);
+ z-index: calc(var(--z-canvas-chrome) + 1);
+ display: flex;
+ align-items: flex-start;
+ justify-content: flex-end;
+ gap: var(--space-3);
+ width: min(760px, calc(100% - var(--space-4)));
+ height: var(--workflows-canvas-ai-panel-available-height);
+ max-height: var(--workflows-canvas-ai-panel-available-height);
+ pointer-events: none;
+
+ > * {
+ pointer-events: auto;
+ }
+ }
+
+ &__ai-progress-panel {
+ flex: 0 1 18rem;
+ min-width: 14rem;
+ max-height: 100%;
+ min-height: 0;
+ box-sizing: border-box;
+ padding: var(--space-3);
+ overflow-y: auto;
+ border: 1px solid var(--primary-low);
+ border-radius: var(--d-border-radius);
+ background: var(--secondary);
+ box-shadow: 0 10px 32px rgb(0, 0, 0, 0.16);
+ }
+
+ &__ai-progress-title {
+ margin: 0 0 var(--space-2);
+ color: var(--primary-high);
+ font-size: var(--font-down-1);
+ font-weight: 700;
+ }
+
+ &__ai-panel {
+ display: flex;
+ flex-direction: column;
+ flex: 0 0 min(440px, 100%);
+ gap: var(--space-4);
+ width: min(440px, 100%);
+ max-height: 100%;
+ min-height: 0;
+ min-width: 0;
+ box-sizing: border-box;
+ padding: var(--space-4);
+ overflow-y: auto;
+ border: 1px solid var(--primary-low);
+ border-radius: 18px;
+ background: var(--secondary);
+ box-shadow: 0 16px 48px rgb(0, 0, 0, 0.22);
+
+ &.is-reviewing {
+ overflow: hidden;
+ }
+ }
+
+ &__ai-panel-header {
+ display: flex;
+ align-items: flex-start;
+ justify-content: space-between;
+ gap: var(--space-3);
+ }
+
+ &__ai-title-row {
+ display: flex;
+ flex-direction: column;
+ min-width: 0;
+
+ h3 {
+ margin: 0;
+ color: var(--primary);
+ font-size: var(--font-up-1);
+ line-height: 1.15;
+ }
+
+ p {
+ margin: var(--space-half) 0 0;
+ color: var(--primary-medium);
+ font-size: var(--font-down-2);
+ line-height: 1.25;
+ }
+ }
+
+ &__ai-title {
+ display: flex;
+ gap: var(--space-2);
+ align-items: center;
+ }
+
+ &__ai-title-icon {
+ display: flex;
+ flex: 0 0 auto;
+ align-items: center;
+ justify-content: center;
+ width: 2.25rem;
+ height: 2.25rem;
+ border-radius: 50%;
+ background: var(--tertiary-low);
+ color: var(--tertiary);
+ }
+
+ &__ai-close {
+ flex: 0 0 auto;
+ }
+
+ &__ai-status-row {
+ display: flex;
+ align-items: flex-start;
+ gap: var(--space-2);
+ }
+
+ &__ai-status {
+ flex: 0 0 auto;
+ padding: 0.2rem 0.55rem;
+ border-radius: 999px;
+ background: var(--primary-low);
+ color: var(--primary-high);
+ font-size: var(--font-down-3);
+ font-weight: 700;
+ line-height: 1.2;
+ text-transform: uppercase;
+
+ &.is-working {
+ background: var(--tertiary-low);
+ color: var(--tertiary);
+ }
+
+ &.is-ready {
+ background: var(--success-low);
+ color: var(--success);
+ }
+
+ &.is-error {
+ background: var(--danger-low);
+ color: var(--danger);
+ }
+ }
+
+ &__ai-panel-description {
+ margin: 0;
+ color: var(--primary-medium);
+ font-size: var(--font-down-1);
+ line-height: 1.35;
+ }
+
+ &__ai-prompt-wrap {
+ display: flex;
+ flex-direction: column;
+ gap: var(--space-1);
+
+ label {
+ color: var(--primary-high);
+ font-size: var(--font-down-1);
+ font-weight: 600;
+ }
+ }
+
+ &__ai-prompt {
+ width: 100%;
+ min-height: 11rem;
+ box-sizing: border-box;
+ resize: vertical;
+ border-radius: var(--d-border-radius);
+ }
+
+ &__ai-panel-actions,
+ &__ai-review-actions {
+ display: flex;
+ flex-wrap: wrap;
+ gap: var(--space-2);
+ justify-content: flex-end;
+ }
+
+ &__ai-start-over-btn {
+ flex: 0 0 auto;
+ min-width: 6.75rem;
+ white-space: nowrap;
+ }
+
+ &__ai-review-step {
+ display: flex;
+ flex: 1 1 auto;
+ flex-direction: column;
+ gap: var(--space-3);
+ min-height: 0;
+ }
+
+ &__ai-review-actions {
+ flex: 0 0 auto;
+ justify-content: flex-start;
+ }
+
+ &__ai-review-footer {
+ display: flex;
+ flex: 0 0 auto;
+ justify-content: flex-end;
+ padding-top: var(--space-3);
+ border-top: 1px solid var(--primary-low);
+ background: var(--secondary);
+ }
+
+ &__ai-clarification {
+ display: flex;
+ flex-direction: column;
+ gap: var(--space-3);
+ }
+
+ &__ai-clarification-header {
+ h4,
+ p {
+ margin: 0;
+ }
+
+ h4 {
+ color: var(--primary-high);
+ font-size: var(--font-0);
+ }
+
+ p {
+ margin-top: var(--space-half);
+ color: var(--primary-medium);
+ font-size: var(--font-down-1);
+ line-height: 1.35;
+ }
+ }
+
+ &__ai-question-progress {
+ display: flex;
+ flex-direction: column;
+ gap: var(--space-1);
+ margin-top: var(--space-2);
+ color: var(--primary-medium);
+ font-size: var(--font-down-2);
+ font-weight: 600;
+ }
+
+ &__ai-question-progress-bar {
+ width: 100%;
+ height: 0.35rem;
+ overflow: hidden;
+ border: 0;
+ border-radius: 999px;
+ background: var(--primary-low);
+
+ &::-webkit-progress-bar {
+ background: var(--primary-low);
+ }
+
+ &::-webkit-progress-value {
+ border-radius: 999px;
+ background: var(--tertiary);
+ }
+
+ &::-moz-progress-bar {
+ border-radius: 999px;
+ background: var(--tertiary);
+ }
+ }
+
+ &__ai-question-card {
+ display: flex;
+ flex-direction: column;
+ gap: var(--space-2);
+ padding: var(--space-3);
+ border: 1px solid var(--primary-low);
+ border-radius: var(--d-border-radius);
+ background: var(--primary-very-low);
+
+ h5 {
+ margin: 0;
+ color: var(--primary-high);
+ font-size: var(--font-down-1);
+ line-height: 1.3;
+ }
+ }
+
+ &__ai-question-options {
+ display: flex;
+ flex-direction: column;
+ gap: var(--space-1);
+ }
+
+ &__ai-question-option {
+ display: flex;
+ flex-direction: column;
+ gap: var(--space-half);
+ width: 100%;
+ padding: var(--space-2);
+ border: 1px solid var(--primary-low-mid);
+ border-radius: var(--d-border-radius);
+ background: var(--secondary);
+ color: var(--primary);
+ font: inherit;
+ text-align: left;
+ cursor: pointer;
+
+ span {
+ font-size: var(--font-down-1);
+ font-weight: 600;
+ line-height: 1.25;
+ }
+
+ small {
+ color: var(--primary-medium);
+ font-size: var(--font-down-2);
+ line-height: 1.25;
+ }
+
+ &:hover,
+ &.is-selected {
+ border-color: var(--tertiary);
+ box-shadow: 0 0 0 1px var(--tertiary-low);
+ }
+
+ &.is-selected {
+ background: var(--tertiary-low);
+ }
+ }
+
+ &__ai-custom-answer {
+ display: flex;
+ flex-direction: column;
+ gap: var(--space-1);
+ width: 100%;
+
+ > span {
+ color: var(--primary-medium);
+ font-size: var(--font-down-2);
+ font-weight: 600;
+ }
+ }
+
+ &__ai-custom-answer-input {
+ width: 100%;
+ min-height: 4rem;
+ box-sizing: border-box;
+ resize: vertical;
+ border-radius: var(--d-border-radius);
+ }
+
+ &__ai-progress {
+ display: flex;
+ flex-direction: column;
+ gap: var(--space-2);
+ margin: 0;
+ padding: 0;
+ color: var(--primary-medium);
+ font-size: var(--font-down-1);
+ list-style: none;
+
+ li {
+ position: relative;
+ display: flex;
+ align-items: flex-start;
+ gap: var(--space-2);
+ line-height: 1.35;
+
+ &:not(:last-child)::after {
+ content: "";
+ position: absolute;
+ top: 1rem;
+ left: 0.25rem;
+ width: 1px;
+ height: calc(100% - 0.35rem);
+ background: var(--primary-low-mid);
+ }
+ }
+
+ &.is-working li:last-child .workflows-canvas__ai-progress-marker {
+ animation: workflow-ai-progress-pulse 1.2s ease-in-out infinite;
+ }
+ }
+
+ &__ai-progress-marker {
+ flex: 0 0 auto;
+ width: 0.55rem;
+ height: 0.55rem;
+ margin-top: 0.35rem;
+ border-radius: 50%;
+ background: var(--tertiary);
+ box-shadow: 0 0 0 3px var(--tertiary-low);
+ }
+
+ &__ai-response,
+ &__ai-proposal {
+ max-width: 100%;
+ min-width: 0;
+ box-sizing: border-box;
+ padding: var(--space-3);
+ overflow-wrap: anywhere;
+ border: 1px solid var(--primary-low);
+ border-radius: var(--d-border-radius);
+ background: var(--primary-very-low);
+
+ h4,
+ h5,
+ p,
+ ul {
+ margin-block: 0 var(--space-2);
+ }
+
+ > :last-child {
+ margin-bottom: 0;
+ }
+ }
+
+ &__ai-proposal {
+ background: var(--secondary);
+ }
+
+ &__ai-review-step &__ai-proposal {
+ flex: 1 1 auto;
+ min-height: 0;
+ overflow-y: auto;
+ }
+
+ &__ai-review-step &__ai-code-preview pre {
+ max-height: none;
+ overflow: visible;
+ }
+
+ &__ai-response--error {
+ border-color: var(--danger-low-mid);
+ background: var(--danger-low);
+ color: var(--danger);
+ }
+
+ &__ai-code-previews {
+ display: flex;
+ flex-direction: column;
+ gap: var(--space-2);
+ margin-block: var(--space-3);
+ }
+
+ &__ai-code-preview {
+ overflow: hidden;
+ border: 1px solid var(--primary-low);
+ border-radius: var(--d-border-radius);
+ background: var(--secondary);
+
+ pre {
+ max-height: 16rem;
+ margin: 0;
+ padding: var(--space-3);
+ overflow: auto;
+ background: var(--primary-very-low);
+ font-size: var(--font-down-2);
+ white-space: pre-wrap;
+ }
+ }
+
+ &__ai-code-preview-header {
+ display: flex;
+ justify-content: space-between;
+ gap: var(--space-2);
+ padding: var(--space-2) var(--space-3);
+ border-bottom: 1px solid var(--primary-low);
+ color: var(--primary-medium);
+ font-size: var(--font-down-2);
+ font-weight: 600;
+ }
+
+ &__ai-validation {
+ margin: 0;
+ padding: var(--space-2) var(--space-3);
+ font-size: var(--font-down-2);
+
+ ul {
+ margin: var(--space-1) 0 0;
+ }
+ }
+
+ &__ai-validation--passed {
+ color: var(--success);
+ }
+
+ &__ai-validation--failed {
+ color: var(--danger);
+ }
+}
+
+@keyframes workflow-ai-progress-pulse {
+ 0%,
+ 100% {
+ box-shadow: 0 0 0 3px var(--tertiary-low);
+ }
+
+ 50% {
+ box-shadow: 0 0 0 6px var(--tertiary-low);
+ }
+}
diff --git a/plugins/discourse-workflows/assets/stylesheets/common/canvas/canvas.scss b/plugins/discourse-workflows/assets/stylesheets/common/canvas/canvas.scss
index 1abdc67215a..5e413c0867e 100644
--- a/plugins/discourse-workflows/assets/stylesheets/common/canvas/canvas.scss
+++ b/plugins/discourse-workflows/assets/stylesheets/common/canvas/canvas.scss
@@ -133,21 +133,36 @@
min-width: 6.5em;
}
- &__publish-status {
+ &__top-bar {
position: absolute;
top: var(--space-2);
- left: 50%;
+ right: var(--space-2);
+ left: var(--space-2);
z-index: var(--z-canvas-chrome);
+ display: grid;
+ grid-template-columns: minmax(0, 1fr) auto;
+ align-items: start;
+ gap: var(--space-2);
+ pointer-events: none;
+
+ > * {
+ pointer-events: auto;
+ }
+ }
+
+ &__publish-status {
+ grid-column: 1;
+ justify-self: center;
display: flex;
align-items: center;
gap: var(--space-4);
- max-width: min(65vw, 36rem);
+ min-width: 0;
+ max-width: min(100%, 36rem);
padding: var(--space-1) var(--space-2);
border: 1px solid var(--primary-low-mid);
border-radius: var(--d-border-radius);
background: var(--secondary);
box-shadow: 0 2px 8px rgb(0, 0, 0, 0.1);
- transform: translateX(-50%);
}
&__publish-status-body {
@@ -200,12 +215,10 @@
}
&__toolbar-top-right {
- position: absolute;
- top: var(--space-2);
- right: var(--space-2);
+ grid-column: 2;
+ justify-self: end;
display: flex;
gap: 6px;
- z-index: var(--z-canvas-chrome);
}
&__add-node-btn {
@@ -251,6 +264,17 @@
}
}
+@keyframes workflow-highlight-pulse {
+ 0%,
+ 100% {
+ box-shadow: 0 0 0 2px var(--tertiary-low);
+ }
+
+ 50% {
+ box-shadow: 0 0 0 6px var(--tertiary-low);
+ }
+}
+
@media screen and (width <= 767px) {
.workflows-canvas {
&__empty-state-options {
@@ -312,6 +336,14 @@
box-shadow: 0 0 0 1px var(--tertiary);
}
+ @media (prefers-reduced-motion: no-preference) {
+ &.is-highlighted &__icon-block {
+ border-color: var(--tertiary);
+ box-shadow: 0 0 0 3px var(--tertiary-low);
+ animation: workflow-highlight-pulse 1.25s ease-in-out 4;
+ }
+ }
+
&.is-trigger &__icon-block {
width: 74px;
border-width: 2px;
diff --git a/plugins/discourse-workflows/assets/stylesheets/common/index.scss b/plugins/discourse-workflows/assets/stylesheets/common/index.scss
index 28559f300c7..6f9dfc1279f 100644
--- a/plugins/discourse-workflows/assets/stylesheets/common/index.scss
+++ b/plugins/discourse-workflows/assets/stylesheets/common/index.scss
@@ -2,6 +2,7 @@
@import "workflows-index";
@import "editor/editor";
@import "canvas/canvas";
+@import "canvas/ai-build-tool";
@import "canvas/hover-toolbar";
@import "canvas/node-panel";
@import "canvas/sticky-note";
diff --git a/plugins/discourse-workflows/config/locales/client.en.yml b/plugins/discourse-workflows/config/locales/client.en.yml
index 19d5491310e..b1736a91ee1 100644
--- a/plugins/discourse-workflows/config/locales/client.en.yml
+++ b/plugins/discourse-workflows/config/locales/client.en.yml
@@ -16,9 +16,16 @@ en:
discourse_workflows_variable_created: "Create workflow variable"
discourse_workflows_variable_destroyed: "Delete workflow variable"
discourse_workflows_variable_updated: "Update workflow variable"
+ discourse_workflows_ai_proposal_applied: "Apply AI workflow proposal"
discourse_workflows_workflow_created: "Create workflow"
discourse_workflows_workflow_destroyed: "Delete workflow"
js:
+ discourse_ai:
+ features:
+ discourse_workflows:
+ name: "Workflows"
+ description: "AI-assisted workflow authoring"
+ workflow_authoring: "Workflow authoring"
discourse_workflows:
actor:
system: "System user"
@@ -39,6 +46,55 @@ en:
all_items: "One run for all items"
admin:
title: "Workflows"
+ ai:
+ button: "Build with AI"
+ title: "Workflow assistant"
+ subtitle: "Create automatic drafts. Publishing stays manual."
+ close: "Close workflow assistant"
+ description: "Describe a change, then generate a draft to review. Publishing stays manual."
+ review_description: "Review this draft, then apply it when it looks right."
+ prompt_label: "What should change?"
+ prompt_placeholder: "Example: When a new support topic is created, tag it needs-review and reply with a checklist."
+ generate: "Generate draft"
+ apply: "Apply draft"
+ back_to_prompt: "Edit request"
+ start_over: "Start over"
+ applied: "AI workflow proposal applied to the draft. Publish when you're ready."
+ risks: "Risks"
+ created_agents: "AI agents to create"
+ created_agent_system_prompt: "System prompt"
+ questions: "Questions"
+ status_idle: "Ready"
+ status_working: "Working"
+ status_ready: "Draft ready"
+ status_error: "Needs attention"
+ unexpected_error: "Something went wrong while generating the draft. Please try again."
+ needs_clarification: "Choose an answer, or type a custom response, so the assistant can continue."
+ clarification_intro: "Choose the best option for this question. Use custom answer when the options do not fit."
+ question_progress: "Question %{current} of %{total}"
+ next_question: "Next question"
+ previous_question: "Previous question"
+ continue: "Continue"
+ custom_answer: "Custom answer"
+ custom_answer_placeholder: "Type a different answer…"
+ code_node: "Code node"
+ script_preview: "Code script preview"
+ script_mode: "Mode: %{mode}"
+ script_validation_passed: "Script validation passed"
+ script_validation_failed: "Script validation failed"
+ progress_title: "Progress"
+ progress:
+ queued: "Workflow authoring request queued"
+ loading_context: "Loading workflow authoring context"
+ planning: "Asking the workflow authoring agent to draft a response"
+ writing_scripts: "Reviewing generated Code node scripts"
+ validating_scripts: "Validating generated Code node scripts"
+ validating_patch: "Validating workflow patch"
+ drafting_response: "Drafting workflow authoring response"
+ writing_response: "Writing workflow authoring response"
+ using_tool: "Using %{tool}"
+ tool_finished: "Finished %{tool}"
+ summarizing: "Preparing workflow authoring response"
title: "Workflows"
templates:
title: "Templates"
@@ -163,6 +219,7 @@ en:
"action:code": "Code"
"action:topic": "Topic"
"action:post": "Post"
+ "action:send_personal_message": "Send personal message"
"action:set_fields": "Set fields"
"trigger:stale_topic": "Stale topic"
"trigger:schedule": "Schedule"
@@ -200,8 +257,9 @@ en:
"condition:filter": "Continue only if conditions are met"
"action:topic_tags": "Add or remove tags on a topic"
"action:code": "Run custom JavaScript code"
- "action:topic": "Create, retrieve, list, close, or set custom fields on topics"
+ "action:topic": "Create, retrieve, list, close, archive, or set custom fields on topics"
"action:post": "Create, edit, retrieve, or list posts"
+ "action:send_personal_message": "Send a personal message to users or groups"
"action:set_fields": "Set or modify data fields in the workflow context"
"trigger:stale_topic": "Fires when a topic has had no activity for a period"
"trigger:schedule": "Fires on a recurring schedule"
@@ -211,7 +269,7 @@ en:
"action:sort": "Sort items by field values, randomly, or with custom code"
"action:http_request": "Make an HTTP request to an external API"
"action:data_table": "Read, write, or query a workflow data table"
- "action:group": "Add or remove a user from a group"
+ "action:group": "Read, check, or update group membership"
"action:badge": "Grant or revoke a badge"
"trigger:form": "Generates a public web form and fires when it is submitted"
"action:form": "Adds a page to a multi-step form"
@@ -289,6 +347,7 @@ en:
add: "Add user"
remove: "Remove user"
get: "Get group"
+ check_membership: "Check membership"
username: "User"
group_id: "Group"
group_id_placeholder: "Select a group"
@@ -303,6 +362,15 @@ en:
badge_id: "Badge"
badge_id_placeholder: "Select a badge"
actor_username: "Performed by user"
+ send_personal_message:
+ recipient_usernames: "Recipients"
+ recipient_usernames_description: "Select one or more users"
+ recipient_group_names: "Recipient groups"
+ recipient_group_names_description: "Select one or more groups"
+ title: "Title"
+ raw: "Body"
+ raw_description: "Raw content for the personal message"
+ sender_username: "Sender"
post:
operation: "Operation"
operations:
@@ -386,6 +454,7 @@ en:
get: "Get topic"
list: "List topics"
close: "Close topic"
+ archive: "Archive topic"
set_custom_fields: "Set custom fields"
topic_id: "Topic ID"
title: "Title"
@@ -478,12 +547,14 @@ en:
column_name: "a column name"
data_table_id: "a data table ID"
group_id: "a group ID"
+ group_names: "group names"
id: "an ID"
number: "a number"
option_value: "an option value"
query_id: "a query ID"
tag_names: "tag names"
username: "a username"
+ usernames: "usernames"
user_or_group_name: "a username or group name"
add_attributes: "Attributes"
assignment_name: "Name"
diff --git a/plugins/discourse-workflows/config/locales/server.en.yml b/plugins/discourse-workflows/config/locales/server.en.yml
index fe487b7820c..9eeccce2948 100644
--- a/plugins/discourse-workflows/config/locales/server.en.yml
+++ b/plugins/discourse-workflows/config/locales/server.en.yml
@@ -7,6 +7,38 @@ en:
error_workflow_id:
cannot_be_self: "cannot be set to the workflow itself"
discourse_workflows:
+ ai:
+ default_code_node_name: "Code"
+ error_agent_not_configured: "The workflow authoring agent is not configured."
+ error_invalid_mode: "Invalid AI workflow authoring mode."
+ error_invalid_patch: "The AI proposal did not pass workflow validation: %{errors}"
+ error_invalid_response: "AI returned an invalid response."
+ error_invalid_script: "The AI generated Code node JavaScript that did not pass validation. Regenerate the proposal or ask the assistant to fix the script."
+ error_invalid_script_with_errors: "The AI generated Code node JavaScript that did not pass validation: %{errors}. Regenerate the proposal or ask the assistant to fix the script."
+ error_message_required: "Enter a prompt for the workflow assistant."
+ error_message_too_long: "The workflow assistant prompt is too long."
+ error_no_operations: "The AI response did not include any workflow patch operations."
+ error_not_enabled: "AI-assisted workflow authoring is not enabled."
+ error_proposal_not_ready: "This AI proposal is not ready to apply."
+ error_stale_proposal: "The workflow changed after this AI proposal was generated. Regenerate the proposal."
+ clarification_message: "Choose answers so the assistant can continue drafting the workflow."
+ tool_call_proposal_message: "The assistant drafted a workflow patch and the server validated it."
+ tool_call_proposal_summary:
+ one: "The assistant drafted one workflow patch operation. Review it before applying."
+ other: "The assistant drafted %{count} workflow patch operations. Review them before applying."
+ tool_call_proposal_title: "Workflow patch"
+ progress:
+ queued: "Workflow authoring request queued"
+ loading_context: "Loading workflow authoring context"
+ planning: "Asking the workflow authoring agent to draft a response"
+ writing_scripts: "Reviewing generated Code node scripts"
+ validating_scripts: "Validating generated Code node scripts"
+ validating_patch: "Validating workflow patch"
+ drafting_response: "Drafting workflow authoring response"
+ writing_response: "Writing workflow authoring response"
+ using_tool: "Using %{tool}"
+ tool_finished: "Finished %{tool}"
+ summarizing: "Preparing workflow authoring response"
errors:
approval_timed_out: "Approval timed out"
webhook_timed_out: "Webhook timed out"
@@ -47,6 +79,8 @@ en:
edit_failed: "Failed to edit post."
unknown_operation: "Unknown operation: %{operation}."
invalid_filter: "Invalid post filter fragment: %{fragments}."
+ send_personal_message:
+ no_recipients: "At least one personal message recipient is required."
credential:
missing_required_field: "is missing required field '%{field}'"
wait:
@@ -97,3 +131,45 @@ en:
field_not_found: "The field '%{field}' wasn't found in any input item."
site_settings:
discourse_workflows_enabled: "Enable the discourse-workflows plugin."
+ discourse_workflows_ai_authoring_enabled: "Enable AI-assisted workflow authoring."
+ discourse_workflows_ai_authoring_max_prompt_length: "Maximum length for AI workflow authoring prompts."
+ discourse_workflows_ai_authoring_rate_limit_per_minute: "Maximum AI workflow authoring requests per minute per user."
+ discourse_ai:
+ ai_bot:
+ agents:
+ ai_workflow_author:
+ name: "Workflow author"
+ description: "Builds and edits Discourse workflows from natural language"
+ tool_help:
+ workflow_node_catalog: "Lists available workflow nodes and their configuration schema"
+ workflow_ai_agent_catalog: "Lists existing Discourse AI agents that workflow drafts can reuse"
+ workflow_graph_context: "Describes the current workflow graph"
+ workflow_validate_patch: "Dry-runs and validates workflow patch operations"
+ workflow_ask_questions: "Asks the workflow admin to choose clarification answers"
+ workflow_authoring_result: "Returns the final workflow authoring result"
+ workflow_resolve_entity: "Resolves Discourse names to workflow parameter values"
+ search_chat_channels: "Searches chat channel names and IDs for workflow parameters"
+ workflow_script_context: "Returns context for writing workflow Code node JavaScript"
+ workflow_validate_script: "Validates workflow Code node JavaScript"
+ tool_summary:
+ workflow_node_catalog: "Reading workflow node catalog"
+ workflow_ai_agent_catalog: "Reading AI agent catalog"
+ workflow_graph_context: "Reading workflow graph"
+ workflow_validate_patch: "Validating workflow patch"
+ workflow_ask_questions: "Asking clarification questions"
+ workflow_authoring_result: "Returning workflow authoring result"
+ workflow_resolve_entity: "Resolving Discourse entities"
+ search_chat_channels: "Searching chat channels"
+ workflow_script_context: "Loading script context"
+ workflow_validate_script: "Validating script"
+ tool_description:
+ workflow_node_catalog: "Read workflow node catalog"
+ workflow_ai_agent_catalog: "Read AI agent catalog"
+ workflow_graph_context: "Read workflow graph"
+ workflow_validate_patch: "Validated workflow patch"
+ workflow_ask_questions: "Asked clarification questions"
+ workflow_authoring_result: "Returned workflow authoring result"
+ workflow_resolve_entity: "Resolved Discourse entities"
+ search_chat_channels: "Searched chat channels"
+ workflow_script_context: "Loaded script context"
+ workflow_validate_script: "Validated script"
diff --git a/plugins/discourse-workflows/config/routes.rb b/plugins/discourse-workflows/config/routes.rb
index 7cb62406186..d2817b0e4fa 100644
--- a/plugins/discourse-workflows/config/routes.rb
+++ b/plugins/discourse-workflows/config/routes.rb
@@ -27,6 +27,9 @@ DiscourseWorkflows::Engine.routes.draw do
scope format: :json do
get "/workflows" => "workflows#index"
post "/workflows" => "workflows#create"
+ post "/workflows/ai/author" => "ai_authoring#create"
+ post "/workflows/:workflow_id/ai/author" => "ai_authoring#create"
+ post "/workflows/:workflow_id/ai/apply" => "ai_authoring#apply"
get "/workflows/:id" => "workflows#show"
put "/workflows/:id" => "workflows#update"
post "/workflows/:id/discard-draft" => "workflows#discard_draft"
diff --git a/plugins/discourse-workflows/config/settings.yml b/plugins/discourse-workflows/config/settings.yml
index 15f7228071e..40e1aed3417 100644
--- a/plugins/discourse-workflows/config/settings.yml
+++ b/plugins/discourse-workflows/config/settings.yml
@@ -3,6 +3,20 @@ plugins:
default: false
client: true
hidden: true
+ discourse_workflows_ai_authoring_enabled:
+ default: false
+ client: true
+ hidden: true
+ discourse_workflows_ai_authoring_max_prompt_length:
+ default: 4000
+ min: 1
+ max: 20000
+ hidden: true
+ discourse_workflows_ai_authoring_rate_limit_per_minute:
+ default: 10
+ min: 1
+ max: 100
+ hidden: true
discourse_workflows_max_executions_per_minute:
default: 20
hidden: true
diff --git a/plugins/discourse-workflows/db/migrate/20260601063855_create_ai_authoring_sessions.rb b/plugins/discourse-workflows/db/migrate/20260601063855_create_ai_authoring_sessions.rb
new file mode 100644
index 00000000000..003cb6ace70
--- /dev/null
+++ b/plugins/discourse-workflows/db/migrate/20260601063855_create_ai_authoring_sessions.rb
@@ -0,0 +1,30 @@
+# frozen_string_literal: true
+
+class CreateAiAuthoringSessions < ActiveRecord::Migration[8.0]
+ def change
+ create_table :discourse_workflows_ai_authoring_sessions do |t|
+ t.bigint :workflow_id
+ t.integer :user_id, null: false
+ t.string :status, null: false, limit: 40, default: "drafting"
+ t.jsonb :messages, null: false, default: []
+ t.text :latest_request
+ t.jsonb :latest_response, null: false, default: {}
+ t.jsonb :proposed_patch, null: false, default: {}
+ t.string :base_workflow_version_id, limit: 36
+ t.string :base_graph_digest, limit: 64
+ t.string :risk_level, limit: 20
+ t.datetime :applied_at
+ t.timestamps null: false
+ end
+
+ add_index :discourse_workflows_ai_authoring_sessions,
+ :workflow_id,
+ name: "idx_dwf_ai_sessions_on_workflow_id"
+ add_index :discourse_workflows_ai_authoring_sessions,
+ :user_id,
+ name: "idx_dwf_ai_sessions_on_user_id"
+ add_index :discourse_workflows_ai_authoring_sessions,
+ %i[status updated_at],
+ name: "idx_dwf_ai_sessions_on_status_updated_at"
+ end
+end
diff --git a/plugins/discourse-workflows/lib/discourse_workflows/ai/graph_digest.rb b/plugins/discourse-workflows/lib/discourse_workflows/ai/graph_digest.rb
new file mode 100644
index 00000000000..188da7117ed
--- /dev/null
+++ b/plugins/discourse-workflows/lib/discourse_workflows/ai/graph_digest.rb
@@ -0,0 +1,22 @@
+# frozen_string_literal: true
+
+module DiscourseWorkflows
+ module Ai
+ module GraphDigest
+ module_function
+
+ def call(workflow)
+ Digest::SHA256.hexdigest(
+ JSON.generate(
+ {
+ name: workflow.name,
+ nodes: workflow.nodes || [],
+ connections: workflow.connections || {},
+ settings: workflow.settings || {},
+ },
+ ),
+ )
+ end
+ end
+ end
+end
diff --git a/plugins/discourse-workflows/lib/discourse_workflows/ai/progress_publisher.rb b/plugins/discourse-workflows/lib/discourse_workflows/ai/progress_publisher.rb
new file mode 100644
index 00000000000..53d5d58bb3f
--- /dev/null
+++ b/plugins/discourse-workflows/lib/discourse_workflows/ai/progress_publisher.rb
@@ -0,0 +1,21 @@
+# frozen_string_literal: true
+
+module DiscourseWorkflows
+ module Ai
+ class ProgressPublisher
+ CHANNEL_PREFIX = "/discourse-workflows/ai-authoring"
+ MAX_BACKLOG_AGE = 5.minutes.to_i
+
+ def self.publish(generation_id:, user:, status:, **payload)
+ return if generation_id.blank? || user.blank?
+
+ MessageBus.publish(
+ "#{CHANNEL_PREFIX}/#{generation_id}",
+ payload.merge(status: status, generation_id: generation_id),
+ user_ids: [user.id],
+ max_backlog_age: MAX_BACKLOG_AGE,
+ )
+ end
+ end
+ end
+end
diff --git a/plugins/discourse-workflows/lib/discourse_workflows/ai/tools/base.rb b/plugins/discourse-workflows/lib/discourse_workflows/ai/tools/base.rb
new file mode 100644
index 00000000000..82dba68242a
--- /dev/null
+++ b/plugins/discourse-workflows/lib/discourse_workflows/ai/tools/base.rb
@@ -0,0 +1,29 @@
+# frozen_string_literal: true
+
+module DiscourseWorkflows
+ module Ai
+ module Tools
+ class Base < DiscourseAi::Agents::Tools::Tool
+ def self.custom?
+ true
+ end
+
+ private
+
+ def ensure_can_manage_workflows!
+ return true if context.user&.guardian&.can_manage_workflows?
+
+ false
+ end
+
+ def not_allowed_response
+ error_response(I18n.t("discourse.errors.disallowed"))
+ end
+
+ def json_safe(value)
+ JSON.parse(value.to_json)
+ end
+ end
+ end
+ end
+end
diff --git a/plugins/discourse-workflows/lib/discourse_workflows/ai/tools/search_chat_channels.rb b/plugins/discourse-workflows/lib/discourse_workflows/ai/tools/search_chat_channels.rb
new file mode 100644
index 00000000000..02451ea6530
--- /dev/null
+++ b/plugins/discourse-workflows/lib/discourse_workflows/ai/tools/search_chat_channels.rb
@@ -0,0 +1,90 @@
+# frozen_string_literal: true
+
+module DiscourseWorkflows
+ module Ai
+ module Tools
+ class SearchChatChannels < Base
+ MAX_RESULTS = 20
+ CHANNEL_NAME_SQL = "COALESCE(chat_channels.name, categories.name)"
+
+ def self.signature
+ {
+ name: name,
+ description:
+ "Searches open Discourse chat channels and returns channel names and IDs for workflow chat node parameters.",
+ parameters: [
+ {
+ name: "query",
+ description:
+ "Partial channel name, slug, category name, or #channel mention to search for",
+ type: "string",
+ required: false,
+ },
+ ],
+ }
+ end
+
+ def self.name
+ "search_chat_channels"
+ end
+
+ def self.available?
+ defined?(::Chat::Channel) && defined?(SiteSetting.chat_enabled) &&
+ SiteSetting.chat_enabled
+ end
+
+ def invoke
+ return not_allowed_response if !ensure_can_manage_workflows!
+ return error_response("Chat is not enabled") if !self.class.available?
+
+ query = normalize_query(parameters[:query])
+
+ {
+ status: "success",
+ query: query,
+ matches: channels_matching(query).map { |channel| channel_data(channel) },
+ }
+ end
+
+ private
+
+ def channels_matching(query)
+ channels =
+ ::Chat::Channel
+ .public_channels
+ .includes(:chatable)
+ .where(status: ::Chat::Channel.statuses[:open])
+
+ if query.present?
+ sql_query = "%#{ActiveRecord::Base.sanitize_sql_like(query.downcase)}%"
+ channels =
+ channels.where(
+ "LOWER(#{CHANNEL_NAME_SQL}) LIKE :query OR LOWER(chat_channels.slug) LIKE :query OR LOWER(categories.slug) LIKE :query",
+ query: sql_query,
+ )
+ end
+
+ channels.order("LOWER(#{CHANNEL_NAME_SQL}) ASC").limit(MAX_RESULTS)
+ end
+
+ def channel_data(channel)
+ category = channel.chatable if channel.chatable.is_a?(::Category)
+
+ {
+ id: channel.id,
+ name: channel.name.presence || category&.name,
+ slug: channel.slug,
+ category_id: category&.id,
+ category_name: category&.name,
+ category_slug: category&.slug,
+ url: channel.relative_url,
+ }
+ end
+
+ def normalize_query(query)
+ query.to_s.strip.delete_prefix("#").strip
+ end
+ end
+ end
+ end
+end
diff --git a/plugins/discourse-workflows/lib/discourse_workflows/ai/tools/workflow_ai_agent_catalog.rb b/plugins/discourse-workflows/lib/discourse_workflows/ai/tools/workflow_ai_agent_catalog.rb
new file mode 100644
index 00000000000..d8428c93e92
--- /dev/null
+++ b/plugins/discourse-workflows/lib/discourse_workflows/ai/tools/workflow_ai_agent_catalog.rb
@@ -0,0 +1,89 @@
+# frozen_string_literal: true
+
+module DiscourseWorkflows
+ module Ai
+ module Tools
+ class WorkflowAiAgentCatalog < Base
+ MAX_RESULTS = 10
+ PROMPT_EXCERPT_LENGTH = 500
+
+ def self.signature
+ {
+ name: name,
+ description:
+ "Searches existing Discourse AI agents so workflow drafts can reuse a suitable enabled agent instead of creating a duplicate.",
+ json_schema: {
+ type: "object",
+ additionalProperties: false,
+ properties: {
+ query: {
+ type: "string",
+ description: "Search terms for the needed agent behavior, name, or description.",
+ },
+ include_disabled: {
+ type: "boolean",
+ description:
+ "Whether to include disabled agents for awareness. Defaults to false; disabled agents should not be used in workflow nodes.",
+ },
+ },
+ },
+ }
+ end
+
+ def self.name
+ "workflow_ai_agent_catalog"
+ end
+
+ def invoke
+ return not_allowed_response if !ensure_can_manage_workflows!
+ return error_response("AI agents are not available") if !defined?(::AiAgent)
+
+ agents = matching_agents
+ {
+ status: "success",
+ agents: agents.map { |agent| serialize_agent(agent) },
+ instruction:
+ "Reuse a suitable enabled agent by setting action:ai_agent agent_id to its id. If no suitable enabled agent exists, propose a create_ai_agent operation with name, description, and system_prompt.",
+ }
+ end
+
+ private
+
+ def matching_agents
+ scope = ::AiAgent.order("lower(name) ASC")
+ scope = scope.where(enabled: true) if !include_disabled?
+
+ terms = query_terms
+ records = scope.limit(::AiAgent::MAX_AGENTS_PER_SITE).to_a
+ records = records.select { |agent| matches_terms?(agent, terms) } if terms.present?
+ records.first(MAX_RESULTS)
+ end
+
+ def include_disabled?
+ parameters[:include_disabled].to_s == "true" || parameters[:include_disabled] == true
+ end
+
+ def query_terms
+ parameters[:query].to_s.downcase.scan(/[a-z0-9_:-]+/).uniq
+ end
+
+ def matches_terms?(agent, terms)
+ words = [agent.name, agent.description, agent.system_prompt].join(" ")
+ .downcase
+ .scan(/[a-z0-9_:-]+/)
+ terms.all? { |term| words.any? { |word| word == term || word.start_with?(term) } }
+ end
+
+ def serialize_agent(agent)
+ {
+ id: agent.id,
+ name: agent.name,
+ description: agent.description,
+ enabled: agent.enabled?,
+ system_prompt_excerpt: agent.system_prompt.to_s.truncate(PROMPT_EXCERPT_LENGTH),
+ }
+ end
+ end
+ end
+ end
+end
diff --git a/plugins/discourse-workflows/lib/discourse_workflows/ai/tools/workflow_ask_questions.rb b/plugins/discourse-workflows/lib/discourse_workflows/ai/tools/workflow_ask_questions.rb
new file mode 100644
index 00000000000..110bd3917d5
--- /dev/null
+++ b/plugins/discourse-workflows/lib/discourse_workflows/ai/tools/workflow_ask_questions.rb
@@ -0,0 +1,136 @@
+# frozen_string_literal: true
+
+module DiscourseWorkflows
+ module Ai
+ module Tools
+ class WorkflowAskQuestions < Base
+ MAX_QUESTIONS = 4
+ MAX_OPTIONS = 8
+ MAX_TEXT_LENGTH = 500
+
+ def self.signature
+ {
+ name: name,
+ description:
+ "Ask the workflow admin concise clarification questions and pause workflow authoring until the admin answers.",
+ json_schema: {
+ type: "object",
+ additionalProperties: false,
+ required: %w[questions],
+ properties: {
+ questions: {
+ type: "array",
+ minItems: 1,
+ maxItems: MAX_QUESTIONS,
+ items: {
+ type: "object",
+ additionalProperties: false,
+ required: %w[id question options],
+ properties: {
+ id: {
+ type: "string",
+ description: "Stable short identifier for this question.",
+ },
+ question: {
+ type: "string",
+ description: "The question to show to the admin.",
+ },
+ multi_select: {
+ type: "boolean",
+ description: "Whether the admin may choose more than one option.",
+ },
+ custom_allowed: {
+ type: "boolean",
+ description: "Whether the admin may type a custom answer.",
+ },
+ options: {
+ type: "array",
+ minItems: 2,
+ maxItems: MAX_OPTIONS,
+ items: {
+ type: "object",
+ additionalProperties: false,
+ required: %w[label description],
+ properties: {
+ label: {
+ type: "string",
+ description: "Short option label.",
+ },
+ description: {
+ type: "string",
+ description: "One sentence describing what this option means.",
+ },
+ },
+ },
+ },
+ },
+ },
+ },
+ },
+ },
+ }
+ end
+
+ def self.name
+ "workflow_ask_questions"
+ end
+
+ def invoke
+ return not_allowed_response if !ensure_can_manage_workflows!
+
+ questions =
+ Array
+ .wrap(parameters[:questions])
+ .first(MAX_QUESTIONS)
+ .filter_map
+ .with_index { |question, index| normalize_question(question, index) }
+ return error_response("At least one question is required") if questions.blank?
+
+ { status: "waiting_for_user", questions: questions }
+ end
+
+ def chain_next_response?
+ false
+ end
+
+ private
+
+ def normalize_question(question, index)
+ question = normalized_hash(question)
+ text = truncate_text(question[:question])
+ return if text.blank?
+
+ options =
+ Array
+ .wrap(question[:options])
+ .first(MAX_OPTIONS)
+ .filter_map { |option| normalize_option(option) }
+
+ {
+ id: truncate_text(question[:id].presence || "question_#{index + 1}", 80),
+ question: text,
+ multi_select: !!question[:multi_select],
+ custom_allowed: question.key?(:custom_allowed) ? !!question[:custom_allowed] : true,
+ options: options,
+ }
+ end
+
+ def normalize_option(option)
+ option = option.is_a?(Hash) ? normalized_hash(option) : { label: option.to_s }
+ label = truncate_text(option[:label])
+ return if label.blank?
+
+ { label: label, description: truncate_text(option[:description]) }
+ end
+
+ def truncate_text(text, length = MAX_TEXT_LENGTH)
+ text.to_s.strip.truncate(length)
+ end
+
+ def normalized_hash(value)
+ value.respond_to?(:to_h) ? value.to_h.with_indifferent_access : {}.with_indifferent_access
+ end
+ end
+ end
+ end
+end
diff --git a/plugins/discourse-workflows/lib/discourse_workflows/ai/tools/workflow_authoring_result.rb b/plugins/discourse-workflows/lib/discourse_workflows/ai/tools/workflow_authoring_result.rb
new file mode 100644
index 00000000000..49a174750a6
--- /dev/null
+++ b/plugins/discourse-workflows/lib/discourse_workflows/ai/tools/workflow_authoring_result.rb
@@ -0,0 +1,227 @@
+# frozen_string_literal: true
+
+module DiscourseWorkflows
+ module Ai
+ module Tools
+ class WorkflowAuthoringResult < Base
+ STATUSES = %w[needs_clarification proposed_patch explanation error].freeze
+ RISK_LEVELS = %w[low medium high].freeze
+ MAX_TEXT_LENGTH = 2000
+
+ def self.signature
+ {
+ name: name,
+ description:
+ "Return the final workflow authoring result to Discourse and stop the authoring turn. Use this instead of writing a JSON final answer.",
+ json_schema: {
+ type: "object",
+ additionalProperties: false,
+ required: %w[status message],
+ properties: {
+ status: {
+ type: "string",
+ enum: STATUSES,
+ description:
+ "Final result status: needs_clarification, proposed_patch, explanation, or error.",
+ },
+ message: {
+ type: "string",
+ description: "Short user-facing summary of the result.",
+ },
+ questions: {
+ type: "array",
+ description: "Clarification questions when status is needs_clarification.",
+ items: {
+ type: "object",
+ additionalProperties: true,
+ properties: {
+ id: {
+ type: "string",
+ },
+ question: {
+ type: "string",
+ },
+ multi_select: {
+ type: "boolean",
+ },
+ custom_allowed: {
+ type: "boolean",
+ },
+ options: {
+ type: "array",
+ items: {
+ type: "object",
+ additionalProperties: true,
+ properties: {
+ label: {
+ type: "string",
+ },
+ description: {
+ type: "string",
+ },
+ },
+ },
+ },
+ },
+ },
+ },
+ proposal: {
+ type: "object",
+ description:
+ "Workflow patch proposal when status is proposed_patch. Include title, summary, assumptions, risks, risk_level, and operations.",
+ additionalProperties: true,
+ properties: {
+ title: {
+ type: "string",
+ },
+ workflow_name: {
+ type: "string",
+ },
+ summary: {
+ type: "string",
+ },
+ assumptions: {
+ type: "array",
+ items: {
+ type: "string",
+ },
+ },
+ risks: {
+ type: "array",
+ items: {
+ type: "string",
+ },
+ },
+ risk_level: {
+ type: "string",
+ enum: RISK_LEVELS,
+ },
+ operations: {
+ type: "array",
+ items: {
+ type: "object",
+ additionalProperties: true,
+ },
+ },
+ },
+ },
+ },
+ },
+ }
+ end
+
+ def self.name
+ "workflow_authoring_result"
+ end
+
+ def invoke
+ return not_allowed_response if !ensure_can_manage_workflows!
+
+ normalize_response
+ end
+
+ def chain_next_response?
+ false
+ end
+
+ private
+
+ def normalize_response
+ params = normalized_hash(parameters)
+ proposal = normalized_hash(params[:proposal])
+ operations = normalized_patch_operations(proposal[:operations])
+ proposal[:operations] = operations if operations.present?
+
+ status = params[:status].to_s
+ status = "proposed_patch" if status.blank? && operations.present?
+
+ response = {
+ status: status,
+ message: truncate_text(params[:message]),
+ questions: normalized_questions(params[:questions]),
+ proposal: json_safe(proposal),
+ }
+
+ validate_response(response)
+ end
+
+ def validate_response(response)
+ if STATUSES.exclude?(response[:status])
+ return error_result("Invalid workflow authoring result status")
+ end
+
+ if response[:status] == "needs_clarification" && response[:questions].blank?
+ return error_result("Clarification results must include at least one question")
+ end
+
+ if response[:status] == "proposed_patch" && response.dig(:proposal, "operations").blank?
+ return error_result("Proposed patch results must include proposal.operations")
+ end
+
+ response
+ end
+
+ def error_result(message)
+ { status: "error", message: message, questions: [], proposal: {} }
+ end
+
+ def normalized_questions(questions)
+ Array
+ .wrap(questions)
+ .first(WorkflowAskQuestions::MAX_QUESTIONS)
+ .filter_map
+ .with_index { |question, index| normalize_question(question, index) }
+ end
+
+ def normalize_question(question, index)
+ question = normalized_hash(question)
+ text = truncate_text(question[:question], WorkflowAskQuestions::MAX_TEXT_LENGTH)
+ return if text.blank?
+
+ options =
+ Array
+ .wrap(question[:options])
+ .first(WorkflowAskQuestions::MAX_OPTIONS)
+ .filter_map { |option| normalize_option(option) }
+
+ {
+ id:
+ truncate_text(
+ question[:id].presence || "question_#{index + 1}",
+ WorkflowAskQuestions::MAX_TEXT_LENGTH,
+ ),
+ question: text,
+ multi_select: !!question[:multi_select],
+ custom_allowed: question.key?(:custom_allowed) ? !!question[:custom_allowed] : true,
+ options: options,
+ }
+ end
+
+ def normalize_option(option)
+ option = option.is_a?(Hash) ? normalized_hash(option) : { label: option.to_s }
+ label = truncate_text(option[:label], WorkflowAskQuestions::MAX_TEXT_LENGTH)
+ return if label.blank?
+
+ {
+ label: label,
+ description: truncate_text(option[:description], WorkflowAskQuestions::MAX_TEXT_LENGTH),
+ }
+ end
+
+ def normalized_patch_operations(operations)
+ Array
+ .wrap(operations)
+ .map { |operation| operation.respond_to?(:to_h) ? operation.to_h : operation }
+ end
+
+ def normalized_hash(value)
+ value.respond_to?(:to_h) ? value.to_h.with_indifferent_access : {}.with_indifferent_access
+ end
+
+ def truncate_text(text, length = MAX_TEXT_LENGTH)
+ text.to_s.strip.truncate(length)
+ end
+ end
+ end
+ end
+end
diff --git a/plugins/discourse-workflows/lib/discourse_workflows/ai/tools/workflow_graph_context.rb b/plugins/discourse-workflows/lib/discourse_workflows/ai/tools/workflow_graph_context.rb
new file mode 100644
index 00000000000..d373075f5b6
--- /dev/null
+++ b/plugins/discourse-workflows/lib/discourse_workflows/ai/tools/workflow_graph_context.rb
@@ -0,0 +1,94 @@
+# frozen_string_literal: true
+
+module DiscourseWorkflows
+ module Ai
+ module Tools
+ class WorkflowGraphContext < Base
+ def self.signature
+ {
+ name: name,
+ description:
+ "Returns the current draft workflow graph in a compact form for AI workflow authoring.",
+ parameters: [
+ {
+ name: "workflow_id",
+ description: "The workflow ID. Omit when creating a new workflow.",
+ type: "integer",
+ required: false,
+ },
+ ],
+ }
+ end
+
+ def self.name
+ "workflow_graph_context"
+ end
+
+ def invoke
+ return not_allowed_response if !ensure_can_manage_workflows!
+
+ workflow_id = parameters[:workflow_id].presence
+ return empty_workflow_context if workflow_id.blank?
+
+ workflow = DiscourseWorkflows::Workflow.find_by(id: workflow_id)
+ return error_response("Workflow not found") if workflow.blank?
+
+ nodes = workflow.nodes || []
+ connections =
+ DiscourseWorkflows::WorkflowDocument.connection_records(
+ nodes,
+ workflow.connections || {},
+ )
+
+ {
+ status: "success",
+ workflow: {
+ id: workflow.id,
+ name: workflow.name,
+ published: workflow.published?,
+ has_unpublished_changes: workflow.has_unpublished_changes?,
+ version_id: workflow.version_id,
+ active_version_id: workflow.active_version_id,
+ graph_digest: DiscourseWorkflows::Ai::GraphDigest.call(workflow),
+ },
+ nodes: nodes.map { |node| serialize_node(node) },
+ connections: connections.map { |connection| serialize_connection(connection, nodes) },
+ }
+ end
+
+ private
+
+ def empty_workflow_context
+ { status: "success", workflow: nil, nodes: [], connections: [] }
+ end
+
+ def serialize_node(node)
+ {
+ id: node["id"],
+ name: node["name"],
+ type: node["type"],
+ type_version: node["typeVersion"],
+ parameters: DiscourseWorkflows::NodeData.parameters(node),
+ position: node["position"],
+ }
+ end
+
+ def serialize_connection(connection, nodes)
+ nodes_by_id = nodes.index_by { |node| node["id"].to_s }
+ source = nodes_by_id[connection["source_node_id"].to_s]
+ target = nodes_by_id[connection["target_node_id"].to_s]
+
+ {
+ from_node_id: connection["source_node_id"],
+ from_node_name: source&.dig("name"),
+ to_node_id: connection["target_node_id"],
+ to_node_name: target&.dig("name"),
+ connection_type: connection["connection_type"],
+ output_index: connection["source_output_index"],
+ input_index: connection["target_input_index"],
+ }
+ end
+ end
+ end
+ end
+end
diff --git a/plugins/discourse-workflows/lib/discourse_workflows/ai/tools/workflow_node_catalog.rb b/plugins/discourse-workflows/lib/discourse_workflows/ai/tools/workflow_node_catalog.rb
new file mode 100644
index 00000000000..98144850060
--- /dev/null
+++ b/plugins/discourse-workflows/lib/discourse_workflows/ai/tools/workflow_node_catalog.rb
@@ -0,0 +1,362 @@
+# frozen_string_literal: true
+
+module DiscourseWorkflows
+ module Ai
+ module Tools
+ class WorkflowNodeCatalog < Base
+ TOPIC_LIST_ITEM_SCHEMA = {
+ "topic" => "TopicListItemSerializer payload",
+ "topic.id" => "integer",
+ "topic.title" => "string",
+ "topic.fancy_title" => "string",
+ "topic.slug" => "string",
+ "topic.posts_count" => "integer",
+ "topic.category_id" => "integer",
+ "topic.tags" => "array<string>",
+ "topic.first_post_id" => "integer",
+ "topic.closed" => "boolean",
+ "topic.archived" => "boolean",
+ "topic.created_at" => "datetime",
+ "topic.last_posted_at" => "datetime",
+ "topic.bumped_at" => "datetime",
+ }.freeze
+
+ POST_SCHEMA = {
+ "post" => "DiscourseWorkflows::PostSerializer payload",
+ "post.id" => "integer",
+ "post.raw" => "string",
+ "post.post_number" => "integer",
+ "post.reply_to_post_number" => "integer|null",
+ "post.topic_id" => "integer",
+ "post.topic_slug" => "string",
+ "post.topic_title" => "string",
+ "post.post_url" => "string",
+ "post.category_id" => "integer",
+ "post.category_name" => "string|null",
+ "post.user_id" => "integer",
+ "post.username" => "string",
+ "post.created_at" => "datetime",
+ "post.updated_at" => "datetime",
+ "post.excerpt" => "string",
+ "post.like_count" => "integer",
+ "post.reply_count" => "integer",
+ "post.score" => "number|null",
+ "post.tags" => "array<string>",
+ }.freeze
+
+ WEBHOOK_POST_SCHEMA =
+ POST_SCHEMA.except(
+ "post.category_name",
+ "post.excerpt",
+ "post.like_count",
+ "post.tags",
+ ).merge("post" => "WebHookPostSerializer payload", "post.category_slug" => "string")
+
+ USER_SCHEMA = {
+ "user" => "Basic safe user attributes for the post author",
+ "user.id" => "integer",
+ "user.username" => "string",
+ "user.name" => "string|null",
+ "user.trust_level" => "integer",
+ "user.trust_level_name" => "string",
+ "user.admin" => "boolean",
+ "user.moderator" => "boolean",
+ "user.staff" => "boolean",
+ }.freeze
+
+ GROUP_MEMBERSHIP_SCHEMA = {
+ "group_membership" => "Group membership check result",
+ "group_membership.group_id" => "integer",
+ "group_membership.group_name" => "string",
+ "group_membership.user_id" => "integer",
+ "group_membership.username" => "string",
+ "group_membership.in_group" => "boolean",
+ }.freeze
+
+ OUTPUT_SCHEMAS = {
+ "trigger:manual" => {
+ },
+ "trigger:topic_admin_button" => TOPIC_LIST_ITEM_SCHEMA,
+ "trigger:topic_created" => TOPIC_LIST_ITEM_SCHEMA.merge(POST_SCHEMA),
+ "trigger:post_created" => POST_SCHEMA.merge(TOPIC_LIST_ITEM_SCHEMA).merge(USER_SCHEMA),
+ "trigger:post_edited" => POST_SCHEMA.merge(TOPIC_LIST_ITEM_SCHEMA).merge(USER_SCHEMA),
+ "trigger:topic_closed" => TOPIC_LIST_ITEM_SCHEMA,
+ "action:topic" => TOPIC_LIST_ITEM_SCHEMA.merge(WEBHOOK_POST_SCHEMA),
+ "action:topic_tags" => {
+ "topic_id" => "integer",
+ "tag_names" => "array<string>",
+ },
+ "action:post" => POST_SCHEMA,
+ "action:send_personal_message" => TOPIC_LIST_ITEM_SCHEMA.merge(POST_SCHEMA),
+ "action:send_chat_message" => {
+ "channel_id" => "integer",
+ "message" => "string",
+ },
+ "action:ai_agent" => {
+ "result" => "string",
+ },
+ }.freeze
+
+ EXAMPLES = {
+ "action:code" => [
+ {
+ name: "Add a derived field",
+ mode: "runOnceForAllItems",
+ code:
+ "var items = $input.all();\n" \
+ "items.forEach(function(item) {\n" \
+ " item.json.summary = item.json.topic && item.json.topic.title;\n" \
+ "});\n" \
+ "return items;",
+ },
+ ],
+ "condition:filter" => [
+ {
+ name: "Keep TL1 posts mentioning cake",
+ parameters: {
+ combinator: "and",
+ conditions: [
+ {
+ id: "author_trust_level",
+ leftValue: "={{ $json.user.trust_level }}",
+ operator: {
+ operation: "equals",
+ type: "number",
+ singleValue: false,
+ },
+ rightValue: "1",
+ },
+ {
+ id: "post_mentions_cake",
+ leftValue: "={{ $json.post.raw }}",
+ operator: {
+ operation: "contains",
+ type: "string",
+ singleValue: false,
+ },
+ rightValue: "cake",
+ },
+ ],
+ },
+ },
+ {
+ name: "Keep TL1-or-lower post authors",
+ parameters: {
+ combinator: "and",
+ conditions: [
+ {
+ id: "post_author_trust_level",
+ leftValue: "={{ $json.user.trust_level }}",
+ operator: {
+ operation: "lte",
+ type: "number",
+ singleValue: false,
+ },
+ rightValue: "1",
+ },
+ ],
+ },
+ },
+ ],
+ "condition:if" => [
+ {
+ name: "Branch on TL1-or-lower post authors",
+ parameters: {
+ combinator: "and",
+ conditions: [
+ {
+ id: "post_author_trust_level",
+ leftValue: "={{ $json.user.trust_level }}",
+ operator: {
+ operation: "lte",
+ type: "number",
+ singleValue: false,
+ },
+ rightValue: "1",
+ },
+ ],
+ },
+ },
+ ],
+ "action:group" => [
+ {
+ name: "Keep posts from members of a group",
+ parameters: {
+ operation: "check_membership",
+ username: "={{ $json.user.username }}",
+ group_id: 123,
+ actor_username: "system",
+ },
+ },
+ ],
+ "action:topic" => [
+ {
+ name: "Get trigger topic details",
+ parameters: {
+ operation: "get",
+ topic_id: "={{ $json.topic.id }}",
+ actor_username: "system",
+ },
+ },
+ ],
+ "action:post" => [
+ {
+ name: "Reply to the trigger topic",
+ parameters: {
+ operation: "create",
+ topic_id: "={{ $json.topic.id }}",
+ raw: "Thanks for the report. A staff member will review this soon.",
+ author_username: "system",
+ },
+ },
+ ],
+ "action:send_personal_message" => [
+ {
+ name: "DM a post link to an admin",
+ parameters: {
+ recipient_usernames: ["admin"],
+ title: "=New post from @{{ $json.post.username }}",
+ raw: "=A group member posted: {{ $json.post.post_url }}",
+ sender_username: "system",
+ },
+ },
+ ],
+ "action:ai_agent" => [
+ {
+ name: "Classify the trigger post with an existing agent",
+ parameters: {
+ agent_id: 123,
+ agent_name: "Post classifier",
+ prompt:
+ "=Classify this Discourse post and return a short label: {{ $json.post.raw }}",
+ },
+ },
+ ],
+ "action:topic_tags" => [
+ {
+ name: "Add a tag to the trigger topic",
+ parameters: {
+ operation: "add",
+ topic_id: "={{ $json.topic.id }}",
+ tag_names: "needs-review",
+ actor_username: "system",
+ },
+ },
+ ],
+ }.freeze
+
+ QUERY_STOP_WORDS = %w[
+ node
+ nodes
+ trigger
+ triggers
+ action
+ actions
+ condition
+ conditions
+ flow
+ ].freeze
+
+ SEARCH_ALIASES = {
+ "action:send_personal_message" => "dm direct message pm personal private message",
+ "action:ai_agent" => "ai agent bot llm classify summarize generate sentiment triage",
+ "action:group" => "group membership member belongs friend friends",
+ }.freeze
+
+ def self.signature
+ {
+ name: name,
+ description:
+ "Lists available Discourse workflow node types with versions, parameters, capabilities, output schemas, and examples.",
+ parameters: [
+ {
+ name: "query",
+ description: "Optional search terms for node type, name, group, or parameter names",
+ type: "string",
+ required: false,
+ },
+ {
+ name: "include_examples",
+ description: "Whether to include curated examples for matching nodes",
+ type: "boolean",
+ required: false,
+ },
+ ],
+ }
+ end
+
+ def self.name
+ "workflow_node_catalog"
+ end
+
+ def self.output_schema_for(identifier, parameters: {}, input_schema: {})
+ parameters = parameters.respond_to?(:to_h) ? parameters.to_h.with_indifferent_access : {}
+
+ if identifier.to_s == "action:group" && parameters[:operation].to_s == "check_membership"
+ return input_schema.merge(GROUP_MEMBERSHIP_SCHEMA)
+ end
+
+ OUTPUT_SCHEMAS.fetch(identifier.to_s, {})
+ end
+
+ def invoke
+ return not_allowed_response if !ensure_can_manage_workflows!
+
+ query_terms = self.class.query_terms(parameters[:query])
+ include_examples =
+ parameters[:include_examples].to_s == "true" || parameters[:include_examples] == true
+
+ nodes =
+ DiscourseWorkflows::Registry.nodes.filter_map do |node_class|
+ serialize_node(node_class, query_terms, include_examples)
+ end
+
+ { status: "success", nodes: nodes }
+ end
+
+ def self.query_terms(query)
+ query
+ .to_s
+ .downcase
+ .scan(/[a-z0-9_:-]+/)
+ .map { |term| term.delete_prefix("type:") }
+ .reject { |term| QUERY_STOP_WORDS.include?(term) }
+ .uniq
+ end
+
+ private
+
+ def serialize_node(node_class, query_terms, include_examples)
+ description = node_class.description
+ identifier = node_class.identifier
+ properties = json_safe(node_class.properties || {})
+ group = description[:group].to_s.presence
+
+ haystack = [
+ identifier,
+ group,
+ properties.keys.join(" "),
+ SEARCH_ALIASES[identifier],
+ ].compact.join(" ").downcase
+ return if query_terms.present? && query_terms.none? { |term| haystack.include?(term) }
+
+ payload = {
+ type: identifier,
+ version: node_class.version,
+ group: group,
+ available: node_class.available?,
+ palette_visible: node_class.palette_visible?,
+ inputs: json_safe(node_class.inputs),
+ outputs: json_safe(node_class.outputs),
+ properties: properties,
+ credentials: json_safe(node_class.credentials),
+ capabilities: json_safe(description[:capabilities] || {}),
+ output_schema: self.class.output_schema_for(identifier),
+ }
+ payload[:examples] = EXAMPLES[identifier] if include_examples && EXAMPLES.key?(identifier)
+ payload
+ end
+ end
+ end
+ end
+end
diff --git a/plugins/discourse-workflows/lib/discourse_workflows/ai/tools/workflow_resolve_entity.rb b/plugins/discourse-workflows/lib/discourse_workflows/ai/tools/workflow_resolve_entity.rb
new file mode 100644
index 00000000000..320a7befa5a
--- /dev/null
+++ b/plugins/discourse-workflows/lib/discourse_workflows/ai/tools/workflow_resolve_entity.rb
@@ -0,0 +1,109 @@
+# frozen_string_literal: true
+
+module DiscourseWorkflows
+ module Ai
+ module Tools
+ class WorkflowResolveEntity < Base
+ SUPPORTED_KINDS = %w[category tag user group badge data_table].freeze
+ MAX_RESULTS = 10
+
+ def self.signature
+ {
+ name: name,
+ description:
+ "Resolves Discourse entity names to IDs or names that can be used in workflow node parameters.",
+ parameters: [
+ {
+ name: "kind",
+ description: "One of: #{SUPPORTED_KINDS.join(", ")}",
+ type: "string",
+ required: true,
+ },
+ {
+ name: "query",
+ description: "Name, slug, username, or partial text to search for",
+ type: "string",
+ required: true,
+ },
+ ],
+ }
+ end
+
+ def self.name
+ "workflow_resolve_entity"
+ end
+
+ def invoke
+ return not_allowed_response if !ensure_can_manage_workflows!
+
+ kind = parameters[:kind].to_s
+ query = parameters[:query].to_s.strip
+ return error_response("Unsupported entity kind") if SUPPORTED_KINDS.exclude?(kind)
+ return error_response("Query is required") if query.blank?
+
+ { status: "success", kind: kind, matches: send("resolve_#{kind}", query) }
+ end
+
+ private
+
+ def resolve_category(query)
+ Category
+ .where(
+ "name ILIKE :query OR slug ILIKE :query",
+ query: "%#{Category.sanitize_sql_like(query)}%",
+ )
+ .order(:name)
+ .limit(MAX_RESULTS)
+ .map { |category| { id: category.id, name: category.name, slug: category.slug } }
+ end
+
+ def resolve_tag(query)
+ Tag
+ .where("name ILIKE ?", "%#{Tag.sanitize_sql_like(query)}%")
+ .order(:name)
+ .limit(MAX_RESULTS)
+ .pluck(:id, :name)
+ .map { |id, name| { id: id, name: name } }
+ end
+
+ def resolve_user(query)
+ User
+ .real
+ .where("username_lower LIKE ?", "%#{User.normalize_username(query)}%")
+ .order(:username_lower)
+ .limit(MAX_RESULTS)
+ .pluck(:id, :username, :name)
+ .map { |id, username, name| { id: id, username: username, name: name } }
+ end
+
+ def resolve_group(query)
+ Group
+ .where("name ILIKE ?", "%#{Group.sanitize_sql_like(query)}%")
+ .order(:name)
+ .limit(MAX_RESULTS)
+ .pluck(:id, :name)
+ .map { |id, name| { id: id, name: name } }
+ end
+
+ def resolve_badge(query)
+ Badge
+ .where(enabled: true)
+ .where("name ILIKE ?", "%#{Badge.sanitize_sql_like(query)}%")
+ .order(:name)
+ .limit(MAX_RESULTS)
+ .pluck(:id, :name)
+ .map { |id, name| { id: id, name: name } }
+ end
+
+ def resolve_data_table(query)
+ DiscourseWorkflows::DataTable
+ .where("name ILIKE ?", "%#{DiscourseWorkflows::DataTable.sanitize_sql_like(query)}%")
+ .order(:name)
+ .limit(MAX_RESULTS)
+ .pluck(:id, :name)
+ .map { |id, name| { id: id, name: name } }
+ end
+ end
+ end
+ end
+end
diff --git a/plugins/discourse-workflows/lib/discourse_workflows/ai/tools/workflow_script_context.rb b/plugins/discourse-workflows/lib/discourse_workflows/ai/tools/workflow_script_context.rb
new file mode 100644
index 00000000000..42169f3c60a
--- /dev/null
+++ b/plugins/discourse-workflows/lib/discourse_workflows/ai/tools/workflow_script_context.rb
@@ -0,0 +1,231 @@
+# frozen_string_literal: true
+
+module DiscourseWorkflows
+ module Ai
+ module Tools
+ class WorkflowScriptContext < Base
+ AVAILABLE_VARIABLES = {
+ "$input.item.json" => "Current item's JSON data",
+ "$input.all()" => "Array of all input items; only valid in runOnceForAllItems mode",
+ "$json" => "Shortcut for $input.item.json",
+ "$(\"NodeName\").item" => "Paired item from another node",
+ "$vars.KEY" => "Workflow variables",
+ "$site_settings.NAME" => "Site settings",
+ "$execution" => "Execution metadata",
+ "$current_user" => "User running the workflow",
+ "console.log" => "Workflow execution log",
+ }.freeze
+
+ RETURN_CONTRACT = {
+ "runOnceForAllItems" =>
+ "Return an array of items. Each item should be { json: { ... } } or a plain object that can be normalized.",
+ "runOnceForEachItem" =>
+ "Return one object per input item. Do not return an array in this mode.",
+ "reserved_top_level_keys" => %w[json pairedItem error index],
+ }.freeze
+
+ MODE_RESTRICTIONS = {
+ "runOnceForEachItem" => {
+ "disallowed_input_methods" => %w[
+ $input.first
+ $input.last
+ $input.all
+ $input.itemMatching
+ ],
+ },
+ }.freeze
+
+ EXAMPLES = [
+ {
+ name: "Add a derived field to each item",
+ mode: "runOnceForAllItems",
+ code:
+ "var items = $input.all();\n" \
+ "items.forEach(function(item) {\n" \
+ " item.json.summary = item.json.topic && item.json.topic.title;\n" \
+ "});\n" \
+ "return items;",
+ },
+ {
+ name: "Build one Markdown reply from all items",
+ mode: "runOnceForAllItems",
+ code:
+ "var lines = $input.all().map(function(item) {\n" \
+ " return '- ' + item.json.title;\n" \
+ "});\n" \
+ "return [{ json: { raw: lines.join('\\n') } }];",
+ },
+ ].freeze
+
+ def self.signature
+ {
+ name: name,
+ description:
+ "Returns the runtime, input, output, sample data, and return-contract context needed to write a workflow Code node script.",
+ parameters: [
+ { name: "workflow_id", description: "Workflow ID", type: "integer", required: false },
+ {
+ name: "target_node_id",
+ description: "Existing Code node ID when editing a script",
+ type: "string",
+ required: false,
+ },
+ {
+ name: "upstream_node_id",
+ description: "Node ID that feeds the Code node",
+ type: "string",
+ required: false,
+ },
+ {
+ name: "downstream_node_id",
+ description: "Node ID that consumes the Code node output",
+ type: "string",
+ required: false,
+ },
+ {
+ name: "sample_limit",
+ description: "Maximum number of pinned sample items to return",
+ type: "integer",
+ required: false,
+ },
+ ],
+ }
+ end
+
+ def self.name
+ "workflow_script_context"
+ end
+
+ def invoke
+ return not_allowed_response if !ensure_can_manage_workflows!
+
+ workflow = find_workflow
+ if parameters[:workflow_id].present? && workflow.blank?
+ return error_response("Workflow not found")
+ end
+
+ @workflow_for_schema = workflow
+ nodes = workflow&.nodes || []
+ target_node = find_node(nodes, parameters[:target_node_id])
+ upstream_node = find_node(nodes, parameters[:upstream_node_id])
+ downstream_node = find_node(nodes, parameters[:downstream_node_id])
+
+ {
+ status: "success",
+ runtime: runtime,
+ available_variables: AVAILABLE_VARIABLES,
+ return_contract: RETURN_CONTRACT,
+ mode_restrictions: MODE_RESTRICTIONS,
+ upstream_schema: node_schema(upstream_node),
+ downstream_requirements: downstream_requirements(downstream_node),
+ sample_input_items: sample_input_items(workflow, upstream_node),
+ existing_code: existing_code(target_node),
+ examples: EXAMPLES,
+ }
+ end
+
+ private
+
+ def find_workflow
+ workflow_id = parameters[:workflow_id].presence
+ return nil if workflow_id.blank?
+
+ DiscourseWorkflows::Workflow.find_by(id: workflow_id)
+ end
+
+ def find_node(nodes, node_id)
+ return nil if node_id.blank?
+
+ nodes.find { |node| node["id"].to_s == node_id.to_s }
+ end
+
+ def runtime
+ {
+ language: "javascript",
+ node_type: "action:code",
+ version: "1.0",
+ modes: %w[runOnceForAllItems runOnceForEachItem],
+ default_mode: "runOnceForAllItems",
+ }
+ end
+
+ def node_schema(node)
+ return nil if node.blank?
+
+ {
+ node_id: node["id"],
+ node_name: node["name"],
+ node_type: node["type"],
+ fields:
+ DiscourseWorkflows::Ai::Tools::WorkflowNodeCatalog::OUTPUT_SCHEMAS.fetch(
+ node["type"],
+ infer_schema_from_pin_data(node),
+ ),
+ }
+ end
+
+ def infer_schema_from_pin_data(node)
+ sample = @workflow_for_schema&.node_pin_data(node["name"])&.first
+ flatten_schema(sample&.dig("json") || {})
+ end
+
+ def downstream_requirements(node)
+ return nil if node.blank?
+
+ node_type =
+ DiscourseWorkflows::Registry.find_node_type(node["type"], version: node["typeVersion"])
+ properties = node_type&.properties || {}
+ required_fields =
+ properties.each_with_object({}) do |(name, property), result|
+ next unless property[:required]
+
+ result[name.to_s] = property[:type].to_s
+ end
+
+ {
+ node_id: node["id"],
+ node_name: node["name"],
+ node_type: node["type"],
+ required_fields: required_fields,
+ }
+ end
+
+ def sample_input_items(workflow, upstream_node)
+ return [] if workflow.blank? || upstream_node.blank?
+
+ limit = parameters[:sample_limit].presence&.to_i || 5
+ Array.wrap(workflow.node_pin_data(upstream_node["name"])).first(limit)
+ end
+
+ def existing_code(node)
+ return nil if node.blank? || node["type"] != "action:code"
+
+ DiscourseWorkflows::NodeData.parameters(node)["code"]
+ end
+
+ def flatten_schema(value, prefix = nil, result = {})
+ case value
+ when Hash
+ value.each do |key, child|
+ child_prefix = [prefix, key].compact.join(".")
+ flatten_schema(child, child_prefix, result)
+ end
+ when Array
+ result[prefix] = "array"
+ when Integer
+ result[prefix] = "integer"
+ when Float
+ result[prefix] = "number"
+ when TrueClass, FalseClass
+ result[prefix] = "boolean"
+ when NilClass
+ result[prefix] = "null"
+ else
+ result[prefix] = value.class.name.downcase
+ end
+ result
+ end
+ end
+ end
+ end
+end
diff --git a/plugins/discourse-workflows/lib/discourse_workflows/ai/tools/workflow_validate_patch.rb b/plugins/discourse-workflows/lib/discourse_workflows/ai/tools/workflow_validate_patch.rb
new file mode 100644
index 00000000000..316d826a82e
--- /dev/null
+++ b/plugins/discourse-workflows/lib/discourse_workflows/ai/tools/workflow_validate_patch.rb
@@ -0,0 +1,369 @@
+# frozen_string_literal: true
+
+module DiscourseWorkflows
+ module Ai
+ module Tools
+ class WorkflowValidatePatch < Base
+ def self.signature
+ {
+ name: name,
+ description:
+ "Dry-runs a workflow patch and returns validation errors, normalized graph data, inferred node input/output schemas, proposed created resources, and a diff summary without saving anything.",
+ json_schema: {
+ type: "object",
+ additionalProperties: false,
+ required: %w[operations],
+ properties: {
+ workflow_id: {
+ type: "integer",
+ description: "Workflow ID.",
+ },
+ workflow_name: {
+ type: "string",
+ description: "Name to use when validating a brand-new workflow patch.",
+ },
+ operations: {
+ type: "array",
+ description:
+ "Array of workflow patch operation objects. Each item must be an object, not a JSON string.",
+ items: {
+ type: "object",
+ additionalProperties: true,
+ },
+ },
+ },
+ },
+ }
+ end
+
+ def self.name
+ "workflow_validate_patch"
+ end
+
+ def invoke
+ return not_allowed_response if !ensure_can_manage_workflows!
+
+ workflow = find_or_build_workflow
+ result =
+ DiscourseWorkflows::Workflow::Action::ApplyPatch.call(
+ workflow: workflow,
+ operations: normalized_patch_operations(parameters[:operations]),
+ persist: false,
+ )
+
+ if result[:valid]
+ schemas = node_schemas(result[:nodes], result[:connections])
+ graph_errors = connection_validation_errors(result[:nodes], result[:connections])
+ expression_errors = expression_validation_errors(result[:nodes], schemas)
+ else
+ schemas = []
+ graph_errors = []
+ expression_errors = []
+ end
+
+ valid = result[:valid] && graph_errors.blank? && expression_errors.blank?
+ errors = Array.wrap(result[:errors]) + graph_errors + expression_errors
+
+ {
+ status: "success",
+ valid: valid,
+ errors: errors,
+ graph_errors: graph_errors,
+ expression_errors: expression_errors,
+ normalized_graph:
+ result[:valid] ? { nodes: result[:nodes], connections: result[:connections] } : nil,
+ node_schemas: schemas,
+ diff: result[:diff],
+ created_resources: Array.wrap(result[:created_resources]),
+ }
+ end
+
+ private
+
+ PASS_THROUGH_NODE_TYPES = %w[condition:filter condition:if action:limit flow:wait].freeze
+ CONDITION_NODE_TYPES = %w[condition:filter condition:if].freeze
+
+ JSON_REFERENCE_REGEX = /\$json(?:\.[A-Za-z_][A-Za-z0-9_]*)+/
+ MAX_AVAILABLE_PATHS = 12
+
+ FIXED_OUTPUT_SCHEMAS = {
+ "action:send_chat_message" => {
+ "channel_id" => "integer",
+ "message" => "string",
+ },
+ }.freeze
+
+ def node_schemas(nodes, connections)
+ connection_records =
+ DiscourseWorkflows::WorkflowDocument.connection_records(nodes, connections)
+ output_schemas = {}
+ input_schemas = {}
+
+ (nodes.length + 1).times do
+ changed = false
+
+ nodes.each do |node|
+ node_id = node["id"].to_s
+ next_input_schema = input_schema_for(node_id, connection_records, output_schemas)
+ next_output_schema = output_schema_for(node, next_input_schema)
+
+ if input_schemas[node_id] != next_input_schema ||
+ output_schemas[node_id] != next_output_schema
+ input_schemas[node_id] = next_input_schema
+ output_schemas[node_id] = next_output_schema
+ changed = true
+ end
+ end
+
+ break if !changed
+ end
+
+ nodes.map do |node|
+ node_id = node["id"].to_s
+ {
+ node_id: node_id,
+ node_name: node["name"],
+ node_type: node["type"],
+ input_schema: expression_schema(input_schemas[node_id] || {}),
+ output_schema: expression_schema(output_schemas[node_id] || {}),
+ input_sources: input_sources(node_id, nodes, connection_records, output_schemas),
+ }
+ end
+ end
+
+ def input_schema_for(node_id, connection_records, output_schemas)
+ incoming = incoming_connections(node_id, connection_records)
+ return {} if incoming.blank?
+
+ incoming.each_with_object({}) do |connection, result|
+ result.merge!(output_schemas[connection["source_node_id"].to_s] || {})
+ end
+ end
+
+ def output_schema_for(node, input_schema)
+ catalog_schema =
+ DiscourseWorkflows::Ai::Tools::WorkflowNodeCatalog.output_schema_for(
+ node["type"],
+ parameters: node["parameters"] || {},
+ input_schema: input_schema,
+ )
+ return catalog_schema if catalog_schema.present?
+ return input_schema if PASS_THROUGH_NODE_TYPES.include?(node["type"].to_s)
+
+ FIXED_OUTPUT_SCHEMAS.fetch(node["type"].to_s, {})
+ end
+
+ def input_sources(node_id, nodes, connection_records, output_schemas)
+ nodes_by_id = nodes.index_by { |node| node["id"].to_s }
+ incoming_connections(node_id, connection_records).map do |connection|
+ source_node = nodes_by_id[connection["source_node_id"].to_s]
+ {
+ source_node_id: connection["source_node_id"].to_s,
+ source_node_name: source_node&.dig("name"),
+ source_node_type: source_node&.dig("type"),
+ output_index: connection["source_output_index"],
+ input_index: connection["target_input_index"],
+ schema: expression_schema(output_schemas[connection["source_node_id"].to_s] || {}),
+ }
+ end
+ end
+
+ def connection_validation_errors(nodes, connections)
+ connection_records =
+ DiscourseWorkflows::WorkflowDocument.connection_records(nodes, connections)
+ nodes_by_id = nodes.index_by { |node| node["id"].to_s }
+
+ connection_records.filter_map do |connection|
+ source_node = nodes_by_id[connection["source_node_id"].to_s]
+ next if source_node.blank?
+
+ connection_type = connection["connection_type"].to_s.presence || "main"
+ valid_types = output_connection_types(source_node)
+ next if valid_types.include?(connection_type)
+
+ "#{node_label(source_node)} output connection_type #{connection_type.inspect} is invalid for #{source_node["type"]}. Use one of: #{valid_types.join(", ")}."
+ end
+ end
+
+ def output_connection_types(node)
+ node_class =
+ DiscourseWorkflows::Registry.find_node_type(node["type"], version: node["typeVersion"])
+ outputs = Array.wrap(node_class&.outputs(node["parameters"] || {}) || [:main])
+ outputs.map do |output|
+ output.respond_to?(:to_h) ? output.to_h.with_indifferent_access[:key].to_s : output.to_s
+ end
+ end
+
+ def incoming_connections(node_id, connection_records)
+ connection_records
+ .select { |connection| connection["target_node_id"].to_s == node_id.to_s }
+ .sort_by do |connection|
+ [connection["target_input_index"].to_i, connection["source_output_index"].to_i]
+ end
+ end
+
+ def expression_schema(schema)
+ schema.transform_keys { |key| key.to_s.start_with?("$json") ? key.to_s : "$json.#{key}" }
+ end
+
+ def expression_validation_errors(nodes, schemas)
+ schemas_by_node_id = schemas.index_by { |schema| schema[:node_id].to_s }
+
+ nodes.flat_map do |node|
+ schema = schemas_by_node_id[node["id"].to_s] || {}
+ input_schema = schema[:input_schema] || {}
+ expression_errors_for_node(node, input_schema) + condition_configuration_errors(node)
+ end
+ end
+
+ def expression_errors_for_node(node, input_schema)
+ parameter_values(node["parameters"] || {}).flat_map do |path, value|
+ next [] if !value.is_a?(String)
+
+ errors = []
+ if unprefixed_template_expression?(value)
+ errors << "#{node_label(node)} parameter #{path} contains {{ }} expressions but does not start with =. Prefix dynamic template strings with =, for example =Text {{ $json.topic.id }}."
+ end
+
+ if invalid_bare_json_expression?(value)
+ errors << "#{node_label(node)} parameter #{path} references $json in an expression string without {{ }}. Use ={{ $json.field }} for whole-field values or =Text {{ $json.field }} for template strings."
+ end
+
+ errors + unavailable_json_path_errors(node, path, value, input_schema)
+ end
+ end
+
+ def condition_configuration_errors(node)
+ return [] if !CONDITION_NODE_TYPES.include?(node["type"].to_s)
+
+ conditions = Array.wrap((node["parameters"] || {})["conditions"])
+ conditions.flat_map.with_index do |condition, index|
+ condition = condition.respond_to?(:to_h) ? condition.to_h.with_indifferent_access : {}
+ condition_index = index + 1
+ errors = []
+
+ if condition[:leftValue].blank?
+ hint = condition.key?(:left) ? " Use leftValue instead of left." : ""
+ errors << "#{node_label(node)} condition #{condition_index} must set leftValue.#{hint}"
+ elsif invalid_condition_value?(condition[:leftValue])
+ errors << "#{node_label(node)} condition #{condition_index} leftValue must be a scalar or expression string, not an object."
+ end
+
+ operator = condition[:operator].respond_to?(:to_h) ? condition[:operator].to_h : {}
+ operator = operator.with_indifferent_access
+ if operator[:type].blank?
+ errors << "#{node_label(node)} condition #{condition_index} must set operator.type."
+ end
+ if operator[:operation].blank?
+ errors << "#{node_label(node)} condition #{condition_index} must set operator.operation."
+ end
+
+ if !operator[:singleValue] && !condition.key?(:rightValue)
+ hint = condition.key?(:right) ? " Use rightValue instead of right." : ""
+ errors << "#{node_label(node)} condition #{condition_index} must set rightValue for #{operator[:operation].presence || "this"} comparisons.#{hint}"
+ elsif condition.key?(:rightValue) && invalid_condition_value?(condition[:rightValue])
+ errors << "#{node_label(node)} condition #{condition_index} rightValue must be a scalar or expression string, not an object."
+ end
+
+ errors
+ end
+ end
+
+ def invalid_condition_value?(value)
+ value.is_a?(Hash) || value.is_a?(Array)
+ end
+
+ def parameter_values(value, prefix = nil)
+ case value
+ when Hash
+ value.flat_map do |key, nested_value|
+ parameter_values(nested_value, [prefix, key].compact.join("."))
+ end
+ when Array
+ value.flat_map.with_index do |nested_value, index|
+ parameter_values(nested_value, "#{prefix}[#{index}]")
+ end
+ else
+ [[prefix || "parameters", value]]
+ end
+ end
+
+ def unprefixed_template_expression?(value)
+ value.include?("{{") && value.include?("}}") && !value.start_with?("=")
+ end
+
+ def invalid_bare_json_expression?(value)
+ value.start_with?("=") && value.include?("$json") && !value.include?("{{")
+ end
+
+ def unavailable_json_path_errors(node, parameter_path, value, input_schema)
+ references = value.scan(JSON_REFERENCE_REGEX).uniq
+ return [] if references.blank? || input_schema.blank?
+
+ references.filter_map do |reference|
+ next if schema_path_available?(reference, input_schema)
+
+ "#{node_label(node)} parameter #{parameter_path} references #{reference}, but that path is not available in this node's input schema. Available paths: #{available_paths_summary(input_schema)}."
+ end
+ end
+
+ def schema_path_available?(reference, input_schema)
+ schema_paths = input_schema.keys.map(&:to_s)
+ return true if schema_paths.include?(reference)
+ return true if schema_paths.any? { |path| path.start_with?("#{reference}.") }
+
+ segments = reference.split(".")
+ while segments.length > 2
+ segments.pop
+ return true if schema_paths.include?(segments.join("."))
+ end
+
+ false
+ end
+
+ def available_paths_summary(input_schema)
+ paths = input_schema.keys.map(&:to_s).sort
+ summary = paths.first(MAX_AVAILABLE_PATHS).join(", ")
+ summary += ", ..." if paths.length > MAX_AVAILABLE_PATHS
+ summary.presence || "none"
+ end
+
+ def node_label(node)
+ node["name"].presence || node["id"].presence || node["type"]
+ end
+
+ def normalized_patch_operations(operations)
+ Array
+ .wrap(operations)
+ .filter_map do |operation|
+ if operation.is_a?(String)
+ parse_json_hash(operation.strip) || operation
+ else
+ operation
+ end
+ end
+ end
+
+ def parse_json_hash(candidate)
+ parsed = JSON.parse(candidate)
+ parsed if parsed.is_a?(Hash)
+ rescue JSON::ParserError, Oj::ParseError
+ nil
+ end
+
+ def find_or_build_workflow
+ workflow_id = parameters[:workflow_id].presence
+ return DiscourseWorkflows::Workflow.find(workflow_id) if workflow_id.present?
+
+ DiscourseWorkflows::Workflow.new(
+ name: parameters[:workflow_name].presence || "AI workflow draft",
+ created_by: context.user,
+ nodes: [],
+ connections: {
+ },
+ )
+ end
+ end
+ end
+ end
+end
diff --git a/plugins/discourse-workflows/lib/discourse_workflows/ai/tools/workflow_validate_script.rb b/plugins/discourse-workflows/lib/discourse_workflows/ai/tools/workflow_validate_script.rb
new file mode 100644
index 00000000000..803d2c02c7d
--- /dev/null
+++ b/plugins/discourse-workflows/lib/discourse_workflows/ai/tools/workflow_validate_script.rb
@@ -0,0 +1,194 @@
+# frozen_string_literal: true
+
+module DiscourseWorkflows
+ module Ai
+ module Tools
+ class WorkflowValidateScript < Base
+ RUN_ONCE_FOR_ALL_ITEMS = "runOnceForAllItems"
+ RUN_ONCE_FOR_EACH_ITEM = "runOnceForEachItem"
+ MODES = [RUN_ONCE_FOR_ALL_ITEMS, RUN_ONCE_FOR_EACH_ITEM].freeze
+ DISALLOWED_FOR_EACH_METHODS = %w[first last all itemMatching].freeze
+ RESERVED_ITEM_KEYS = %w[json pairedItem error index].freeze
+ MAX_SAMPLE_ITEMS = 20
+ MAX_CODE_BYTES = 20_000
+
+ def self.signature
+ {
+ name: name,
+ description:
+ "Validates JavaScript generated for a Discourse workflow Code node against syntax, mode restrictions, and return shape.",
+ parameters: [
+ { name: "mode", description: "Code node mode", type: "string", required: true },
+ { name: "code", description: "JavaScript source", type: "string", required: true },
+ {
+ name: "sample_input_items",
+ description: "Optional sample input items to execute the script against",
+ type: "array",
+ required: false,
+ },
+ ],
+ }
+ end
+
+ def self.name
+ "workflow_validate_script"
+ end
+
+ def invoke
+ return not_allowed_response if !ensure_can_manage_workflows!
+
+ mode = parameters[:mode].to_s
+ code = parameters[:code].to_s
+ sample_input_items = Array.wrap(parameters[:sample_input_items]).first(MAX_SAMPLE_ITEMS)
+ errors = []
+ warnings = []
+
+ errors << "Mode must be one of #{MODES.join(", ")}" if MODES.exclude?(mode)
+ errors << "Code is required" if code.blank?
+ errors << "Code exceeds #{MAX_CODE_BYTES} bytes" if code.bytesize > MAX_CODE_BYTES
+ errors.concat(disallowed_method_errors(code)) if mode == RUN_ONCE_FOR_EACH_ITEM
+
+ return invalid_response(errors, warnings) if errors.present?
+
+ sample_output_items = execute_sample(code, mode, sample_input_items)
+ validate_output_shape(sample_output_items, mode, errors, warnings)
+
+ {
+ status: "success",
+ valid: errors.empty?,
+ errors: errors,
+ warnings: warnings,
+ sample_output_items: errors.empty? ? sample_output_items : [],
+ }
+ rescue MiniRacer::Error => e
+ invalid_response(["JavaScript execution error: #{e.message}"], [])
+ end
+
+ private
+
+ def invalid_response(errors, warnings)
+ {
+ status: "success",
+ valid: false,
+ errors: errors,
+ warnings: warnings,
+ sample_output_items: [],
+ }
+ end
+
+ def disallowed_method_errors(code)
+ code
+ .scan(/\$input\.(#{DISALLOWED_FOR_EACH_METHODS.join("|")})\b/)
+ .flatten
+ .uniq
+ .map { |method| "$input.#{method} is only available in #{RUN_ONCE_FOR_ALL_ITEMS} mode" }
+ end
+
+ def execute_sample(code, mode, sample_input_items)
+ context = MiniRacer::Context.new(timeout: 100, max_memory: 10.megabytes)
+ context.eval("var __sampleInputItems = #{sample_items_json(sample_input_items)};")
+ context.eval(runtime_js(mode))
+ context.eval("(function() {\n#{code}\n}).call({});")
+ ensure
+ context&.dispose
+ end
+
+ def sample_items_json(sample_input_items)
+ items = sample_input_items.presence || [{ "json" => {} }]
+ JSON.generate(items)
+ end
+
+ def runtime_js(mode)
+ <<~JS
+ var __mode = #{mode.to_json};
+ var __currentItem = __sampleInputItems[0] || { json: {} };
+ var $input = Object.freeze({
+ item: __currentItem,
+ all: function() { return __sampleInputItems; },
+ first: function() { return __sampleInputItems[0] || { json: {} }; },
+ last: function() { return __sampleInputItems[__sampleInputItems.length - 1] || { json: {} }; },
+ itemMatching: function(index) { return __sampleInputItems[index] || { json: {} }; }
+ });
+ var $json = __currentItem.json || {};
+ var $vars = Object.freeze({});
+ var $site_settings = Object.freeze({});
+ var $execution = Object.freeze({});
+ var $current_user = Object.freeze({});
+ var console = Object.freeze({
+ log: function() {},
+ info: function() {},
+ warn: function() {},
+ error: function() {}
+ });
+ function $(name) {
+ return Object.freeze({
+ item: { json: {} },
+ all: function() { return []; },
+ first: function() { return { json: {} }; },
+ last: function() { return { json: {} }; }
+ });
+ }
+ JS
+ end
+
+ def validate_output_shape(output, mode, errors, warnings)
+ if mode == RUN_ONCE_FOR_EACH_ITEM
+ validate_each_item_output(output, errors, warnings)
+ else
+ validate_all_items_output(output, errors, warnings)
+ end
+ end
+
+ def validate_each_item_output(output, errors, warnings)
+ if output.is_a?(Array)
+ errors << "#{RUN_ONCE_FOR_EACH_ITEM} must return one object, not an array"
+ return
+ end
+
+ validate_item(output, errors, warnings)
+ end
+
+ def validate_all_items_output(output, errors, warnings)
+ if output.nil?
+ warnings << "Script returned null or undefined; this produces no output items"
+ return
+ end
+
+ unless output.is_a?(Array) || output.is_a?(Hash)
+ errors << "#{RUN_ONCE_FOR_ALL_ITEMS} must return an array of objects or one object"
+ return
+ end
+
+ Array.wrap(output).each { |item| validate_item(item, errors, warnings) }
+ end
+
+ def validate_item(item, errors, warnings)
+ unless item.is_a?(Hash)
+ errors << "Output item must be an object"
+ return
+ end
+
+ validate_top_level_keys(item, errors, warnings)
+ if item.key?("json") && !item["json"].is_a?(Hash)
+ errors << "Output item json field must be an object"
+ end
+ end
+
+ def validate_top_level_keys(item, errors, warnings)
+ unknown_keys = item.keys.reject { |key| reserved_item_key?(key) }
+ return if unknown_keys.empty?
+
+ if item.keys.any? { |key| reserved_item_key?(key) }
+ errors << "Output item mixes reserved item keys with plain fields"
+ else
+ warnings << "Output item is a plain object and will be normalized under json"
+ end
+ end
+
+ def reserved_item_key?(key)
+ RESERVED_ITEM_KEYS.include?(key.to_s)
+ end
+ end
+ end
+ end
+end
diff --git a/plugins/discourse-workflows/lib/discourse_workflows/ai_authoring_enqueuer.rb b/plugins/discourse-workflows/lib/discourse_workflows/ai_authoring_enqueuer.rb
new file mode 100644
index 00000000000..115c065e447
--- /dev/null
+++ b/plugins/discourse-workflows/lib/discourse_workflows/ai_authoring_enqueuer.rb
@@ -0,0 +1,30 @@
+# frozen_string_literal: true
+
+module DiscourseWorkflows
+ class AiAuthoringEnqueuer
+ def self.enabled?
+ SiteSetting.discourse_workflows_enabled &&
+ SiteSetting.discourse_workflows_ai_authoring_enabled && defined?(DiscourseAi).present?
+ end
+
+ def self.enqueue(session:, generation_id:, user:)
+ return if !enabled?
+
+ session.update!(status: "generating")
+ Ai::ProgressPublisher.publish(
+ generation_id: generation_id,
+ user: user,
+ status: "progress",
+ stage: "queued",
+ message: I18n.t("discourse_workflows.ai.progress.queued"),
+ )
+
+ Jobs.enqueue(
+ Jobs::DiscourseWorkflows::AuthorWithAi,
+ session_id: session.id,
+ user_id: user.id,
+ generation_id: generation_id,
+ )
+ end
+ end
+end
diff --git a/plugins/discourse-workflows/lib/discourse_workflows/ai_workflow_author.rb b/plugins/discourse-workflows/lib/discourse_workflows/ai_workflow_author.rb
new file mode 100644
index 00000000000..9ed376751d0
--- /dev/null
+++ b/plugins/discourse-workflows/lib/discourse_workflows/ai_workflow_author.rb
@@ -0,0 +1,125 @@
+# frozen_string_literal: true
+
+module DiscourseWorkflows
+ class AiWorkflowAuthor < DiscourseAi::Agents::Agent
+ DISCOVERY_TOOL_CLASS_NAMES = %w[
+ DiscourseAi::Agents::Tools::ListCategories
+ DiscourseAi::Agents::Tools::Search
+ DiscourseAi::Agents::Tools::Read
+ DiscourseAi::Agents::Tools::Time
+ ].freeze
+
+ def self.execution_mode
+ "agentic"
+ end
+
+ def self.max_turn_tokens
+ 100_000
+ end
+
+ def tools
+ [
+ DiscourseWorkflows::Ai::Tools::WorkflowAskQuestions,
+ DiscourseWorkflows::Ai::Tools::WorkflowAuthoringResult,
+ DiscourseWorkflows::Ai::Tools::WorkflowResolveEntity,
+ DiscourseWorkflows::Ai::Tools::WorkflowAiAgentCatalog,
+ DiscourseWorkflows::Ai::Tools::WorkflowNodeCatalog,
+ DiscourseWorkflows::Ai::Tools::WorkflowGraphContext,
+ DiscourseWorkflows::Ai::Tools::WorkflowValidatePatch,
+ DiscourseWorkflows::Ai::Tools::WorkflowScriptContext,
+ DiscourseWorkflows::Ai::Tools::WorkflowValidateScript,
+ *discovery_tools,
+ *chat_tools,
+ ]
+ end
+
+ def system_prompt
+ <<~PROMPT
+ You help Discourse admins author Discourse Workflows.
+
+ Rules:
+ - Never say a workflow change is live.
+ - Never publish a workflow.
+ - Produce draft proposals only.
+ - Use the compact workflow authoring context supplied with the request for workflow id/name and important field facts.
+ - Use workflow_graph_context when you need the current workflow graph; the full graph is not preloaded.
+ - Use workflow_node_catalog with targeted queries when you need node parameters, capabilities, schemas, or examples; the full node catalog is not preloaded. Prefer one broad query containing the relevant node names/keywords over many repeated catalog calls.
+ - Do not invent node types, node versions, node parameters, expression variables, or existing AI agent IDs.
+ - Ask clarifying questions when required values are missing or ambiguous.
+ - Use tools for all workflow authoring outcomes. Do not write a final prose, markdown, or JSON answer.
+ - When you need clarification, call workflow_ask_questions with concise multiple-choice questions instead of writing a needs_clarification final response. Include 2-6 useful options per question and allow a custom answer when the listed options may not cover the admin's intent.
+ - When the user responds with workflow_ask_questions_result JSON, use those answers and continue drafting; do not ask the same question again unless the answer is still unclear.
+ - When authoring is complete, call workflow_authoring_result exactly once with status, message, questions, and proposal. This final result tool halts the turn and is the only supported final response mechanism.
+ - workflow_authoring_result status must be one of: needs_clarification, proposed_patch, explanation, error.
+ - For proposed_patch results, include a proposal object with title, summary, assumptions, risks, risk_level, and operations.
+ - Use the compact workflow authoring context supplied with the request before proposing changes, and call workflow_graph_context/workflow_node_catalog for details when needed.
+ - Do not ask admins for exact IDs, slugs, or names when an available tool can look them up; use discovery and resolver tools first.
+ - Use categories, tags, search, read, and time tools for current forum discovery when they help draft the workflow safely; do not use forum search/read to discover workflow node behavior or schemas because workflow_node_catalog and workflow_validate_patch return schema details.
+ - Use workflow_resolve_entity when the user names a category, tag, group, user, badge, or data table and you need its exact workflow parameter value.
+ - Use workflow_ai_agent_catalog before adding action:ai_agent nodes. Reuse a suitable enabled AI agent by setting agent_id to its numeric id. Only propose a new agent when the workflow genuinely needs AI judgment/generation and no suitable enabled agent exists.
+ - New AI agents must be prompt-only by default: name, description, and system_prompt only. Do not add tools, RAG, MCP servers, bot users, mention permissions, default LLM overrides, or broad group access for generated agents.
+ - Keep generated AI agent system prompts focused on the workflow task. A simple helpful prompt is acceptable when the task is broad, but prefer concise task-specific instructions when the workflow needs a clear output.
+ - When proposing a new AI agent, include a create_ai_agent operation before the action:ai_agent node that uses it. Reference the proposed agent with agent_id: { "$ref": "agent-client-id" } and set agent_name to the proposed agent name.
+ - Include created AI agents in proposal assumptions or risks so admins know the draft creates a reusable agent record.
+ - Use search_chat_channels before asking the admin to choose a chat channel or before setting action:send_chat_message channel_id. Never invent chat channel names, IDs, or clarification options. If search_chat_channels returns matches, ask using those exact channel names/IDs or use the named match. If it returns no matches, ask for a custom channel name/ID instead of suggesting made-up channels.
+ - Use workflow_validate_patch as a dry-run planning tool when drafting workflow changes. It does not save anything. For non-trivial workflows, query relevant node types with workflow_node_catalog, then call workflow_validate_patch after adding or connecting candidate nodes to inspect node_schemas for exact input/output field paths, then continue from those schemas.
+ - If workflow_validate_patch returns expression_errors or schema-path errors, repair the operations and call workflow_validate_patch again before returning a final proposal.
+ - Action nodes may replace the current item JSON. Always use the downstream node's input_schema from workflow_validate_patch rather than assuming trigger fields are still available after an action node.
+ - When a downstream node needs fields from an earlier node after an action replaced the current item JSON, prefer previous-node expressions such as ={{ $("When a post is created").item.json.post.post_url }} or template references such as {{ $("When a post is created").item.json.post.username }}. Do not add a Code node only to copy trigger fields forward.
+ - Before proposing a Code node, call workflow_script_context for the runtime API and call workflow_validate_script with the exact mode and code. If validation fails, repair the JavaScript and validate it again before returning a final proposal.
+ - Do not stop after validating a partial graph; continue drafting until the complete workflow is represented in operations.
+ - Before calling workflow_authoring_result with a proposed_patch status, call workflow_validate_patch with the complete operations unless the change is a trivial edit that does not affect graph structure.
+ - Only call workflow_ask_questions when you cannot safely draft a workflow without more admin input.
+ - If you propose a workflow change, include the proposal data in the workflow_authoring_result tool call.
+ - Use this patch schema exactly:
+ - create_ai_agent: { op: "create_ai_agent", client_id: "agent-temporary-id", agent: { name, description, system_prompt } }
+ - add_node: { op: "add_node", client_id: "temporary-id", node: { type, typeVersion, name, position, parameters, credentials } }
+ - update_node_parameters: { op: "update_node_parameters", node_id, parameters }
+ - rename_node: { op: "rename_node", node_id, name }
+ - remove_node: { op: "remove_node", node_id }
+ - add_connection: { op: "add_connection", from, to, output_index, input_index, connection_type }
+ - remove_connection: { op: "remove_connection", from, to, output_index, input_index }
+ - In add_connection, use connection_type "main" for normal single-output nodes. For condition:filter and condition:if, connect the passing branch with connection_type "true"; use "false" only when the rejected/false branch should continue.
+ - If you update an existing node's parameters, also rename that node when its current name would no longer match the updated behavior. Keep edited node names aligned with the latest requested configuration; for example, when changing a wait node from one hour to two hours, include a rename_node operation such as "Wait 2 hours" in the same proposal.
+ - In add_node, node.credentials must be a JSON object. Use {} when no saved credential is selected, and do not copy the catalog's credential requirements array into node.credentials. Keep credentials as a sibling of parameters in node, never nested inside parameters.
+ - In add_node, prefer position as an object like { "x": 280, "y": 0 }. The server can normalize [x, y] arrays, but object positions are clearer.
+ - In create_ai_agent, client_id must be unique among proposed agents and agent must include only name, description, and system_prompt. The server will create a non-system, prompt-only, enabled AI agent when the draft is applied.
+ - In action:ai_agent nodes that use a proposed agent, set parameters.agent_id to { "$ref": "agent-client-id" } and parameters.agent_name to the same name from create_ai_agent. For existing agents, set parameters.agent_id to the numeric id returned by workflow_ai_agent_catalog.
+ - In add_connection and remove_connection, from/to must be existing node IDs or client_id values introduced by add_node operations in the same proposal.
+ - Include risk notes for automatic triggers, public content changes, external HTTP requests, credentials, loops, and Code nodes.
+ - Prefer declarative node configuration over Code nodes when the requested behavior can be expressed without JavaScript.
+ - For simple checks on trigger fields, such as trust level comparisons, text contains, tags, category, staff/admin/moderator flags, use condition:filter instead of a Code node. Use condition:if only when the workflow needs separate true/false branches.
+ - For requests phrased as "when someone posts" or "when anyone posts", use trigger:post_created for all regular posts, including first posts and replies, unless the admin explicitly asks for only new topics or only replies. Do not ask to distinguish replies vs topic starters for a generic "posts" request.
+ - For group membership checks, resolve the named group with workflow_resolve_entity(kind: "group", ...), then use action:group with operation "check_membership", group_id set to the resolved group id, and username ={{ $json.user.username }} when the input schema includes user.username, otherwise use the exact username field from the current input schema. The node adds $json.group_membership.in_group and keeps the original item fields. If the workflow needs different member and non-member paths, add condition:if after the group node and compare $json.group_membership.in_group to true or false.
+ - For personal messages, private messages, DMs, direct messages, or PM-style notifications, use action:send_personal_message. Resolve named user recipients with workflow_resolve_entity(kind: "user") and set recipient_usernames to an array containing the resolved username. Resolve named group recipients with workflow_resolve_entity(kind: "group") and set recipient_group_names to an array containing the resolved group name, not the group id. Use leading-= template strings for title/raw when including dynamic post or topic links.
+ - When using an output_schema field, use the exact documented path (for example $json.user.trust_level, $json.user.username, $json.post.raw, or $json.post.post_url). Do not generate fallback chains for undocumented aliases such as $json.user.trustLevel or $json.trust_level.
+ - Dynamic parameter values must start with =. Use ={{ $json.topic.id }} for a whole-field expression, and use template strings such as =Archived topic: {{ $json.topic.title }} (/t/{{ $json.topic.slug }}/{{ $json.topic.id }}) when mixing text and expressions.
+ - Do not write bare {{ $json.field }} templates without the leading =; without = they are treated as literal text.
+ - For topic links from topic payloads, prefer /t/{{ $json.topic.slug }}/{{ $json.topic.id }} in a leading-= template string. Only use $json.post.post_url when the current node input_schema includes $json.post.post_url.
+ - Discourse trust levels are automatic groups named trust_level_0 through trust_level_4. Membership is cumulative: the trust_level_N group contains every user whose trust level is N or higher. When a workflow needs a trust-level check but the current input_schema has no trust_level field (for example after trigger:topic_closed or action:topic get, which expose post.username but not the author trust level), resolve the relevant trust_level_N group with workflow_resolve_entity and use action:group with operation "check_membership", the resolved group_id, and the available username field (such as $json.post.username) instead of asking for clarification or adding a Code node. For "TL1 or lower", check membership in trust_level_2 and branch on $json.group_membership.in_group being false; for "TL2 or higher", branch on it being true.
+ - Do not assume $json.post.trust_level exists. The post payload never includes trust level; trust level is only available as $json.user.trust_level on triggers that expose a user object (such as trigger:post_created). For topic-only payloads, use the trust_level_N group membership approach above.
+ - Do not ask whether the first post or topic author trust level is available until you have checked the current node schemas with workflow_validate_patch.
+ - In condition nodes, each condition must use leftValue, operator, and rightValue keys. Do not use left/right keys. Use operator.type "number" for integer/number fields, "string" for string fields, and "boolean" for boolean fields.
+ - Use Code nodes for data transformation when needed; the server validates generated scripts before a proposal can be applied.
+ - When adding or updating a Code node, set parameters.mode and parameters.code.
+ - The server validates workflow patches before they can be applied.
+ PROMPT
+ end
+
+ private
+
+ def discovery_tools
+ tool_class_names = DISCOVERY_TOOL_CLASS_NAMES.dup
+ tool_class_names << "DiscourseAi::Agents::Tools::ListTags" if SiteSetting.tagging_enabled
+ tool_class_names.filter_map(&:safe_constantize)
+ end
+
+ def chat_tools
+ if DiscourseWorkflows::Ai::Tools::SearchChatChannels.available?
+ [DiscourseWorkflows::Ai::Tools::SearchChatChannels]
+ else
+ []
+ end
+ end
+ end
+end
diff --git a/plugins/discourse-workflows/lib/discourse_workflows/dev_populator.rb b/plugins/discourse-workflows/lib/discourse_workflows/dev_populator.rb
new file mode 100644
index 00000000000..8d347610b63
--- /dev/null
+++ b/plugins/discourse-workflows/lib/discourse_workflows/dev_populator.rb
@@ -0,0 +1,138 @@
+# frozen_string_literal: true
+
+module DiscourseWorkflows
+ class DevPopulator
+ MANUAL_LOG_WORKFLOW_NAME = "Example: Log manual trigger"
+ TOPIC_BUTTON_WORKFLOW_NAME = "Example: Topic admin reply button"
+
+ def self.populate!
+ new.populate!
+ end
+
+ def populate!
+ if !Rails.env.development?
+ raise "Workflow examples are only supported in development environment"
+ end
+
+ if !SiteSetting.discourse_workflows_enabled
+ SiteSetting.set(:discourse_workflows_enabled, true)
+ end
+
+ ensure_manual_log_workflow!
+ ensure_topic_admin_button_workflow!
+ end
+
+ private
+
+ def ensure_manual_log_workflow!
+ ensure_workflow!(
+ name: MANUAL_LOG_WORKFLOW_NAME,
+ nodes: [
+ node(
+ id: "manual-trigger",
+ type: "trigger:manual",
+ name: "Manual trigger",
+ position: {
+ "x" => 80,
+ "y" => 120,
+ },
+ ),
+ node(
+ id: "write-log",
+ type: "action:log",
+ name: "Write log",
+ position: {
+ "x" => 360,
+ "y" => 120,
+ },
+ parameters: {
+ "mode" => "runOnceForAllItems",
+ "entries" => {
+ "values" => [
+ { "key" => "message", "value" => "Hello from an example Discourse workflow" },
+ ],
+ },
+ },
+ ),
+ ],
+ connections: {
+ "Manual trigger" => {
+ "main" => [[{ "node" => "Write log", "type" => "main", "index" => 0 }]],
+ },
+ },
+ )
+ end
+
+ def ensure_topic_admin_button_workflow!
+ ensure_workflow!(
+ name: TOPIC_BUTTON_WORKFLOW_NAME,
+ nodes: [
+ node(
+ id: "topic-admin-button",
+ type: "trigger:topic_admin_button",
+ name: "Topic admin button",
+ position: {
+ "x" => 80,
+ "y" => 320,
+ },
+ parameters: {
+ "label" => "Add workflow note",
+ "icon" => "bolt",
+ },
+ ),
+ node(
+ id: "create-reply",
+ type: "action:post",
+ name: "Create reply",
+ position: {
+ "x" => 360,
+ "y" => 320,
+ },
+ parameters: {
+ "operation" => "create",
+ "topic_id" => "={{ $json.topic.id }}",
+ "raw" => "This automated reply was created by an example Discourse workflow.",
+ "author_username" => "system",
+ },
+ ),
+ ],
+ connections: {
+ "Topic admin button" => {
+ "main" => [[{ "node" => "Create reply", "type" => "main", "index" => 0 }]],
+ },
+ },
+ )
+ end
+
+ def ensure_workflow!(name:, nodes:, connections:)
+ workflow = Workflow.find_by(name: name)
+ return workflow if workflow
+
+ workflow =
+ Workflow.create!(name: name, nodes: nodes, connections: connections, created_by: actor)
+ version = workflow.initial_snapshot!(user: actor)
+ workflow.publish!(user: actor)
+ WorkflowDependencyIndexer.call(workflow.reload, version: version)
+ Workflow::Action::ExpireCaches.call
+ workflow
+ end
+
+ def node(id:, type:, name:, position:, parameters: {})
+ {
+ "id" => id,
+ "type" => type,
+ "typeVersion" => "1.0",
+ "name" => name,
+ "parameters" => parameters,
+ "credentials" => {
+ },
+ "webhookId" => nil,
+ "position" => position,
+ }
+ end
+
+ def actor
+ @actor ||= User.where(admin: true).order(:id).first || Discourse.system_user
+ end
+ end
+end
diff --git a/plugins/discourse-workflows/lib/discourse_workflows/executor/node_execution_context.rb b/plugins/discourse-workflows/lib/discourse_workflows/executor/node_execution_context.rb
index d72d940a9e4..a061ec50f85 100644
--- a/plugins/discourse-workflows/lib/discourse_workflows/executor/node_execution_context.rb
+++ b/plugins/discourse-workflows/lib/discourse_workflows/executor/node_execution_context.rb
@@ -43,6 +43,14 @@ module DiscourseWorkflows
).deep_symbolize_keys
end
+ def self.serialize_user(user, guardian: Discourse.system_user.guardian)
+ return if user.blank?
+
+ MultiJson.load(
+ DiscourseWorkflows::UserSerializer.new(user, scope: guardian, root: false).to_json,
+ ).deep_symbolize_keys
+ end
+
class RuntimeState
attr_reader :condition_step_details, :execution_hints, :log, :metadata, :wait_request
diff --git a/plugins/discourse-workflows/lib/discourse_workflows/node_type.rb b/plugins/discourse-workflows/lib/discourse_workflows/node_type.rb
index 5ea07e94720..c49820b7b57 100644
--- a/plugins/discourse-workflows/lib/discourse_workflows/node_type.rb
+++ b/plugins/discourse-workflows/lib/discourse_workflows/node_type.rb
@@ -216,6 +216,10 @@ module DiscourseWorkflows
)
end
+ def serialize_user(user, guardian: Discourse.system_user.guardian)
+ DiscourseWorkflows::Executor::NodeExecutionContext.serialize_user(user, guardian: guardian)
+ end
+
def with_paired_item(item, paired_item)
Item.with_paired_item(item, paired_item)
end
diff --git a/plugins/discourse-workflows/lib/discourse_workflows/nodes/group/v1.rb b/plugins/discourse-workflows/lib/discourse_workflows/nodes/group/v1.rb
index 88ed17ad0bf..c49a98f922e 100644
--- a/plugins/discourse-workflows/lib/discourse_workflows/nodes/group/v1.rb
+++ b/plugins/discourse-workflows/lib/discourse_workflows/nodes/group/v1.rb
@@ -4,7 +4,7 @@ module DiscourseWorkflows
module Nodes
module Group
class V1 < NodeType
- OPERATIONS = %w[add remove get].freeze
+ OPERATIONS = %w[add remove get check_membership].freeze
description(
name: "action:group",
@@ -32,7 +32,7 @@ module DiscourseWorkflows
required: true,
display_options: {
show: {
- operation: %w[add remove],
+ operation: %w[add remove check_membership],
},
},
ui: {
@@ -44,7 +44,6 @@ module DiscourseWorkflows
required: true,
type_options: {
load_options_method: "groups",
- load_options_depends_on: %w[operation],
},
ui: {
control: :group_select,
@@ -70,12 +69,8 @@ module DiscourseWorkflows
def self.load_options_context(context)
case context.method_name
when "groups"
- scope = ::Group.order(:name)
- scope = scope.where(automatic: false) unless context.get_current_node_parameter(
- "operation",
- ) == "get"
-
- scope
+ ::Group
+ .order(:name)
.pluck(:id, :name)
.select { |_, name| context.matches_filter?(name) }
.map { |id, name| { id:, name: } }
@@ -84,13 +79,17 @@ module DiscourseWorkflows
def execute(exec_ctx)
items =
- exec_ctx.input_items.map.with_index do |_item, item_index|
+ exec_ctx.input_items.map.with_index do |item, item_index|
config = {
"operation" => exec_ctx.get_node_parameter("operation", item_index, default: "add"),
"username" => exec_ctx.get_node_parameter("username", item_index),
"group_id" => exec_ctx.get_node_parameter("group_id", item_index),
}
+ if config["operation"] == "check_membership"
+ next check_membership(exec_ctx, item, config, item_index)
+ end
+
wrap(process(exec_ctx, config, item_index))
end
@@ -126,6 +125,27 @@ module DiscourseWorkflows
{ group: serialized_group, user: user_data(user, guardian) }
end
+ def check_membership(exec_ctx, item, config, item_index)
+ group = ::Group.find(config["group_id"])
+ actor = exec_ctx.actor_from_parameter("actor_username", item_index)
+ guardian = actor.guardian
+ guardian.ensure_can_see_group!(group)
+
+ user = exec_ctx.find_user(username: config["username"])
+ membership_data = {
+ "group_id" => group.id,
+ "group_name" => group.name,
+ "user_id" => user.id,
+ "username" => user.username,
+ "in_group" => user.in_any_groups?([group.id]),
+ }
+
+ wrap(
+ item.fetch("json", {}).merge("group_membership" => membership_data),
+ paired_item: exec_ctx.paired_item_for(item),
+ )
+ end
+
def group_data(group, guardian)
serialize_record(group, WebHookGroupSerializer, scope: guardian)
end
diff --git a/plugins/discourse-workflows/lib/discourse_workflows/nodes/post_created/v1.rb b/plugins/discourse-workflows/lib/discourse_workflows/nodes/post_created/v1.rb
index 08a074fd118..884aab255b2 100644
--- a/plugins/discourse-workflows/lib/discourse_workflows/nodes/post_created/v1.rb
+++ b/plugins/discourse-workflows/lib/discourse_workflows/nodes/post_created/v1.rb
@@ -96,7 +96,7 @@ module DiscourseWorkflows
end
def output
- { post: post_data(@post), topic: topic_data(@post.topic) }
+ { post: post_data(@post), topic: topic_data(@post.topic), user: user_data(@post.user) }
end
def matches?(trigger_ctx)
@@ -122,6 +122,10 @@ module DiscourseWorkflows
serialize_record(topic, TopicListItemSerializer)
end
+ def user_data(user)
+ serialize_user(user)
+ end
+
def matches_topic_type?(topic, topic_type)
case topic_type.presence || "topics"
when "all"
diff --git a/plugins/discourse-workflows/lib/discourse_workflows/nodes/post_edited/v1.rb b/plugins/discourse-workflows/lib/discourse_workflows/nodes/post_edited/v1.rb
index f86a236af83..a5e6fcc9330 100644
--- a/plugins/discourse-workflows/lib/discourse_workflows/nodes/post_edited/v1.rb
+++ b/plugins/discourse-workflows/lib/discourse_workflows/nodes/post_edited/v1.rb
@@ -67,6 +67,7 @@ module DiscourseWorkflows
{
post: serialize_post(@post, include_cooked: true).merge(cooked: @cooked),
topic: topic_data(@post.topic),
+ user: user_data(@post.user),
}
end
@@ -83,6 +84,10 @@ module DiscourseWorkflows
serialize_record(topic, TopicListItemSerializer)
end
+ def user_data(user)
+ serialize_user(user)
+ end
+
def matches_post_scope?(post_scope)
case post_scope
when "all_posts"
diff --git a/plugins/discourse-workflows/lib/discourse_workflows/nodes/send_personal_message/v1.rb b/plugins/discourse-workflows/lib/discourse_workflows/nodes/send_personal_message/v1.rb
new file mode 100644
index 00000000000..2311e45f46a
--- /dev/null
+++ b/plugins/discourse-workflows/lib/discourse_workflows/nodes/send_personal_message/v1.rb
@@ -0,0 +1,150 @@
+# frozen_string_literal: true
+
+module DiscourseWorkflows
+ module Nodes
+ module SendPersonalMessage
+ class V1 < NodeType
+ description(
+ name: "action:send_personal_message",
+ version: "1.0",
+ defaults: {
+ icon: "envelope",
+ color: "teal",
+ },
+ group: "discourse_actions",
+ capabilities: {
+ run_scope: "per_item",
+ },
+ properties: {
+ recipient_usernames: {
+ type: :array,
+ required: false,
+ ui: {
+ control: :user,
+ expression: true,
+ multiple: true,
+ },
+ },
+ recipient_group_names: {
+ type: :array,
+ required: false,
+ type_options: {
+ load_options_method: "groups",
+ },
+ ui: {
+ control: :group_select,
+ expression: true,
+ multiple: true,
+ },
+ control_options: {
+ value_property: "name",
+ name_property: "name",
+ filterable: true,
+ },
+ },
+ title: {
+ type: :string,
+ required: true,
+ },
+ raw: {
+ type: :string,
+ required: true,
+ ui: {
+ control: :textarea,
+ },
+ },
+ sender_username: {
+ type: :string,
+ required: false,
+ default: "system",
+ ui: {
+ control: :actor,
+ },
+ },
+ },
+ )
+
+ def self.load_options_context(context)
+ case context.method_name
+ when "groups"
+ ::Group
+ .order(:name)
+ .pluck(:id, :name)
+ .select { |_, name| context.matches_filter?(name) }
+ .map { |id, name| { id:, name: } }
+ end
+ end
+
+ def execute(exec_ctx)
+ items =
+ exec_ctx.input_items.map.with_index do |_item, item_index|
+ config = {
+ "recipient_usernames" =>
+ exec_ctx.get_node_parameter("recipient_usernames", item_index),
+ "recipient_group_names" =>
+ exec_ctx.get_node_parameter("recipient_group_names", item_index),
+ "title" => exec_ctx.get_node_parameter("title", item_index),
+ "raw" => exec_ctx.get_node_parameter("raw", item_index),
+ }
+
+ wrap(process(exec_ctx, config, item_index))
+ end
+
+ [items]
+ end
+
+ private
+
+ def process(exec_ctx, config, item_index)
+ sender = exec_ctx.actor_from_parameter("sender_username", item_index)
+ post_args = post_args(config)
+ post = PostCreator.new(sender, post_args).create!
+
+ {
+ topic: topic_data(post.topic, sender.guardian),
+ post:
+ exec_ctx.serialize_post(
+ post,
+ guardian: sender.guardian,
+ include_raw: true,
+ include_cooked: true,
+ ),
+ }
+ end
+
+ def post_args(config)
+ recipient_usernames = normalize_recipients(config["recipient_usernames"])
+ recipient_group_names = normalize_recipients(config["recipient_group_names"])
+
+ if recipient_usernames.blank? && recipient_group_names.blank?
+ raise_node_error!(
+ I18n.t("discourse_workflows.errors.send_personal_message.no_recipients"),
+ )
+ end
+
+ {
+ archetype: Archetype.private_message,
+ target_usernames: recipient_usernames.presence,
+ target_group_names: recipient_group_names.presence,
+ title: config["title"],
+ raw: config["raw"],
+ skip_workflows: true,
+ }.compact
+ end
+
+ def normalize_recipients(value)
+ Array
+ .wrap(value)
+ .flat_map { |entry| entry.to_s.split(",") }
+ .map(&:strip)
+ .reject(&:blank?)
+ .join(",")
+ end
+
+ def topic_data(topic, guardian)
+ serialize_record(topic, TopicListItemSerializer, scope: guardian)
+ end
+ end
+ end
+ end
+end
diff --git a/plugins/discourse-workflows/lib/discourse_workflows/nodes/topic/v1.rb b/plugins/discourse-workflows/lib/discourse_workflows/nodes/topic/v1.rb
index 40d684ac4fa..630d65bd015 100644
--- a/plugins/discourse-workflows/lib/discourse_workflows/nodes/topic/v1.rb
+++ b/plugins/discourse-workflows/lib/discourse_workflows/nodes/topic/v1.rb
@@ -4,7 +4,7 @@ module DiscourseWorkflows
module Nodes
module Topic
class V1 < NodeType
- OPERATIONS = %w[create get list close set_custom_fields].freeze
+ OPERATIONS = %w[create get list close archive set_custom_fields].freeze
MAX_LIMIT = 100
DEFAULT_LIMIT = 30
CUSTOM_FIELD_OPTIONS_LIMIT = 100
@@ -32,7 +32,7 @@ module DiscourseWorkflows
required: true,
display_options: {
show: {
- operation: %w[get close set_custom_fields],
+ operation: %w[get close archive set_custom_fields],
},
},
},
@@ -232,6 +232,8 @@ module DiscourseWorkflows
list_topics(exec_ctx, config, item_index).map { |data| wrap(data) }
when "close"
wrap(close_topic(exec_ctx, config, item_index))
+ when "archive"
+ wrap(archive_topic(exec_ctx, config, item_index))
when "set_custom_fields"
wrap(set_custom_fields(exec_ctx, config, item_index))
else
@@ -274,6 +276,7 @@ module DiscourseWorkflows
{
topic: exec_ctx.serialize_topic(topic, guardian: guardian),
+ post: post_data(post),
post_id: post.id,
post_number: post.post_number,
}
@@ -293,6 +296,7 @@ module DiscourseWorkflows
guardian: actor.guardian,
custom_field_names: custom_field_names,
),
+ post: post_data(topic.first_post),
}
end
@@ -325,6 +329,7 @@ module DiscourseWorkflows
guardian: actor.guardian,
custom_field_names: custom_field_names,
),
+ post: post_data(topic.first_post),
}
end
end
@@ -336,7 +341,26 @@ module DiscourseWorkflows
topic.update_status("closed", true, actor)
- { topic: exec_ctx.serialize_topic(topic.reload, guardian: actor.guardian) }
+ topic.reload
+ {
+ topic: exec_ctx.serialize_topic(topic, guardian: actor.guardian),
+ post: post_data(topic.first_post),
+ }
+ end
+
+ def archive_topic(exec_ctx, config, item_index)
+ topic = ::Topic.find(config["topic_id"])
+ actor = exec_ctx.actor_from_parameter("actor_username", item_index)
+ guardian = actor.guardian
+ guardian.ensure_can_archive_topic!(topic)
+
+ topic.update_status("archived", true, actor)
+
+ topic.reload
+ {
+ topic: exec_ctx.serialize_topic(topic, guardian: guardian),
+ post: post_data(topic.first_post),
+ }
end
def set_custom_fields(exec_ctx, config, item_index)
@@ -369,6 +393,12 @@ module DiscourseWorkflows
fields[key] = entry["value"]
end
end
+
+ def post_data(post)
+ return if post.blank?
+
+ serialize_record(post, WebHookPostSerializer)
+ end
end
end
end
diff --git a/plugins/discourse-workflows/lib/discourse_workflows/property_schema_validator.rb b/plugins/discourse-workflows/lib/discourse_workflows/property_schema_validator.rb
index b41253222c5..07cc1dfde45 100644
--- a/plugins/discourse-workflows/lib/discourse_workflows/property_schema_validator.rb
+++ b/plugins/discourse-workflows/lib/discourse_workflows/property_schema_validator.rb
@@ -63,6 +63,7 @@ module DiscourseWorkflows
flat
format
hidden
+ multiple
show_description
show_label
singular_name
diff --git a/plugins/discourse-workflows/lib/tasks/workflows.rake b/plugins/discourse-workflows/lib/tasks/workflows.rake
new file mode 100644
index 00000000000..8274d7e8fca
--- /dev/null
+++ b/plugins/discourse-workflows/lib/tasks/workflows.rake
@@ -0,0 +1,10 @@
+# frozen_string_literal: true
+
+require_relative "../discourse_workflows/dev_populator"
+
+namespace :workflows do
+ desc "Creates example Discourse workflows"
+ task populate: ["db:load_config"] do
+ DiscourseWorkflows::DevPopulator.populate!
+ end
+end
diff --git a/plugins/discourse-workflows/plugin.rb b/plugins/discourse-workflows/plugin.rb
index 848867d815b..31719670624 100644
--- a/plugins/discourse-workflows/plugin.rb
+++ b/plugins/discourse-workflows/plugin.rb
@@ -86,6 +86,30 @@ after_initialize do
self,
)
+ if defined?(DiscourseAi)
+ require_relative "lib/discourse_workflows/ai/tools/base"
+ require_relative "lib/discourse_workflows/ai/graph_digest"
+ require_relative "lib/discourse_workflows/ai/progress_publisher"
+ require_relative "lib/discourse_workflows/ai/tools/workflow_node_catalog"
+ require_relative "lib/discourse_workflows/ai/tools/workflow_ai_agent_catalog"
+ require_relative "lib/discourse_workflows/ai/tools/workflow_graph_context"
+ require_relative "lib/discourse_workflows/ai/tools/workflow_validate_patch"
+ require_relative "lib/discourse_workflows/ai/tools/workflow_ask_questions"
+ require_relative "lib/discourse_workflows/ai/tools/workflow_resolve_entity"
+ require_relative "lib/discourse_workflows/ai/tools/search_chat_channels"
+ require_relative "lib/discourse_workflows/ai/tools/workflow_script_context"
+ require_relative "lib/discourse_workflows/ai/tools/workflow_validate_script"
+ require_relative "lib/discourse_workflows/ai_workflow_author"
+
+ DiscourseAi.register_feature(
+ module_name: :discourse_workflows,
+ feature: :workflow_authoring,
+ agent_klass: DiscourseWorkflows::AiWorkflowAuthor,
+ enabled_by_setting: "discourse_workflows_ai_authoring_enabled",
+ plugin: self,
+ )
+ end
+
add_to_serializer :site,
:topic_admin_button_workflows,
include_condition: -> { scope.is_admin? } do
diff --git a/plugins/discourse-workflows/spec/fabricators/discourse_workflows_fabricator.rb b/plugins/discourse-workflows/spec/fabricators/discourse_workflows_fabricator.rb
index f4df9c3a655..2a01504402e 100644
--- a/plugins/discourse-workflows/spec/fabricators/discourse_workflows_fabricator.rb
+++ b/plugins/discourse-workflows/spec/fabricators/discourse_workflows_fabricator.rb
@@ -102,3 +102,14 @@ Fabricator(:discourse_workflows_credential, class_name: "DiscourseWorkflows::Cre
credential_type "basic_auth"
data { { "user" => "admin", "password" => "secret" } }
end
+
+Fabricator(
+ :discourse_workflows_ai_authoring_session,
+ class_name: "DiscourseWorkflows::AiAuthoringSession",
+) do
+ user { Fabricate(:admin) }
+ status "drafting"
+ messages { [] }
+ latest_response { {} }
+ proposed_patch { {} }
+end
diff --git a/plugins/discourse-workflows/spec/jobs/regular/discourse_workflows/author_with_ai_spec.rb b/plugins/discourse-workflows/spec/jobs/regular/discourse_workflows/author_with_ai_spec.rb
new file mode 100644
index 00000000000..4d2fd870419
--- /dev/null
+++ b/plugins/discourse-workflows/spec/jobs/regular/discourse_workflows/author_with_ai_spec.rb
@@ -0,0 +1,399 @@
+# frozen_string_literal: true
+
+RSpec.describe Jobs::DiscourseWorkflows::AuthorWithAi do
+ fab!(:admin)
+ fab!(:ai_agent)
+
+ before do
+ SiteSetting.discourse_workflows_ai_authoring_enabled = true
+ SiteSetting.discourse_workflows_workflow_authoring_agent = ai_agent.id
+ end
+
+ def authoring_result_raw_context(payload, tool_call_id: "tool-call-id")
+ [
+ [
+ { arguments: payload }.to_json,
+ tool_call_id,
+ "tool_call",
+ DiscourseWorkflows::Ai::Tools::WorkflowAuthoringResult.name,
+ ],
+ [
+ payload.to_json,
+ tool_call_id,
+ "tool",
+ DiscourseWorkflows::Ai::Tools::WorkflowAuthoringResult.name,
+ ],
+ ]
+ end
+
+ it "passes persisted messages to the AI bot with valid types" do
+ session =
+ Fabricate(
+ :discourse_workflows_ai_authoring_session,
+ user: admin,
+ messages: [{ "type" => "user", "content" => "Create a workflow" }],
+ )
+ captured_messages = nil
+ fake_bot = double
+ response = {
+ status: "needs_clarification",
+ message: "Which category should trigger it?",
+ questions: [
+ {
+ id: "category",
+ question: "Which category?",
+ options: [
+ { label: "Support", description: "Support category" },
+ { label: "All", description: "All categories" },
+ ],
+ },
+ ],
+ proposal: {
+ },
+ }
+
+ allow(fake_bot).to receive(:reply) do |context|
+ captured_messages = context.messages
+ authoring_result_raw_context(response)
+ end
+ allow(DiscourseAi::Agents::Bot).to receive(:as).and_return(fake_bot)
+
+ described_class.new.execute(
+ session_id: session.id,
+ user_id: admin.id,
+ generation_id: SecureRandom.hex,
+ )
+
+ expect(captured_messages).to eq([{ type: :user, content: "Create a workflow" }])
+ expect(session.reload).to have_attributes(
+ status: "needs_clarification",
+ latest_response: include("message" => "Which category should trigger it?"),
+ )
+ end
+
+ it "publishes progress for agent tool and response updates", :aggregate_failures do
+ session =
+ Fabricate(
+ :discourse_workflows_ai_authoring_session,
+ user: admin,
+ messages: [{ "type" => "user", "content" => "Create a workflow" }],
+ )
+ generation_id = SecureRandom.hex
+ fake_bot = double
+ response = { status: "explanation", message: "No changes needed", questions: [], proposal: {} }
+
+ allow(fake_bot).to receive(:reply) do |_context, &block|
+ block.call("", "**Read workflow node catalog**\nChecking node schemas\n\n", :thinking)
+ block.call("**Read workflow node catalog**\nFound matching nodes\n\n", nil, :thinking)
+ block.call("", "**Return workflow authoring result**\nPreparing final result\n\n", :thinking)
+ block.call(
+ "**Return workflow authoring result**\nReturned workflow authoring result\n\n",
+ nil,
+ :thinking,
+ )
+ authoring_result_raw_context(response)
+ end
+ allow(DiscourseAi::Agents::Bot).to receive(:as).and_return(fake_bot)
+
+ messages =
+ MessageBus.track_publish("/discourse-workflows/ai-authoring/#{generation_id}") do
+ described_class.new.execute(
+ session_id: session.id,
+ user_id: admin.id,
+ generation_id: generation_id,
+ )
+ end
+ progress = messages.map(&:data).select { |data| data[:status] == "progress" }
+
+ expect(progress.map { |data| data[:message] }).to include(
+ "Using Read workflow node catalog",
+ "Finished Read workflow node catalog",
+ "Using Return workflow authoring result",
+ "Finished Return workflow authoring result",
+ )
+ expect(progress.map { |data| data[:stage] }).to include("agent_update")
+ end
+
+ it "highlights trigger author trust-level fields in AI context", :aggregate_failures do
+ session =
+ Fabricate(
+ :discourse_workflows_ai_authoring_session,
+ user: admin,
+ messages: [{ "type" => "user", "content" => "Create a TL1 post workflow" }],
+ )
+ captured_custom_instructions = nil
+ fake_bot = double
+ response = { status: "explanation", message: "No changes needed", questions: [], proposal: {} }
+
+ allow(fake_bot).to receive(:reply) do |context|
+ captured_custom_instructions = context.custom_instructions
+ authoring_result_raw_context(response)
+ end
+ allow(DiscourseAi::Agents::Bot).to receive(:as).and_return(fake_bot)
+ allow(DiscourseWorkflows::Ai::Tools::SearchChatChannels).to receive(:available?).and_return(
+ true,
+ )
+
+ described_class.new.execute(
+ session_id: session.id,
+ user_id: admin.id,
+ generation_id: SecureRandom.hex,
+ )
+
+ expect(captured_custom_instructions).to include(
+ "trigger:post_created exposes the created post under post.*",
+ "user.trust_level",
+ "do not assume post.trust_level",
+ "Full graph and node catalog are intentionally not preloaded",
+ "Do not ask whether trust level is available",
+ )
+ payload_json = captured_custom_instructions.split("tools for details:\n", 2).last
+ payload = JSON.parse(payload_json)
+ expect(payload).not_to have_key("node_catalog")
+ expect(payload).not_to have_key("workflow_graph")
+ expect(payload.dig("context_tools", "workflow_node_catalog")).to include("node parameters")
+ expect(payload.dig("context_tools", "workflow_graph_context")).to include("current graph")
+ expect(payload.dig("context_tools", "search_chat_channels")).to include("never invent")
+ expect(payload.dig("context_tools", "workflow_validate_script")).to include("exact Code node")
+ expect(payload.dig("context_tools", "workflow_authoring_result")).to include("final response")
+ expect(payload["trigger_author_field_facts"]).to include(
+ a_string_including("trigger:post_created"),
+ )
+ end
+
+ it "uses authoring result tool calls for patch proposals", :aggregate_failures do
+ workflow = Fabricate(:discourse_workflows_workflow, created_by: admin)
+ session =
+ Fabricate(
+ :discourse_workflows_ai_authoring_session,
+ user: admin,
+ workflow: workflow,
+ messages: [{ "type" => "user", "content" => "Create a manual workflow" }],
+ )
+ operations = [
+ {
+ op: "add_node",
+ client_id: "manual-trigger",
+ node: {
+ type: "trigger:manual",
+ name: "Manual trigger",
+ },
+ },
+ ]
+ response = {
+ status: "proposed_patch",
+ message: "Create a manual workflow",
+ questions: [],
+ proposal: {
+ title: "Manual workflow",
+ summary: "Start with a manual trigger.",
+ risk_level: "low",
+ operations: operations,
+ },
+ }
+ fake_bot = double
+
+ allow(fake_bot).to receive(:reply).and_return(authoring_result_raw_context(response))
+ allow(DiscourseAi::Agents::Bot).to receive(:as).and_return(fake_bot)
+
+ described_class.new.execute(
+ session_id: session.id,
+ user_id: admin.id,
+ generation_id: SecureRandom.hex,
+ )
+
+ expect(session.reload).to have_attributes(status: "proposal_ready", risk_level: "low")
+ expect(session.latest_response).to include("message" => "Create a manual workflow")
+ expect(session.proposed_patch.dig("patch_validation", "valid")).to eq(true)
+ end
+
+ it "uses ask-questions tool calls when the agent needs clarification", :aggregate_failures do
+ session =
+ Fabricate(
+ :discourse_workflows_ai_authoring_session,
+ user: admin,
+ latest_request: "Create a workflow",
+ messages: [{ "type" => "user", "content" => "Create a workflow" }],
+ )
+ questions = [
+ {
+ id: "trigger_scope",
+ question: "Which topics should trigger this workflow?",
+ multi_select: false,
+ custom_allowed: true,
+ options: [
+ { label: "All topics", description: "Run for every topic." },
+ { label: "Support only", description: "Run only in support categories." },
+ ],
+ },
+ ]
+ raw_context = [
+ [
+ { arguments: { questions: questions } }.to_json,
+ "tool-call-id",
+ "tool_call",
+ "workflow_ask_questions",
+ ],
+ [
+ { status: "waiting_for_user", questions: questions }.to_json,
+ "tool-call-id",
+ "tool",
+ "workflow_ask_questions",
+ ],
+ ]
+ fake_bot = double
+
+ allow(fake_bot).to receive(:reply).and_return(raw_context)
+ allow(DiscourseAi::Agents::Bot).to receive(:as).and_return(fake_bot)
+
+ described_class.new.execute(
+ session_id: session.id,
+ user_id: admin.id,
+ generation_id: SecureRandom.hex,
+ )
+
+ expect(session.reload).to have_attributes(status: "needs_clarification", risk_level: nil)
+ expect(session.latest_response).to include(
+ "message" => I18n.t("discourse_workflows.ai.clarification_message"),
+ "questions" => [JSON.parse(questions.first.to_json)],
+ )
+ end
+
+ it "uses patch tool calls when final text is blank", :aggregate_failures do
+ workflow = Fabricate(:discourse_workflows_workflow, created_by: admin)
+ session =
+ Fabricate(
+ :discourse_workflows_ai_authoring_session,
+ user: admin,
+ workflow: workflow,
+ latest_request: "Create a manual workflow",
+ messages: [{ "type" => "user", "content" => "Create a manual workflow" }],
+ )
+ operations = [
+ {
+ op: "add_node",
+ client_id: "manual-trigger",
+ node: {
+ type: "trigger:manual",
+ name: "Manual trigger",
+ credentials: [],
+ },
+ },
+ ]
+ raw_context = [
+ [
+ { arguments: { workflow_id: workflow.id, operations: operations.map(&:to_json) } }.to_json,
+ "tool-call-id",
+ "tool_call",
+ "workflow_validate_patch",
+ ],
+ [
+ { status: "success", valid: true }.to_json,
+ "tool-call-id",
+ "tool",
+ "workflow_validate_patch",
+ ],
+ ]
+ fake_bot = double
+
+ allow(fake_bot).to receive(:reply).and_return(raw_context)
+ allow(DiscourseAi::Agents::Bot).to receive(:as).and_return(fake_bot)
+
+ described_class.new.execute(
+ session_id: session.id,
+ user_id: admin.id,
+ generation_id: SecureRandom.hex,
+ )
+
+ expect(session.reload).to have_attributes(status: "proposal_ready", risk_level: "medium")
+ expect(session.latest_response).to include(
+ "message" => I18n.t("discourse_workflows.ai.tool_call_proposal_message"),
+ )
+ expect(session.proposed_patch.dig("patch_validation", "valid")).to eq(true)
+ end
+
+ it "stores Code node validation errors in the response", :aggregate_failures do
+ session =
+ Fabricate(
+ :discourse_workflows_ai_authoring_session,
+ user: admin,
+ messages: [{ "type" => "user", "content" => "Create a workflow with code" }],
+ )
+ operations = [
+ {
+ op: "add_node",
+ client_id: "bad-code",
+ node: {
+ type: "action:code",
+ name: "Merge post data with result",
+ parameters: {
+ mode: "runOnceForEachItem",
+ code: "var items = $input.all();\nreturn items;",
+ },
+ },
+ },
+ ]
+ response = {
+ status: "proposed_patch",
+ message: "Create a workflow with code",
+ questions: [],
+ proposal: {
+ title: "Code workflow",
+ summary: "Adds a Code node.",
+ risk_level: "medium",
+ operations: operations,
+ },
+ }
+ fake_bot = double
+
+ allow(fake_bot).to receive(:reply).and_return(authoring_result_raw_context(response))
+ allow(DiscourseAi::Agents::Bot).to receive(:as).and_return(fake_bot)
+
+ described_class.new.execute(
+ session_id: session.id,
+ user_id: admin.id,
+ generation_id: SecureRandom.hex,
+ )
+
+ expect(session.reload).to have_attributes(status: "error")
+ expect(session.latest_response["message"]).to include(
+ "Merge post data with result: $input.all is only available in runOnceForAllItems mode",
+ )
+ expect(session.proposed_patch["script_validations"]).to contain_exactly(
+ include(
+ "node_name" => "Merge post data with result",
+ "valid" => false,
+ "errors" => ["$input.all is only available in runOnceForAllItems mode"],
+ ),
+ )
+ end
+
+ it "requires a tool call for the final authoring result" do
+ session =
+ Fabricate(
+ :discourse_workflows_ai_authoring_session,
+ user: admin,
+ messages: [{ "type" => "user", "content" => "Create a manual log workflow" }],
+ )
+ fake_bot = double
+ raw_response = {
+ status: "proposed_patch",
+ message: "Create a manual log workflow",
+ questions: [],
+ proposal: {
+ operations: [{ op: "add_node", client_id: "manual-trigger" }],
+ },
+ }.to_json
+
+ allow(fake_bot).to receive(:reply).and_return([[raw_response, "system"]])
+ allow(DiscourseAi::Agents::Bot).to receive(:as).and_return(fake_bot)
+
+ described_class.new.execute(
+ session_id: session.id,
+ user_id: admin.id,
+ generation_id: SecureRandom.hex,
+ )
+
+ expect(session.reload).to have_attributes(status: "error")
+ end
+end
diff --git a/plugins/discourse-workflows/spec/lib/discourse_workflows/ai/tools/search_chat_channels_spec.rb b/plugins/discourse-workflows/spec/lib/discourse_workflows/ai/tools/search_chat_channels_spec.rb
new file mode 100644
index 00000000000..834f39e63d8
--- /dev/null
+++ b/plugins/discourse-workflows/spec/lib/discourse_workflows/ai/tools/search_chat_channels_spec.rb
@@ -0,0 +1,51 @@
+# frozen_string_literal: true
+
+RSpec.describe DiscourseWorkflows::Ai::Tools::SearchChatChannels do
+ fab!(:admin)
+
+ before { SiteSetting.chat_enabled = true if defined?(SiteSetting.chat_enabled) }
+
+ def invoke_tool(query:)
+ context = DiscourseAi::Agents::BotContext.new(messages: [], user: admin)
+ described_class.new(
+ { query: query },
+ bot_user: Discourse.system_user,
+ llm: nil,
+ context: context,
+ ).invoke
+ end
+
+ it "searches open public chat channels by partial hashtag name" do
+ skip "Chat plugin is not available" if !defined?(::Chat::Channel)
+
+ category = Fabricate(:category, name: "General", slug: "general")
+ channel = Fabricate(:category_channel, chatable: category, name: "general")
+
+ result = invoke_tool(query: "#genera")
+
+ expect(result).to include(status: "success", query: "genera")
+ expect(result[:matches]).to contain_exactly(
+ {
+ id: channel.id,
+ name: "general",
+ slug: channel.slug,
+ category_id: category.id,
+ category_name: "General",
+ category_slug: "general",
+ url: channel.relative_url,
+ },
+ )
+ end
+
+ it "does not return non-selectable channels" do
+ skip "Chat plugin is not available" if !defined?(::Chat::Channel)
+
+ open_channel = Fabricate(:category_channel, name: "general")
+ Fabricate(:category_channel, name: "general closed", status: :closed)
+ Fabricate(:direct_message_channel, name: nil)
+
+ result = invoke_tool(query: "general")
+
+ expect(result[:matches].map { |match| match[:id] }).to contain_exactly(open_channel.id)
+ end
+end
diff --git a/plugins/discourse-workflows/spec/lib/discourse_workflows/ai/tools/workflow_ai_agent_catalog_spec.rb b/plugins/discourse-workflows/spec/lib/discourse_workflows/ai/tools/workflow_ai_agent_catalog_spec.rb
new file mode 100644
index 00000000000..0d609d98f57
--- /dev/null
+++ b/plugins/discourse-workflows/spec/lib/discourse_workflows/ai/tools/workflow_ai_agent_catalog_spec.rb
@@ -0,0 +1,57 @@
+# frozen_string_literal: true
+
+RSpec.describe DiscourseWorkflows::Ai::Tools::WorkflowAiAgentCatalog do
+ fab!(:admin)
+ fab!(:matching_agent) do
+ Fabricate(
+ :ai_agent,
+ name: "Workflow triage helper",
+ description: "Classifies incoming support posts.",
+ system_prompt: "Decide whether a Discourse support post needs urgent triage.",
+ enabled: true,
+ )
+ end
+
+ fab!(:disabled_agent) do
+ Fabricate(
+ :ai_agent,
+ name: "Disabled triage helper",
+ description: "Old support classifier.",
+ system_prompt: "Classify support posts.",
+ enabled: false,
+ )
+ end
+
+ def invoke_tool(query:, include_disabled: false)
+ context = DiscourseAi::Agents::BotContext.new(messages: [], user: admin)
+ described_class.new(
+ { query: query, include_disabled: include_disabled },
+ bot_user: Discourse.system_user,
+ llm: nil,
+ context: context,
+ ).invoke
+ end
+
+ it "returns enabled AI agents matching the query", :aggregate_failures do
+ result = invoke_tool(query: "support triage")
+
+ expect(result[:status]).to eq("success")
+ expect(result[:agents]).to contain_exactly(
+ include(
+ id: matching_agent.id,
+ name: matching_agent.name,
+ description: matching_agent.description,
+ enabled: true,
+ system_prompt_excerpt: matching_agent.system_prompt,
+ ),
+ )
+ end
+
+ it "can include disabled matches for awareness", :aggregate_failures do
+ result = invoke_tool(query: "old", include_disabled: true)
+
+ expect(result[:agents]).to contain_exactly(
+ include(id: disabled_agent.id, name: disabled_agent.name, enabled: false),
+ )
+ end
+end
diff --git a/plugins/discourse-workflows/spec/lib/discourse_workflows/ai/tools/workflow_ask_questions_spec.rb b/plugins/discourse-workflows/spec/lib/discourse_workflows/ai/tools/workflow_ask_questions_spec.rb
new file mode 100644
index 00000000000..a11c02bfbfe
--- /dev/null
+++ b/plugins/discourse-workflows/spec/lib/discourse_workflows/ai/tools/workflow_ask_questions_spec.rb
@@ -0,0 +1,44 @@
+# frozen_string_literal: true
+
+RSpec.describe DiscourseWorkflows::Ai::Tools::WorkflowAskQuestions do
+ fab!(:admin)
+
+ it "normalizes clarification questions and pauses the agent chain", :aggregate_failures do
+ tool =
+ described_class.new(
+ {
+ questions: [
+ {
+ id: "trigger_scope",
+ question: "Which topics should trigger this workflow?",
+ multi_select: true,
+ options: [
+ { label: "All topics", description: "Run for every topic." },
+ { label: "Support only", description: "Run only in support categories." },
+ ],
+ },
+ ],
+ },
+ bot_user: Discourse.system_user,
+ llm: nil,
+ context: DiscourseAi::Agents::BotContext.new(messages: [], user: admin),
+ )
+
+ expect(tool.invoke).to eq(
+ status: "waiting_for_user",
+ questions: [
+ {
+ id: "trigger_scope",
+ question: "Which topics should trigger this workflow?",
+ multi_select: true,
+ custom_allowed: true,
+ options: [
+ { label: "All topics", description: "Run for every topic." },
+ { label: "Support only", description: "Run only in support categories." },
+ ],
+ },
+ ],
+ )
+ expect(tool.chain_next_response?).to eq(false)
+ end
+end
diff --git a/plugins/discourse-workflows/spec/lib/discourse_workflows/ai/tools/workflow_authoring_result_spec.rb b/plugins/discourse-workflows/spec/lib/discourse_workflows/ai/tools/workflow_authoring_result_spec.rb
new file mode 100644
index 00000000000..a29cb6a5ba0
--- /dev/null
+++ b/plugins/discourse-workflows/spec/lib/discourse_workflows/ai/tools/workflow_authoring_result_spec.rb
@@ -0,0 +1,110 @@
+# frozen_string_literal: true
+
+RSpec.describe DiscourseWorkflows::Ai::Tools::WorkflowAuthoringResult do
+ fab!(:admin)
+
+ it "normalizes a proposed patch result and pauses the chain", :aggregate_failures do
+ tool =
+ described_class.new(
+ {
+ status: "proposed_patch",
+ message: "Create a manual workflow",
+ proposal: {
+ title: "Manual workflow",
+ summary: "Start with a manual trigger.",
+ risk_level: "low",
+ operations: [
+ {
+ op: "add_node",
+ client_id: "manual-trigger",
+ node: {
+ type: "trigger:manual",
+ name: "Manual trigger",
+ },
+ },
+ ],
+ },
+ },
+ bot_user: Discourse.system_user,
+ llm: nil,
+ context: DiscourseAi::Agents::BotContext.new(messages: [], user: admin),
+ )
+
+ expect(tool.invoke).to eq(
+ status: "proposed_patch",
+ message: "Create a manual workflow",
+ questions: [],
+ proposal: {
+ "title" => "Manual workflow",
+ "summary" => "Start with a manual trigger.",
+ "risk_level" => "low",
+ "operations" => [
+ {
+ "op" => "add_node",
+ "client_id" => "manual-trigger",
+ "node" => {
+ "type" => "trigger:manual",
+ "name" => "Manual trigger",
+ },
+ },
+ ],
+ },
+ )
+ expect(tool.chain_next_response?).to eq(false)
+ end
+
+ it "normalizes clarification questions" do
+ tool =
+ described_class.new(
+ {
+ status: "needs_clarification",
+ message: "Choose a category.",
+ questions: [
+ {
+ question: "Which category should trigger this workflow?",
+ options: [
+ { label: "Support", description: "Only support topics." },
+ { label: "All", description: "All topics." },
+ ],
+ },
+ ],
+ },
+ bot_user: Discourse.system_user,
+ llm: nil,
+ context: DiscourseAi::Agents::BotContext.new(messages: [], user: admin),
+ )
+
+ expect(tool.invoke[:questions]).to eq(
+ [
+ {
+ id: "question_1",
+ question: "Which category should trigger this workflow?",
+ multi_select: false,
+ custom_allowed: true,
+ options: [
+ { label: "Support", description: "Only support topics." },
+ { label: "All", description: "All topics." },
+ ],
+ },
+ ],
+ )
+ end
+
+ it "returns an error for invalid proposed patches" do
+ tool =
+ described_class.new(
+ { status: "proposed_patch", message: "Missing operations", proposal: {} },
+ bot_user: Discourse.system_user,
+ llm: nil,
+ context: DiscourseAi::Agents::BotContext.new(messages: [], user: admin),
+ )
+
+ expect(tool.invoke).to eq(
+ status: "error",
+ message: "Proposed patch results must include proposal.operations",
+ questions: [],
+ proposal: {
+ },
+ )
+ end
+end
diff --git a/plugins/discourse-workflows/spec/lib/discourse_workflows/ai/tools/workflow_node_catalog_spec.rb b/plugins/discourse-workflows/spec/lib/discourse_workflows/ai/tools/workflow_node_catalog_spec.rb
new file mode 100644
index 00000000000..8da60fe52b1
--- /dev/null
+++ b/plugins/discourse-workflows/spec/lib/discourse_workflows/ai/tools/workflow_node_catalog_spec.rb
@@ -0,0 +1,167 @@
+# frozen_string_literal: true
+
+RSpec.describe DiscourseWorkflows::Ai::Tools::WorkflowNodeCatalog do
+ fab!(:admin)
+
+ before { SiteSetting.discourse_ai_enabled = true }
+
+ def invoke_tool(query: nil, include_examples: false)
+ context = DiscourseAi::Agents::BotContext.new(messages: [], user: admin)
+ described_class.new(
+ { query: query, include_examples: include_examples }.compact,
+ bot_user: Discourse.system_user,
+ llm: nil,
+ context: context,
+ ).invoke
+ end
+
+ it "exposes post author, topic link, and action output fields", :aggregate_failures do
+ result = invoke_tool
+ nodes_by_type = result[:nodes].index_by { |node| node[:type] }
+
+ expect(result[:status]).to eq("success")
+ expect(nodes_by_type.dig("trigger:topic_created", :output_schema)).to include(
+ "post.user_id" => "integer",
+ "post.username" => "string",
+ "post.post_number" => "integer",
+ "post.topic_id" => "integer",
+ "post.post_url" => "string",
+ )
+ expect(nodes_by_type.dig("trigger:topic_created", :output_schema)).not_to include(
+ "post.trust_level",
+ "user.trust_level",
+ )
+ expect(nodes_by_type.dig("trigger:post_created", :output_schema)).to include(
+ "post.user_id" => "integer",
+ "post.username" => "string",
+ "post.post_number" => "integer",
+ "post.topic_id" => "integer",
+ "post.post_url" => "string",
+ "user.id" => "integer",
+ "user.username" => "string",
+ "user.trust_level" => "integer",
+ "user.trust_level_name" => "string",
+ "user.admin" => "boolean",
+ "user.moderator" => "boolean",
+ "user.staff" => "boolean",
+ )
+ expect(nodes_by_type.dig("trigger:post_created", :output_schema)).not_to include(
+ "post.trust_level",
+ "post.admin",
+ "post.moderator",
+ "post.staff",
+ )
+ expect(nodes_by_type.dig("trigger:post_edited", :output_schema)).to include(
+ "post.id" => "integer",
+ "post.raw" => "string",
+ "user.trust_level" => "integer",
+ "user.trust_level_name" => "string",
+ )
+ expect(nodes_by_type.dig("trigger:topic_closed", :output_schema)).to include(
+ "topic.id" => "integer",
+ "topic.title" => "string",
+ "topic.slug" => "string",
+ "topic.closed" => "boolean",
+ "topic.archived" => "boolean",
+ )
+ expect(nodes_by_type.dig("action:topic", :output_schema)).to include(
+ "topic.id" => "integer",
+ "topic.slug" => "string",
+ "topic.archived" => "boolean",
+ "post.post_url" => "string",
+ )
+ expect(nodes_by_type.dig("action:topic", :output_schema)).not_to include("post.trust_level")
+ expect(nodes_by_type.dig("action:topic_tags", :output_schema)).to include(
+ "topic_id" => "integer",
+ "tag_names" => "array<string>",
+ )
+ expect(nodes_by_type.dig("action:post", :output_schema)).to include(
+ "post.id" => "integer",
+ "post.topic_id" => "integer",
+ "post.post_url" => "string",
+ )
+ expect(nodes_by_type.dig("action:send_personal_message", :output_schema)).to include(
+ "topic.id" => "integer",
+ "topic.slug" => "string",
+ "post.id" => "integer",
+ "post.post_url" => "string",
+ )
+ expect(nodes_by_type.dig("action:ai_agent", :output_schema)).to include("result" => "string")
+ end
+
+ it "matches broad multi-term catalog queries", :aggregate_failures do
+ result =
+ invoke_tool(
+ query:
+ "trigger topic_closed action topic get condition filter chat message dm group membership",
+ include_examples: true,
+ )
+ node_types = result[:nodes].map { |node| node[:type] }
+
+ expect(node_types).to include(
+ "trigger:topic_closed",
+ "action:topic",
+ "condition:filter",
+ "action:group",
+ "action:send_chat_message",
+ "action:send_personal_message",
+ )
+ expect(result[:nodes].find { |node| node[:type] == "action:topic" }[:examples]).to be_present
+ end
+
+ it "includes declarative filter and topic lookup examples", :aggregate_failures do
+ result = invoke_tool(include_examples: true)
+ filter_node = result[:nodes].find { |node| node[:type] == "condition:filter" }
+ group_node = result[:nodes].find { |node| node[:type] == "action:group" }
+ topic_node = result[:nodes].find { |node| node[:type] == "action:topic" }
+ post_node = result[:nodes].find { |node| node[:type] == "action:post" }
+ personal_message_node =
+ result[:nodes].find { |node| node[:type] == "action:send_personal_message" }
+ if_node = result[:nodes].find { |node| node[:type] == "condition:if" }
+ cake_example =
+ filter_node[:examples].find { |example| example[:name] == "Keep TL1 posts mentioning cake" }
+ trust_level_example =
+ filter_node[:examples].find { |example| example[:name] == "Keep TL1-or-lower post authors" }
+
+ expect(cake_example[:parameters]).to include(combinator: "and")
+ expect(cake_example.dig(:parameters, :conditions)).to contain_exactly(
+ include(leftValue: "={{ $json.user.trust_level }}", rightValue: "1"),
+ include(leftValue: "={{ $json.post.raw }}", rightValue: "cake"),
+ )
+ expect(trust_level_example.dig(:parameters, :conditions)).to contain_exactly(
+ include(
+ leftValue: "={{ $json.user.trust_level }}",
+ rightValue: "1",
+ operator: include(operation: "lte", type: "number"),
+ ),
+ )
+ expect(topic_node[:examples]).to contain_exactly(
+ include(parameters: include(operation: "get", topic_id: "={{ $json.topic.id }}")),
+ )
+ expect(post_node[:examples]).to contain_exactly(
+ include(parameters: include(operation: "create", topic_id: "={{ $json.topic.id }}")),
+ )
+ expect(group_node[:examples]).to contain_exactly(
+ include(
+ parameters:
+ include(
+ operation: "check_membership",
+ username: "={{ $json.user.username }}",
+ group_id: 123,
+ ),
+ ),
+ )
+ expect(personal_message_node[:examples]).to contain_exactly(
+ include(
+ parameters:
+ include(
+ recipient_usernames: ["admin"],
+ raw: "=A group member posted: {{ $json.post.post_url }}",
+ ),
+ ),
+ )
+ expect(if_node[:examples].first.dig(:parameters, :conditions)).to contain_exactly(
+ include(leftValue: "={{ $json.user.trust_level }}", rightValue: "1"),
+ )
+ end
+end
diff --git a/plugins/discourse-workflows/spec/lib/discourse_workflows/ai/tools/workflow_resolve_entity_spec.rb b/plugins/discourse-workflows/spec/lib/discourse_workflows/ai/tools/workflow_resolve_entity_spec.rb
new file mode 100644
index 00000000000..884fbc1fc04
--- /dev/null
+++ b/plugins/discourse-workflows/spec/lib/discourse_workflows/ai/tools/workflow_resolve_entity_spec.rb
@@ -0,0 +1,23 @@
+# frozen_string_literal: true
+
+RSpec.describe DiscourseWorkflows::Ai::Tools::WorkflowResolveEntity do
+ fab!(:admin)
+
+ it "resolves categories by name" do
+ category = Fabricate(:category, name: "Bug Reports", slug: "bugs")
+ context = DiscourseAi::Agents::BotContext.new(messages: [], user: admin)
+ result =
+ described_class.new(
+ { kind: "category", query: "bug" },
+ bot_user: Discourse.system_user,
+ llm: nil,
+ context: context,
+ ).invoke
+
+ expect(result).to eq(
+ status: "success",
+ kind: "category",
+ matches: [{ id: category.id, name: category.name, slug: category.slug }],
+ )
+ end
+end
diff --git a/plugins/discourse-workflows/spec/lib/discourse_workflows/ai/tools/workflow_validate_patch_spec.rb b/plugins/discourse-workflows/spec/lib/discourse_workflows/ai/tools/workflow_validate_patch_spec.rb
new file mode 100644
index 00000000000..9eb62656295
--- /dev/null
+++ b/plugins/discourse-workflows/spec/lib/discourse_workflows/ai/tools/workflow_validate_patch_spec.rb
@@ -0,0 +1,879 @@
+# frozen_string_literal: true
+
+RSpec.describe DiscourseWorkflows::Ai::Tools::WorkflowValidatePatch do
+ fab!(:admin)
+
+ def invoke_tool(operations)
+ context = DiscourseAi::Agents::BotContext.new(messages: [], user: admin)
+ described_class.new(
+ { operations: operations },
+ bot_user: Discourse.system_user,
+ llm: nil,
+ context: context,
+ ).invoke
+ end
+
+ it "returns inferred schemas for a dry-run graph", :aggregate_failures do
+ operations = [
+ {
+ op: "add_node",
+ client_id: "post-created",
+ node: {
+ type: "trigger:post_created",
+ typeVersion: "1.0",
+ name: "When post is created",
+ position: {
+ x: 0,
+ y: 0,
+ },
+ parameters: {
+ },
+ credentials: {
+ },
+ },
+ },
+ {
+ op: "add_node",
+ client_id: "filter-posts",
+ node: {
+ type: "condition:filter",
+ typeVersion: "1.0",
+ name: "Filter TL1 cake posts",
+ position: {
+ x: 280,
+ y: 0,
+ },
+ parameters: {
+ combinator: "and",
+ conditions: [],
+ },
+ credentials: {
+ },
+ },
+ },
+ {
+ op: "add_connection",
+ from: "post-created",
+ to: "filter-posts",
+ output_index: 0,
+ input_index: 0,
+ connection_type: "main",
+ },
+ ]
+
+ result = invoke_tool(operations.map(&:to_json))
+ schemas_by_name = result[:node_schemas].index_by { |schema| schema[:node_name] }
+
+ expect(result).to include(status: "success", valid: true, errors: [])
+ expect(schemas_by_name.dig("When post is created", :output_schema)).to include(
+ "$json.user.trust_level" => "integer",
+ "$json.user.trust_level_name" => "string",
+ "$json.post.raw" => "string",
+ "$json.post.post_url" => "string",
+ )
+ expect(schemas_by_name.dig("When post is created", :output_schema)).not_to include(
+ "$json.post.trust_level",
+ )
+ expect(schemas_by_name.dig("Filter TL1 cake posts", :input_schema)).to include(
+ "$json.user.trust_level" => "integer",
+ "$json.post.raw" => "string",
+ "$json.post.post_url" => "string",
+ )
+ expect(schemas_by_name.dig("Filter TL1 cake posts", :output_schema)).to include(
+ "$json.user.trust_level" => "integer",
+ "$json.post.raw" => "string",
+ "$json.post.post_url" => "string",
+ )
+ end
+
+ it "validates proposed AI agents and agent output schemas", :aggregate_failures do
+ operations = [
+ {
+ op: "create_ai_agent",
+ client_id: "sentiment-agent",
+ agent: {
+ name: "Workflow sentiment agent",
+ description: "Determines whether a post needs follow up.",
+ system_prompt: "Return positive, neutral, or negative for each Discourse post.",
+ },
+ },
+ {
+ op: "add_node",
+ client_id: "post-created",
+ node: {
+ type: "trigger:post_created",
+ typeVersion: "1.0",
+ name: "Post created",
+ position: {
+ x: 0,
+ y: 0,
+ },
+ parameters: {
+ },
+ credentials: {
+ },
+ },
+ },
+ {
+ op: "add_node",
+ client_id: "classify-post",
+ node: {
+ type: "action:ai_agent",
+ typeVersion: "1.0",
+ name: "Classify post",
+ position: {
+ x: 280,
+ y: 0,
+ },
+ parameters: {
+ agent_id: {
+ "$ref" => "sentiment-agent",
+ },
+ prompt: "=Classify this post: {{ $json.post.raw }}",
+ },
+ credentials: {
+ },
+ },
+ },
+ {
+ op: "add_node",
+ client_id: "write-log",
+ node: {
+ type: "action:log",
+ typeVersion: "1.0",
+ name: "Log classification",
+ position: {
+ x: 560,
+ y: 0,
+ },
+ parameters: {
+ entries: {
+ values: [{ key: "classification", value: "={{ $json.result }}" }],
+ },
+ },
+ credentials: {
+ },
+ },
+ },
+ {
+ op: "add_connection",
+ from: "post-created",
+ to: "classify-post",
+ output_index: 0,
+ input_index: 0,
+ connection_type: "main",
+ },
+ {
+ op: "add_connection",
+ from: "classify-post",
+ to: "write-log",
+ output_index: 0,
+ input_index: 0,
+ connection_type: "main",
+ },
+ ]
+
+ result = invoke_tool(operations)
+ schemas_by_name = result[:node_schemas].index_by { |schema| schema[:node_name] }
+
+ expect(result).to include(status: "success", valid: true, errors: [])
+ expect(result[:created_resources]).to contain_exactly(
+ include(
+ "type" => "ai_agent",
+ "client_id" => "sentiment-agent",
+ "name" => "Workflow sentiment agent",
+ ),
+ )
+ expect(schemas_by_name.dig("Classify post", :output_schema)).to include(
+ "$json.result" => "string",
+ )
+ expect(schemas_by_name.dig("Log classification", :input_schema)).to include(
+ "$json.result" => "string",
+ )
+ end
+
+ it "passes schemas through group checks into private messages", :aggregate_failures do
+ operations = [
+ {
+ op: "add_node",
+ client_id: "post-created",
+ node: {
+ type: "trigger:post_created",
+ typeVersion: "1.0",
+ name: "Post created",
+ position: {
+ x: 0,
+ y: 0,
+ },
+ parameters: {
+ },
+ credentials: {
+ },
+ },
+ },
+ {
+ op: "add_node",
+ client_id: "group-membership",
+ node: {
+ type: "action:group",
+ typeVersion: "1.0",
+ name: "Check friend group membership",
+ position: {
+ x: 280,
+ y: 0,
+ },
+ parameters: {
+ operation: "check_membership",
+ username: "={{ $json.post.username }}",
+ group_id: 1,
+ actor_username: "system",
+ },
+ credentials: {
+ },
+ },
+ },
+ {
+ op: "add_node",
+ client_id: "friend-group",
+ node: {
+ type: "condition:if",
+ typeVersion: "1.0",
+ name: "Keep friend group posts",
+ position: {
+ x: 560,
+ y: 0,
+ },
+ parameters: {
+ combinator: "and",
+ conditions: [
+ {
+ id: "member_of_friend_group",
+ leftValue: "={{ $json.group_membership.in_group }}",
+ operator: {
+ operation: "equals",
+ type: "boolean",
+ singleValue: false,
+ },
+ rightValue: true,
+ },
+ ],
+ },
+ credentials: {
+ },
+ },
+ },
+ {
+ op: "add_node",
+ client_id: "dm-admin",
+ node: {
+ type: "action:send_personal_message",
+ typeVersion: "1.0",
+ name: "DM admin",
+ position: {
+ x: 840,
+ y: 0,
+ },
+ parameters: {
+ recipient_usernames: ["admin"],
+ title: "=New post from @{{ $json.post.username }}",
+ raw: "=A friend group member posted: {{ $json.post.post_url }}",
+ sender_username: "system",
+ },
+ credentials: {
+ },
+ },
+ },
+ {
+ op: "add_connection",
+ from: "post-created",
+ to: "group-membership",
+ output_index: 0,
+ input_index: 0,
+ connection_type: "main",
+ },
+ {
+ op: "add_connection",
+ from: "group-membership",
+ to: "friend-group",
+ output_index: 0,
+ input_index: 0,
+ connection_type: "main",
+ },
+ {
+ op: "add_connection",
+ from: "friend-group",
+ to: "dm-admin",
+ output_index: 0,
+ input_index: 0,
+ connection_type: "true",
+ },
+ ]
+
+ result = invoke_tool(operations)
+ schemas_by_name = result[:node_schemas].index_by { |schema| schema[:node_name] }
+
+ expect(result).to include(status: "success", valid: true, errors: [])
+ expect(schemas_by_name.dig("Keep friend group posts", :input_schema)).to include(
+ "$json.post.username" => "string",
+ "$json.post.post_url" => "string",
+ "$json.group_membership.in_group" => "boolean",
+ )
+ expect(schemas_by_name.dig("DM admin", :input_schema)).to include(
+ "$json.post.username" => "string",
+ "$json.post.post_url" => "string",
+ )
+ expect(schemas_by_name.dig("DM admin", :output_schema)).to include(
+ "$json.topic.id" => "integer",
+ "$json.post.post_url" => "string",
+ )
+ end
+
+ it "returns action output schemas and rejects unavailable downstream paths",
+ :aggregate_failures do
+ operations = [
+ {
+ op: "add_node",
+ client_id: "topic-created",
+ node: {
+ type: "trigger:topic_created",
+ typeVersion: "1.0",
+ name: "Topic created",
+ position: {
+ x: 0,
+ y: 0,
+ },
+ parameters: {
+ },
+ credentials: {
+ },
+ },
+ },
+ {
+ op: "add_node",
+ client_id: "add-tag",
+ node: {
+ type: "action:topic_tags",
+ typeVersion: "1.0",
+ name: "Add tag",
+ position: {
+ x: 280,
+ y: 0,
+ },
+ parameters: {
+ operation: "add",
+ topic_id: "={{ $json.topic.id }}",
+ tag_names: "needs-review",
+ actor_username: "system",
+ },
+ credentials: {
+ },
+ },
+ },
+ {
+ op: "add_node",
+ client_id: "reply",
+ node: {
+ type: "action:post",
+ typeVersion: "1.0",
+ name: "Reply",
+ position: {
+ x: 560,
+ y: 0,
+ },
+ parameters: {
+ operation: "create",
+ topic_id: "={{ $json.topic.id }}",
+ raw: "Thanks for contacting support.",
+ author_username: "system",
+ },
+ credentials: {
+ },
+ },
+ },
+ {
+ op: "add_connection",
+ from: "topic-created",
+ to: "add-tag",
+ output_index: 0,
+ input_index: 0,
+ connection_type: "main",
+ },
+ {
+ op: "add_connection",
+ from: "add-tag",
+ to: "reply",
+ output_index: 0,
+ input_index: 0,
+ connection_type: "main",
+ },
+ ]
+
+ result = invoke_tool(operations)
+ schemas_by_name = result[:node_schemas].index_by { |schema| schema[:node_name] }
+
+ expect(result[:valid]).to eq(false)
+ expect(result[:expression_errors]).to contain_exactly(
+ a_string_including("Reply parameter topic_id references $json.topic.id"),
+ )
+ expect(schemas_by_name.dig("Add tag", :output_schema)).to include(
+ "$json.topic_id" => "integer",
+ "$json.tag_names" => "array<string>",
+ )
+ expect(schemas_by_name.dig("Reply", :input_schema)).to include(
+ "$json.topic_id" => "integer",
+ "$json.tag_names" => "array<string>",
+ )
+ end
+
+ it "rejects condition builder keys that would not execute", :aggregate_failures do
+ operations = [
+ {
+ op: "add_node",
+ client_id: "post-created",
+ node: {
+ type: "trigger:post_created",
+ typeVersion: "1.0",
+ name: "Post created",
+ position: {
+ x: 0,
+ y: 0,
+ },
+ parameters: {
+ },
+ credentials: {
+ },
+ },
+ },
+ {
+ op: "add_node",
+ client_id: "bad-condition",
+ node: {
+ type: "condition:if",
+ typeVersion: "1.0",
+ name: "Bad condition",
+ position: {
+ x: 260,
+ y: 0,
+ },
+ parameters: {
+ combinator: "and",
+ conditions: [
+ {
+ left: "={{ $json.user.trust_level }}",
+ operator: {
+ operation: "lte",
+ type: "number",
+ },
+ right: 1,
+ },
+ ],
+ },
+ credentials: {
+ },
+ },
+ },
+ {
+ op: "add_connection",
+ from: "post-created",
+ to: "bad-condition",
+ output_index: 0,
+ input_index: 0,
+ connection_type: "main",
+ },
+ ]
+
+ result = invoke_tool(operations)
+
+ expect(result[:valid]).to eq(false)
+ expect(result[:expression_errors]).to contain_exactly(
+ "Bad condition condition 1 must set leftValue. Use leftValue instead of left.",
+ "Bad condition condition 1 must set rightValue for lte comparisons. Use rightValue instead of right.",
+ )
+ end
+
+ it "rejects object-shaped condition values from AI drafts", :aggregate_failures do
+ operations = [
+ {
+ op: "add_node",
+ client_id: "post-created",
+ node: {
+ type: "trigger:post_created",
+ typeVersion: "1.0",
+ name: "Post created",
+ position: {
+ x: 0,
+ y: 0,
+ },
+ parameters: {
+ },
+ credentials: {
+ },
+ },
+ },
+ {
+ op: "add_node",
+ client_id: "bad-condition",
+ node: {
+ type: "condition:filter",
+ typeVersion: "1.0",
+ name: "Bad condition",
+ position: {
+ x: 260,
+ y: 0,
+ },
+ parameters: {
+ combinator: "and",
+ conditions: [
+ {
+ leftValue: {
+ type: "number",
+ value: "user.trust_level",
+ },
+ operator: {
+ operation: "lte",
+ type: "number",
+ },
+ rightValue: {
+ type: "number",
+ value: 1,
+ },
+ },
+ ],
+ },
+ credentials: {
+ },
+ },
+ },
+ {
+ op: "add_connection",
+ from: "post-created",
+ to: "bad-condition",
+ output_index: 0,
+ input_index: 0,
+ connection_type: "main",
+ },
+ ]
+
+ result = invoke_tool(operations)
+
+ expect(result[:valid]).to eq(false)
+ expect(result[:expression_errors]).to contain_exactly(
+ "Bad condition condition 1 leftValue must be a scalar or expression string, not an object.",
+ "Bad condition condition 1 rightValue must be a scalar or expression string, not an object.",
+ )
+ end
+
+ it "rejects invalid output connection types", :aggregate_failures do
+ operations = [
+ {
+ op: "add_node",
+ client_id: "post-created",
+ node: {
+ type: "trigger:post_created",
+ typeVersion: "1.0",
+ name: "Post created",
+ position: {
+ x: 0,
+ y: 0,
+ },
+ parameters: {
+ },
+ credentials: {
+ },
+ },
+ },
+ {
+ op: "add_node",
+ client_id: "filter-posts",
+ node: {
+ type: "condition:filter",
+ typeVersion: "1.0",
+ name: "Filter posts",
+ position: {
+ x: 260,
+ y: 0,
+ },
+ parameters: {
+ combinator: "and",
+ conditions: [],
+ },
+ credentials: {
+ },
+ },
+ },
+ {
+ op: "add_node",
+ client_id: "log",
+ node: {
+ type: "action:log",
+ typeVersion: "1.0",
+ name: "Log post",
+ position: {
+ x: 520,
+ y: 0,
+ },
+ parameters: {
+ entries: {
+ values: [{ key: "message", value: "post matched" }],
+ },
+ },
+ credentials: {
+ },
+ },
+ },
+ {
+ op: "add_connection",
+ from: "post-created",
+ to: "filter-posts",
+ output_index: 0,
+ input_index: 0,
+ connection_type: "main",
+ },
+ {
+ op: "add_connection",
+ from: "filter-posts",
+ to: "log",
+ output_index: 0,
+ input_index: 0,
+ connection_type: "main",
+ },
+ ]
+
+ result = invoke_tool(operations)
+
+ expect(result[:valid]).to eq(false)
+ expect(result[:graph_errors]).to contain_exactly(
+ 'Filter posts output connection_type "main" is invalid for condition:filter. Use one of: true, false.',
+ )
+ end
+
+ it "does not advertise unavailable first-post trust fields after topic lookups",
+ :aggregate_failures do
+ operations = [
+ {
+ op: "add_node",
+ client_id: "closed",
+ node: {
+ type: "trigger:topic_closed",
+ typeVersion: "1.0",
+ name: "Topic closed",
+ position: {
+ x: 0,
+ y: 0,
+ },
+ parameters: {
+ category_id: 1,
+ },
+ credentials: {
+ },
+ },
+ },
+ {
+ op: "add_node",
+ client_id: "get-topic",
+ node: {
+ type: "action:topic",
+ typeVersion: "1.0",
+ name: "Get closed topic",
+ position: {
+ x: 260,
+ y: 0,
+ },
+ parameters: {
+ operation: "get",
+ topic_id: "={{ $json.topic.id }}",
+ actor_username: "system",
+ },
+ credentials: {
+ },
+ },
+ },
+ {
+ op: "add_node",
+ client_id: "filter-tl1",
+ node: {
+ type: "condition:filter",
+ typeVersion: "1.0",
+ name: "Keep known topic authors",
+ position: {
+ x: 520,
+ y: 0,
+ },
+ parameters: {
+ combinator: "and",
+ conditions: [
+ {
+ id: "topic_author_user_id",
+ leftValue: "={{ $json.post.user_id }}",
+ operator: {
+ operation: "gt",
+ type: "number",
+ singleValue: false,
+ },
+ rightValue: "0",
+ },
+ ],
+ },
+ credentials: {
+ },
+ },
+ },
+ {
+ op: "add_connection",
+ from: "closed",
+ to: "get-topic",
+ output_index: 0,
+ input_index: 0,
+ connection_type: "main",
+ },
+ {
+ op: "add_connection",
+ from: "get-topic",
+ to: "filter-tl1",
+ output_index: 0,
+ input_index: 0,
+ connection_type: "main",
+ },
+ ]
+
+ result = invoke_tool(operations)
+ schemas_by_name = result[:node_schemas].index_by { |schema| schema[:node_name] }
+
+ expect(result).to include(status: "success", valid: true, errors: [])
+ expect(schemas_by_name.dig("Topic closed", :output_schema)).not_to include(
+ "$json.post.trust_level",
+ )
+ expect(schemas_by_name.dig("Get closed topic", :output_schema)).to include(
+ "$json.post.post_url" => "string",
+ "$json.post.user_id" => "integer",
+ )
+ expect(schemas_by_name.dig("Get closed topic", :output_schema)).not_to include(
+ "$json.post.trust_level",
+ )
+ expect(schemas_by_name.dig("Keep known topic authors", :input_schema)).to include(
+ "$json.post.post_url" => "string",
+ "$json.post.user_id" => "integer",
+ )
+ end
+
+ it "validates topic-closed schemas and dynamic template prefixes", :aggregate_failures do
+ operations = [
+ {
+ op: "add_node",
+ client_id: "closed",
+ node: {
+ type: "trigger:topic_closed",
+ typeVersion: "1.0",
+ name: "Topic closed",
+ position: {
+ x: 0,
+ y: 0,
+ },
+ parameters: {
+ },
+ credentials: {
+ },
+ },
+ },
+ {
+ op: "add_node",
+ client_id: "wait",
+ node: {
+ type: "flow:wait",
+ typeVersion: "1.0",
+ name: "Wait 30 days",
+ position: {
+ x: 280,
+ y: 0,
+ },
+ parameters: {
+ resume: "time_interval",
+ wait_amount: 30,
+ wait_unit: "days",
+ },
+ credentials: {
+ },
+ },
+ },
+ {
+ op: "add_node",
+ client_id: "archive",
+ node: {
+ type: "action:topic",
+ typeVersion: "1.0",
+ name: "Archive topic",
+ position: {
+ x: 560,
+ y: 0,
+ },
+ parameters: {
+ operation: "archive",
+ topic_id: "={{ $json.topic.id }}",
+ actor_username: "system",
+ },
+ credentials: {
+ },
+ },
+ },
+ {
+ op: "add_node",
+ client_id: "chat",
+ node: {
+ type: "action:send_chat_message",
+ typeVersion: "1.0",
+ name: "Notify chat",
+ position: {
+ x: 840,
+ y: 0,
+ },
+ parameters: {
+ channel_id: 2,
+ message: "Topic archived: {{ $json.topic.title }} ({{ $json.post.post_url }})",
+ },
+ credentials: {
+ },
+ },
+ },
+ {
+ op: "add_connection",
+ from: "closed",
+ to: "wait",
+ output_index: 0,
+ input_index: 0,
+ connection_type: "main",
+ },
+ {
+ op: "add_connection",
+ from: "wait",
+ to: "archive",
+ output_index: 0,
+ input_index: 0,
+ connection_type: "main",
+ },
+ {
+ op: "add_connection",
+ from: "archive",
+ to: "chat",
+ output_index: 0,
+ input_index: 0,
+ connection_type: "main",
+ },
+ ]
+
+ result = invoke_tool(operations)
+ schemas_by_name = result[:node_schemas].index_by { |schema| schema[:node_name] }
+
+ expect(result[:valid]).to eq(false)
+ expect(result[:expression_errors]).to contain_exactly(
+ a_string_including("Notify chat parameter message contains {{ }} expressions"),
+ )
+ expect(schemas_by_name.dig("Topic closed", :output_schema)).to include(
+ "$json.topic.id" => "integer",
+ "$json.topic.slug" => "string",
+ )
+ expect(schemas_by_name.dig("Notify chat", :input_schema)).to include(
+ "$json.topic.id" => "integer",
+ "$json.topic.slug" => "string",
+ )
+ end
+end
diff --git a/plugins/discourse-workflows/spec/lib/discourse_workflows/ai/tools/workflow_validate_script_spec.rb b/plugins/discourse-workflows/spec/lib/discourse_workflows/ai/tools/workflow_validate_script_spec.rb
new file mode 100644
index 00000000000..cd9888281bb
--- /dev/null
+++ b/plugins/discourse-workflows/spec/lib/discourse_workflows/ai/tools/workflow_validate_script_spec.rb
@@ -0,0 +1,62 @@
+# frozen_string_literal: true
+
+RSpec.describe DiscourseWorkflows::Ai::Tools::WorkflowValidateScript do
+ fab!(:admin)
+
+ def invoke_tool(parameters)
+ context = DiscourseAi::Agents::BotContext.new(messages: [], user: admin)
+ described_class.new(
+ parameters,
+ bot_user: Discourse.system_user,
+ llm: nil,
+ context: context,
+ ).invoke
+ end
+
+ it "validates a run-once script and returns sample output" do
+ result =
+ invoke_tool(
+ {
+ mode: "runOnceForAllItems",
+ code: "var items = $input.all(); items[0].json.added = true; return items;",
+ sample_input_items: [{ "json" => { "id" => 1 } }],
+ },
+ )
+
+ expect(result).to include(
+ status: "success",
+ valid: true,
+ errors: [],
+ sample_output_items: [{ "json" => { "id" => 1, "added" => true } }],
+ )
+ end
+
+ it "rejects all-items access in per-item mode" do
+ result =
+ invoke_tool(
+ {
+ mode: "runOnceForEachItem",
+ code: "var items = $input.all(); return { json: { count: items.length } };",
+ },
+ )
+
+ expect(result).to include(
+ status: "success",
+ valid: false,
+ errors: ["$input.all is only available in runOnceForAllItems mode"],
+ )
+ end
+
+ it "rejects output that mixes reserved item keys with plain fields" do
+ result =
+ invoke_tool(
+ { mode: "runOnceForAllItems", code: "return [{ json: { id: 1 }, extra: true }];" },
+ )
+
+ expect(result).to include(
+ status: "success",
+ valid: false,
+ errors: ["Output item mixes reserved item keys with plain fields"],
+ )
+ end
+end
diff --git a/plugins/discourse-workflows/spec/lib/discourse_workflows/ai_workflow_author_spec.rb b/plugins/discourse-workflows/spec/lib/discourse_workflows/ai_workflow_author_spec.rb
new file mode 100644
index 00000000000..e4241814ecb
--- /dev/null
+++ b/plugins/discourse-workflows/spec/lib/discourse_workflows/ai_workflow_author_spec.rb
@@ -0,0 +1,49 @@
+# frozen_string_literal: true
+
+RSpec.describe DiscourseWorkflows::AiWorkflowAuthor do
+ before { SiteSetting.tagging_enabled = true }
+
+ it "includes workflow authoring and safe forum discovery tools" do
+ expect(described_class.new.tools).to include(
+ DiscourseAi::Agents::Tools::ListCategories,
+ DiscourseAi::Agents::Tools::ListTags,
+ DiscourseAi::Agents::Tools::Search,
+ DiscourseAi::Agents::Tools::Read,
+ DiscourseAi::Agents::Tools::Time,
+ DiscourseWorkflows::Ai::Tools::WorkflowNodeCatalog,
+ DiscourseWorkflows::Ai::Tools::WorkflowGraphContext,
+ DiscourseWorkflows::Ai::Tools::WorkflowValidatePatch,
+ DiscourseWorkflows::Ai::Tools::WorkflowScriptContext,
+ DiscourseWorkflows::Ai::Tools::WorkflowValidateScript,
+ DiscourseWorkflows::Ai::Tools::WorkflowAiAgentCatalog,
+ DiscourseWorkflows::Ai::Tools::WorkflowAuthoringResult,
+ )
+ end
+
+ it "requires the final authoring result tool" do
+ author = described_class.new
+
+ expect(author.response_format).to be_nil
+ expect(author.system_prompt).to include(
+ "Do not write a final prose, markdown, or JSON answer",
+ "call workflow_authoring_result exactly once",
+ "Use workflow_ai_agent_catalog before adding action:ai_agent nodes",
+ "Use search_chat_channels before asking the admin to choose a chat channel",
+ "call workflow_validate_script with the exact mode and code",
+ "Do not add a Code node only to copy trigger fields forward",
+ "create_ai_agent",
+ )
+ end
+
+ it "includes chat channel search only when chat is enabled" do
+ skip "Chat plugin is not available" if !defined?(::Chat::Channel)
+
+ SiteSetting.chat_enabled = false
+ expect(described_class.new.tools).not_to include(
+ DiscourseWorkflows::Ai::Tools::SearchChatChannels,
+ )
+
+ SiteSetting.chat_enabled = true
+ expect(described_class.new.tools).to include(DiscourseWorkflows::Ai::Tools::SearchChatChannels)
+ end
+end
diff --git a/plugins/discourse-workflows/spec/lib/discourse_workflows/nodes/group_spec.rb b/plugins/discourse-workflows/spec/lib/discourse_workflows/nodes/group_spec.rb
index 597547c7afa..35aca7dc5d0 100644
--- a/plugins/discourse-workflows/spec/lib/discourse_workflows/nodes/group_spec.rb
+++ b/plugins/discourse-workflows/spec/lib/discourse_workflows/nodes/group_spec.rb
@@ -19,22 +19,16 @@ RSpec.describe DiscourseWorkflows::Nodes::Group::V1 do
described_class.load_options_context(context)
end
- it "returns non-automatic groups for the chooser" do
- expect(load_options).to include(
+ it "returns groups for the chooser", :aggregate_failures do
+ options = load_options
+
+ expect(options).to include(
{ id: group.id, name: group.name },
{ id: group_2.id, name: group_2.name },
)
- end
- it "excludes automatic groups" do
- auto_group_ids = load_options.map { |g| g[:id] }
- expect(auto_group_ids).not_to include(*Group::AUTO_GROUPS.values)
- end
-
- it "can include automatic groups when the current operation only reads a group" do
- group_ids = load_options(parameters: { operation: "get" }).map { |g| g[:id] }
-
- expect(group_ids).to include(*Group::AUTO_GROUPS.values)
+ option_ids = options.map { |option| option[:id] }
+ expect(option_ids).to include(*Group::AUTO_GROUPS.values)
end
it "filters groups by the filter term" do
@@ -220,5 +214,107 @@ RSpec.describe DiscourseWorkflows::Nodes::Group::V1 do
)
end
end
+
+ context "with check_membership operation" do
+ fab!(:member, :user)
+ fab!(:non_member, :user)
+
+ before { group.add(member) }
+
+ it "adds membership data to each item", :aggregate_failures do
+ output =
+ execute_node_output(
+ configuration: {
+ "operation" => "check_membership",
+ "username" => "={{ $json.username }}",
+ "group_id" => group.id,
+ "actor_username" => "system",
+ },
+ input_items: [
+ { "json" => { "username" => member.username, "post_id" => 1 } },
+ { "json" => { "username" => non_member.username, "post_id" => 2 } },
+ ],
+ )
+
+ expect(output.first.map { |item| item["json"] }).to contain_exactly(
+ include(
+ "username" => member.username,
+ "post_id" => 1,
+ "group_membership" =>
+ include(
+ "group_id" => group.id,
+ "group_name" => group.name,
+ "user_id" => member.id,
+ "username" => member.username,
+ "in_group" => true,
+ ),
+ ),
+ include(
+ "username" => non_member.username,
+ "post_id" => 2,
+ "group_membership" =>
+ include(
+ "group_id" => group.id,
+ "group_name" => group.name,
+ "user_id" => non_member.id,
+ "username" => non_member.username,
+ "in_group" => false,
+ ),
+ ),
+ )
+ end
+
+ it "handles the everyone pseudogroup without group_users rows", :aggregate_failures do
+ everyone = Group.refresh_automatic_group!(:everyone)
+ GroupUser.where(group: everyone, user: member).delete_all
+
+ output =
+ execute_node_output(
+ configuration: {
+ "operation" => "check_membership",
+ "username" => member.username,
+ "group_id" => everyone.id,
+ "actor_username" => "system",
+ },
+ )
+
+ membership_data = output.first.first.dig("json", "group_membership")
+
+ expect(membership_data).to include(
+ "group_id" => everyone.id,
+ "group_name" => everyone.name,
+ "user_id" => member.id,
+ "username" => member.username,
+ "in_group" => true,
+ )
+ expect(GroupUser.exists?(group: everyone, user: member)).to be(false)
+ end
+
+ it "raises when the user cannot be found" do
+ expect do
+ execute_node(
+ configuration: {
+ "operation" => "check_membership",
+ "username" => "missing_user",
+ "group_id" => group.id,
+ },
+ )
+ end.to raise_error(DiscourseWorkflows::NodeError, "User 'missing_user' not found")
+ end
+
+ it "raises when actor_username cannot see the group" do
+ group.update!(visibility_level: Group.visibility_levels[:staff])
+ config = {
+ "operation" => "check_membership",
+ "username" => member.username,
+ "group_id" => group.id.to_s,
+ "actor_username" => user.username,
+ }
+
+ expect { execute_node(configuration: config, item: item) }.to raise_error(
+ Discourse::InvalidAccess,
+ )
+ end
+ end
end
end
diff --git a/plugins/discourse-workflows/spec/lib/discourse_workflows/nodes/post_created_spec.rb b/plugins/discourse-workflows/spec/lib/discourse_workflows/nodes/post_created_spec.rb
index 0bbe4c4de78..a770fdaac40 100644
--- a/plugins/discourse-workflows/spec/lib/discourse_workflows/nodes/post_created_spec.rb
+++ b/plugins/discourse-workflows/spec/lib/discourse_workflows/nodes/post_created_spec.rb
@@ -65,6 +65,15 @@ RSpec.describe DiscourseWorkflows::Nodes::PostCreated::V1 do
expect(output[:post][:reply_to_post_number]).to eq(topic.first_post.post_number)
expect(output[:post][:user_id]).to eq(reply_user.id)
expect(output[:post][:username]).to eq(reply_user.username)
+ expect(output[:user]).to include(
+ id: reply_user.id,
+ username: reply_user.username,
+ trust_level: reply_user.trust_level,
+ trust_level_name: TrustLevel.name(reply_user.trust_level),
+ admin: false,
+ moderator: false,
+ staff: false,
+ )
expect(output[:topic][:id]).to eq(topic.id)
expect(output[:topic][:title]).to eq(topic.title)
expect(output[:topic][:tags].map { |topic_tag| topic_tag[:name] }).to eq(["test-tag"])
diff --git a/plugins/discourse-workflows/spec/lib/discourse_workflows/nodes/post_edited/v1_spec.rb b/plugins/discourse-workflows/spec/lib/discourse_workflows/nodes/post_edited/v1_spec.rb
index 651bef48850..dbc2e84626b 100644
--- a/plugins/discourse-workflows/spec/lib/discourse_workflows/nodes/post_edited/v1_spec.rb
+++ b/plugins/discourse-workflows/spec/lib/discourse_workflows/nodes/post_edited/v1_spec.rb
@@ -50,6 +50,12 @@ RSpec.describe DiscourseWorkflows::Nodes::PostEdited::V1 do
expect(output[:post][:id]).to eq(first_post.id)
expect(output[:post][:raw]).to eq(first_post.raw)
expect(output[:post][:cooked]).to eq("<p>Cooked</p>")
+ expect(output[:user]).to include(
+ id: user.id,
+ username: user.username,
+ trust_level: user.trust_level,
+ trust_level_name: TrustLevel.name(user.trust_level),
+ )
expect(output[:topic][:id]).to eq(topic.id)
expect(output[:topic][:tags].map { |topic_tag| topic_tag[:name] }).to eq(["test-tag"])
expect(output).not_to have_key(:cooked)
diff --git a/plugins/discourse-workflows/spec/lib/discourse_workflows/nodes/send_personal_message_spec.rb b/plugins/discourse-workflows/spec/lib/discourse_workflows/nodes/send_personal_message_spec.rb
new file mode 100644
index 00000000000..341c8e193d7
--- /dev/null
+++ b/plugins/discourse-workflows/spec/lib/discourse_workflows/nodes/send_personal_message_spec.rb
@@ -0,0 +1,109 @@
+# frozen_string_literal: true
+
+RSpec.describe DiscourseWorkflows::Nodes::SendPersonalMessage::V1 do
+ fab!(:sender, :admin)
+ fab!(:recipient, :user)
+ fab!(:second_recipient, :user)
+
+ describe "#execute" do
+ it "creates a personal message for the configured recipient", :aggregate_failures do
+ result = nil
+
+ expect do
+ result =
+ execute_node(
+ configuration: {
+ "recipient_usernames" => [recipient.username],
+ "title" => "Friend group post",
+ "raw" => "A friend posted: /t/example/1/1",
+ "sender_username" => sender.username,
+ },
+ )
+ end.to change { Topic.where(archetype: Archetype.private_message).count }.by(1)
+
+ topic = Topic.where(archetype: Archetype.private_message).order(:id).last
+ post = topic.first_post
+
+ expect(topic.title).to eq("Friend group post")
+ expect(post.raw).to eq("A friend posted: /t/example/1/1")
+ expect(post.user).to eq(sender)
+ expect(topic.allowed_users).to contain_exactly(sender, recipient)
+ expect(result["topic"]).to include(
+ "id" => topic.id,
+ "title" => topic.title,
+ "archetype" => Archetype.private_message,
+ )
+ expect(result["post"]).to include(
+ "id" => post.id,
+ "topic_id" => topic.id,
+ "post_number" => 1,
+ "post_url" => post.url,
+ "raw" => post.raw,
+ "cooked" => post.cooked,
+ "user_id" => sender.id,
+ "username" => sender.username,
+ )
+ end
+
+ it "resolves dynamic recipients and message body", :aggregate_failures do
+ result =
+ execute_node(
+ configuration: {
+ "recipient_usernames" => "={{ $json.recipients }}",
+ "title" => "=New post from @{{ $json.author }}",
+ "raw" => "=Link: {{ $json.url }}",
+ "sender_username" => "system",
+ },
+ item: {
+ "json" => {
+ "recipients" => [recipient.username],
+ "author" => "friend",
+ "url" => "/t/post/2/1",
+ },
+ },
+ )
+
+ topic = Topic.where(archetype: Archetype.private_message).order(:id).last
+
+ expect(topic.title).to eq("New post from @friend")
+ expect(topic.first_post.raw).to eq("Link: /t/post/2/1")
+ expect(topic.allowed_users).to contain_exactly(Discourse.system_user, recipient)
+ expect(result.dig("post", "user_id")).to eq(Discourse.system_user.id)
+ end
+
+ it "accepts dynamic comma-separated recipients", :aggregate_failures do
+ execute_node(
+ configuration: {
+ "recipient_usernames" => "={{ $json.recipient_usernames }}",
+ "title" => "Comma separated recipients",
+ "raw" => "This should reach both users",
+ "sender_username" => sender.username,
+ },
+ item: {
+ "json" => {
+ "recipient_usernames" => "#{recipient.username},#{second_recipient.username}",
+ },
+ },
+ )
+
+ topic = Topic.where(archetype: Archetype.private_message).order(:id).last
+
+ expect(topic.title).to eq("Comma separated recipients")
+ expect(topic.allowed_users).to contain_exactly(sender, recipient, second_recipient)
+ end
+
+ it "raises when no recipients are configured" do
+ expect do
+ execute_node(
+ configuration: {
+ "title" => "Missing recipients",
+ "raw" => "This should not be created",
+ },
+ )
+ end.to raise_error(
+ DiscourseWorkflows::NodeError,
+ I18n.t("discourse_workflows.errors.send_personal_message.no_recipients"),
+ )
+ end
+ end
+end
diff --git a/plugins/discourse-workflows/spec/lib/discourse_workflows/nodes/topic_spec.rb b/plugins/discourse-workflows/spec/lib/discourse_workflows/nodes/topic_spec.rb
index 81bbd785c07..a41265a814d 100644
--- a/plugins/discourse-workflows/spec/lib/discourse_workflows/nodes/topic_spec.rb
+++ b/plugins/discourse-workflows/spec/lib/discourse_workflows/nodes/topic_spec.rb
@@ -100,6 +100,8 @@ RSpec.describe DiscourseWorkflows::Nodes::Topic::V1 do
expect(result["topic"]["last_poster_username"]).to eq(admin.username)
expect(result["topic"]["posters"].map { |poster| poster["user_id"] }).to include(admin.id)
expect(result).to include("post_id" => topic.first_post.id, "post_number" => 1)
+ expect(result.dig("post", "id")).to eq(topic.first_post.id)
+ expect(result.dig("post", "trust_level")).to eq(admin.trust_level)
end
it "creates a topic as the system user when actor_username is 'system'" do
@@ -178,7 +180,7 @@ RSpec.describe DiscourseWorkflows::Nodes::Topic::V1 do
fab!(:topic) { Fabricate(:topic, category: category, user: user) }
fab!(:post) { Fabricate(:post, topic: topic, user: user, raw: "This is the topic body") }
- it "returns all expected topic fields" do
+ it "returns all expected topic and first post fields" do
result =
execute_node(
configuration: {
@@ -196,6 +198,14 @@ RSpec.describe DiscourseWorkflows::Nodes::Topic::V1 do
expect(result["topic"]["title"]).to eq(topic.title)
expect(result["topic"]["category_id"]).to eq(category.id)
expect(result["topic"]["tags"]).to eq([])
+ expect(result["post"]).to include(
+ "id" => topic.first_post.id,
+ "topic_id" => topic.id,
+ "user_id" => user.id,
+ "username" => user.username,
+ "trust_level" => user.trust_level,
+ "post_url" => topic.first_post.url,
+ )
end
it "returns tag names when topic has tags" do
@@ -296,6 +306,42 @@ RSpec.describe DiscourseWorkflows::Nodes::Topic::V1 do
end
end
+ context "with operation 'archive'" do
+ fab!(:topic) { Fabricate(:topic, category: category, user: user) }
+ fab!(:post) { Fabricate(:post, topic: topic, user: user) }
+
+ it "archives the topic for the configured actor" do
+ result =
+ execute_node(
+ configuration: {
+ "operation" => "archive",
+ "topic_id" => topic.id.to_s,
+ "actor_username" => admin.username,
+ },
+ item: item,
+ )
+
+ expect(topic.reload).to be_archived
+ expect(result["topic"]).to include("id" => topic.id, "archived" => true)
+ expect(result.dig("post", "id")).to eq(topic.first_post.id)
+ end
+
+ it "raises when the actor cannot archive the topic" do
+ expect do
+ execute_node(
+ configuration: {
+ "operation" => "archive",
+ "topic_id" => topic.id.to_s,
+ "actor_username" => user.username,
+ },
+ item: item,
+ )
+ end.to raise_error(Discourse::InvalidAccess)
+
+ expect(topic.reload).not_to be_archived
+ end
+ end
+
context "with operation 'list'" do
fab!(:topic_1, :topic) do
Fabricate(:topic, category: category, user: user, title: "First topic about workflows")
@@ -417,7 +463,9 @@ RSpec.describe DiscourseWorkflows::Nodes::Topic::V1 do
},
)
- topic_data = result.find { |r| r["json"]["topic"]["id"] == topic_1.id }.dig("json", "topic")
+ topic_entry = result.find { |r| r["json"]["topic"]["id"] == topic_1.id }.dig("json")
+ topic_data = topic_entry["topic"]
+ post_data = topic_entry["post"]
expect(topic_data).to include(
"title" => topic_1.title,
"category_id" => category.id,
@@ -432,6 +480,11 @@ RSpec.describe DiscourseWorkflows::Nodes::Topic::V1 do
expect(topic_data["like_count"]).to be_present
expect(topic_data["created_at"]).to be_present
expect(topic_data["bumped_at"]).to be_present
+ expect(post_data).to include(
+ "id" => topic_1.first_post.id,
+ "topic_id" => topic_1.id,
+ "trust_level" => user.trust_level,
+ )
end
it "preloads selected custom fields when requested" do
diff --git a/plugins/discourse-workflows/spec/requests/discourse_workflows/ai_authoring_controller_spec.rb b/plugins/discourse-workflows/spec/requests/discourse_workflows/ai_authoring_controller_spec.rb
new file mode 100644
index 00000000000..788ac3f0492
--- /dev/null
+++ b/plugins/discourse-workflows/spec/requests/discourse_workflows/ai_authoring_controller_spec.rb
@@ -0,0 +1,214 @@
+# frozen_string_literal: true
+
+RSpec.describe DiscourseWorkflows::AiAuthoringController do
+ fab!(:admin)
+
+ before do
+ SiteSetting.discourse_workflows_ai_authoring_enabled = true
+ sign_in(admin)
+ end
+
+ describe "POST /admin/plugins/discourse-workflows/workflows/ai/author" do
+ it "creates a session and enqueues authoring" do
+ post "/admin/plugins/discourse-workflows/workflows/ai/author.json",
+ params: {
+ message: "Create a manual workflow that logs hello",
+ mode: "create",
+ }
+
+ expect(response).to have_http_status(:ok)
+ json = response.parsed_body
+ session = DiscourseWorkflows::AiAuthoringSession.find(json["session_id"])
+ expect(session).to have_attributes(
+ user_id: admin.id,
+ status: "generating",
+ latest_request: "Create a manual workflow that logs hello",
+ )
+ expect(Jobs::DiscourseWorkflows::AuthorWithAi.jobs.last["args"].first).to include(
+ "session_id" => session.id,
+ "user_id" => admin.id,
+ "generation_id" => json["generation_id"],
+ )
+ end
+
+ it "returns not found when AI authoring is disabled" do
+ SiteSetting.discourse_workflows_ai_authoring_enabled = false
+
+ post "/admin/plugins/discourse-workflows/workflows/ai/author.json",
+ params: {
+ message: "Create a workflow",
+ mode: "create",
+ }
+
+ expect(response).to have_http_status(:not_found)
+ end
+ end
+
+ describe "POST /admin/plugins/discourse-workflows/workflows/:id/ai/apply" do
+ fab!(:workflow) { Fabricate(:discourse_workflows_workflow, created_by: admin) }
+
+ let(:operations) do
+ [
+ {
+ op: "add_node",
+ client_id: "manual-trigger",
+ node: {
+ type: "trigger:manual",
+ name: "Manual trigger",
+ position: {
+ x: 0,
+ y: 0,
+ },
+ },
+ },
+ {
+ op: "add_node",
+ client_id: "write-log",
+ node: {
+ type: "action:log",
+ name: "Write log",
+ position: {
+ x: 200,
+ y: 0,
+ },
+ parameters: {
+ mode: "runOnceForAllItems",
+ entries: {
+ values: [{ key: "message", value: "hello" }],
+ },
+ },
+ },
+ },
+ {
+ op: "add_connection",
+ from: "manual-trigger",
+ to: "write-log",
+ output_index: 0,
+ input_index: 0,
+ },
+ ]
+ end
+
+ it "applies the stored proposal to the workflow draft" do
+ session =
+ Fabricate(
+ :discourse_workflows_ai_authoring_session,
+ user: admin,
+ workflow: workflow,
+ status: "proposal_ready",
+ proposed_patch: {
+ "operations" => operations,
+ },
+ base_graph_digest: DiscourseWorkflows::Ai::GraphDigest.call(workflow),
+ )
+
+ post "/admin/plugins/discourse-workflows/workflows/#{workflow.id}/ai/apply.json",
+ params: {
+ session_id: session.id,
+ }
+
+ expect(response).to have_http_status(:ok)
+ expect(workflow.reload.nodes.map { |node| node["type"] }).to contain_exactly(
+ "trigger:manual",
+ "action:log",
+ )
+ expect(session.reload.status).to eq("applied")
+ end
+
+ it "applies proposals that create AI agents", :aggregate_failures do
+ agent_operations = [
+ {
+ op: "create_ai_agent",
+ client_id: "triage-agent",
+ agent: {
+ name: "Workflow apply triage agent",
+ description: "Classifies workflow posts during apply.",
+ system_prompt: "You classify Discourse posts during workflow execution.",
+ },
+ },
+ {
+ op: "add_node",
+ client_id: "classify-post",
+ node: {
+ type: "action:ai_agent",
+ name: "Classify post",
+ parameters: {
+ agent_id: {
+ "$ref" => "triage-agent",
+ },
+ prompt: "={{ $json.post.raw }}",
+ },
+ },
+ },
+ ]
+ session =
+ Fabricate(
+ :discourse_workflows_ai_authoring_session,
+ user: admin,
+ workflow: workflow,
+ status: "proposal_ready",
+ proposed_patch: {
+ "operations" => agent_operations,
+ },
+ base_graph_digest: DiscourseWorkflows::Ai::GraphDigest.call(workflow),
+ )
+
+ post "/admin/plugins/discourse-workflows/workflows/#{workflow.id}/ai/apply.json",
+ params: {
+ session_id: session.id,
+ }
+ created_agent = AiAgent.find_by(name: "Workflow apply triage agent")
+ node =
+ workflow.reload.nodes.find { |workflow_node| workflow_node["type"] == "action:ai_agent" }
+
+ expect(response).to have_http_status(:ok)
+ expect(created_agent).to be_present
+ expect(node.dig("parameters", "agent_id")).to eq(created_agent.id)
+ expect(session.reload.status).to eq("applied")
+ end
+
+ it "rejects proposals that are not ready" do
+ session =
+ Fabricate(
+ :discourse_workflows_ai_authoring_session,
+ user: admin,
+ workflow: workflow,
+ status: "error",
+ proposed_patch: {
+ "operations" => operations,
+ },
+ base_graph_digest: DiscourseWorkflows::Ai::GraphDigest.call(workflow),
+ )
+
+ post "/admin/plugins/discourse-workflows/workflows/#{workflow.id}/ai/apply.json",
+ params: {
+ session_id: session.id,
+ }
+
+ expect(response).to have_http_status(:unprocessable_entity)
+ expect(workflow.reload.nodes).to eq([])
+ end
+
+ it "rejects stale proposals" do
+ session =
+ Fabricate(
+ :discourse_workflows_ai_authoring_session,
+ user: admin,
+ workflow: workflow,
+ status: "proposal_ready",
+ proposed_patch: {
+ "operations" => operations,
+ },
+ base_graph_digest: "stale",
+ )
+
+ post "/admin/plugins/discourse-workflows/workflows/#{workflow.id}/ai/apply.json",
+ params: {
+ session_id: session.id,
+ }
+
+ expect(response).to have_http_status(:conflict)
+ expect(session.reload.status).to eq("proposal_ready")
+ end
+ end
+end
diff --git a/plugins/discourse-workflows/spec/requests/discourse_workflows/node_types_controller_spec.rb b/plugins/discourse-workflows/spec/requests/discourse_workflows/node_types_controller_spec.rb
index 26a5b5b15a1..f0bf3c33b21 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
@@ -28,8 +28,10 @@ RSpec.describe DiscourseWorkflows::NodeTypesController do
expect(identifiers).to include("action:topic_tags")
expect(identifiers).to include("action:post")
expect(identifiers).to include("action:topic")
+ expect(identifiers).to include("action:group")
expect(identifiers).to include("condition:if")
- expect(identifiers).not_to include("action:create_post")
+ expect(identifiers).to include("action:send_personal_message")
+ expect(identifiers).not_to include("condition:user_in_group")
end
it "returns Post operation and List posts query control metadata" do
@@ -65,12 +67,51 @@ RSpec.describe DiscourseWorkflows::NodeTypesController do
expect(properties["advanced_filter"]["ui"]).to include("hidden" => true)
end
+ it "returns Send personal message recipient control metadata" do
+ get "/admin/plugins/discourse-workflows/node-types.json"
+
+ personal_message_node =
+ response.parsed_body["node_types"].find do |node_type|
+ node_type["identifier"] == "action:send_personal_message"
+ end
+ properties = personal_message_node["properties"]
+
+ expect(properties["recipient_usernames"]).to include(
+ "type" => "array",
+ "ui" => include("control" => "user", "expression" => true, "multiple" => true),
+ )
+ expect(properties["recipient_group_names"]).to include(
+ "type" => "array",
+ "type_options" => include("load_options_method" => "groups"),
+ "ui" => include("control" => "group_select", "expression" => true, "multiple" => true),
+ "control_options" =>
+ include("value_property" => "name", "name_property" => "name", "filterable" => true),
+ )
+ expect(properties["sender_username"]).to include(
+ "type" => "string",
+ "default" => "system",
+ "ui" => include("control" => "actor"),
+ )
+ expect(personal_message_node.dig("metadata", "groups")).to include(
+ include("id" => Group::AUTO_GROUPS[:everyone], "name" => "everyone"),
+ )
+ end
+
it "includes load options metadata in node type response" do
get "/admin/plugins/discourse-workflows/node-types.json"
badge_node =
response.parsed_body["node_types"].find { |nt| nt["identifier"] == "action:badge" }
expect(badge_node.dig("metadata", "badges")).to all(include("id", "name"))
+
+ group_node =
+ response.parsed_body["node_types"].find { |nt| nt["identifier"] == "action:group" }
+ expect(group_node.dig("metadata", "groups")).to include(
+ include("id" => Group::AUTO_GROUPS[:everyone], "name" => "everyone"),
+ )
+ expect(group_node.dig("properties", "group_id", "type_options")).not_to include(
+ "load_options_depends_on",
+ )
end
it "does not preload load options metadata that depends on node parameters" do
diff --git a/plugins/discourse-workflows/spec/services/discourse_workflows/ai_authoring/apply_spec.rb b/plugins/discourse-workflows/spec/services/discourse_workflows/ai_authoring/apply_spec.rb
new file mode 100644
index 00000000000..3c66ab687ad
--- /dev/null
+++ b/plugins/discourse-workflows/spec/services/discourse_workflows/ai_authoring/apply_spec.rb
@@ -0,0 +1,112 @@
+# frozen_string_literal: true
+
+RSpec.describe DiscourseWorkflows::AiAuthoring::Apply do
+ before { SiteSetting.discourse_workflows_ai_authoring_enabled = true }
+
+ describe described_class::Contract, type: :model do
+ it { is_expected.to validate_presence_of(:session_id) }
+ it { is_expected.to validate_presence_of(:workflow_id) }
+ end
+
+ describe ".call" do
+ subject(:result) { described_class.call(params:, **dependencies) }
+
+ fab!(:user, :admin)
+ fab!(:workflow) { Fabricate(:discourse_workflows_workflow, created_by: user) }
+
+ let(:session) do
+ Fabricate(
+ :discourse_workflows_ai_authoring_session,
+ user: user,
+ workflow: workflow,
+ status: status,
+ proposed_patch: {
+ "operations" => operations,
+ },
+ base_graph_digest: base_graph_digest,
+ risk_level: "medium",
+ )
+ end
+
+ let(:params) { { session_id: session.id, workflow_id: workflow.id } }
+ let(:dependencies) { { guardian: user.guardian } }
+ let(:status) { "proposal_ready" }
+ let(:base_graph_digest) { DiscourseWorkflows::Ai::GraphDigest.call(workflow) }
+ let(:operations) do
+ [
+ {
+ op: "add_node",
+ client_id: "manual-trigger",
+ node: {
+ type: "trigger:manual",
+ name: "Manual trigger",
+ position: {
+ x: 0,
+ y: 0,
+ },
+ },
+ },
+ ]
+ end
+
+ context "when AI authoring is disabled" do
+ before { SiteSetting.discourse_workflows_ai_authoring_enabled = false }
+
+ it { is_expected.to fail_a_policy(:ai_authoring_enabled) }
+ end
+
+ context "when contract is invalid" do
+ let(:params) { { session_id: nil, workflow_id: workflow.id } }
+
+ it { is_expected.to fail_a_contract }
+ end
+
+ context "when user cannot manage workflows" do
+ fab!(:user)
+
+ it { is_expected.to fail_a_policy(:can_manage_workflows) }
+ end
+
+ context "when session does not exist" do
+ let(:params) { { session_id: -1, workflow_id: workflow.id } }
+
+ it { is_expected.to fail_to_find_a_model(:session) }
+ end
+
+ context "when proposal is not ready" do
+ let(:status) { "error" }
+
+ it { is_expected.to fail_a_policy(:proposal_ready) }
+ end
+
+ context "without operations" do
+ let(:operations) { [] }
+
+ it { is_expected.to fail_to_find_a_model(:operations) }
+ end
+
+ context "when proposal is stale" do
+ let(:base_graph_digest) { "stale" }
+
+ it { is_expected.to fail_a_policy(:proposal_current) }
+ end
+
+ context "when patch is invalid" do
+ let(:operations) { [{ op: "unknown" }] }
+
+ it { is_expected.to fail_a_policy(:patch_valid) }
+ end
+
+ context "when everything's ok" do
+ it { is_expected.to run_successfully }
+
+ it "applies the patch and marks the session applied" do
+ expect { result }.to change { workflow.reload.nodes.size }.from(0).to(1)
+
+ expect(workflow.nodes.first["type"]).to eq("trigger:manual")
+ expect(session.reload).to have_attributes(status: "applied")
+ expect(session.applied_at).to be_present
+ end
+ end
+ end
+end
diff --git a/plugins/discourse-workflows/spec/services/discourse_workflows/ai_authoring/start_spec.rb b/plugins/discourse-workflows/spec/services/discourse_workflows/ai_authoring/start_spec.rb
new file mode 100644
index 00000000000..4a7a837aca2
--- /dev/null
+++ b/plugins/discourse-workflows/spec/services/discourse_workflows/ai_authoring/start_spec.rb
@@ -0,0 +1,166 @@
+# frozen_string_literal: true
+
+RSpec.describe DiscourseWorkflows::AiAuthoring::Start do
+ before { SiteSetting.discourse_workflows_ai_authoring_enabled = true }
+
+ describe described_class::Contract, type: :model do
+ subject(:contract) do
+ described_class.new(message: message, mode: mode, workflow_id: workflow_id)
+ end
+
+ let(:message) { "Create a manual workflow" }
+ let(:mode) { "create" }
+ let(:workflow_id) { nil }
+
+ it { is_expected.to be_valid }
+
+ context "when message is blank" do
+ let(:message) { " " }
+
+ it "adds the authoring message error" do
+ expect(contract).not_to be_valid
+ expect(contract.errors.full_messages).to contain_exactly(
+ I18n.t("discourse_workflows.ai.error_message_required"),
+ )
+ end
+ end
+
+ context "when message is too long" do
+ let(:message) { "a" * (SiteSetting.discourse_workflows_ai_authoring_max_prompt_length + 1) }
+
+ it "adds the prompt length error" do
+ expect(contract).not_to be_valid
+ expect(contract.errors.full_messages).to contain_exactly(
+ I18n.t("discourse_workflows.ai.error_message_too_long"),
+ )
+ end
+ end
+
+ context "when mode is invalid" do
+ let(:mode) { "rewrite" }
+
+ it "adds the mode error" do
+ expect(contract).not_to be_valid
+ expect(contract.errors.full_messages).to contain_exactly(
+ I18n.t("discourse_workflows.ai.error_invalid_mode"),
+ )
+ end
+ end
+ end
+
+ describe ".call" do
+ subject(:result) { described_class.call(params:, **dependencies) }
+
+ fab!(:user, :admin)
+
+ let(:params) do
+ { message: message, mode: mode, workflow_id: workflow_id, session_id: session_id }
+ end
+ let(:dependencies) { { guardian: user.guardian } }
+ let(:message) { "Create a manual workflow that logs hello" }
+ let(:mode) { "create" }
+ let(:workflow_id) { nil }
+ let(:session_id) { nil }
+
+ context "when AI authoring is disabled" do
+ before { SiteSetting.discourse_workflows_ai_authoring_enabled = false }
+
+ it { is_expected.to fail_a_policy(:ai_authoring_enabled) }
+ end
+
+ context "when contract is invalid" do
+ let(:message) { "" }
+
+ it { is_expected.to fail_a_contract }
+ end
+
+ context "when user cannot manage workflows" do
+ fab!(:user)
+
+ it { is_expected.to fail_a_policy(:can_manage_workflows) }
+ end
+
+ context "when requested workflow does not exist" do
+ let(:workflow_id) { -1 }
+
+ it { is_expected.to fail_a_policy(:workflow_exists_when_requested) }
+ end
+
+ context "when requested session does not exist" do
+ let(:session_id) { -1 }
+
+ it { is_expected.to fail_to_find_a_model(:session) }
+ end
+
+ context "when everything's ok" do
+ it { is_expected.to run_successfully }
+
+ it "creates a session and enqueues authoring" do
+ expect { result }.to change(DiscourseWorkflows::AiAuthoringSession, :count).by(1)
+
+ session = result[:session]
+ expect(session).to have_attributes(
+ user_id: user.id,
+ workflow_id: nil,
+ status: "generating",
+ latest_request: "Create a manual workflow that logs hello",
+ )
+ expect(Jobs::DiscourseWorkflows::AuthorWithAi.jobs.last["args"].first).to include(
+ "session_id" => session.id,
+ "user_id" => user.id,
+ "generation_id" => result[:generation_id],
+ )
+ end
+ end
+
+ context "with a workflow" do
+ fab!(:workflow) { Fabricate(:discourse_workflows_workflow, created_by: user) }
+
+ let(:mode) { nil }
+ let(:workflow_id) { workflow.id }
+
+ it "stores the workflow base graph and defaults to edit mode" do
+ result
+
+ session = result[:session]
+ expect(session).to have_attributes(
+ workflow_id: workflow.id,
+ base_workflow_version_id: workflow.version_id,
+ base_graph_digest: DiscourseWorkflows::Ai::GraphDigest.call(workflow),
+ )
+ expect(session.messages.last["content"]).to eq(
+ JSON.pretty_generate(
+ {
+ mode: "edit",
+ message: "Create a manual workflow that logs hello",
+ workflow_id: workflow.id,
+ },
+ ),
+ )
+ end
+ end
+
+ context "with an existing session" do
+ fab!(:session) do
+ Fabricate(:discourse_workflows_ai_authoring_session, user: user, status: "drafting")
+ end
+
+ let(:session_id) { session.id }
+ let(:mode) { "debug" }
+
+ it "appends the new request to the session" do
+ expect { result }.not_to change(DiscourseWorkflows::AiAuthoringSession, :count)
+
+ expect(session.reload).to have_attributes(
+ status: "generating",
+ latest_request: "Create a manual workflow that logs hello",
+ )
+ expect(session.messages.last["content"]).to eq(
+ JSON.pretty_generate(
+ { mode: "debug", message: "Create a manual workflow that logs hello" },
+ ),
+ )
+ end
+ end
+ end
+end
diff --git a/plugins/discourse-workflows/spec/services/discourse_workflows/workflow/action/apply_patch_spec.rb b/plugins/discourse-workflows/spec/services/discourse_workflows/workflow/action/apply_patch_spec.rb
new file mode 100644
index 00000000000..63e0bf85e94
--- /dev/null
+++ b/plugins/discourse-workflows/spec/services/discourse_workflows/workflow/action/apply_patch_spec.rb
@@ -0,0 +1,230 @@
+# frozen_string_literal: true
+
+RSpec.describe DiscourseWorkflows::Workflow::Action::ApplyPatch do
+ fab!(:admin)
+ fab!(:workflow) { Fabricate(:discourse_workflows_workflow, created_by: admin) }
+
+ let(:operations) do
+ [
+ {
+ op: "add_node",
+ client_id: "manual-trigger",
+ node: {
+ type: "trigger:manual",
+ name: "Manual trigger",
+ position: {
+ x: 0,
+ y: 0,
+ },
+ },
+ },
+ {
+ op: "add_node",
+ client_id: "write-log",
+ node: {
+ type: "action:log",
+ name: "Write log",
+ position: {
+ x: 200,
+ y: 0,
+ },
+ parameters: {
+ entries: {
+ values: [{ key: "message", value: "hello" }],
+ },
+ },
+ },
+ },
+ { op: "add_connection", from: "manual-trigger", to: "write-log" },
+ ]
+ end
+
+ it "dry-runs patch operations without changing the workflow draft" do
+ result = described_class.call(workflow:, operations:, persist: false, user: admin)
+
+ expect(result).to include(valid: true, errors: [])
+ expect(result[:nodes].map { |node| node["type"] }).to contain_exactly(
+ "trigger:manual",
+ "action:log",
+ )
+ expect(workflow.reload.nodes).to eq([])
+ end
+
+ it "normalizes empty credential arrays from AI patches" do
+ result =
+ described_class.call(
+ workflow: workflow,
+ operations: [
+ {
+ op: "add_node",
+ node: {
+ type: "trigger:manual",
+ typeVersion: 1,
+ name: "Manual trigger",
+ credentials: [],
+ },
+ },
+ ],
+ persist: false,
+ user: admin,
+ )
+
+ expect(result).to include(valid: true, errors: [])
+ expect(result[:nodes].first).to include("credentials" => {}, "typeVersion" => "1.0")
+ end
+
+ it "normalizes array positions from AI patches" do
+ result =
+ described_class.call(
+ workflow: workflow,
+ operations: [
+ {
+ op: "add_node",
+ node: {
+ type: "trigger:manual",
+ name: "Manual trigger",
+ position: [100, 200],
+ },
+ },
+ ],
+ persist: false,
+ user: admin,
+ )
+
+ expect(result).to include(valid: true, errors: [])
+ expect(result[:nodes].first["position"]).to eq("x" => 100.0, "y" => 200.0)
+ end
+
+ it "returns errors for malformed operations" do
+ result =
+ described_class.call(workflow:, operations: ["add a node"], persist: false, user: admin)
+
+ expect(result).to include(valid: false, errors: ["Patch operation must be an object"])
+ expect(workflow.reload.nodes).to eq([])
+ end
+
+ it "dry-runs prompt-only AI agent creation", :aggregate_failures do
+ result =
+ described_class.call(
+ workflow: workflow,
+ operations: [
+ {
+ op: "create_ai_agent",
+ client_id: "triage-agent",
+ agent: {
+ name: "Workflow triage agent",
+ description: "Classifies posts for a workflow.",
+ system_prompt: "You classify Discourse posts for triage.",
+ },
+ },
+ {
+ op: "add_node",
+ client_id: "classify-post",
+ node: {
+ type: "action:ai_agent",
+ name: "Classify post",
+ position: {
+ x: 200,
+ y: 0,
+ },
+ parameters: {
+ agent_id: {
+ "$ref" => "triage-agent",
+ },
+ prompt: "={{ $json.post.raw }}",
+ },
+ },
+ },
+ ],
+ persist: false,
+ user: admin,
+ )
+
+ expect(result).to include(valid: true, errors: [])
+ expect(result[:created_resources]).to contain_exactly(
+ include(
+ "type" => "ai_agent",
+ "client_id" => "triage-agent",
+ "name" => "Workflow triage agent",
+ "system_prompt" => "You classify Discourse posts for triage.",
+ ),
+ )
+ expect(AiAgent.find_by(name: "Workflow triage agent")).to be_nil
+ end
+
+ it "creates proposed AI agents when persisted", :aggregate_failures do
+ result =
+ described_class.call(
+ workflow: workflow,
+ operations: [
+ {
+ op: "create_ai_agent",
+ client_id: "summary-agent",
+ agent: {
+ name: "Workflow summary agent",
+ description: "Summarizes posts for a workflow.",
+ system_prompt: "You summarize Discourse posts in one sentence.",
+ },
+ },
+ {
+ op: "add_node",
+ client_id: "summarize-post",
+ node: {
+ type: "action:ai_agent",
+ name: "Summarize post",
+ parameters: {
+ agent_id: {
+ "$ref" => "summary-agent",
+ },
+ prompt: "={{ $json.post.raw }}",
+ },
+ },
+ },
+ ],
+ persist: true,
+ user: admin,
+ )
+ created_agent = AiAgent.find_by(name: "Workflow summary agent")
+ node = workflow.reload.nodes.find { |workflow_node| workflow_node["type"] == "action:ai_agent" }
+
+ expect(result).to include(valid: true, errors: [])
+ expect(created_agent).to have_attributes(
+ description: "Summarizes posts for a workflow.",
+ system_prompt: "You summarize Discourse posts in one sentence.",
+ tools: [],
+ allowed_group_ids: [],
+ created_by_id: admin.id,
+ )
+ expect(node.dig("parameters", "agent_id")).to eq(created_agent.id)
+ expect(node.dig("parameters", "agent_name")).to eq("Workflow summary agent")
+ end
+
+ it "rejects unknown AI agent references" do
+ result =
+ described_class.call(
+ workflow: workflow,
+ operations: [
+ {
+ op: "add_node",
+ client_id: "classify-post",
+ node: {
+ type: "action:ai_agent",
+ name: "Classify post",
+ parameters: {
+ agent_id: {
+ "$ref" => "missing-agent",
+ },
+ },
+ },
+ },
+ ],
+ persist: false,
+ user: admin,
+ )
+
+ expect(result).to include(
+ valid: false,
+ errors: ['Classify post references unknown AI agent client_id "missing-agent"'],
+ )
+ end
+end
diff --git a/plugins/discourse-workflows/spec/system/page_objects/pages/workflow_editor.rb b/plugins/discourse-workflows/spec/system/page_objects/pages/workflow_editor.rb
index 5d608a23951..1b3c334157f 100644
--- a/plugins/discourse-workflows/spec/system/page_objects/pages/workflow_editor.rb
+++ b/plugins/discourse-workflows/spec/system/page_objects/pages/workflow_editor.rb
@@ -94,6 +94,7 @@ module PageObjects
"add" => "Add to group",
"remove" => "Remove from group",
"get" => "Get group",
+ "check_membership" => "Check membership",
},
"action:data_table" => {
"insert" => "Insert",
diff --git a/plugins/discourse-workflows/test/javascripts/integration/components/workflows/expression-wrapper-test.gjs b/plugins/discourse-workflows/test/javascripts/integration/components/workflows/expression-wrapper-test.gjs
new file mode 100644
index 00000000000..72483cb0782
--- /dev/null
+++ b/plugins/discourse-workflows/test/javascripts/integration/components/workflows/expression-wrapper-test.gjs
@@ -0,0 +1,112 @@
+import { tracked } from "@glimmer/tracking";
+import { click, render } 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 ExpressionWrapper from "discourse/plugins/discourse-workflows/admin/components/workflows/configurators/expression-wrapper";
+
+class TestField {
+ @tracked value;
+
+ constructor(value) {
+ this.value = value;
+ }
+
+ set(newValue) {
+ this.value = newValue;
+ }
+}
+
+module(
+ "Integration | Component | Workflows | ExpressionWrapper",
+ function (hooks) {
+ setupRenderingTest(hooks);
+
+ hooks.beforeEach(function () {
+ pretender.get("/admin/plugins/discourse-workflows/variables.json", () =>
+ response(200, { variables: [] })
+ );
+ });
+
+ test("converts fixed arrays to whole expressions", async function (assert) {
+ this.field = new TestField(["sam", "alice"]);
+ this.schema = { type: "array" };
+
+ await render(
+ <template>
+ <ExpressionWrapper
+ @field={{this.field}}
+ @schema={{this.schema}}
+ @supportsExpression={{true}}
+ >
+ <div class="plain-control"></div>
+ </ExpressionWrapper>
+ </template>
+ );
+
+ await click(
+ '.workflows-property-engine__mode-control input[value="dynamic"]'
+ );
+
+ assert.strictEqual(
+ this.field.value,
+ '={{ ["sam","alice"] }}',
+ "the dynamic value preserves the array type"
+ );
+ });
+
+ test("converts comma-separated dynamic values to fixed arrays", async function (assert) {
+ this.field = new TestField("=sam,alice");
+ this.schema = { type: "array" };
+
+ await render(
+ <template>
+ <ExpressionWrapper
+ @field={{this.field}}
+ @schema={{this.schema}}
+ @supportsExpression={{true}}
+ >
+ <div class="plain-control"></div>
+ </ExpressionWrapper>
+ </template>
+ );
+
+ await click(
+ '.workflows-property-engine__mode-control input[value="plain"]'
+ );
+
+ assert.deepEqual(
+ this.field.value,
+ ["sam", "alice"],
+ "the fixed value is converted to an array"
+ );
+ });
+
+ test("converts dynamic array literals to fixed arrays", async function (assert) {
+ this.field = new TestField('={{ ["sam","alice"] }}');
+ this.schema = { type: "array" };
+
+ await render(
+ <template>
+ <ExpressionWrapper
+ @field={{this.field}}
+ @schema={{this.schema}}
+ @supportsExpression={{true}}
+ >
+ <div class="plain-control"></div>
+ </ExpressionWrapper>
+ </template>
+ );
+
+ await click(
+ '.workflows-property-engine__mode-control input[value="plain"]'
+ );
+
+ assert.deepEqual(
+ this.field.value,
+ ["sam", "alice"],
+ "the dynamic array literal is converted to an array"
+ );
+ });
+ }
+);
diff --git a/plugins/discourse-workflows/test/javascripts/integration/components/workflows/group-select-test.gjs b/plugins/discourse-workflows/test/javascripts/integration/components/workflows/group-select-test.gjs
new file mode 100644
index 00000000000..b3c41df9e35
--- /dev/null
+++ b/plugins/discourse-workflows/test/javascripts/integration/components/workflows/group-select-test.gjs
@@ -0,0 +1,71 @@
+import { tracked } from "@glimmer/tracking";
+import { render } from "@ember/test-helpers";
+import { module, test } from "qunit";
+import { setupRenderingTest } from "discourse/tests/helpers/component-test";
+import selectKit from "discourse/tests/helpers/select-kit-helper";
+import GroupSelect from "discourse/plugins/discourse-workflows/admin/components/workflows/configurators/group-select";
+
+class TestField {
+ @tracked value;
+
+ constructor(value) {
+ this.value = value;
+ }
+
+ set(newValue) {
+ this.value = newValue;
+ }
+}
+
+module("Integration | Component | Workflows | GroupSelect", function (hooks) {
+ setupRenderingTest(hooks);
+
+ test("stores selected group names when configured as multiple", async function (assert) {
+ this.field = new TestField([]);
+ this.schema = {
+ type_options: {
+ load_options_method: "groups",
+ },
+ ui: {
+ control: "group_select",
+ multiple: true,
+ },
+ control_options: {
+ filterable: true,
+ name_property: "name",
+ value_property: "name",
+ },
+ };
+ this.nodeDefinition = {
+ identifier: "action:send_personal_message",
+ metadata: {
+ groups: [
+ { id: 1, name: "support" },
+ { id: 2, name: "moderators" },
+ ],
+ },
+ };
+
+ await render(
+ <template>
+ <GroupSelect
+ @field={{this.field}}
+ @fieldName="recipient_group_names"
+ @nodeDefinition={{this.nodeDefinition}}
+ @schema={{this.schema}}
+ @supportsExpression={{false}}
+ />
+ </template>
+ );
+
+ const chooser = selectKit(".group-chooser");
+ await chooser.expand();
+ await chooser.selectRowByValue("support");
+
+ assert.deepEqual(this.field.value, ["support"]);
+
+ await chooser.selectRowByValue("moderators");
+
+ assert.deepEqual(this.field.value, ["support", "moderators"]);
+ });
+});
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 f27dcc0e11f..67b1fa9483a 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
@@ -247,6 +247,86 @@ module("Integration | Component | workflows property engine", function (hooks) {
assert.strictEqual(this.formApi.get("group_inbox_id"), null);
});
+ test("renders preloaded automatic group option by name", async function (assert) {
+ this.setProperties({
+ configuration: {
+ operation: "check_membership",
+ group_id: 14,
+ },
+ formApi: null,
+ node: {
+ clientId: "node-1",
+ type: "action:group",
+ typeVersion: "1.0",
+ },
+ nodeType: "action:group",
+ nodeTypes: [
+ {
+ identifier: "action:group",
+ name: "action:group",
+ version: "1.0",
+ metadata: {
+ groups: [
+ { id: 0, name: "everyone" },
+ { id: 14, name: "trust_level_2" },
+ ],
+ },
+ },
+ ],
+ schema: {
+ group_id: {
+ type: "integer",
+ required: true,
+ type_options: {
+ load_options_method: "groups",
+ },
+ ui: {
+ control: "group_select",
+ },
+ control_options: {
+ filterable: true,
+ name_property: "name",
+ value_property: "id",
+ },
+ },
+ },
+ registerApi: (api) => {
+ this.set("formApi", api);
+ },
+ });
+
+ await render(
+ <template>
+ <Form
+ @data={{this.configuration}}
+ @onRegisterApi={{this.registerApi}}
+ as |form transientData|
+ >
+ <PropertyEngineConfigurator
+ @form={{form}}
+ @formApi={{this.formApi}}
+ @configuration={{transientData}}
+ @node={{this.node}}
+ @nodeType={{this.nodeType}}
+ @nodeTypes={{this.nodeTypes}}
+ @schema={{this.schema}}
+ @session={{this.session}}
+ />
+ </Form>
+ </template>
+ );
+
+ const groupSelector = selectKit(".combo-box");
+
+ assert.strictEqual(groupSelector.header().value(), "14");
+ assert.strictEqual(groupSelector.header().label(), "trust_level_2");
+
+ await groupSelector.expand();
+ assert
+ .dom(".combo-box .select-kit-row[data-value='0']")
+ .hasText("everyone");
+ });
+
test("preserves focus for collection fields while typing", async function (assert) {
this.setProperties({
configuration: {
diff --git a/plugins/discourse-workflows/test/javascripts/integration/components/workflows/user-control-test.gjs b/plugins/discourse-workflows/test/javascripts/integration/components/workflows/user-control-test.gjs
new file mode 100644
index 00000000000..5f4498a530d
--- /dev/null
+++ b/plugins/discourse-workflows/test/javascripts/integration/components/workflows/user-control-test.gjs
@@ -0,0 +1,78 @@
+import { tracked } from "@glimmer/tracking";
+import { render } 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 selectKit from "discourse/tests/helpers/select-kit-helper";
+import UserControl from "discourse/plugins/discourse-workflows/admin/components/workflows/configurators/user-control";
+
+class TestField {
+ @tracked value;
+
+ constructor(value) {
+ this.value = value;
+ }
+
+ set(newValue) {
+ this.value = newValue;
+ }
+}
+
+module("Integration | Component | Workflows | UserControl", function (hooks) {
+ setupRenderingTest(hooks);
+
+ hooks.beforeEach(function () {
+ pretender.get("/u/search/users", () =>
+ response(200, {
+ users: [
+ { username: "sam", name: "Sam" },
+ { username: "alice", name: "Alice" },
+ ],
+ })
+ );
+ });
+
+ test("stores one username by default", async function (assert) {
+ this.field = new TestField("");
+
+ await render(
+ <template>
+ <UserControl @field={{this.field}} @supportsExpression={{false}} />
+ </template>
+ );
+
+ const chooser = selectKit(".user-chooser");
+ await chooser.expand();
+ await chooser.fillInFilter("s");
+ await chooser.selectRowByValue("sam");
+
+ assert.strictEqual(this.field.value, "sam");
+ });
+
+ test("stores all selected usernames when configured as multiple", async function (assert) {
+ this.field = new TestField([]);
+ this.schema = { ui: { multiple: true } };
+
+ await render(
+ <template>
+ <UserControl
+ @field={{this.field}}
+ @schema={{this.schema}}
+ @supportsExpression={{false}}
+ />
+ </template>
+ );
+
+ const chooser = selectKit(".user-chooser");
+ await chooser.expand();
+ await chooser.fillInFilter("s");
+ await chooser.selectRowByValue("sam");
+
+ assert.deepEqual(this.field.value, ["sam"]);
+
+ await chooser.fillInFilter("a");
+ await chooser.selectRowByValue("alice");
+
+ assert.deepEqual(this.field.value, ["sam", "alice"]);
+ });
+});
diff --git a/plugins/discourse-workflows/test/javascripts/unit/components/workflows/build-with-ai-modal-test.js b/plugins/discourse-workflows/test/javascripts/unit/components/workflows/build-with-ai-modal-test.js
new file mode 100644
index 00000000000..d98e5a3df66
--- /dev/null
+++ b/plugins/discourse-workflows/test/javascripts/unit/components/workflows/build-with-ai-modal-test.js
@@ -0,0 +1,235 @@
+import { setupTest } from "ember-qunit";
+import { module, test } from "qunit";
+import { i18n } from "discourse-i18n";
+import BuildWithAiModal from "discourse/plugins/discourse-workflows/admin/components/workflows/build-with-ai-modal";
+
+module("Unit | Component | Workflows | BuildWithAiModal", function (hooks) {
+ setupTest(hooks);
+
+ test("proposal review replaces prompt composer", function (assert) {
+ const modal = Object.create(BuildWithAiModal.prototype);
+
+ modal.aiGenerating = false;
+ modal.aiResponse = {
+ status: "proposed_patch",
+ response: {
+ message: "Draft proposal ready",
+ proposal: {
+ operations: [{ op: "rename_node", node_id: "node-1", name: "Wait" }],
+ },
+ },
+ };
+
+ assert.true(
+ modal.aiShowingProposalReview,
+ "proposal review is shown when a draft exists"
+ );
+ assert.false(
+ modal.aiShowingPromptComposer,
+ "prompt composer is hidden while reviewing a draft"
+ );
+ assert.strictEqual(
+ modal.aiResponseMessage,
+ null,
+ "proposal response message is hidden to avoid duplicate review copy"
+ );
+ });
+
+ test("proposal exposes created agent resources", function (assert) {
+ const modal = Object.create(BuildWithAiModal.prototype);
+
+ modal.aiResponse = {
+ status: "proposed_patch",
+ response: {
+ proposal: {
+ operations: [
+ {
+ op: "create_ai_agent",
+ client_id: "triage-agent",
+ agent: {
+ name: "Workflow triage agent",
+ description: "Classifies support posts.",
+ system_prompt: "Classify Discourse posts.",
+ },
+ },
+ ],
+ },
+ },
+ };
+
+ assert.deepEqual(
+ modal.aiCreatedAgentResources,
+ [
+ {
+ key: "triage-agent-Workflow triage agent",
+ name: "Workflow triage agent",
+ description: "Classifies support posts.",
+ systemPrompt: "Classify Discourse posts.",
+ },
+ ],
+ "created AI agents are available for proposal review"
+ );
+ });
+
+ test("clarification questions advance one at a time", async function (assert) {
+ const modal = Object.create(BuildWithAiModal.prototype);
+
+ modal.aiGenerating = false;
+ modal.aiClarificationQuestionIndex = 0;
+ modal.aiResponse = {
+ status: "needs_clarification",
+ response: {
+ questions: [
+ { id: "scope", question: "Scope?", options: ["General"] },
+ { id: "users", question: "Users?", options: ["TL2"] },
+ ],
+ },
+ };
+ Object.defineProperty(modal, "aiClarificationCurrentQuestionDisabled", {
+ value: false,
+ });
+
+ assert.strictEqual(
+ modal.aiCurrentQuestionNumber,
+ 1,
+ "starts on the first question"
+ );
+ assert.strictEqual(
+ modal.aiQuestionText(modal.aiCurrentQuestion),
+ "Scope?",
+ "only the first question is current"
+ );
+ assert.strictEqual(
+ modal.aiClarificationContinueLabel,
+ i18n("discourse_workflows.ai.next_question"),
+ "non-final questions use a next label"
+ );
+
+ await modal.continueAiClarificationQuestion();
+
+ assert.strictEqual(
+ modal.aiCurrentQuestionNumber,
+ 2,
+ "moves to the second question"
+ );
+ assert.strictEqual(
+ modal.aiQuestionText(modal.aiCurrentQuestion),
+ "Users?",
+ "the second question becomes current"
+ );
+
+ modal.previousAiClarificationQuestion();
+
+ assert.strictEqual(
+ modal.aiCurrentQuestionNumber,
+ 1,
+ "can move back to the previous question"
+ );
+
+ await modal.continueAiClarificationQuestion();
+ Object.defineProperty(modal, "submitAiClarification", {
+ value: async () => assert.step("submitted"),
+ });
+
+ assert.strictEqual(
+ modal.aiClarificationContinueLabel,
+ i18n("discourse_workflows.ai.continue"),
+ "the final question uses the continue label"
+ );
+
+ await modal.continueAiClarificationQuestion();
+
+ assert.verifySteps(["submitted"]);
+ });
+
+ test("progress is shown only while generating", function (assert) {
+ const modal = Object.create(BuildWithAiModal.prototype);
+
+ modal.aiProgressEvents = [{ stage: "queued" }];
+ modal.aiGenerating = false;
+
+ assert.false(
+ modal.aiShowingProgress,
+ "completed authoring does not show old progress"
+ );
+
+ modal.aiGenerating = true;
+
+ assert.true(
+ modal.aiShowingProgress,
+ "active authoring shows progress events"
+ );
+
+ modal.aiProgressEvents = [];
+
+ assert.false(
+ modal.aiShowingProgress,
+ "active authoring without events does not show progress"
+ );
+ });
+
+ test("returning to the prompt clears in-progress authoring state", function (assert) {
+ const modal = Object.create(BuildWithAiModal.prototype);
+ const handler = () => {};
+
+ Object.defineProperty(modal, "messageBus", {
+ value: {
+ unsubscribe(channel, callback) {
+ assert.strictEqual(
+ channel,
+ "/discourse-workflows/ai-authoring/generation-1",
+ "unsubscribes from the active authoring channel"
+ );
+ assert.strictEqual(
+ callback,
+ handler,
+ "unsubscribes the active authoring handler"
+ );
+ assert.step("unsubscribed");
+ },
+ },
+ });
+
+ modal.aiGenerating = true;
+ modal.aiProgressEvents = [{ stage: "queued" }];
+ modal.aiResponse = { status: "needs_clarification" };
+ modal.aiSessionId = "session-1";
+ modal.aiGenerationId = "generation-1";
+ modal.aiClarificationAnswers = { scope: { selected: ["General"] } };
+ modal.aiClarificationQuestionIndex = 1;
+ modal.aiError = "The request failed";
+ modal.aiAuthoringChannel = "/discourse-workflows/ai-authoring/generation-1";
+ modal.aiAuthoringHandler = handler;
+
+ assert.true(
+ modal.aiCanReturnToPrompt,
+ "stateful AI authoring can return to the prompt"
+ );
+
+ modal.returnToAiPrompt();
+
+ assert.verifySteps(["unsubscribed"]);
+ assert.false(modal.aiGenerating, "generation stops locally");
+ assert.deepEqual(modal.aiProgressEvents, [], "progress is cleared");
+ assert.strictEqual(modal.aiResponse, null, "response is cleared");
+ assert.strictEqual(modal.aiSessionId, null, "session is cleared");
+ assert.strictEqual(modal.aiGenerationId, null, "generation is cleared");
+ assert.deepEqual(
+ modal.aiClarificationAnswers,
+ {},
+ "clarification answers are cleared"
+ );
+ assert.strictEqual(
+ modal.aiClarificationQuestionIndex,
+ 0,
+ "clarification index is reset"
+ );
+ assert.strictEqual(modal.aiError, null, "error state is cleared");
+ assert.strictEqual(modal.aiAuthoringChannel, null, "channel is cleared");
+ assert.strictEqual(modal.aiAuthoringHandler, null, "handler is cleared");
+ assert.false(
+ modal.aiCanReturnToPrompt,
+ "cleared state no longer shows a start-over action"
+ );
+ });
+});