A platform for community discussion. Free, open, simple.
FEATURE: Support AI agent workflow uploads and runner (#41042)
Sam313f8e716bb2
diff --git a/plugins/discourse-ai/config/locales/client.en.yml b/plugins/discourse-ai/config/locales/client.en.ymlindex 71f7037bb26..8764cea1ff7 100644--- a/plugins/discourse-ai/config/locales/client.en.yml+++ b/plugins/discourse-ai/config/locales/client.en.yml@@ -240,6 +240,11 @@ en:llm_model_default: "Use agent default"llm_model_default_with_name: "Use agent default (%{value})"prompt: "Prompt"+ runner_username: "Run as"+ runner_username_tooltip: "User whose permissions are used for upload visibility and AI agent tools. Use system for workflow-owned automation."+ upload_ids: "Upload IDs"+ upload_ids_tooltip: "Optional upload IDs to attach to the prompt. Image uploads are included when the agent has vision enabled; document uploads are included when the selected LLM supports their file type."+ upload_ids_placeholder: "={{ $json.post.upload_ids }}"select_agent: "Select an agent..."bot_chats:diff --git a/plugins/discourse-ai/discourse_workflows/nodes/ai_agent/v1.rb b/plugins/discourse-ai/discourse_workflows/nodes/ai_agent/v1.rbindex 098cef8715c..0c5e7528cf8 100644--- a/plugins/discourse-ai/discourse_workflows/nodes/ai_agent/v1.rb+++ b/plugins/discourse-ai/discourse_workflows/nodes/ai_agent/v1.rb@@ -98,12 +98,29 @@ if defined?(DiscourseWorkflows)},},},+ runner_username: {+ type: :string,+ required: false,+ default: "system",+ ui: {+ control: :actor,+ },+ },prompt: {type: :string,ui: {control: :textarea,},},+ upload_ids: {+ type: :array,+ required: false,+ default: [],+ ui: {+ control: :multi_input,+ expression: true,+ },+ },},)@@ -167,8 +184,11 @@ if defined?(DiscourseWorkflows)"agent_id" => exec_ctx.get_node_parameter("agent_id", item_index),"llm_model_id" => exec_ctx.get_node_parameter("llm_model_id", item_index),"prompt" => exec_ctx.get_node_parameter("prompt", item_index),+ "upload_ids" => exec_ctx.get_node_parameter("upload_ids", item_index),}- result = run_agent(config, exec_ctx.log)+ runner =+ exec_ctx.actor_from_parameter("runner_username", item_index, default: "system")+ result = run_agent(config, exec_ctx.log, runner)wrap({ "result" => result }, paired_item: exec_ctx.paired_item_for(item))end@@ -217,7 +237,51 @@ if defined?(DiscourseWorkflows))end- def run_agent(config, log)+ def prompt_content(prompt, upload_ids, agent_record, llm_model, guardian, log)+ upload_ids = filtered_upload_ids(upload_ids, agent_record, llm_model, guardian)+ return prompt if upload_ids.blank?++ log.info("Attachments: #{upload_ids.size} upload(s)")+ [prompt, *upload_ids.map { |upload_id| { upload_id: upload_id } }]+ end++ def filtered_upload_ids(upload_ids, agent_record, llm_model, guardian)+ upload_ids = normalize_upload_ids(upload_ids)+ return [] if upload_ids.blank?++ ::DiscourseAi::Completions::PromptMessagesBuilder.filtered_upload_ids_for_prompt(+ upload_ids,+ include_image_uploads: agent_record.vision_enabled,+ include_document_uploads: llm_model.allowed_attachment_types.present?,+ allowed_attachment_types: llm_model.allowed_attachment_types,+ guardian: guardian,+ ) || []+ end++ def normalize_upload_ids(upload_ids)+ case upload_ids+ when String+ parsed = parse_upload_ids_json(upload_ids)+ return normalize_upload_ids(parsed) if parsed++ upload_ids.split(",")+ when Array+ upload_ids.flatten+ else+ Array.wrap(upload_ids)+ end.filter_map do |upload_id|+ id = Integer(upload_id, exception: false)+ id if id&.positive?+ end+ end++ def parse_upload_ids_json(upload_ids)+ JSON.parse(upload_ids)+ rescue JSON::ParserError, TypeError+ nil+ end++ def run_agent(config, log, runner)agent_id = config["agent_id"]prompt = config["prompt"].to_s@@ -232,6 +296,7 @@ if defined?(DiscourseWorkflows)llm_model = resolve_llm_model(agent_record, config["llm_model_id"])log.info("Agent: #{agent_record.name}")+ log.info("Runner: #{runner.username}")log.info("LLM: #{llm_model.display_name} (#{llm_model.id})")log.info("Prompt: #{prompt.to_s[0..200]}")@@ -242,10 +307,21 @@ if defined?(DiscourseWorkflows)model: llm_model,)+ content =+ prompt_content(+ prompt,+ config["upload_ids"],+ agent_record,+ llm_model,+ runner.guardian,+ log,+ )+bot_context =DiscourseAi::Agents::BotContext.new(- user: Discourse.system_user,- messages: [{ type: :user, content: prompt }],+ user: runner,+ guardian: runner.guardian,+ messages: [{ type: :user, content: content }],feature_name: "workflow",)diff --git a/plugins/discourse-ai/spec/lib/discourse_workflows/nodes/ai_agent_spec.rb b/plugins/discourse-ai/spec/lib/discourse_workflows/nodes/ai_agent_spec.rbindex 3c4c2f15ff9..d5ee361e8c7 100644--- a/plugins/discourse-ai/spec/lib/discourse_workflows/nodes/ai_agent_spec.rb+++ b/plugins/discourse-ai/spec/lib/discourse_workflows/nodes/ai_agent_spec.rb@@ -8,19 +8,23 @@ RSpec.describe DiscourseWorkflows::Nodes::AiAgent::V1 doendlet(:bot) { instance_double(DiscourseAi::Agents::Bot) }+ let(:bot_as_users) { [] }+ let(:bot_contexts) { [] }let(:bot_models) { [] }let(:prompts) { [] }before doSiteSetting.discourse_ai_enabled = true- allow(DiscourseAi::Agents::Bot).to receive(:as) do |_user, agent:, model:|+ allow(DiscourseAi::Agents::Bot).to receive(:as) do |user, agent:, model:|+ bot_as_users << userbot_models << modelbotendallow(bot).to receive(:reply) do |bot_context, &block|prompt = bot_context.messages.first[:content]+ bot_contexts << bot_contextprompts << promptblock.call("Reply to #{prompt}", nil, nil)end@@ -95,6 +99,13 @@ RSpec.describe DiscourseWorkflows::Nodes::AiAgent::V1 doendend+ it "declares an explicit runner actor control" do+ runner_schema = described_class.property_schema[:runner_username]++ expect(runner_schema).to include(type: :string, default: "system")+ expect(runner_schema[:ui]).to include(control: :actor)+ end+it "runs the agent once per input item with item-specific parameters" doitems =execute_node_output(@@ -113,6 +124,170 @@ RSpec.describe DiscourseWorkflows::Nodes::AiAgent::V1 doexpect(bot).to have_received(:reply).twiceend+ it "uses the system user as the default runner" do+ execute_node_output(configuration: { "agent_id" => agent.id, "prompt" => "Hello" })++ expect(bot_as_users).to eq([Discourse.system_user])+ expect(bot_contexts.last.user).to eq(Discourse.system_user)+ expect(bot_contexts.last.guardian.user).to eq(Discourse.system_user)+ end++ it "uses a specific configured runner for agent context and permissions" do+ runner = Fabricate(:user)++ execute_node_output(+ configuration: {+ "agent_id" => agent.id,+ "runner_username" => runner.username,+ "prompt" => "Hello",+ },+ )++ expect(bot_contexts.last.user).to eq(runner)+ expect(bot_contexts.last.guardian.user).to eq(runner)+ end++ it "supports anonymous as the configured runner" do+ execute_node_output(+ configuration: {+ "agent_id" => agent.id,+ "runner_username" => DiscourseWorkflows::AnonymousActor::USERNAME,+ "prompt" => "Hello",+ },+ )++ expect(bot_contexts.last.user).to be_a(DiscourseWorkflows::AnonymousActor)+ expect(bot_contexts.last.guardian).to be_anonymous+ end++ it "passes configured upload IDs to the agent prompt" do+ agent.update!(vision_enabled: true)+ upload = Fabricate(:image_upload)++ execute_node_output(+ configuration: {+ "agent_id" => agent.id,+ "prompt" => "Review the screenshot",+ "upload_ids" => "={{ $json.upload_ids }}",+ },+ input_items: [{ "json" => { "upload_ids" => [upload.id] } }],+ )++ expect(prompts).to eq([["Review the screenshot", { upload_id: upload.id }]])+ end++ it "filters image upload IDs when the agent does not have vision enabled" do+ agent.update!(vision_enabled: false)+ upload = Fabricate(:image_upload)++ execute_node_output(+ configuration: {+ "agent_id" => agent.id,+ "prompt" => "Review the screenshot",+ "upload_ids" => [upload.id],+ },+ )++ expect(prompts).to eq(["Review the screenshot"])+ end++ it "filters upload IDs the execution user cannot see" do+ agent.update!(vision_enabled: true)+ visible_upload = Fabricate(:image_upload)+ hidden_upload = Fabricate(:image_upload)+ owner = Fabricate(:user)+ recipient = Fabricate(:user)+ private_topic = Fabricate(:private_message_topic, user: owner, recipient: recipient)+ private_post = Fabricate(:post, topic: private_topic, user: owner)+ hidden_upload.update!(access_control_post_id: private_post.id)++ runner = Fabricate(:user)++ execute_node_output(+ configuration: {+ "agent_id" => agent.id,+ "runner_username" => runner.username,+ "prompt" => "Review the screenshot",+ "upload_ids" => [visible_upload.id, hidden_upload.id],+ },+ )++ expect(prompts).to eq([["Review the screenshot", { upload_id: visible_upload.id }]])+ end++ it "resolves runner expressions per item" do+ agent.update!(vision_enabled: true)+ owner = Fabricate(:user)+ runner = Fabricate(:user)+ private_topic = Fabricate(:private_message_topic, user: owner, recipient: runner)+ private_post = Fabricate(:post, topic: private_topic, user: owner)+ upload = Fabricate(:image_upload)+ upload.update!(access_control_post_id: private_post.id)++ execute_node_output(+ configuration: {+ "agent_id" => agent.id,+ "runner_username" => "={{ $json.runner_username }}",+ "prompt" => "Review the screenshot",+ "upload_ids" => [upload.id],+ },+ input_items: [{ "json" => { "runner_username" => runner.username } }],+ )++ expect(bot_contexts.last.user).to eq(runner)+ expect(prompts).to eq([["Review the screenshot", { upload_id: upload.id }]])+ end++ it "normalizes comma-separated and JSON upload ID values" do+ agent.update!(vision_enabled: true)+ first_upload = Fabricate(:image_upload)+ second_upload = Fabricate(:image_upload)++ execute_node_output(+ configuration: {+ "agent_id" => agent.id,+ "prompt" => "Review the uploads",+ "upload_ids" => "#{first_upload.id}, not-an-id, #{second_upload.id}",+ },+ )++ expect(prompts).to eq(+ [["Review the uploads", { upload_id: first_upload.id }, { upload_id: second_upload.id }]],+ )++ prompts.clear++ execute_node_output(+ configuration: {+ "agent_id" => agent.id,+ "prompt" => "Review the uploads",+ "upload_ids" =>+ "[#{first_upload.id}, {\"id\": #{second_upload.id}}, true, \"#{second_upload.id}\"]",+ },+ )++ expect(prompts).to eq(+ [["Review the uploads", { upload_id: first_upload.id }, { upload_id: second_upload.id }]],+ )+ end++ it "passes document upload IDs when the selected LLM supports their attachment type" do+ llm_model.update!(allowed_attachment_types: ["pdf"])+ SiteSetting.authorized_extensions += "|pdf"+ agent.update!(vision_enabled: false)+ upload = Fabricate(:upload, original_filename: "report.pdf", extension: "pdf")++ execute_node_output(+ configuration: {+ "agent_id" => agent.id,+ "prompt" => "Review the document",+ "upload_ids" => [upload.id],+ },+ )++ expect(prompts).to eq([["Review the document", { upload_id: upload.id }]])+ end+it "uses an empty string when the optional prompt is blank" doitems = execute_node_output(configuration: { "agent_id" => agent.id }).firstdiff --git a/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/configurators/field.gjs b/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/configurators/field.gjsindex 7e2d9c4523d..4b00292d1c0 100644--- a/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/configurators/field.gjs+++ b/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/configurators/field.gjs@@ -16,6 +16,7 @@ import {propertyDynamicValueHint,propertyLabel,propertyPlaceholder,+ propertyTooltip,} from "../../../lib/workflows/property-engine";const CRON_FIELD_PATTERN =@@ -130,6 +131,7 @@ export default class Field extends Component {if (!fieldShowDescription(this.args.schema)) {return undefined;}+const description = propertyDescription(this.nodeDefinition,this.args.fieldName@@ -137,6 +139,14 @@ export default class Field extends Component {return description ? trustHTML(description) : undefined;}+ get fieldTooltip() {+ if (!this.showLabel) {+ return undefined;+ }++ return propertyTooltip(this.nodeDefinition, this.args.fieldName);+ }+get dynamicValueHint() {if (!this.supportsExpression) {return null;@@ -181,6 +191,7 @@ export default class Field extends Component {@title={{this.fieldTitle}}@showTitle={{this.showLabel}}@description={{this.fieldDescription}}+ @tooltip={{this.fieldTooltip}}@type={{this.resolvedFieldType}}@format={{this.format}}@validation={{this.validation}}diff --git a/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/configurators/multi-input.gjs b/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/configurators/multi-input.gjsnew file mode 100644index 00000000000..17baa5fd4dd--- /dev/null+++ b/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/configurators/multi-input.gjs@@ -0,0 +1,41 @@+import Component from "@glimmer/component";+import { hash } from "@ember/helper";+import { action } from "@ember/object";+import { makeArray } from "discourse/lib/helpers";+import MultiSelect from "discourse/select-kit/components/multi-select";+import ExpressionWrapper from "./expression-wrapper";++export default class MultiInput extends Component {+ get value() {+ return makeArray(this.args.field.value);+ }++ get content() {+ return this.value.map((value) => ({ id: value, name: String(value) }));+ }++ @action+ handleChange(values) {+ this.args.field.set(makeArray(values));+ }++ <template>+ <ExpressionWrapper+ @field={{@field}}+ @schema={{@schema}}+ @supportsExpression={{@supportsExpression}}+ @placeholder={{@placeholder}}+ @dynamicValueHint={{@dynamicValueHint}}+ @session={{@session}}+ >+ <MultiSelect+ @content={{this.content}}+ @value={{this.value}}+ @nameProperty="name"+ @valueProperty="id"+ @onChange={{this.handleChange}}+ @options={{hash allowAny=true}}+ />+ </ExpressionWrapper>+ </template>+}diff --git a/plugins/discourse-workflows/admin/assets/javascripts/admin/lib/workflows/field-control-registry.js b/plugins/discourse-workflows/admin/assets/javascripts/admin/lib/workflows/field-control-registry.jsindex 7dfa98d33ea..93eeae9daf2 100644--- a/plugins/discourse-workflows/admin/assets/javascripts/admin/lib/workflows/field-control-registry.js+++ b/plugins/discourse-workflows/admin/assets/javascripts/admin/lib/workflows/field-control-registry.js@@ -14,6 +14,7 @@ import FilterQuery from "../../components/workflows/configurators/filter-query";import GroupSelect from "../../components/workflows/configurators/group-select";import IconControl from "../../components/workflows/configurators/icon-control";import MultiComboBox from "../../components/workflows/configurators/multi-combo-box";+import MultiInput from "../../components/workflows/configurators/multi-input";import NoticeControl from "../../components/workflows/configurators/notice-control";import QueryParams from "../../components/workflows/configurators/query-params";import SelectControl from "../../components/workflows/configurators/select-control";@@ -49,6 +50,7 @@ const FIELD_CONTROL_REGISTRY = {renderer: DataTableColumnSelect,},multi_combo_box: { kind: "field", type: "custom", renderer: MultiComboBox },+ multi_input: { kind: "field", type: "custom", renderer: MultiInput },filter_query: { kind: "field", type: "custom", renderer: FilterQuery },url_preview: { kind: "field", type: "custom", renderer: UrlPreview },tags: { kind: "field", type: "custom", renderer: TagsControl },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.jsindex e9c91a309b1..063033f95d8 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@@ -111,6 +111,12 @@ export function propertyDescription(nodeDefinitionOrType, fieldName) {);}+export function propertyTooltip(nodeDefinitionOrType, fieldName) {+ return translatedOrNull(+ `${i18nBase(nodeDefinitionOrType)}.${localeKeyPart(fieldName)}_tooltip`+ );+}+export function propertyPlaceholder(nodeDefinitionOrType, fieldName) {return translatedOrNull(`${i18nBase(nodeDefinitionOrType)}.${localeKeyPart(fieldName)}_placeholder`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.rbindex e4da3f3890b..d28e6a138a1 100644--- 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@@ -183,8 +183,13 @@ module Jobsenddef parse_tool_call_response(raw_context)- parse_authoring_result_tool_response(raw_context) ||- parse_ask_questions_tool_response(raw_context) ||+ authoring_response = parse_authoring_result_tool_response(raw_context)+ if invalid_empty_proposed_patch_response?(authoring_response)+ patch_response = parse_validate_patch_tool_response(raw_context)+ return patch_response if patch_response.present?+ end++ authoring_response || parse_ask_questions_tool_response(raw_context) ||parse_validate_patch_tool_response(raw_context)end@@ -280,8 +285,7 @@ module Jobsdef tool_call_proposal_response(arguments, operations)operations = normalized_patch_operations(operations)title =- arguments[:workflow_name].presence ||- @session.latest_request.to_s.truncate(80).presence ||+ arguments[:workflow_name].presence || human_request_title ||I18n.t("discourse_workflows.ai.tool_call_proposal_title"){@@ -331,6 +335,41 @@ module Jobs}end+ def invalid_empty_proposed_patch_response?(parsed)+ parsed = normalized_hash(parsed)+ tool_class = ::DiscourseWorkflows::Ai::Tools::WorkflowAuthoringResult+ missing_operations_message = tool_class::MISSING_PROPOSAL_OPERATIONS_MESSAGE++ parsed[:status].to_s == "error" && parsed[:proposal].blank? &&+ parsed[:message].to_s == missing_operations_message+ end++ def human_request_title+ human_request = latest_human_request+ human_request.presence&.truncate(80)+ end++ def latest_human_request+ requests = [@session.latest_request]+ @session.messages.reverse_each do |message|+ next if message["type"].to_s != "user"++ requests << user_message_text(message["content"])+ end++ requests.find { |request| request.present? && !clarification_result_message?(request) }+ end++ def user_message_text(content)+ parsed = parse_json_hash(content.to_s)+ normalized_hash(parsed)[:message].presence || content.to_s+ end++ def clarification_result_message?(message)+ parsed = parse_json_hash(message.to_s)+ normalized_hash(parsed)[:type].to_s == "workflow_ask_questions_result"+ end+def proposed_patch_response?(parsed)parsed["status"].to_s == "proposed_patch"enddiff --git a/plugins/discourse-workflows/app/serializers/discourse_workflows/post_serializer.rb b/plugins/discourse-workflows/app/serializers/discourse_workflows/post_serializer.rbindex 495f187e42b..7cb011de7f1 100644--- a/plugins/discourse-workflows/app/serializers/discourse_workflows/post_serializer.rb+++ b/plugins/discourse-workflows/app/serializers/discourse_workflows/post_serializer.rb@@ -21,6 +21,7 @@ module DiscourseWorkflows:category_id,:category_name,:tags,+ :upload_ids,:raw,:cooked@@ -72,6 +73,10 @@ module DiscourseWorkflowstopic.tags.visible(scope).pluck(:name)end+ def upload_ids+ object.upload_ids+ end+def include_raw?@include_rawenddiff --git a/plugins/discourse-workflows/config/settings.yml b/plugins/discourse-workflows/config/settings.ymlindex 40e1aed3417..7bda0b7dcdb 100644--- a/plugins/discourse-workflows/config/settings.yml+++ b/plugins/discourse-workflows/config/settings.yml@@ -6,7 +6,6 @@ plugins:discourse_workflows_ai_authoring_enabled:default: falseclient: true- hidden: truediscourse_workflows_ai_authoring_max_prompt_length:default: 4000min: 1diff --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.rbindex 49a174750a6..b15a0303f58 100644--- 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@@ -7,6 +7,8 @@ module DiscourseWorkflowsSTATUSES = %w[needs_clarification proposed_patch explanation error].freezeRISK_LEVELS = %w[low medium high].freezeMAX_TEXT_LENGTH = 2000+ MISSING_PROPOSAL_OPERATIONS_MESSAGE =+ "Proposed patch results must include proposal.operations"def self.signature{@@ -155,7 +157,7 @@ module DiscourseWorkflowsendif response[:status] == "proposed_patch" && response.dig(:proposal, "operations").blank?- return error_result("Proposed patch results must include proposal.operations")+ return error_result(MISSING_PROPOSAL_OPERATIONS_MESSAGE)endresponsediff --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.rbindex 98144850060..dc22d41ef73 100644--- 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@@ -42,6 +42,7 @@ module DiscourseWorkflows"post.reply_count" => "integer","post.score" => "number|null","post.tags" => "array<string>",+ "post.upload_ids" => "array<integer>",}.freezeWEBHOOK_POST_SCHEMA =@@ -50,6 +51,7 @@ module DiscourseWorkflows"post.excerpt","post.like_count","post.tags",+ "post.upload_ids",).merge("post" => "WebHookPostSerializer payload", "post.category_slug" => "string")USER_SCHEMA = {@@ -227,6 +229,7 @@ module DiscourseWorkflowsparameters: {agent_id: 123,agent_name: "Post classifier",+ runner_username: "system",prompt:"=Classify this Discourse post and return a short label: {{ $json.post.raw }}",},@@ -259,7 +262,8 @@ module DiscourseWorkflowsSEARCH_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:ai_agent" =>+ "ai agent bot llm classify summarize generate sentiment triage runner run as permissions uploads attachments","action:group" => "group membership member belongs friend friends",}.freezediff --git a/plugins/discourse-workflows/lib/discourse_workflows/ai_workflow_author.rb b/plugins/discourse-workflows/lib/discourse_workflows/ai_workflow_author.rbindex 9ed376751d0..e1e6a2a3dd8 100644--- a/plugins/discourse-workflows/lib/discourse_workflows/ai_workflow_author.rb+++ b/plugins/discourse-workflows/lib/discourse_workflows/ai_workflow_author.rb@@ -85,6 +85,8 @@ module DiscourseWorkflows- 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.+ - For action:ai_agent nodes, set parameters.runner_username when permissions matter. Use "system" for workflow-owned automation, "anonymous" for public anonymous permissions, or a username/expression such as ={{ $json.post.username }} when the agent should only see and use tools as that user.+ - When an action:ai_agent node should analyze images or documents and the current input schema exposes upload IDs, set parameters.upload_ids to a whole-field expression such as ={{ $json.post.upload_ids }}. Do not paste upload URLs into the prompt.- 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.diff --git a/plugins/discourse-workflows/lib/discourse_workflows/property_schema_validator.rb b/plugins/discourse-workflows/lib/discourse_workflows/property_schema_validator.rbindex 07cc1dfde45..cf6e5b3eaf6 100644--- a/plugins/discourse-workflows/lib/discourse_workflows/property_schema_validator.rb+++ b/plugins/discourse-workflows/lib/discourse_workflows/property_schema_validator.rb@@ -104,6 +104,7 @@ module DiscourseWorkflowsgroup_selecticonmulti_combo_box+ multi_inputnoticepasswordquery_paramsdiff --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.rbindex 4d2fd870419..033804c5ec0 100644--- 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@@ -266,8 +266,33 @@ RSpec.describe Jobs::DiscourseWorkflows::AuthorWithAi do:discourse_workflows_ai_authoring_session,user: admin,workflow: workflow,- latest_request: "Create a manual workflow",- messages: [{ "type" => "user", "content" => "Create a manual workflow" }],+ latest_request:+ '{"type":"workflow_ask_questions_result","answers":[{"id":"trigger_scope","selected_options":["First post only"]}]}',+ messages: [+ {+ "type" => "user",+ "content" =>+ JSON.pretty_generate(+ {+ mode: "edit",+ message: "Create a manual workflow after asking questions",+ workflow_id: workflow.id,+ },+ ),+ },+ {+ "type" => "user",+ "content" =>+ JSON.pretty_generate(+ {+ mode: "edit",+ message:+ '{"type":"workflow_ask_questions_result","answers":[{"id":"trigger_scope","selected_options":["First post only"]}]}',+ workflow_id: workflow.id,+ },+ ),+ },+ ],)operations = [{@@ -309,6 +334,72 @@ RSpec.describe Jobs::DiscourseWorkflows::AuthorWithAi doexpect(session.latest_response).to include("message" => I18n.t("discourse_workflows.ai.tool_call_proposal_message"),)+ expect(session.proposed_patch["title"]).to eq("Create a manual workflow after asking questions")+ expect(session.proposed_patch.dig("patch_validation", "valid")).to eq(true)+ end++ it "falls back to validated patch tool calls when the final result omits operations",+ :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,+ "validate-patch-call-id",+ "tool_call",+ "workflow_validate_patch",+ ],+ [+ { status: "success", valid: true }.to_json,+ "validate-patch-call-id",+ "tool",+ "workflow_validate_patch",+ ],+ [+ {+ status: "error",+ message: "Proposed patch results must include proposal.operations",+ questions: [],+ proposal: {+ },+ }.to_json,+ "authoring-result-call-id",+ "tool",+ DiscourseWorkflows::Ai::Tools::WorkflowAuthoringResult.name,+ ],+ ]+ 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.proposed_patch["title"]).to eq("Create a manual workflow")+ expect(session.proposed_patch["operations"]).to eq(JSON.parse(operations.to_json))expect(session.proposed_patch.dig("patch_validation", "valid")).to eq(true)enddiff --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.rbindex 8da60fe52b1..39ea6dab72b 100644--- 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@@ -26,6 +26,7 @@ RSpec.describe DiscourseWorkflows::Ai::Tools::WorkflowNodeCatalog do"post.post_number" => "integer","post.topic_id" => "integer","post.post_url" => "string",+ "post.upload_ids" => "array<integer>",)expect(nodes_by_type.dig("trigger:topic_created", :output_schema)).not_to include("post.trust_level",@@ -70,7 +71,10 @@ RSpec.describe DiscourseWorkflows::Ai::Tools::WorkflowNodeCatalog do"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", :output_schema)).not_to include(+ "post.trust_level",+ "post.upload_ids",+ )expect(nodes_by_type.dig("action:topic_tags", :output_schema)).to include("topic_id" => "integer","tag_names" => "array<string>",@@ -109,6 +113,15 @@ RSpec.describe DiscourseWorkflows::Ai::Tools::WorkflowNodeCatalog doexpect(result[:nodes].find { |node| node[:type] == "action:topic" }[:examples]).to be_presentend+ it "matches AI agent runner and attachment queries" do+ result = invoke_tool(query: "runner permissions attachments", include_examples: true)+ ai_agent_node = result[:nodes].find { |node| node[:type] == "action:ai_agent" }++ expect(ai_agent_node).to be_present+ expect(ai_agent_node.dig(:properties, "runner_username", "ui", "control")).to eq("actor")+ expect(ai_agent_node.dig(:examples, 0, :parameters)).to include(runner_username: "system")+ end+it "includes declarative filter and topic lookup examples", :aggregate_failures doresult = invoke_tool(include_examples: true)filter_node = result[:nodes].find { |node| node[:type] == "condition:filter" }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.rbindex e4241814ecb..d2165735211 100644--- 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@@ -28,6 +28,8 @@ RSpec.describe DiscourseWorkflows::AiWorkflowAuthor do"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",+ "parameters.runner_username",+ "parameters.upload_ids","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",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.rbindex a770fdaac40..9e57b18bd79 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@@ -56,6 +56,9 @@ RSpec.describe DiscourseWorkflows::Nodes::PostCreated::V1 dodescribe "#output" doit "returns post and topic data" do+ upload = Fabricate(:image_upload)+ UploadReference.create!(target: reply, upload: upload)+trigger = described_class.new(reply)output = trigger.output@@ -65,6 +68,7 @@ RSpec.describe DiscourseWorkflows::Nodes::PostCreated::V1 doexpect(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[:post][:upload_ids]).to contain_exactly(upload.id)expect(output[:user]).to include(id: reply_user.id,username: reply_user.username,diff --git a/plugins/discourse-workflows/spec/support/node_execution_helpers.rb b/plugins/discourse-workflows/spec/support/node_execution_helpers.rbindex 3958632d8be..9e5b8256942 100644--- a/plugins/discourse-workflows/spec/support/node_execution_helpers.rb+++ b/plugins/discourse-workflows/spec/support/node_execution_helpers.rb@@ -7,6 +7,7 @@ module NodeExecutionHelpersinput_items: nil,input_groups: nil,node_context: nil,+ user: nil,&block)item = { "json" => {} } if item.nil? && input_items.nil?@@ -15,8 +16,9 @@ module NodeExecutionHelpersnode_parameters = configuration.except("credentials")action = described_class.new(parameters: node_parameters, credentials: node_credentials)resolver_context = { "$json" => input_items.first&.dig("json") || {} }- sandbox = DiscourseWorkflows::JsSandbox.new(resolver_context)- resolver = DiscourseWorkflows::ExpressionResolver.new(resolver_context, sandbox: sandbox)+ sandbox = DiscourseWorkflows::JsSandbox.new(resolver_context, user: user)+ resolver =+ DiscourseWorkflows::ExpressionResolver.new(resolver_context, sandbox: sandbox, user: user)kwargs = {input_items: input_items,input_groups: input_groups,@@ -27,6 +29,7 @@ module NodeExecutionHelperscredential_schema: described_class.credentials,node_identifier: described_class.identifier,resolver_context: resolver_context,+ user: user,}kwargs[:node_context] = node_context if node_contextdiff --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.gjsindex 67b1fa9483a..58d601c64f8 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@@ -12,6 +12,7 @@ import Form from "discourse/components/form";import { setupRenderingTest } from "discourse/tests/helpers/component-test";import pretender, { response } from "discourse/tests/helpers/create-pretender";import selectKit from "discourse/tests/helpers/select-kit-helper";+import I18n from "discourse-i18n";import PropertyEngineConfigurator from "discourse/plugins/discourse-workflows/admin/components/workflows/configurators/property-engine";import WorkflowEditorSession from "discourse/plugins/discourse-workflows/admin/lib/workflows/editor-session";@@ -35,6 +36,8 @@ module("Integration | Component | workflows property engine", function (hooks) {});hooks.afterEach(function () {+ delete I18n.translations[I18n.locale]?.js?.discourse_workflows?.post+ ?.raw_tooltip;sinon.restore();});@@ -70,6 +73,91 @@ module("Integration | Component | workflows property engine", function (hooks) {assert.dom("input").isFocused();});+ test("renders an inline description and a tooltip independently", async function (assert) {+ I18n.translations[I18n.locale].js.discourse_workflows.post.raw_tooltip =+ "Only visible to the agent";++ this.setProperties({+ configuration: { raw: "" },+ nodeType: "action:post",+ nodeTypes: [{ identifier: "action:post", name: "action:post" }],+ schema: {+ raw: {+ type: "string",+ ui: {+ control: "textarea",+ },+ },+ },+ });++ await render(+ <template>+ <Form @data={{this.configuration}} as |form transientData|>+ <PropertyEngineConfigurator+ @form={{form}}+ @configuration={{transientData}}+ @nodeType={{this.nodeType}}+ @nodeTypes={{this.nodeTypes}}+ @schema={{this.schema}}+ @session={{this.session}}+ />+ </Form>+ </template>+ );++ assert+ .dom(".form-kit__container-description")+ .hasText("Raw content for the post");+ assert.dom(".fk-d-tooltip__trigger").exists();++ await click(".fk-d-tooltip__trigger");++ assert+ .dom(".fk-d-tooltip__inner-content")+ .hasText("Only visible to the agent");+ });++ test("hides the tooltip when the label is hidden", async function (assert) {+ I18n.translations[I18n.locale].js.discourse_workflows.post.raw_tooltip =+ "Only visible to the agent";++ this.setProperties({+ configuration: { raw: "" },+ nodeType: "action:post",+ nodeTypes: [{ identifier: "action:post", name: "action:post" }],+ schema: {+ raw: {+ type: "string",+ ui: {+ control: "textarea",+ show_label: false,+ },+ },+ },+ });++ await render(+ <template>+ <Form @data={{this.configuration}} as |form transientData|>+ <PropertyEngineConfigurator+ @form={{form}}+ @configuration={{transientData}}+ @nodeType={{this.nodeType}}+ @nodeTypes={{this.nodeTypes}}+ @schema={{this.schema}}+ @session={{this.session}}+ />+ </Form>+ </template>+ );++ assert.dom(".fk-d-tooltip__trigger").doesNotExist();+ assert+ .dom(".form-kit__container-description")+ .hasText("Raw content for the post");+ });+test("renders checkbox controls from metadata", async function (assert) {this.setProperties({configuration: {@@ -1258,4 +1346,78 @@ module("Integration | Component | workflows property engine", function (hooks) {custom_field_names: [],});});++ test("multi_input fields accept arbitrary ids and convert between fixed and dynamic", async function (assert) {+ this.setProperties({+ configuration: { upload_ids: [] },+ formApi: null,+ nodeType: "action:ai_agent",+ schema: {+ upload_ids: {+ type: "array",+ required: false,+ ui: {+ control: "multi_input",+ expression: true,+ },+ },+ },+ registerApi: (api) => {+ this.set("formApi", api);+ },+ });++ await render(+ <template>+ <Form+ @data={{this.configuration}}+ @onRegisterApi={{this.registerApi}}+ as |form transientData|+ >+ <PropertyEngineConfigurator+ @form={{form}}+ @formApi={{this.formApi}}+ @configuration={{transientData}}+ @nodeType={{this.nodeType}}+ @schema={{this.schema}}+ @session={{this.session}}+ />+ </Form>+ </template>+ );++ const selector = selectKit(".multi-select");++ await selector.expand();+ await selector.fillInFilter("12");+ await selector.selectRowByValue("12");+ await selector.fillInFilter("34");+ await selector.selectRowByValue("34");++ assert.deepEqual(+ this.formApi.get("upload_ids"),+ ["12", "34"],+ "stores entered ids"+ );++ await click(+ '.workflows-property-engine__mode-control input[value="dynamic"]'+ );++ assert.strictEqual(+ this.formApi.get("upload_ids"),+ '={{ ["12","34"] }}',+ "converts the fixed list into a dynamic expression"+ );++ await click(+ '.workflows-property-engine__mode-control input[value="plain"]'+ );++ assert.deepEqual(+ this.formApi.get("upload_ids"),+ ["12", "34"],+ "converts the dynamic expression back into a fixed list"+ );+ });});diff --git a/script/i18n_lint.rb b/script/i18n_lint.rbindex 62f9d3c0435..21c6d502712 100755--- a/script/i18n_lint.rb+++ b/script/i18n_lint.rb@@ -59,6 +59,7 @@ class LocaleFileValidatorEXEMPTED_DOUBLE_CURLY_BRACKET_KEYS = %w[js.discourse_automation.scriptables.auto_responder.fields.word_answer_list.descriptiondiscourse_automation.scriptables.email_on_flagged_post.default_template+ js.discourse_ai.discourse_workflows.ai_agent.upload_ids_placeholder]def initialize(filename)