Skip to content

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

FEATURE: add image generation tools (#35946)

Keegan Georgece2e2788bc9e
diff --git a/plugins/discourse-ai/admin/assets/javascripts/discourse/routes/admin-plugins/show/discourse-ai-tools/new.js b/plugins/discourse-ai/admin/assets/javascripts/discourse/routes/admin-plugins/show/discourse-ai-tools/new.js
index 463ae21a214..e32b9e89f4d 100644
--- a/plugins/discourse-ai/admin/assets/javascripts/discourse/routes/admin-plugins/show/discourse-ai-tools/new.js
+++ b/plugins/discourse-ai/admin/assets/javascripts/discourse/routes/admin-plugins/show/discourse-ai-tools/new.js
@@ -1,6 +1,10 @@
import DiscourseRoute from "discourse/routes/discourse";
export default class DiscourseAiToolsNewRoute extends DiscourseRoute {
+ queryParams = {
+ presetId: { refreshModel: false },
+ };
+
beforeModel(transition) {
this.preset = transition.to.queryParams.presetId || "empty_tool";
}
diff --git a/plugins/discourse-ai/app/controllers/discourse_ai/ai_helper/assistant_controller.rb b/plugins/discourse-ai/app/controllers/discourse_ai/ai_helper/assistant_controller.rb
index 53e2b0c4d8e..c4e3f2786b6 100644
--- a/plugins/discourse-ai/app/controllers/discourse_ai/ai_helper/assistant_controller.rb
+++ b/plugins/discourse-ai/app/controllers/discourse_ai/ai_helper/assistant_controller.rb
@@ -106,9 +106,55 @@ module DiscourseAi
def suggest_thumbnails(input)
hijack do
- thumbnails = DiscourseAi::AiHelper::Painter.new.commission_thumbnails(input, current_user)
-
- render json: { thumbnails: thumbnails }, status: :ok
+ result =
+ DiscourseAi::AiHelper::GenerateThumbnails.call(
+ params: {
+ text: input,
+ },
+ guardian: guardian,
+ )
+
+ if result.failure?
+ failing_step = nil
+ failing_step = "contract.default" if result[:"result.contract.default"]&.failure?
+ failing_step = "model.persona" if result[:"result.model.persona"]&.failure?
+ failing_step = "policy.has_image_generation_tool" if result[
+ :"result.policy.has_image_generation_tool"
+ ]&.failure?
+ failing_step = "model.llm_model" if result[:"result.model.llm_model"]&.failure?
+
+ status =
+ case failing_step
+ when "contract.default"
+ 422
+ when "model.persona"
+ 404
+ when "policy.has_image_generation_tool"
+ 422
+ when "model.llm_model"
+ 500
+ else
+ 500
+ end
+
+ translation_key =
+ case failing_step
+ when "contract.default"
+ "discourse_ai.ai_helper.errors.completion_request_failed"
+ when "model.persona"
+ "discourse_ai.ai_helper.errors.no_illustrator_persona"
+ when "policy.has_image_generation_tool"
+ "discourse_ai.ai_helper.errors.no_image_generation_tool"
+ when "model.llm_model"
+ "discourse_ai.ai_helper.errors.llm_model_not_configured"
+ else
+ "discourse_ai.ai_helper.errors.no_image_generated"
+ end
+
+ render_json_error(I18n.t(translation_key), status: status)
+ else
+ render json: { thumbnails: result[:thumbnails] }, status: :ok
+ end
end
end
diff --git a/plugins/discourse-ai/app/models/ai_persona.rb b/plugins/discourse-ai/app/models/ai_persona.rb
index 5d7d98eefc7..56a7da344dd 100644
--- a/plugins/discourse-ai/app/models/ai_persona.rb
+++ b/plugins/discourse-ai/app/models/ai_persona.rb
@@ -343,6 +343,18 @@ class AiPersona < ActiveRecord::Base
end
end
+ def has_image_generation_tool?
+ persona_klass = class_instance.new
+ persona_klass.tools.any? do |tool_klass|
+ if tool_klass.respond_to?(:custom?) && tool_klass.custom?
+ ai_tool = AiTool.find_by(id: tool_klass.tool_id)
+ ai_tool&.image_generation_tool?
+ else
+ false
+ end
+ end
+ end
+
def features
DiscourseAi::Configuration::Feature.find_features_using(persona_id: id)
end
diff --git a/plugins/discourse-ai/app/models/ai_tool.rb b/plugins/discourse-ai/app/models/ai_tool.rb
index 956cdd0e609..1ce463d37af 100644
--- a/plugins/discourse-ai/app/models/ai_tool.rb
+++ b/plugins/discourse-ai/app/models/ai_tool.rb
@@ -12,6 +12,7 @@ class AiTool < ActiveRecord::Base
has_many :rag_document_fragments, dependent: :destroy, as: :target
has_many :upload_references, as: :target, dependent: :destroy
has_many :uploads, through: :upload_references
+ before_save :set_image_generation_tool_flag
before_update :regenerate_rag_fragments
ALPHANUMERIC_PATTERN = /\A[a-zA-Z0-9_]+\z/
@@ -59,6 +60,21 @@ class AiTool < ActiveRecord::Base
end
end
+ def image_generation_tool?
+ is_image_generation_tool
+ end
+
+ private
+
+ def set_image_generation_tool_flag
+ has_prompt_parameter = parameters.is_a?(Array) && parameters.any? { |p| p["name"] == "prompt" }
+ has_upload_create = script.include?("upload.create")
+ has_chain_set_custom_raw = script.include?("chain.setCustomRaw")
+
+ self.is_image_generation_tool =
+ has_prompt_parameter && has_upload_create && has_chain_set_custom_raw
+ end
+
def validate_parameters_enum
return unless parameters.is_a?(Array)
@@ -83,309 +99,153 @@ class AiTool < ActiveRecord::Base
end
end
+ # Load a JavaScript file from the ai_tool_scripts directory
+ def self.load_script(filename)
+ path = File.join(__dir__, "../../lib/ai_tool_scripts", filename)
+ File.read(path)
+ end
+
def self.preamble
- <<~JS
- /**
- * Tool API Quick Reference
- *
- * Entry Functions
- *
- * invoke(parameters): Main function. Receives parameters defined in the tool's signature (Object).
- * Must return a JSON-serializable value (e.g., string, number, object, array).
- * Example:
- * function invoke(parameters) { return { result: "Data processed", input: parameters.query }; }
- *
- * details(): Optional function. Returns a string (can include basic HTML) describing
- * the tool's action after invocation, often using data from the invocation.
- * This is displayed in the chat interface.
- * Example:
- * let lastUrl;
- * function invoke(parameters) {
- * lastUrl = parameters.url;
- * // ... perform action ...
- * return { success: true, content: "..." };
- * }
- * function details() {
- * return `Browsed: <a href="${lastUrl}">${lastUrl}</a>`;
- * }
- *
- * Provided Objects & Functions
- *
- * 1. http
- * Performs HTTP requests. Max 20 requests per execution.
- *
- * http.get(url, options?): Performs GET request.
- * Parameters:
- * url (string): The request URL.
- * options (Object, optional):
- * headers (Object): Request headers (e.g., { "Authorization": "Bearer key" }).
- * Returns: { status: number, body: string }
- *
- * http.post(url, options?): Performs POST request.
- * Parameters:
- * url (string): The request URL.
- * options (Object, optional):
- * headers (Object): Request headers.
- * body (string | Object): Request body. If an object, it's stringified as JSON.
- * Returns: { status: number, body: string }
- *
- * http.put(url, options?): Performs PUT request (similar to POST).
- * http.patch(url, options?): Performs PATCH request (similar to POST).
- * http.delete(url, options?): Performs DELETE request (similar to GET/POST).
- *
- * 2. llm
- * Interacts with the Language Model.
- *
- * llm.truncate(text, length): Truncates text to a specified token length based on the configured LLM's tokenizer.
- * Parameters:
- * text (string): Text to truncate.
- * length (number): Maximum number of tokens.
- * Returns: string (truncated text)
- *
- * llm.generate(prompt): Generates text using the configured LLM associated with the tool runner.
- * Parameters:
- * prompt (string | Object): The prompt. Can be a simple string or an object
- * like { messages: [{ type: "system", content: "..." }, { type: "user", content: "..." }] }.
- * Returns: string (generated text)
- *
- * 3. index
- * Searches attached RAG (Retrieval-Augmented Generation) documents linked to this tool.
- *
- * index.search(query, options?): Searches indexed document fragments.
- * Parameters:
- * query (string): The search query used for semantic search.
- * options (Object, optional):
- * filenames (Array<string>): Filter search to fragments from specific uploaded filenames.
- * limit (number): Maximum number of fragments to return (default: 10, max: 200).
- * Returns: Array<{ fragment: string, metadata: string | null }> - Ordered by relevance.
- *
- * 4. upload
- * Handles file uploads within Discourse.
- *
- * upload.create(filename, base_64_content): Uploads a file created by the tool, making it available in Discourse.
- * Parameters:
- * filename (string): The desired name for the file (basename is used for security).
- * base_64_content (string): Base64 encoded content of the file.
- * Returns: { id: number, url: string, short_url: string } - Details of the created upload record.
- *
- * upload.getUrl(shortUrl): Given a short URL, eg upload://12345, returns the full CDN friendly URL of the upload.
- * 5. chain
- * Controls the execution flow.
- *
- * chain.setCustomRaw(raw): Sets the final raw content of the bot's post and immediately
- * stops the tool execution chain. Useful for tools that directly
- * generate the full response content (e.g., image generation tools attaching the image markdown).
- * Parameters:
- * raw (string): The raw Markdown content for the post.
- * Returns: void
- *
- * 6. discourse
- * Interacts with Discourse specific features. Access is generally performed as the SystemUser.
- *
- * discourse.search(params): Performs a Discourse search.
- * Parameters:
- * params (Object): Search parameters (e.g., { search_query: "keyword", with_private: true, max_results: 10 }).
- * `with_private: true` searches across all posts visible to the SystemUser. `result_style: 'detailed'` is used by default.
- * Returns: Object (Discourse search results structure, includes posts, topics, users etc.)
- *
- * discourse.getPost(post_id): Retrieves details for a specific post.
- * Parameters:
- * post_id (number): The ID of the post.
- * Returns: Object (Post details including `raw`, nested `topic` object with ListableTopicSerializer structure) or null if not found/accessible.
- *
- * discourse.getTopic(topic_id): Retrieves details for a specific topic.
- * Parameters:
- * topic_id (number): The ID of the topic.
- * Returns: Object (Topic details using ListableTopicSerializer structure) or null if not found/accessible.
- *
- * discourse.getUser(user_id_or_username): Retrieves details for a specific user.
- * Parameters:
- * user_id_or_username (number | string): The ID or username of the user.
- * Returns: Object (User details using UserSerializer structure) or null if not found.
- *
- * discourse.getPersona(name): Gets an object representing another AI Persona configured on the site.
- * Parameters:
- * name (string): The name of the target persona.
- * Returns: Object { respondTo: function(params) } or null if persona not found.
- * respondTo(params): Instructs the target persona to generate a response within the current context (e.g., replying to the same post or chat message).
- * Parameters:
- * params (Object, optional): { instructions: string, whisper: boolean }
- * Returns: { success: boolean, post_id?: number, post_number?: number, message_id?: number } or { error: string }
- *
- * discourse.createChatMessage(params): Creates a new message in a Discourse Chat channel.
- * Parameters:
- * params (Object): { channel_name: string, username: string, message: string }
- * `channel_name` can be the channel name or slug.
- * `username` specifies the user who should appear as the sender. The user must exist.
- * The sending user must have permission to post in the channel.
- * Returns: { success: boolean, message_id?: number, message?: string, created_at?: string } or { error: string }
- *
- * 7. context
- * An object containing information about the environment where the tool is being run.
- * Available properties depend on the invocation context, but may include:
- * post_id (number): ID of the post triggering the tool (if in a Post context).
- * topic_id (number): ID of the topic (if in a Post context).
- * private_message (boolean): Whether the context is a private message (in Post context).
- * message_id (number): ID of the chat message triggering the tool (if in Chat context).
- * channel_id (number): ID of the chat channel (if in Chat context).
- * user (Object): Details of the user invoking the tool/persona (structure may vary, often null or SystemUser details unless explicitly passed).
- * participants (string): Comma-separated list of usernames in a PM (if applicable).
- * // ... other potential context-specific properties added by the calling environment.
- *
- * Constraints
- *
- * Execution Time: ≤ 2000ms (default timeout in milliseconds) - This timer *pauses* during external HTTP requests or LLM calls initiated via `http.*` or `llm.generate`, but applies to the script's own processing time.
- * Memory: ≤ 10MB (V8 heap limit)
- * Stack Depth: ≤ 20 (Marshal stack depth limit for Ruby interop)
- * HTTP Requests: ≤ 20 per execution
- * Exceeding limits will result in errors or termination (e.g., timeout error, out-of-memory error, TooManyRequestsError).
- *
- * Security
- *
- * Sandboxed Environment: The script runs in a restricted V8 JavaScript environment (via MiniRacer).
- * No direct access to browser or environment, browser globals (like `window` or `document`), or the host system's file system.
- * Network requests are proxied through the Discourse backend, not made directly from the sandbox.
- */
- JS
+ load_script("preamble.js")
end
def self.presets
+ (
+ [
+ {
+ preset_id: "browse_web_jina",
+ name: "Browse Web",
+ tool_name: "browse_web",
+ description: "Browse the web as a markdown document",
+ parameters: [
+ { name: "url", type: "string", required: true, description: "The URL to browse" },
+ ],
+ script: "#{preamble}\n#{load_script("presets/browse_web_jina.js")}",
+ },
+ {
+ preset_id: "exchange_rate",
+ name: "Exchange Rate",
+ tool_name: "exchange_rate",
+ description: "Get current exchange rates for various currencies",
+ parameters: [
+ {
+ name: "base_currency",
+ type: "string",
+ required: true,
+ description: "The base currency code (e.g., USD, EUR)",
+ },
+ {
+ name: "target_currency",
+ type: "string",
+ required: true,
+ description: "The target currency code (e.g., EUR, JPY)",
+ },
+ { name: "amount", type: "number", description: "Amount to convert eg: 123.45" },
+ ],
+ script: "#{preamble}\n#{load_script("presets/exchange_rate.js")}",
+ summary: "Get current exchange rates between two currencies",
+ },
+ {
+ preset_id: "stock_quote",
+ name: "Stock Quote (AlphaVantage)",
+ tool_name: "stock_quote",
+ description: "Get real-time stock quote information using AlphaVantage API",
+ parameters: [
+ {
+ name: "symbol",
+ type: "string",
+ required: true,
+ description: "The stock symbol (e.g., AAPL, GOOGL)",
+ },
+ ],
+ script: "#{preamble}\n#{load_script("presets/stock_quote.js")}",
+ summary: "Get real-time stock quotes using AlphaVantage API",
+ },
+ ] + image_generation_presets +
+ [
+ {
+ preset_id: "empty_tool",
+ script: "#{preamble}\n#{load_script("presets/empty_tool.js")}",
+ },
+ ]
+ ).map do |preset|
+ preset[:preset_name] = I18n.t("discourse_ai.tools.presets.#{preset[:preset_id]}.name")
+ preset
+ end
+ end
+
+ def self.image_generation_presets
[
+ { preset_id: "image_generation_category", is_category: true, category: "image_generation" },
{
- preset_id: "browse_web_jina",
- name: "Browse Web",
- tool_name: "browse_web",
- description: "Browse the web as a markdown document",
+ preset_id: "image_generation_custom",
+ name: "Custom",
+ tool_name: "image_generation_custom",
+ description: "Configure a custom image generation API",
parameters: [
- { name: "url", type: "string", required: true, description: "The URL to browse" },
+ {
+ name: "prompt",
+ type: "string",
+ required: true,
+ description: "The text prompt for image generation",
+ },
],
- script: <<~SCRIPT,
- #{preamble}
- let url;
- function invoke(p) {
- url = p.url;
- result = http.get(`https://r.jina.ai/${url}`);
- // truncates to 15000 tokens
- return llm.truncate(result.body, 15000);
- }
- function details() {
- return "Read: " + url
- }
- SCRIPT
+ script: "#{preamble}\n#{load_script("presets/image_generation/custom.js")}",
+ summary: "Custom image generation",
+ category: "image_generation",
},
{
- preset_id: "exchange_rate",
- name: "Exchange Rate",
- tool_name: "exchange_rate",
- description: "Get current exchange rates for various currencies",
+ preset_id: "image_generation_openai",
+ name: "GPT Image",
+ provider: "OpenAI",
+ model_name: "GPT Image 1",
+ tool_name: "image_generation_openai",
+ description: "Generate images using OpenAI's GPT Image 1 model",
parameters: [
{
- name: "base_currency",
+ name: "prompt",
type: "string",
required: true,
- description: "The base currency code (e.g., USD, EUR)",
+ description: "The text prompt for image generation",
},
{
- name: "target_currency",
+ name: "size",
type: "string",
- required: true,
- description: "The target currency code (e.g., EUR, JPY)",
+ required: false,
+ description: "Image size (1024x1024, 1792x1024, or 1024x1792)",
},
- { name: "amount", type: "number", description: "Amount to convert eg: 123.45" },
],
- script: <<~SCRIPT,
- #{preamble}
- // note: this script uses the open.er-api.com service, it is only updated
- // once every 24 hours, for more up to date rates see: https://www.exchangerate-api.com
- function invoke(params) {
- const url = `https://open.er-api.com/v6/latest/${params.base_currency}`;
- const result = http.get(url);
- if (result.status !== 200) {
- return { error: "Failed to fetch exchange rates" };
- }
- const data = JSON.parse(result.body);
- const rate = data.rates[params.target_currency];
- if (!rate) {
- return { error: "Target currency not found" };
- }
-
- const rval = {
- base_currency: params.base_currency,
- target_currency: params.target_currency,
- exchange_rate: rate,
- last_updated: data.time_last_update_utc
- };
-
- if (params.amount) {
- rval.original_amount = params.amount;
- rval.converted_amount = params.amount * rate;
- }
-
- return rval;
- }
-
- function details() {
- return "<a href='https://www.exchangerate-api.com'>Rates By Exchange Rate API</a>";
- }
- SCRIPT
- summary: "Get current exchange rates between two currencies",
+ script: "#{preamble}\n#{load_script("presets/image_generation/openai.js")}",
+ summary: "Generate images with OpenAI GPT Image 1 model",
+ category: "image_generation",
},
{
- preset_id: "stock_quote",
- name: "Stock Quote (AlphaVantage)",
- tool_name: "stock_quote",
- description: "Get real-time stock quote information using AlphaVantage API",
+ preset_id: "image_generation_gemini",
+ name: "Nano Banana",
+ provider: "Google Nano Banana",
+ model_name: "Gemini 2.5 Flash Image",
+ tool_name: "image_generation_gemini",
+ description: "Generate images using Gemini 2.5 Flash Image (Nano Banana)",
parameters: [
{
- name: "symbol",
+ name: "prompt",
type: "string",
required: true,
- description: "The stock symbol (e.g., AAPL, GOOGL)",
+ description: "The text prompt for image generation",
},
],
- script: <<~SCRIPT,
- #{preamble}
- function invoke(params) {
- const apiKey = 'YOUR_ALPHAVANTAGE_API_KEY'; // Replace with your actual API key
- const url = `https://www.alphavantage.co/query?function=GLOBAL_QUOTE&symbol=${params.symbol}&apikey=${apiKey}`;
-
- const result = http.get(url);
- if (result.status !== 200) {
- return { error: "Failed to fetch stock quote" };
- }
-
- const data = JSON.parse(result.body);
- if (data['Error Message']) {
- return { error: data['Error Message'] };
- }
-
- const quote = data['Global Quote'];
- if (!quote || Object.keys(quote).length === 0) {
- return { error: "No data found for the given symbol" };
- }
-
- return {
- symbol: quote['01. symbol'],
- price: parseFloat(quote['05. price']),
- change: parseFloat(quote['09. change']),
- change_percent: quote['10. change percent'],
- volume: parseInt(quote['06. volume']),
- latest_trading_day: quote['07. latest trading day']
- };
- }
-
- function details() {
- return "<a href='https://www.alphavantage.co'>Stock data provided by AlphaVantage</a>";
- }
- SCRIPT
- summary: "Get real-time stock quotes using AlphaVantage API",
+ script: "#{preamble}\n#{load_script("presets/image_generation/gemini.js")}",
+ summary: "Generate images with Gemini 2.5 Flash Image",
+ category: "image_generation",
},
{
- preset_id: "image_generation",
- name: "Image Generation (Flux)",
+ preset_id: "image_generation_flux",
+ name: "FLUX",
+ provider: "Together.ai",
+ model_name: "FLUX 1.1",
tool_name: "image_generation",
description:
- "Generate images using the FLUX model from Black Forest Labs using together.ai",
+ "Generate images using the FLUX 1.1 Pro model from Black Forest Labs via Together.ai",
parameters: [
{
name: "prompt",
@@ -400,65 +260,11 @@ class AiTool < ActiveRecord::Base
description: "Optional seed for random number generation",
},
],
- script: <<~SCRIPT,
- #{preamble}
- const apiKey = "YOUR_KEY";
- const model = "black-forest-labs/FLUX.1.1-pro";
-
- function invoke(params) {
- let seed = parseInt(params.seed);
- if (!(seed > 0)) {
- seed = Math.floor(Math.random() * 1000000) + 1;
- }
-
- const prompt = params.prompt;
- const body = {
- model: model,
- prompt: prompt,
- width: 1024,
- height: 768,
- steps: 10,
- n: 1,
- seed: seed,
- response_format: "b64_json",
- };
-
- const result = http.post("https://api.together.xyz/v1/images/generations", {
- headers: {
- "Authorization": `Bearer ${apiKey}`,
- "Content-Type": "application/json",
- },
- body: JSON.stringify(body),
- });
-
- const base64Image = JSON.parse(result.body).data[0].b64_json;
- const image = upload.create("generated_image.png", base64Image);
- const raw = `\n![${prompt}](${image.short_url})\n`;
- chain.setCustomRaw(raw);
-
- return { result: "Image generated successfully", seed: seed };
- }
-
- function details() {
- return "Generates images based on a text prompt using the FLUX model.";
- }
- SCRIPT
- summary: "Generate image",
+ script: "#{preamble}\n#{load_script("presets/image_generation/flux.js")}",
+ summary: "Generate images with FLUX 1.1 Pro",
+ category: "image_generation",
},
- { preset_id: "empty_tool", script: <<~SCRIPT },
- #{preamble}
- function invoke(params) {
- // logic here
- return params;
- }
- function details() {
- return "Details about this tool";
- }
- SCRIPT
- ].map do |preset|
- preset[:preset_name] = I18n.t("discourse_ai.tools.presets.#{preset[:preset_id]}.name")
- preset
- end
+ ]
end
end
@@ -469,6 +275,7 @@ end
# id :bigint not null, primary key
# description :string not null
# enabled :boolean default(TRUE), not null
+# is_image_generation_tool :boolean default(FALSE), not null
# name :string not null
# parameters :jsonb not null
# rag_chunk_overlap_tokens :integer default(10), not null
diff --git a/plugins/discourse-ai/app/services/discourse_ai/ai_helper/generate_thumbnails.rb b/plugins/discourse-ai/app/services/discourse_ai/ai_helper/generate_thumbnails.rb
new file mode 100644
index 00000000000..0923fef0f3f
--- /dev/null
+++ b/plugins/discourse-ai/app/services/discourse_ai/ai_helper/generate_thumbnails.rb
@@ -0,0 +1,100 @@
+# frozen_string_literal: true
+
+module DiscourseAi
+ module AiHelper
+ class GenerateThumbnails
+ include Service::Base
+
+ params do
+ attribute :text, :string
+
+ validates :text, presence: true
+ validates :text, length: { maximum: 10_000 }
+ end
+
+ model :persona
+ policy :has_image_generation_tool
+ model :llm_model
+ step :generate_images
+ step :parse_uploads
+ step :serialize_thumbnails
+
+ private
+
+ def fetch_persona
+ persona_id = SiteSetting.ai_helper_post_illustrator_persona
+ AiPersona.find_by(id: persona_id)
+ end
+
+ def has_image_generation_tool(persona:)
+ persona.has_image_generation_tool?
+ end
+
+ def fetch_llm_model(persona:)
+ model =
+ LlmModel.find_by(id: persona.default_llm_id) ||
+ LlmModel.find_by(id: SiteSetting.ai_default_llm_model)
+ fail!("llm_model_not_configured") if model.nil?
+ model
+ end
+
+ def generate_images(persona:, llm_model:, params:, guardian:)
+ bot =
+ DiscourseAi::Personas::Bot.as(
+ guardian.user,
+ persona: persona.class_instance.new,
+ model: llm_model,
+ )
+
+ bot_context =
+ DiscourseAi::Personas::BotContext.new(
+ user: guardian.user,
+ feature_name: "illustrate_post",
+ messages: [{ type: :user, content: params.text }],
+ )
+
+ captured_custom_raw = nil
+
+ bot.reply(bot_context) do |partial, custom_raw, type|
+ # Bot calls callback twice with custom_raw:
+ # 1. During invoke: ("", custom_raw_value, :partial_invoke) - custom_raw in 2nd param
+ # 2. After invoke: (custom_raw_value, nil, :custom_raw) - custom_raw in 1st param
+ if type == :partial_invoke || type == :custom_raw
+ captured_value = type == :partial_invoke ? custom_raw : partial
+ captured_custom_raw = captured_value if captured_value.present?
+ end
+ end
+
+ context[:captured_custom_raw] = captured_custom_raw
+ fail!("no_image_generated") if captured_custom_raw.blank?
+ rescue => e
+ Rails.logger.error(
+ "Image generation failed: #{e.class} - #{e.message}\n#{e.backtrace.first(5).join("\n")}",
+ )
+ fail!("no_image_generated")
+ end
+
+ def parse_uploads
+ captured_custom_raw = context[:captured_custom_raw]
+ upload_short_urls = captured_custom_raw.scan(%r{upload://[a-zA-Z0-9]+(?:\.[a-zA-Z0-9]+)?})
+
+ context[:upload_short_urls] = upload_short_urls
+ fail!("no_image_generated") if upload_short_urls.blank?
+ end
+
+ def serialize_thumbnails
+ upload_short_urls = context[:upload_short_urls]
+
+ thumbnails =
+ upload_short_urls
+ .map do |short_url|
+ upload = Upload.find_by(sha1: Upload.sha1_from_short_url(short_url))
+ UploadSerializer.new(upload, root: false).as_json if upload
+ end
+ .compact
+
+ context[:thumbnails] = thumbnails
+ end
+ end
+ end
+end
diff --git a/plugins/discourse-ai/assets/javascripts/discourse/components/ai-tool-list-editor.gjs b/plugins/discourse-ai/assets/javascripts/discourse/components/ai-tool-list-editor.gjs
index 59a1b4ee12d..dc2422f2141 100644
--- a/plugins/discourse-ai/assets/javascripts/discourse/components/ai-tool-list-editor.gjs
+++ b/plugins/discourse-ai/assets/javascripts/discourse/components/ai-tool-list-editor.gjs
@@ -1,5 +1,7 @@
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 { LinkTo } from "@ember/routing";
import { service } from "@ember/service";
@@ -21,18 +23,63 @@ export default class AiToolListEditor extends Component {
@service router;
@service dialog;
+ @tracked expandedCategory = null;
+
+ get dropdownPresets() {
+ return this.args.tools.resultSetMeta.presets.filter((preset) => {
+ // Filter out individual image generation presets, keep only the category
+ return !preset.category || preset.is_category;
+ });
+ }
+
+ get categoryPresets() {
+ if (!this.expandedCategory) {
+ return [];
+ }
+
+ const presets = this.args.tools.resultSetMeta.presets.filter(
+ (preset) =>
+ preset.category === this.expandedCategory && !preset.is_category
+ );
+
+ // Separate "Custom" from others
+ const customPreset = presets.find(
+ (p) => p.preset_id === "image_generation_custom"
+ );
+ const otherPresets = presets
+ .filter((p) => p.preset_id !== "image_generation_custom")
+ .sort((a, b) => a.provider.localeCompare(b.provider));
+
+ return { otherPresets, customPreset };
+ }
+
get lastIndexOfPresets() {
- return this.args.tools.resultSetMeta.presets.length - 1;
+ return this.dropdownPresets.length - 1;
+ }
+
+ @action
+ expandCategory(preset) {
+ this.expandedCategory = preset.category;
+ }
+
+ @action
+ collapseCategory() {
+ this.expandedCategory = null;
+ }
+
+ @action
+ resetMenuState() {
+ this.expandedCategory = null;
}
@action
routeToNewTool(preset) {
+ const queryParams = { presetId: preset.preset_id };
+
return this.router.transitionTo(
"adminPlugins.show.discourse-ai-tools.new",
{
- queryParams: {
- presetId: preset.preset_id,
- },
+ queryParams,
}
);
}
@@ -131,23 +178,72 @@ export default class AiToolListEditor extends Component {
@label={{i18n "discourse_ai.tools.new"}}
@icon="plus"
@placement="bottom-end"
+ @onClose={{this.resetMenuState}}
>
<:content>
<DropdownMenu as |dropdown|>
- {{#each @tools.resultSetMeta.presets as |preset index|}}
- {{#if (eq index this.lastIndexOfPresets)}}
- <dropdown.divider />
- {{/if}}
-
+ {{#if this.expandedCategory}}
<dropdown.item>
<DButton
- @translatedLabel={{preset.preset_name}}
- @action={{fn this.routeToNewTool preset}}
+ @label="back_button"
+ @icon="chevron-left"
+ @action={{this.collapseCategory}}
class="btn-transparent"
- data-option={{preset.preset_id}}
/>
</dropdown.item>
- {{/each}}
+ <dropdown.divider />
+ {{#each this.categoryPresets.otherPresets as |preset|}}
+ <dropdown.item>
+ <div
+ role="button"
+ class="ai-tool-preset-item"
+ data-option={{preset.preset_id}}
+ {{on "click" (fn this.routeToNewTool preset)}}
+ >
+ <span
+ class="ai-tool-preset-provider"
+ >{{preset.provider}}</span>
+ <span
+ class="ai-tool-preset-model"
+ >{{preset.model_name}}</span>
+ </div>
+ </dropdown.item>
+ {{/each}}
+
+ {{#if this.categoryPresets.customPreset}}
+ <dropdown.divider />
+ <dropdown.item>
+ <DButton
+ @translatedLabel={{this.categoryPresets.customPreset.preset_name}}
+ @action={{fn
+ this.routeToNewTool
+ this.categoryPresets.customPreset
+ }}
+ class="btn-transparent"
+ data-option={{this.categoryPresets.customPreset.preset_id}}
+ />
+ </dropdown.item>
+ {{/if}}
+ {{else}}
+ {{#each this.dropdownPresets as |preset index|}}
+ {{#if (eq index this.lastIndexOfPresets)}}
+ <dropdown.divider />
+ {{/if}}
+
+ <dropdown.item>
+ <DButton
+ @translatedLabel={{preset.preset_name}}
+ @action={{if
+ preset.is_category
+ (fn this.expandCategory preset)
+ (fn this.routeToNewTool preset)
+ }}
+ class="btn-transparent"
+ data-option={{preset.preset_id}}
+ />
+ </dropdown.item>
+ {{/each}}
+ {{/if}}
</DropdownMenu>
</:content>
diff --git a/plugins/discourse-ai/assets/stylesheets/modules/ai-bot/common/ai-tools.scss b/plugins/discourse-ai/assets/stylesheets/modules/ai-bot/common/ai-tools.scss
index acbe5d8cb8a..0d1e7a0a953 100644
--- a/plugins/discourse-ai/assets/stylesheets/modules/ai-bot/common/ai-tools.scss
+++ b/plugins/discourse-ai/assets/stylesheets/modules/ai-bot/common/ai-tools.scss
@@ -62,3 +62,83 @@
}
}
}
+
+.ai-tool-editor__templates {
+ &-list {
+ display: grid;
+ grid-template-columns: repeat(auto-fill, minmax(16em, 1fr));
+ gap: 1em 2em;
+ margin-top: 1em;
+ padding-top: 1em;
+ border-top: 3px solid var(--primary-low);
+ }
+
+ &-list-item {
+ display: grid;
+ grid-template-rows: subgrid;
+ grid-row: span 4;
+ gap: 0;
+ margin-bottom: 2em;
+
+ @include viewport.from(sm) {
+ margin-bottom: 3em;
+ }
+ }
+
+ .admin-section-landing-item__description {
+ color: var(--primary-high);
+ margin: 0.25em 0 0.5em;
+ line-height: var(--line-height-large);
+ align-self: start;
+
+ @include viewport.from(sm) {
+ max-width: 17em;
+ }
+ }
+
+ button {
+ justify-self: start;
+ }
+
+ h4 {
+ font-size: var(--font-down-1);
+ font-weight: normal;
+ color: var(--primary-high);
+ margin: 0;
+ letter-spacing: 0.1px;
+ }
+}
+
+.ai-tool-preset-item {
+ display: flex;
+ flex-direction: column;
+ align-items: flex-start;
+ gap: 0.25em;
+ padding: 0.5em 0.75em;
+ cursor: pointer;
+ width: 100%;
+ box-sizing: border-box;
+ border-radius: var(--d-border-radius);
+ transition: background-color 0.15s ease-in-out;
+
+ &:hover {
+ background-color: var(--d-hover);
+ }
+
+ &:active {
+ background-color: var(--d-selected);
+ }
+
+ .ai-tool-preset-provider {
+ font-size: var(--font-down-1);
+ color: var(--primary-high);
+ line-height: 1.2;
+ }
+
+ .ai-tool-preset-model {
+ font-size: var(--font-0);
+ color: var(--primary);
+ line-height: 1.2;
+ font-weight: 500;
+ }
+}
diff --git a/plugins/discourse-ai/config/locales/client.en.yml b/plugins/discourse-ai/config/locales/client.en.yml
index 4100011769c..d298a8c6180 100644
--- a/plugins/discourse-ai/config/locales/client.en.yml
+++ b/plugins/discourse-ai/config/locales/client.en.yml
@@ -298,6 +298,7 @@ en:
custom_prompt: "Custom prompt"
image_caption: "Caption images"
translator: "Translator"
+ post_illustrator: "Post illustrator"
translation:
name: "Translation"
diff --git a/plugins/discourse-ai/config/locales/server.en.yml b/plugins/discourse-ai/config/locales/server.en.yml
index c456b4de36f..ea5f6da3f20 100644
--- a/plugins/discourse-ai/config/locales/server.en.yml
+++ b/plugins/discourse-ai/config/locales/server.en.yml
@@ -92,6 +92,7 @@ en:
ai_helper_enabled_features: "Select the features to enable in the AI helper."
post_ai_helper_allowed_groups: "User groups allowed to access AI Helper features in posts"
ai_helper_image_caption_model: "Select the model to use for generating image captions"
+ ai_helper_post_illustrator_persona: "The persona to use for the AI helper's illustrate post feature. Note: you must also create an image generation tool (Admin > Plugins > Discourse AI > Tools) for this feature to work."
ai_embeddings_selected_model: "Use the selected model for generating embeddings."
ai_embeddings_generate_for_pms: "Generate embeddings for personal messages."
@@ -272,8 +273,16 @@ en:
name: "Exchange rate"
stock_quote:
name: "Stock quote (AlphaVantage)"
- image_generation:
- name: "Flux image generator (Together.ai)"
+ image_generation_category:
+ name: "Image generation..."
+ image_generation_custom:
+ name: "Custom"
+ image_generation_openai:
+ name: "OpenAI"
+ image_generation_gemini:
+ name: "Nano Banana"
+ image_generation_flux:
+ name: "FLUX"
empty_tool:
name: "Start from blank..."
name:
@@ -284,6 +293,11 @@ en:
completion_request_failed: "Something went wrong while trying to provide suggestions. Please, try again."
credit_limit_exceeded_user: "You've hit the AI credit limit for your plan. Responses will be unavailable until your limit resets %{reset_time}."
credit_limit_exceeded_bot: "AI responses are currently unavailable due to credit limits. Please try again %{reset_time}."
+ no_illustrator_persona: "Post Illustrator persona is not configured. Please check your site settings."
+ no_image_generation_tool: "Post Illustrator persona must have an image generation tool attached. Please configure an image generation tool for this persona in the admin panel."
+ no_image_generated: "Failed to generate image. Please try again or check your tool configuration."
+ llm_model_not_configured: "No language model is configured for image generation. Please configure a default language model in your site settings."
+ unknown_error: "An unexpected error occurred while generating thumbnails. Please try again."
prompts:
translate: Translate to %{language}
generate_titles: Suggest topic titles
@@ -293,10 +307,6 @@ en:
explain: "Explain"
illustrate_post: "Illustrate Post"
replace_dates: "Smart dates"
- painter:
- attribution:
- stable_diffusion_xl: "Image by Stable Diffusion XL"
- dall_e_3: "Image by DALL-E 3"
image_caption:
attribution: "Captioned by AI"
@@ -391,7 +401,7 @@ en:
description: "Default persona powering the Helper's generate Markdown table feature"
post_illustrator:
name: "Post illustrator"
- description: "Generates StableDiffusion prompts to power the Helper's illustrate post feature"
+ description: "Generates images to illustrate posts using available image generation tools"
proofreader:
name: "Proofreader"
description: "Default persona powering the Helper's proofread text feature"
diff --git a/plugins/discourse-ai/config/settings.yml b/plugins/discourse-ai/config/settings.yml
index c9c249a2be5..02e49b1bb9d 100644
--- a/plugins/discourse-ai/config/settings.yml
+++ b/plugins/discourse-ai/config/settings.yml
@@ -138,7 +138,7 @@ discourse_ai:
ai_helper_automatic_chat_thread_title_delay:
default: 5
area: "ai-features/ai_helper"
- ai_helper_illustrate_post_model:
+ ai_helper_illustrate_post_model: # Deprecated. TODO(keegan): Remove 2025-12-01
default: disabled
type: enum
choices:
@@ -146,6 +146,7 @@ discourse_ai:
- dall_e_3
- disabled
area: "ai-features/ai_helper"
+ hidden: true
ai_helper_enabled_features:
client: true
default: "suggestions|context_menu"
diff --git a/plugins/discourse-ai/db/migrate/20251113174112_update_post_illustrator_system_prompt.rb b/plugins/discourse-ai/db/migrate/20251113174112_update_post_illustrator_system_prompt.rb
new file mode 100644
index 00000000000..505f81697b8
--- /dev/null
+++ b/plugins/discourse-ai/db/migrate/20251113174112_update_post_illustrator_system_prompt.rb
@@ -0,0 +1,50 @@
+# frozen_string_literal: true
+
+class UpdatePostIllustratorSystemPrompt < ActiveRecord::Migration[7.1]
+ def up
+ # Update the PostIllustrator persona's system_prompt to match the new class definition
+ # This ensures the admin UI displays the correct prompt
+ persona = DB.query_single("SELECT id FROM ai_personas WHERE id = -21").first
+
+ if persona
+ new_system_prompt = <<~PROMPT.strip
+ You are an AI assistant that creates images to illustrate posts.
+
+ Your task is to analyze the post content provided in <input></input> tags and generate an appropriate image using your image generation tool.
+
+ Create a creative and descriptive image generation prompt (40 words or less) that captures the essence of the post content, then use your image generation tool to create the image.
+
+ Be creative and ensure the image prompt is clear, detailed, and appropriate for the post content.
+ PROMPT
+
+ DB.exec(
+ "UPDATE ai_personas SET system_prompt = :system_prompt WHERE id = -21",
+ system_prompt: new_system_prompt,
+ )
+ end
+ end
+
+ def down
+ persona = DB.query_single("SELECT id FROM ai_personas WHERE id = -21").first
+
+ if persona
+ old_system_prompt = <<~PROMPT.strip
+ Provide me a StableDiffusion prompt to generate an image that illustrates the following post in 40 words or less, be creative.
+ You'll find the post between <input></input> XML tags.
+
+ Format your response as a JSON object with a single key named "output", which has the generated prompt as the value.
+ Your output should be in the following format:
+
+ {"output": "xx"}
+
+ Where "xx" is replaced by the generated prompt.
+ reply with valid JSON only
+ PROMPT
+
+ DB.exec(
+ "UPDATE ai_personas SET system_prompt = :system_prompt WHERE id = -21",
+ system_prompt: old_system_prompt,
+ )
+ end
+ end
+end
diff --git a/plugins/discourse-ai/db/migrate/20251113174215_add_is_image_generation_tool_to_ai_tools.rb b/plugins/discourse-ai/db/migrate/20251113174215_add_is_image_generation_tool_to_ai_tools.rb
new file mode 100644
index 00000000000..b55bcbe61ae
--- /dev/null
+++ b/plugins/discourse-ai/db/migrate/20251113174215_add_is_image_generation_tool_to_ai_tools.rb
@@ -0,0 +1,21 @@
+# frozen_string_literal: true
+
+class AddIsImageGenerationToolToAiTools < ActiveRecord::Migration[7.1]
+ def up
+ add_column :ai_tools, :is_image_generation_tool, :boolean, default: false, null: false
+
+ # Backfill existing tools
+ execute <<~SQL
+ UPDATE ai_tools
+ SET is_image_generation_tool = true
+ WHERE enabled = true
+ AND parameters::text LIKE '%"name":"prompt"%'
+ AND script LIKE '%upload.create%'
+ AND script LIKE '%chain.setCustomRaw%'
+ SQL
+ end
+
+ def down
+ remove_column :ai_tools, :is_image_generation_tool
+ end
+end
diff --git a/plugins/discourse-ai/lib/ai_bot.rb b/plugins/discourse-ai/lib/ai_bot.rb
new file mode 100644
index 00000000000..999f646ef3a
--- /dev/null
+++ b/plugins/discourse-ai/lib/ai_bot.rb
@@ -0,0 +1,9 @@
+# frozen_string_literal: true
+
+module DiscourseAi
+ module AiBot
+ USER_AGENT = "Discourse AI Bot 1.0 (https://www.discourse.org)"
+ TOPIC_AI_BOT_PM_FIELD = "is_ai_bot_pm"
+ POST_AI_LLM_NAME_FIELD = "ai_llm_name"
+ end
+end
diff --git a/plugins/discourse-ai/lib/ai_bot/entry_point.rb b/plugins/discourse-ai/lib/ai_bot/entry_point.rb
index 5bb16aaf5df..4c628ba3e01 100644
--- a/plugins/discourse-ai/lib/ai_bot/entry_point.rb
+++ b/plugins/discourse-ai/lib/ai_bot/entry_point.rb
@@ -2,10 +2,6 @@
module DiscourseAi
module AiBot
- USER_AGENT = "Discourse AI Bot 1.0 (https://www.discourse.org)"
- TOPIC_AI_BOT_PM_FIELD = "is_ai_bot_pm"
- POST_AI_LLM_NAME_FIELD = "ai_llm_name"
-
class EntryPoint
Bot = Struct.new(:id, :name, :llm)
diff --git a/plugins/discourse-ai/lib/ai_helper/assistant.rb b/plugins/discourse-ai/lib/ai_helper/assistant.rb
index 7306f7fcee6..41c2d703272 100644
--- a/plugins/discourse-ai/lib/ai_helper/assistant.rb
+++ b/plugins/discourse-ai/lib/ai_helper/assistant.rb
@@ -36,9 +36,9 @@ module DiscourseAi
.map do |prompt|
next if !user.in_any_groups?(prompt[:allowed_group_ids])
- if prompt[:name] == ILLUSTRATE_POST &&
- SiteSetting.ai_helper_illustrate_post_model == "disabled"
- next
+ if prompt[:name] == ILLUSTRATE_POST
+ persona = AiPersona.find_by(id: SiteSetting.ai_helper_post_illustrator_persona)
+ next if persona.blank? || !persona_has_image_generation_tool?(persona)
end
# We cannot cache this. It depends on the user's effective_locale.
@@ -289,6 +289,15 @@ module DiscourseAi
private
+ def persona_has_image_generation_tool?(persona)
+ persona&.has_image_generation_tool?
+ rescue StandardError => e
+ Rails.logger.warn(
+ "Failed to check image generation tool for persona #{persona&.id}: #{e.message}",
+ )
+ false
+ end
+
def build_bot(helper_mode, user)
persona_id = personas_prompt_map(include_image_caption: true).invert[helper_mode]
raise Discourse::InvalidParameters.new(:mode) if persona_id.blank?
diff --git a/plugins/discourse-ai/lib/ai_helper/painter.rb b/plugins/discourse-ai/lib/ai_helper/painter.rb
deleted file mode 100644
index 37ff3c60824..00000000000
--- a/plugins/discourse-ai/lib/ai_helper/painter.rb
+++ /dev/null
@@ -1,96 +0,0 @@
-# frozen_string_literal: true
-
-module DiscourseAi
- module AiHelper
- class Painter
- def commission_thumbnails(input, user)
- return [] if input.blank?
-
- model = SiteSetting.ai_helper_illustrate_post_model
-
- if model == "stable_diffusion_xl"
- stable_diffusion_prompt = diffusion_prompt(input, user)
- return [] if stable_diffusion_prompt.blank?
-
- artifacts =
- DiscourseAi::Inference::StabilityGenerator
- .perform!(stable_diffusion_prompt)
- .dig(:artifacts)
- .to_a
- .map { |art| art[:base64] }
-
- base64_to_image(artifacts, user.id)
- elsif model == "dall_e_3"
- llm_model = find_llm_model_for_feature("illustrate_post")
- LlmCreditAllocation.check_credits!(llm_model) if llm_model
-
- attribution =
- I18n.t(
- "discourse_ai.ai_helper.painter.attribution.#{SiteSetting.ai_helper_illustrate_post_model}",
- )
- results =
- DiscourseAi::Inference::OpenAiImageGenerator.create_uploads!(
- input,
- model: "dall-e-3",
- user_id: user.id,
- title: attribution,
- )
- results.map { |result| UploadSerializer.new(result[:upload], root: false) }
- end
- end
-
- private
-
- def find_llm_model_for_feature(feature_name)
- persona_id = SiteSetting.ai_helper_post_illustrator_persona
- return nil if persona_id.blank?
-
- persona = AiPersona.find_by(id: persona_id)
- return nil if persona.blank?
-
- LlmModel.find_by(id: persona.default_llm_id)
- end
-
- def base64_to_image(artifacts, user_id)
- attribution =
- I18n.t(
- "discourse_ai.ai_helper.painter.attribution.#{SiteSetting.ai_helper_illustrate_post_model}",
- )
-
- artifacts.each_with_index.map do |art, i|
- f = Tempfile.new("v1_txt2img_#{i}.png")
- f.binmode
- f.write(Base64.decode64(art))
- f.rewind
- upload = UploadCreator.new(f, attribution).create_for(user_id)
- f.unlink
-
- UploadSerializer.new(upload, root: false)
- end
- end
-
- def diffusion_prompt(text, user)
- llm_model =
- AiPersona.find_by(id: SiteSetting.ai_helper_post_illustrator_persona)&.default_llm_id ||
- SiteSetting.ai_default_llm_model
-
- return nil if llm_model.blank?
-
- prompt =
- DiscourseAi::Completions::Prompt.new(
- <<~TEXT.strip,
- Provide me a StableDiffusion prompt to generate an image that illustrates the following post in 40 words or less, be creative.
- You'll find the post between <input></input> XML tags.
- TEXT
- messages: [{ type: :user, content: text, id: user.username }],
- )
-
- DiscourseAi::Completions::Llm.proxy(llm_model).generate(
- prompt,
- user: user,
- feature_name: "illustrate_post",
- )
- end
- end
- end
-end
diff --git a/plugins/discourse-ai/lib/ai_tool_scripts/preamble.js b/plugins/discourse-ai/lib/ai_tool_scripts/preamble.js
new file mode 100644
index 00000000000..7ab296aaf9b
--- /dev/null
+++ b/plugins/discourse-ai/lib/ai_tool_scripts/preamble.js
@@ -0,0 +1,161 @@
+/**
+ * Tool API Quick Reference
+ *
+ * Entry Functions
+ *
+ * invoke(parameters): Main function. Receives parameters defined in the tool's signature (Object).
+ * Must return a JSON-serializable value (e.g., string, number, object, array).
+ * Example:
+ * function invoke(parameters) { return { result: "Data processed", input: parameters.query }; }
+ *
+ * details(): Optional function. Returns a string (can include basic HTML) describing
+ * the tool's action after invocation, often using data from the invocation.
+ * This is displayed in the chat interface.
+ * Example:
+ * let lastUrl;
+ * function invoke(parameters) {
+ * lastUrl = parameters.url;
+ * // ... perform action ...
+ * return { success: true, content: "..." };
+ * }
+ * function details() {
+ * return `Browsed: <a href="${lastUrl}">${lastUrl}</a>`;
+ * }
+ *
+ * Provided Objects & Functions
+ *
+ * 1. http
+ * Performs HTTP requests. Max 20 requests per execution.
+ *
+ * http.get(url, options?): Performs GET request.
+ * Parameters:
+ * url (string): The request URL.
+ * options (Object, optional):
+ * headers (Object): Request headers (e.g., { "Authorization": "Bearer key" }).
+ * Returns: { status: number, body: string }
+ *
+ * http.post(url, options?): Performs POST request.
+ * Parameters:
+ * url (string): The request URL.
+ * options (Object, optional):
+ * headers (Object): Request headers.
+ * body (string | Object): Request body. If an object, it's stringified as JSON.
+ * Returns: { status: number, body: string }
+ *
+ * http.put(url, options?): Performs PUT request (similar to POST).
+ * http.patch(url, options?): Performs PATCH request (similar to POST).
+ * http.delete(url, options?): Performs DELETE request (similar to GET/POST).
+ *
+ * 2. llm
+ * Interacts with the Language Model.
+ *
+ * llm.truncate(text, length): Truncates text to a specified token length based on the configured LLM's tokenizer.
+ * Parameters:
+ * text (string): Text to truncate.
+ * length (number): Maximum number of tokens.
+ * Returns: string (truncated text)
+ *
+ * llm.generate(prompt): Generates text using the configured LLM associated with the tool runner.
+ * Parameters:
+ * prompt (string | Object): The prompt. Can be a simple string or an object
+ * like { messages: [{ type: "system", content: "..." }, { type: "user", content: "..." }] }.
+ * Returns: string (generated text)
+ *
+ * 3. index
+ * Searches attached RAG (Retrieval-Augmented Generation) documents linked to this tool.
+ *
+ * index.search(query, options?): Searches indexed document fragments.
+ * Parameters:
+ * query (string): The search query used for semantic search.
+ * options (Object, optional):
+ * filenames (Array<string>): Filter search to fragments from specific uploaded filenames.
+ * limit (number): Maximum number of fragments to return (default: 10, max: 200).
+ * Returns: Array<{ fragment: string, metadata: string | null }> - Ordered by relevance.
+ *
+ * 4. upload
+ * Handles file uploads within Discourse.
+ *
+ * upload.create(filename, base_64_content): Uploads a file created by the tool, making it available in Discourse.
+ * Parameters:
+ * filename (string): The desired name for the file (basename is used for security).
+ * base_64_content (string): Base64 encoded content of the file.
+ * Returns: { id: number, url: string, short_url: string } - Details of the created upload record.
+ *
+ * upload.getUrl(shortUrl): Given a short URL, eg upload://12345, returns the full CDN friendly URL of the upload.
+ * 5. chain
+ * Controls the execution flow.
+ *
+ * chain.setCustomRaw(raw): Sets the final raw content of the bot's post and immediately
+ * stops the tool execution chain. Useful for tools that directly
+ * generate the full response content (e.g., image generation tools attaching the image markdown).
+ * Parameters:
+ * raw (string): The raw Markdown content for the post.
+ * Returns: void
+ *
+ * 6. discourse
+ * Interacts with Discourse specific features. Access is generally performed as the SystemUser.
+ *
+ * discourse.search(params): Performs a Discourse search.
+ * Parameters:
+ * params (Object): Search parameters (e.g., { search_query: "keyword", with_private: true, max_results: 10 }).
+ * `with_private: true` searches across all posts visible to the SystemUser. `result_style: 'detailed'` is used by default.
+ * Returns: Object (Discourse search results structure, includes posts, topics, users etc.)
+ *
+ * discourse.getPost(post_id): Retrieves details for a specific post.
+ * Parameters:
+ * post_id (number): The ID of the post.
+ * Returns: Object (Post details including `raw`, nested `topic` object with ListableTopicSerializer structure) or null if not found/accessible.
+ *
+ * discourse.getTopic(topic_id): Retrieves details for a specific topic.
+ * Parameters:
+ * topic_id (number): The ID of the topic.
+ * Returns: Object (Topic details using ListableTopicSerializer structure) or null if not found/accessible.
+ *
+ * discourse.getUser(user_id_or_username): Retrieves details for a specific user.
+ * Parameters:
+ * user_id_or_username (number | string): The ID or username of the user.
+ * Returns: Object (User details using UserSerializer structure) or null if not found.
+ *
+ * discourse.getPersona(name): Gets an object representing another AI Persona configured on the site.
+ * Parameters:
+ * name (string): The name of the target persona.
+ * Returns: Object { respondTo: function(params) } or null if persona not found.
+ * respondTo(params): Instructs the target persona to generate a response within the current context (e.g., replying to the same post or chat message).
+ * Parameters:
+ * params (Object, optional): { instructions: string, whisper: boolean }
+ * Returns: { success: boolean, post_id?: number, post_number?: number, message_id?: number } or { error: string }
+ *
+ * discourse.createChatMessage(params): Creates a new message in a Discourse Chat channel.
+ * Parameters:
+ * params (Object): { channel_name: string, username: string, message: string }
+ * `channel_name` can be the channel name or slug.
+ * `username` specifies the user who should appear as the sender. The user must exist.
+ * The sending user must have permission to post in the channel.
+ * Returns: { success: boolean, message_id?: number, message?: string, created_at?: string } or { error: string }
+ *
+ * 7. context
+ * An object containing information about the environment where the tool is being run.
+ * Available properties depend on the invocation context, but may include:
+ * post_id (number): ID of the post triggering the tool (if in a Post context).
+ * topic_id (number): ID of the topic (if in a Post context).
+ * private_message (boolean): Whether the context is a private message (in Post context).
+ * message_id (number): ID of the chat message triggering the tool (if in Chat context).
+ * channel_id (number): ID of the chat channel (if in Chat context).
+ * user (Object): Details of the user invoking the tool/persona (structure may vary, often null or SystemUser details unless explicitly passed).
+ * participants (string): Comma-separated list of usernames in a PM (if applicable).
+ * // ... other potential context-specific properties added by the calling environment.
+ *
+ * Constraints
+ *
+ * Execution Time: ≤ 2000ms (default timeout in milliseconds) - This timer *pauses* during external HTTP requests or LLM calls initiated via `http.*` or `llm.generate`, but applies to the script's own processing time.
+ * Memory: ≤ 10MB (V8 heap limit)
+ * Stack Depth: ≤ 20 (Marshal stack depth limit for Ruby interop)
+ * HTTP Requests: ≤ 20 per execution
+ * Exceeding limits will result in errors or termination (e.g., timeout error, out-of-memory error, TooManyRequestsError).
+ *
+ * Security
+ *
+ * Sandboxed Environment: The script runs in a restricted V8 JavaScript environment (via MiniRacer).
+ * No direct access to browser or environment, browser globals (like `window` or `document`), or the host system's file system.
+ * Network requests are proxied through the Discourse backend, not made directly from the sandbox.
+ */
diff --git a/plugins/discourse-ai/lib/ai_tool_scripts/presets/browse_web_jina.js b/plugins/discourse-ai/lib/ai_tool_scripts/presets/browse_web_jina.js
new file mode 100644
index 00000000000..47b6247b2d7
--- /dev/null
+++ b/plugins/discourse-ai/lib/ai_tool_scripts/presets/browse_web_jina.js
@@ -0,0 +1,11 @@
+/* eslint-disable no-undef, no-unused-vars */
+let url;
+function invoke(p) {
+ url = p.url;
+ const result = http.get(`https://r.jina.ai/${url}`);
+ // truncates to 15000 tokens
+ return llm.truncate(result.body, 15000);
+}
+function details() {
+ return "Read: " + url;
+}
diff --git a/plugins/discourse-ai/lib/ai_tool_scripts/presets/empty_tool.js b/plugins/discourse-ai/lib/ai_tool_scripts/presets/empty_tool.js
new file mode 100644
index 00000000000..41bbe8dba27
--- /dev/null
+++ b/plugins/discourse-ai/lib/ai_tool_scripts/presets/empty_tool.js
@@ -0,0 +1,8 @@
+/* eslint-disable no-undef, no-unused-vars */
+function invoke(params) {
+ // logic here
+ return params;
+}
+function details() {
+ return "Details about this tool";
+}
diff --git a/plugins/discourse-ai/lib/ai_tool_scripts/presets/exchange_rate.js b/plugins/discourse-ai/lib/ai_tool_scripts/presets/exchange_rate.js
new file mode 100644
index 00000000000..9525fc1980c
--- /dev/null
+++ b/plugins/discourse-ai/lib/ai_tool_scripts/presets/exchange_rate.js
@@ -0,0 +1,33 @@
+/* eslint-disable no-undef, no-unused-vars */
+// note: this script uses the open.er-api.com service, it is only updated
+// once every 24 hours, for more up to date rates see: https://www.exchangerate-api.com
+function invoke(params) {
+ const url = `https://open.er-api.com/v6/latest/${params.base_currency}`;
+ const result = http.get(url);
+ if (result.status !== 200) {
+ return { error: "Failed to fetch exchange rates" };
+ }
+ const data = JSON.parse(result.body);
+ const rate = data.rates[params.target_currency];
+ if (!rate) {
+ return { error: "Target currency not found" };
+ }
+
+ const rval = {
+ base_currency: params.base_currency,
+ target_currency: params.target_currency,
+ exchange_rate: rate,
+ last_updated: data.time_last_update_utc,
+ };
+
+ if (params.amount) {
+ rval.original_amount = params.amount;
+ rval.converted_amount = params.amount * rate;
+ }
+
+ return rval;
+}
+
+function details() {
+ return "<a href='https://www.exchangerate-api.com'>Rates By Exchange Rate API</a>";
+}
diff --git a/plugins/discourse-ai/lib/ai_tool_scripts/presets/image_generation/custom.js b/plugins/discourse-ai/lib/ai_tool_scripts/presets/image_generation/custom.js
new file mode 100644
index 00000000000..2f35f668751
--- /dev/null
+++ b/plugins/discourse-ai/lib/ai_tool_scripts/presets/image_generation/custom.js
@@ -0,0 +1,13 @@
+/* eslint-disable no-undef, no-unused-vars */
+function invoke(params) {
+ // Configure your custom image generation API here
+ const apiKey = "YOUR_API_KEY";
+ const apiUrl = "YOUR_API_ENDPOINT";
+
+ // Implement your custom logic here
+ return { error: "Please configure your custom image generation API" };
+}
+
+function details() {
+ return "Custom image generation tool - configure manually";
+}
diff --git a/plugins/discourse-ai/lib/ai_tool_scripts/presets/image_generation/flux.js b/plugins/discourse-ai/lib/ai_tool_scripts/presets/image_generation/flux.js
new file mode 100644
index 00000000000..5213a7e336d
--- /dev/null
+++ b/plugins/discourse-ai/lib/ai_tool_scripts/presets/image_generation/flux.js
@@ -0,0 +1,41 @@
+/* eslint-disable no-undef, no-unused-vars */
+const apiKey = "YOUR_KEY";
+const model = "black-forest-labs/FLUX.1.1-pro";
+
+function invoke(params) {
+ let seed = parseInt(params.seed, 10);
+ if (!(seed > 0)) {
+ seed = Math.floor(Math.random() * 1000000) + 1;
+ }
+
+ const prompt = params.prompt;
+ const body = {
+ model,
+ prompt,
+ width: 1024,
+ height: 768,
+ steps: 10,
+ n: 1,
+ seed,
+ response_format: "b64_json",
+ };
+
+ const result = http.post("https://api.together.xyz/v1/images/generations", {
+ headers: {
+ Authorization: `Bearer ${apiKey}`,
+ "Content-Type": "application/json",
+ },
+ body: JSON.stringify(body),
+ });
+
+ const base64Image = JSON.parse(result.body).data[0].b64_json;
+ const image = upload.create("generated_image.png", base64Image);
+ const raw = `\n![${prompt}](${image.short_url})\n`;
+ chain.setCustomRaw(raw);
+
+ return { result: "Image generated successfully", seed };
+}
+
+function details() {
+ return "Generates images based on a text prompt using the FLUX model.";
+}
diff --git a/plugins/discourse-ai/lib/ai_tool_scripts/presets/image_generation/gemini.js b/plugins/discourse-ai/lib/ai_tool_scripts/presets/image_generation/gemini.js
new file mode 100644
index 00000000000..c6c7d3a39e0
--- /dev/null
+++ b/plugins/discourse-ai/lib/ai_tool_scripts/presets/image_generation/gemini.js
@@ -0,0 +1,95 @@
+/* eslint-disable no-undef, no-unused-vars */
+const apiKey = "YOUR_GOOGLE_API_KEY";
+
+function invoke(params) {
+ const prompt = params.prompt;
+
+ const body = {
+ contents: [
+ {
+ parts: [{ text: prompt }],
+ },
+ ],
+ generationConfig: {
+ responseModalities: ["Image"],
+ },
+ };
+
+ const result = http.post(
+ `https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash-image:generateContent`,
+ {
+ headers: {
+ "x-goog-api-key": `${apiKey}`,
+ "Content-Type": "application/json",
+ },
+ body: JSON.stringify(body),
+ }
+ );
+
+ const responseData = JSON.parse(result.body);
+
+ // Check for API errors
+ if (responseData.error) {
+ return {
+ error: `Gemini API Error: ${responseData.error.message || JSON.stringify(responseData.error)}`,
+ };
+ }
+
+ // Validate response structure
+ if (
+ !responseData.candidates ||
+ !responseData.candidates[0] ||
+ !responseData.candidates[0].content ||
+ !responseData.candidates[0].content.parts
+ ) {
+ return {
+ error: "Unexpected API response format",
+ status: result.status,
+ body_preview: JSON.stringify(responseData).substring(0, 500),
+ };
+ }
+
+ // Find the part with inlineData
+ const parts = responseData.candidates[0].content.parts;
+ let base64Image = null;
+
+ for (const part of parts) {
+ if (part.inlineData && part.inlineData.data) {
+ base64Image = part.inlineData.data;
+ break;
+ }
+ }
+
+ if (!base64Image) {
+ return {
+ error: "No image data found in response",
+ parts_preview: JSON.stringify(parts).substring(0, 500),
+ };
+ }
+
+ const image = upload.create("generated_image.png", base64Image);
+
+ if (!image || image.error) {
+ return {
+ error: `Failed to create upload: ${image ? image.error : "upload.create returned null"}`,
+ };
+ }
+
+ if (!image.short_url) {
+ return {
+ error: "Upload created but short_url is missing",
+ };
+ }
+
+ const raw = `\n![${prompt}](${image.short_url})\n`;
+
+ chain.setCustomRaw(raw);
+
+ return {
+ result: "Image generated successfully",
+ };
+}
+
+function details() {
+ return "Generates images using Gemini 2.5 Flash Image (Nano Banana).";
+}
diff --git a/plugins/discourse-ai/lib/ai_tool_scripts/presets/image_generation/openai.js b/plugins/discourse-ai/lib/ai_tool_scripts/presets/image_generation/openai.js
new file mode 100644
index 00000000000..66fcd2ecd76
--- /dev/null
+++ b/plugins/discourse-ai/lib/ai_tool_scripts/presets/image_generation/openai.js
@@ -0,0 +1,55 @@
+/* eslint-disable no-undef, no-unused-vars */
+const apiKey = "YOUR_OPENAI_API_KEY";
+
+function invoke(params) {
+ const prompt = params.prompt;
+ const size = params.size || "1024x1024";
+
+ const body = {
+ model: "gpt-image-1",
+ prompt,
+ size,
+ n: 1,
+ };
+
+ const result = http.post("https://api.openai.com/v1/images/generations", {
+ headers: {
+ Authorization: `Bearer ${apiKey}`,
+ "Content-Type": "application/json",
+ },
+ body: JSON.stringify(body),
+ });
+
+ const responseData = JSON.parse(result.body);
+
+ // Check for API errors
+ if (responseData.error) {
+ return {
+ error: `OpenAI API Error: ${responseData.error.message || JSON.stringify(responseData.error)}`,
+ };
+ }
+
+ // Validate response structure
+ if (
+ !responseData.data ||
+ !responseData.data[0] ||
+ !responseData.data[0].b64_json
+ ) {
+ return {
+ error: "Unexpected API response format",
+ status: result.status,
+ body_preview: JSON.stringify(responseData).substring(0, 500),
+ };
+ }
+
+ const base64Image = responseData.data[0].b64_json;
+ const image = upload.create("generated_image.png", base64Image);
+ const raw = `\n![${prompt}](${image.short_url})\n`;
+ chain.setCustomRaw(raw);
+
+ return { result: "Image generated successfully" };
+}
+
+function details() {
+ return "Generates images using OpenAI's GPT Image 1 model.";
+}
diff --git a/plugins/discourse-ai/lib/ai_tool_scripts/presets/stock_quote.js b/plugins/discourse-ai/lib/ai_tool_scripts/presets/stock_quote.js
new file mode 100644
index 00000000000..60bd065afdc
--- /dev/null
+++ b/plugins/discourse-ai/lib/ai_tool_scripts/presets/stock_quote.js
@@ -0,0 +1,33 @@
+/* eslint-disable no-undef, no-unused-vars */
+function invoke(params) {
+ const apiKey = "YOUR_ALPHAVANTAGE_API_KEY"; // Replace with your actual API key
+ const url = `https://www.alphavantage.co/query?function=GLOBAL_QUOTE&symbol=${params.symbol}&apikey=${apiKey}`;
+
+ const result = http.get(url);
+ if (result.status !== 200) {
+ return { error: "Failed to fetch stock quote" };
+ }
+
+ const data = JSON.parse(result.body);
+ if (data["Error Message"]) {
+ return { error: data["Error Message"] };
+ }
+
+ const quote = data["Global Quote"];
+ if (!quote || Object.keys(quote).length === 0) {
+ return { error: "No data found for the given symbol" };
+ }
+
+ return {
+ symbol: quote["01. symbol"],
+ price: parseFloat(quote["05. price"]),
+ change: parseFloat(quote["09. change"]),
+ change_percent: quote["10. change percent"],
+ volume: parseInt(quote["06. volume"], 10),
+ latest_trading_day: quote["07. latest trading day"],
+ };
+}
+
+function details() {
+ return "<a href='https://www.alphavantage.co'>Stock data provided by AlphaVantage</a>";
+}
diff --git a/plugins/discourse-ai/lib/configuration/feature.rb b/plugins/discourse-ai/lib/configuration/feature.rb
index 0d443e9f73b..902fec86770 100644
--- a/plugins/discourse-ai/lib/configuration/feature.rb
+++ b/plugins/discourse-ai/lib/configuration/feature.rb
@@ -121,6 +121,12 @@ module DiscourseAi
DiscourseAi::Configuration::Module::AI_HELPER_ID,
DiscourseAi::Configuration::Module::AI_HELPER,
),
+ new(
+ "post_illustrator",
+ "ai_helper_post_illustrator_persona",
+ DiscourseAi::Configuration::Module::AI_HELPER_ID,
+ DiscourseAi::Configuration::Module::AI_HELPER,
+ ),
]
end
diff --git a/plugins/discourse-ai/lib/personas/post_illustrator.rb b/plugins/discourse-ai/lib/personas/post_illustrator.rb
index f3e012a542a..e1a3615cd1b 100644
--- a/plugins/discourse-ai/lib/personas/post_illustrator.rb
+++ b/plugins/discourse-ai/lib/personas/post_illustrator.rb
@@ -9,21 +9,33 @@ module DiscourseAi
def system_prompt
<<~PROMPT.strip
- Provide me a StableDiffusion prompt to generate an image that illustrates the following post in 40 words or less, be creative.
- You'll find the post between <input></input> XML tags.
+ You are an AI assistant that creates images to illustrate posts.
- Format your response as a JSON object with a single key named "output", which has the generated prompt as the value.
- Your output should be in the following format:
+ Your task is to analyze the post content provided in <input></input> tags and generate an appropriate image using your image generation tool.
- {"output": "xx"}
+ Create a creative and descriptive image generation prompt (40 words or less) that captures the essence of the post content, then use your image generation tool to create the image.
- Where "xx" is replaced by the generated prompt.
- reply with valid JSON only
+ Be creative and ensure the image prompt is clear, detailed, and appropriate for the post content.
PROMPT
end
- def response_format
- [{ "key" => "output", "type" => "string" }]
+ def tools
+ @tools ||=
+ begin
+ image_tool_ids = AiTool.where(enabled: true, is_image_generation_tool: true).pluck(:id)
+
+ image_tool_ids.map do |tool_id|
+ DiscourseAi::Personas::Tools::Custom.class_instance(tool_id)
+ end
+ end
+ end
+
+ def force_tool_use
+ tools
+ end
+
+ def forced_tool_count
+ 1
end
end
end
diff --git a/plugins/discourse-ai/lib/personas/tool_runner.rb b/plugins/discourse-ai/lib/personas/tool_runner.rb
index fe78717f480..07fe12769e9 100644
--- a/plugins/discourse-ai/lib/personas/tool_runner.rb
+++ b/plugins/discourse-ai/lib/personas/tool_runner.rb
@@ -884,9 +884,17 @@ module DiscourseAi
for_private_message: @context.private_message,
).create_for(@bot_user.id)
- { id: upload.id, short_url: upload.short_url, url: upload.url }
+ if upload&.persisted?
+ { "id" => upload.id, "short_url" => upload.short_url, "url" => upload.url }
+ else
+ error_msg =
+ upload&.errors&.full_messages&.join(", ") || "Upload creation failed"
+ { "error" => error_msg }
+ end
end
end
+ rescue => e
+ { "error" => e.message }
end
end,
)
diff --git a/plugins/discourse-ai/lib/personas/tools/custom.rb b/plugins/discourse-ai/lib/personas/tools/custom.rb
index 6361402ccb7..c1a70ad40d5 100644
--- a/plugins/discourse-ai/lib/personas/tools/custom.rb
+++ b/plugins/discourse-ai/lib/personas/tools/custom.rb
@@ -76,9 +76,17 @@ module DiscourseAi
end
end
result = runner.invoke(progress_callback: callback)
- if runner.custom_raw
- self.custom_raw = runner.custom_raw
+
+ # IMPORTANT: Get custom_raw ONCE - calling it multiple times clears it!
+ custom_raw_value = runner.custom_raw
+
+ # Trigger callback if custom_raw is present
+ if custom_raw_value.present?
+ self.custom_raw = custom_raw_value
@chain_next_response = false
+
+ # Manually trigger the callback since setCustomRaw doesn't stream
+ blk&.call(custom_raw_value, true)
end
result
end
diff --git a/plugins/discourse-ai/spec/lib/modules/ai_bot/entry_point_spec.rb b/plugins/discourse-ai/spec/lib/modules/ai_bot/entry_point_spec.rb
index e64d8af5947..7d524aa5404 100644
--- a/plugins/discourse-ai/spec/lib/modules/ai_bot/entry_point_spec.rb
+++ b/plugins/discourse-ai/spec/lib/modules/ai_bot/entry_point_spec.rb
@@ -179,12 +179,14 @@ RSpec.describe DiscourseAi::AiBot::EntryPoint do
end
it "will include ai_search_discoveries field in the user_option if discover persona is enabled" do
- SiteSetting.ai_bot_enabled = true
+ SiteSetting.ai_discover_enabled = true
SiteSetting.ai_discover_persona = Fabricate(:ai_persona).id
- serializer =
- CurrentUserSerializer.new(Fabricate(:user), scope: Guardian.new(Fabricate(:user)))
- expect(serializer.user_option.ai_search_discoveries).to eq(true)
+ user = Fabricate(:user)
+ user.user_option.update!(ai_search_discoveries: true)
+ serializer = CurrentUserSerializer.new(user, scope: Guardian.new(user))
+ serializer = serializer.as_json
+ expect(serializer[:current_user][:user_option][:ai_search_discoveries]).to eq(true)
end
end
end
diff --git a/plugins/discourse-ai/spec/lib/modules/ai_bot/playground_spec.rb b/plugins/discourse-ai/spec/lib/modules/ai_bot/playground_spec.rb
index 2200d8af35c..ab5aa3a43eb 100644
--- a/plugins/discourse-ai/spec/lib/modules/ai_bot/playground_spec.rb
+++ b/plugins/discourse-ai/spec/lib/modules/ai_bot/playground_spec.rb
@@ -268,7 +268,7 @@ RSpec.describe DiscourseAi::AiBot::Playground do
["I understood image"],
) do |_, _, inner_prompts, inner_options|
options = inner_options
- post = create_post(title: "some new topic I created", raw: body)
+ post = create_post(user: admin, title: "some new topic I created", raw: body)
prompts = inner_prompts
end
@@ -611,6 +611,7 @@ RSpec.describe DiscourseAi::AiBot::Playground do
DiscourseAi::Completions::Llm.with_prepared_responses(["Yes I can"]) do
post =
create_post(
+ user: admin,
title: "My public topic",
raw: "Hey @#{persona.user.username}, can you help me?",
post_type: Post.types[:whisper],
@@ -634,6 +635,7 @@ RSpec.describe DiscourseAi::AiBot::Playground do
DiscourseAi::Completions::Llm.with_prepared_responses(["Yes I can"]) do
post =
create_post(
+ user: admin,
title: "My public topic",
raw: "Hey @#{persona.user.username}, can you help me?",
)
diff --git a/plugins/discourse-ai/spec/lib/modules/ai_helper/assistant_spec.rb b/plugins/discourse-ai/spec/lib/modules/ai_helper/assistant_spec.rb
index c4d67fa0f23..c5537d21973 100644
--- a/plugins/discourse-ai/spec/lib/modules/ai_helper/assistant_spec.rb
+++ b/plugins/discourse-ai/spec/lib/modules/ai_helper/assistant_spec.rb
@@ -45,10 +45,7 @@ RSpec.describe DiscourseAi::AiHelper::Assistant do
end
describe("#available_prompts") do
- before do
- SiteSetting.ai_helper_illustrate_post_model = "disabled"
- DiscourseAi::AiHelper::Assistant.clear_prompt_cache!
- end
+ before { DiscourseAi::AiHelper::Assistant.clear_prompt_cache! }
it "returns all available prompts" do
prompts = assistant.available_prompts(user)
@@ -92,24 +89,138 @@ RSpec.describe DiscourseAi::AiHelper::Assistant do
expect { assistant.available_prompts(user) }.not_to raise_error
end
- context "when illustrate post model is enabled" do
- before do
- SiteSetting.ai_helper_illustrate_post_model = "stable_diffusion_xl"
- DiscourseAi::AiHelper::Assistant.clear_prompt_cache!
+ context "when PostIllustrator persona has an image generation tool" do
+ let(:image_tool) do
+ AiTool.create!(
+ name: "Test Image Generator",
+ tool_name: "test_image_generator",
+ description: "Generates test images",
+ summary: "Test image generation",
+ parameters: [{ name: "prompt", type: "string", required: true }],
+ script: <<~JS,
+ function invoke(params) {
+ const image = upload.create("test.png", "base64data");
+ chain.setCustomRaw(`![test](${image.short_url})`);
+ return { result: "success" };
+ }
+ JS
+ created_by_id: user.id,
+ )
end
- it "returns the illustrate_post prompt in the list of all prompts" do
- prompts = assistant.available_prompts(user)
-
- expect(prompts.map { |p| p[:name] }).to contain_exactly(
- "translate",
- "generate_titles",
- "proofread",
- "markdown_table",
- "explain",
- "illustrate_post",
- "replace_dates",
- )
+ context "with system PostIllustrator persona (dynamic tool discovery)" do
+ before do
+ # Use the default system PostIllustrator persona
+ image_tool # Create the tool
+ DiscourseAi::AiHelper::Assistant.clear_prompt_cache!
+ end
+
+ it "automatically discovers and uses the image generation tool" do
+ prompts = assistant.available_prompts(user)
+
+ expect(prompts.map { |p| p[:name] }).to contain_exactly(
+ "translate",
+ "generate_titles",
+ "proofread",
+ "markdown_table",
+ "explain",
+ "illustrate_post",
+ "replace_dates",
+ )
+ end
+
+ it "PostIllustrator persona has tools and forces their use" do
+ persona = AiPersona.find_by(id: SiteSetting.ai_helper_post_illustrator_persona)
+ persona_instance = persona.class_instance.new
+
+ expect(persona_instance.tools).not_to be_empty
+ expect(persona_instance.tools.first).to be_a(Class)
+ expect(persona_instance.tools.first.tool_id).to eq(image_tool.id)
+ expect(persona_instance.force_tool_use).to eq(persona_instance.tools)
+ expect(persona_instance.forced_tool_count).to eq(1)
+ end
+ end
+
+ context "with custom persona" do
+ let(:custom_persona) do
+ AiPersona.create!(
+ name: "Custom Post Illustrator",
+ description: "Test persona with image tool",
+ system_prompt: "You are an AI that generates images from text prompts.",
+ enabled: true,
+ system: false,
+ allowed_group_ids: [Group::AUTO_GROUPS[:trust_level_0]],
+ tools: [["custom-#{image_tool.id}", {}, true]],
+ )
+ end
+
+ before do
+ # Set the custom persona as the illustrator persona
+ SiteSetting.ai_helper_post_illustrator_persona = custom_persona.id
+ DiscourseAi::AiHelper::Assistant.clear_prompt_cache!
+ end
+
+ it "returns the illustrate_post prompt in the list of all prompts" do
+ prompts = assistant.available_prompts(user)
+
+ expect(prompts.map { |p| p[:name] }).to contain_exactly(
+ "translate",
+ "generate_titles",
+ "proofread",
+ "markdown_table",
+ "explain",
+ "illustrate_post",
+ "replace_dates",
+ )
+ end
+ end
+
+ context "when handling edge cases" do
+ before { DiscourseAi::AiHelper::Assistant.clear_prompt_cache! }
+
+ it "does not include illustrate_post when no image generation tools are enabled" do
+ # Disable all image generation tools
+ AiTool.where(is_image_generation_tool: true).update_all(enabled: false)
+ DiscourseAi::AiHelper::Assistant.clear_prompt_cache!
+
+ prompts = assistant.available_prompts(user)
+
+ expect(prompts.map { |p| p[:name] }).not_to include("illustrate_post")
+ end
+
+ it "handles tool discovery returning empty array" do
+ # Create a tool that looks like an image tool but isn't
+ AiTool.create!(
+ name: "Not An Image Tool",
+ tool_name: "not_image_tool",
+ description: "Not an image tool",
+ summary: "Test",
+ parameters: [{ name: "text", type: "string" }],
+ script: "function invoke() { return {}; }",
+ created_by_id: user.id,
+ enabled: true,
+ is_image_generation_tool: false,
+ )
+
+ DiscourseAi::AiHelper::Assistant.clear_prompt_cache!
+ prompts = assistant.available_prompts(user)
+
+ expect(prompts.map { |p| p[:name] }).not_to include("illustrate_post")
+ end
+
+ it "gracefully handles PostIllustrator.tools raising exception" do
+ # Stub the PostIllustrator class to raise an error
+ allow_any_instance_of(DiscourseAi::Personas::PostIllustrator).to receive(
+ :tools,
+ ).and_raise(StandardError.new("Tool discovery failed"))
+
+ DiscourseAi::AiHelper::Assistant.clear_prompt_cache!
+
+ # Should not raise error, just exclude illustrate_post
+ expect { assistant.available_prompts(user) }.not_to raise_error
+ prompts = assistant.available_prompts(user)
+ expect(prompts.map { |p| p[:name] }).not_to include("illustrate_post")
+ end
end
end
end
diff --git a/plugins/discourse-ai/spec/lib/modules/ai_helper/painter_spec.rb b/plugins/discourse-ai/spec/lib/modules/ai_helper/painter_spec.rb
deleted file mode 100644
index 882835d2a0d..00000000000
--- a/plugins/discourse-ai/spec/lib/modules/ai_helper/painter_spec.rb
+++ /dev/null
@@ -1,89 +0,0 @@
-# frozen_string_literal: true
-
-RSpec.describe DiscourseAi::AiHelper::Painter do
- subject(:painter) { described_class.new }
-
- fab!(:user)
-
- before do
- enable_current_plugin
- assign_fake_provider_to(:ai_default_llm_model)
- SiteSetting.ai_stability_api_url = "https://api.stability.dev"
- SiteSetting.ai_stability_api_key = "abc"
- SiteSetting.ai_openai_api_key = "abc"
- end
-
- describe "#commission_thumbnails" do
- context "when illustrate post model is stable_diffusion_xl" do
- before { SiteSetting.ai_helper_illustrate_post_model = "stable_diffusion_xl" }
-
- let(:artifacts) do
- %w[
- iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8z8BQDwAEhQGAhKmMIQAAAABJRU5ErkJggg==
- iVBORw0KGgoAAAANSUhEUgAAAAoAAAAKCAYAAACNMs+9AAAAFUlEQVR42mP8z8BQz0AEYBxVSF+FABJADveWkH6oAAAAAElFTkSuQmCC
- iVBORw0KGgoAAAANSUhEUgAAAAoAAAAKCAYAAACNMs+9AAAAFUlEQVR42mNk+M9Qz0AEYBxVSF+FAAhKDveksOjmAAAAAElFTkSuQmCC
- iVBORw0KGgoAAAANSUhEUgAAAAoAAAAKCAYAAACNMs+9AAAAFUlEQVR42mNkYPhfz0AEYBxVSF+FAP5FDvcfRYWgAAAAAElFTkSuQmCC
- ]
- end
-
- let(:raw_content) do
- "Poetry is a form of artistic expression that uses language aesthetically and rhythmically to evoke emotions and ideas."
- end
-
- let(:expected_image_prompt) { <<~TEXT.strip }
- Visualize a vibrant scene of an inkwell bursting, spreading colors across a blank canvas,
- embodying words in tangible forms, symbolizing the rhythm and emotion evoked by poetry,
- under the soft glow of a full moon.
- TEXT
-
- it "returns 4 samples" do
- StableDiffusionStubs.new.stub_response(expected_image_prompt, artifacts)
-
- thumbnails =
- DiscourseAi::Completions::Llm.with_prepared_responses([expected_image_prompt]) do
- thumbnails = painter.commission_thumbnails(raw_content, user)
- end
-
- thumbnail_urls = Upload.last(4).map(&:short_url)
-
- expect(
- thumbnails.map { |upload_serializer| upload_serializer.short_url },
- ).to contain_exactly(*thumbnail_urls)
- end
- end
-
- context "when illustrate post model is dall_e_3" do
- before { SiteSetting.ai_helper_illustrate_post_model = "dall_e_3" }
-
- let(:artifacts) do
- %w[
- iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8z8BQDwAEhQGAhKmMIQAAAABJRU5ErkJggg==
- ]
- end
-
- let(:raw_content) do
- "Poetry is a form of artistic expression that uses language aesthetically and rhythmically to evoke emotions and ideas."
- end
-
- it "returns an image sample" do
- _post = Fabricate(:post)
-
- data = [{ b64_json: artifacts.first, revised_prompt: "colors on a canvas" }]
- WebMock
- .stub_request(:post, "https://api.openai.com/v1/images/generations")
- .with do |request|
- _json = JSON.parse(request.body, symbolize_names: true)
- true
- end
- .to_return(status: 200, body: { data: data }.to_json)
-
- thumbnails = painter.commission_thumbnails(raw_content, user)
- thumbnail_urls = Upload.last(1).map(&:short_url)
-
- expect(
- thumbnails.map { |upload_serializer| upload_serializer.short_url },
- ).to contain_exactly(*thumbnail_urls)
- end
- end
- end
-end
diff --git a/plugins/discourse-ai/spec/models/ai_tool_spec.rb b/plugins/discourse-ai/spec/models/ai_tool_spec.rb
index 92421011d11..cf647d29852 100644
--- a/plugins/discourse-ai/spec/models/ai_tool_spec.rb
+++ b/plugins/discourse-ai/spec/models/ai_tool_spec.rb
@@ -1178,4 +1178,89 @@ RSpec.describe AiTool do
expect(topic.posts.count).to eq(2)
end
end
+
+ describe "#set_image_generation_tool_flag" do
+ it "sets flag to true when tool has all required characteristics" do
+ tool =
+ create_tool(parameters: [{ name: "prompt", type: "string", required: true }], script: <<~JS)
+ function invoke(params) {
+ const image = upload.create("test.png", "base64data");
+ chain.setCustomRaw(`![test](${image.short_url})`);
+ return { result: "success" };
+ }
+ JS
+
+ expect(tool.is_image_generation_tool).to eq(true)
+ end
+
+ it "sets flag to false when tool missing prompt parameter" do
+ tool =
+ create_tool(parameters: [{ name: "query", type: "string", required: true }], script: <<~JS)
+ function invoke(params) {
+ const image = upload.create("test.png", "base64data");
+ chain.setCustomRaw(`![test](${image.short_url})`);
+ return { result: "success" };
+ }
+ JS
+
+ expect(tool.is_image_generation_tool).to eq(false)
+ end
+
+ it "sets flag to false when tool missing upload.create" do
+ tool =
+ create_tool(parameters: [{ name: "prompt", type: "string", required: true }], script: <<~JS)
+ function invoke(params) {
+ chain.setCustomRaw(`![test](upload://test123)`);
+ return { result: "success" };
+ }
+ JS
+
+ expect(tool.is_image_generation_tool).to eq(false)
+ end
+
+ it "sets flag to false when tool missing chain.setCustomRaw" do
+ tool =
+ create_tool(parameters: [{ name: "prompt", type: "string", required: true }], script: <<~JS)
+ function invoke(params) {
+ const image = upload.create("test.png", "base64data");
+ return { result: "success", image: image };
+ }
+ JS
+
+ expect(tool.is_image_generation_tool).to eq(false)
+ end
+
+ it "updates flag when tool is updated" do
+ tool =
+ create_tool(
+ parameters: [{ name: "query", type: "string", required: true }],
+ script: "function invoke(params) { return params; }",
+ )
+
+ expect(tool.is_image_generation_tool).to eq(false)
+
+ tool.update!(parameters: [{ name: "prompt", type: "string", required: true }], script: <<~JS)
+ function invoke(params) {
+ const image = upload.create("test.png", "base64data");
+ chain.setCustomRaw(`![test](${image.short_url})`);
+ return { result: "success" };
+ }
+ JS
+
+ expect(tool.is_image_generation_tool).to eq(true)
+ end
+
+ it "handles edge case with spaces in method calls" do
+ tool =
+ create_tool(parameters: [{ name: "prompt", type: "string", required: true }], script: <<~JS)
+ function invoke(params) {
+ const image = upload . create("test.png", "base64data");
+ chain . setCustomRaw(`![test](${image.short_url})`);
+ return { result: "success" };
+ }
+ JS
+
+ expect(tool.is_image_generation_tool).to eq(false)
+ end
+ end
end
diff --git a/plugins/discourse-ai/spec/requests/ai_helper/assistant_controller_spec.rb b/plugins/discourse-ai/spec/requests/ai_helper/assistant_controller_spec.rb
index 19393b63c0f..f45444fa30b 100644
--- a/plugins/discourse-ai/spec/requests/ai_helper/assistant_controller_spec.rb
+++ b/plugins/discourse-ai/spec/requests/ai_helper/assistant_controller_spec.rb
@@ -19,7 +19,12 @@ RSpec.describe DiscourseAi::AiHelper::AssistantController do
it "is able to stream suggestions to helper" do
sign_in(user)
- my_post = Fabricate(:post)
+ category = Fabricate(:category)
+ category.set_permissions(everyone: :full)
+ category.save!
+
+ topic = Fabricate(:topic, category: category)
+ my_post = Fabricate(:post, topic: topic)
channel = nil
messages =
@@ -183,17 +188,107 @@ RSpec.describe DiscourseAi::AiHelper::AssistantController do
end
end
- it "prevents double render when mode is ILLUSTRATE_POST" do
- DiscourseAi::Completions::Llm.with_prepared_responses([proofread_text]) do
- expect {
- post "/discourse-ai/ai-helper/suggest",
- params: {
- mode: DiscourseAi::AiHelper::Assistant::ILLUSTRATE_POST,
- text: text_to_proofread,
- force_default_locale: true,
- }
- }.not_to raise_error
+ it "returns error when PostIllustrator persona has no image generation tool" do
+ post "/discourse-ai/ai-helper/suggest",
+ params: {
+ mode: DiscourseAi::AiHelper::Assistant::ILLUSTRATE_POST,
+ text: text_to_proofread,
+ force_default_locale: true,
+ }
+
+ expect(response.status).to eq(422)
+ expect(response.parsed_body["errors"].first).to include(
+ "Post Illustrator persona must have an image generation tool",
+ )
+ end
+
+ it "returns error when PostIllustrator persona is not found" do
+ SiteSetting.ai_helper_post_illustrator_persona = 99_999
+
+ post "/discourse-ai/ai-helper/suggest",
+ params: {
+ mode: DiscourseAi::AiHelper::Assistant::ILLUSTRATE_POST,
+ text: text_to_proofread,
+ force_default_locale: true,
+ }
+
+ expect(response.status).to eq(404)
+ expect(response.parsed_body["errors"].first).to include(
+ "Post Illustrator persona is not configured",
+ )
+ end
+
+ context "when PostIllustrator persona has image generation tool" do
+ let(:image_tool) do
+ AiTool.create!(
+ name: "Test Image Generator",
+ tool_name: "test_image_generator",
+ description: "Generates test images",
+ summary: "Test image generation",
+ parameters: [{ name: "prompt", type: "string", required: true }],
+ script: <<~JS,
+ function invoke(params) {
+ const image = upload.create("test.png", "base64data");
+ chain.setCustomRaw(`![test](${image.short_url})`);
+ return { result: "success" };
+ }
+ JS
+ created_by_id: user.id,
+ enabled: true,
+ is_image_generation_tool: true,
+ )
+ end
+
+ let(:upload) do
+ Fabricate(
+ :upload,
+ sha1: Upload.sha1_from_short_url("upload://test123"),
+ original_filename: "test.png",
+ )
+ end
+
+ let(:post_illustrator_persona) do
+ AiPersona.find_by(id: SiteSetting.ai_helper_post_illustrator_persona)
+ end
+
+ before do
+ image_tool
+ post_illustrator_persona.update_columns(system: false) # Allow editing for test
+ post_illustrator_persona.update!(tools: [["custom-#{image_tool.id}", nil, true]])
+
+ allow_any_instance_of(DiscourseAi::Personas::Bot).to receive(
+ :reply,
+ ) do |_bot, _context, &block|
+ block.call("", "![test](#{upload.short_url})", :partial_invoke)
+ end
+ end
+
+ it "successfully generates thumbnails" do
+ post "/discourse-ai/ai-helper/suggest",
+ params: {
+ mode: DiscourseAi::AiHelper::Assistant::ILLUSTRATE_POST,
+ text: "A beautiful sunset",
+ force_default_locale: true,
+ }
+
expect(response.status).to eq(200)
+ expect(response.parsed_body["thumbnails"]).to be_present
+ expect(response.parsed_body["thumbnails"].length).to eq(1)
+ expect(response.parsed_body["thumbnails"].first["id"]).to eq(upload.id)
+ end
+
+ it "returns error when image generation fails" do
+ allow_any_instance_of(DiscourseAi::Personas::Bot).to receive(:reply).and_return(nil)
+
+ post "/discourse-ai/ai-helper/suggest",
+ params: {
+ mode: DiscourseAi::AiHelper::Assistant::ILLUSTRATE_POST,
+ text: "A beautiful sunset",
+ force_default_locale: true,
+ }
+
+ expect(response.status).to eq(500)
+ expect(response.parsed_body["errors"].first).to include("Failed to generate image")
end
end
diff --git a/plugins/discourse-ai/spec/services/discourse_ai/ai_helper/generate_thumbnails_spec.rb b/plugins/discourse-ai/spec/services/discourse_ai/ai_helper/generate_thumbnails_spec.rb
new file mode 100644
index 00000000000..59d2155dfbb
--- /dev/null
+++ b/plugins/discourse-ai/spec/services/discourse_ai/ai_helper/generate_thumbnails_spec.rb
@@ -0,0 +1,140 @@
+# frozen_string_literal: true
+
+RSpec.describe DiscourseAi::AiHelper::GenerateThumbnails do
+ describe ".call" do
+ subject(:result) { described_class.call(**params, **dependencies) }
+
+ fab!(:user)
+ fab!(:admin)
+ fab!(:post_illustrator_persona) do
+ AiPersona.create!(
+ name: "Post Illustrator",
+ description: "Generates images for posts",
+ system_prompt: "Generate images",
+ enabled: true,
+ created_by_id: admin.id,
+ )
+ end
+ fab!(:image_tool) do
+ AiTool.create!(
+ name: "image_generation_test",
+ tool_name: "image_generation_test",
+ description: "Test image generation",
+ summary: "Test",
+ parameters: [{ name: "prompt", type: "string", required: true }],
+ script: <<~JS,
+ function invoke(params) {
+ const image = upload.create("test.png", "base64data");
+ chain.setCustomRaw("![test](upload://test123)");
+ return { result: "success" };
+ }
+ JS
+ created_by_id: admin.id,
+ enabled: true,
+ is_image_generation_tool: true,
+ )
+ end
+ fab!(:upload) do
+ Fabricate(
+ :upload,
+ sha1: Upload.sha1_from_short_url("upload://test123"),
+ original_filename: "test.png",
+ )
+ end
+
+ let(:params) { { params: { text: } } }
+ let(:dependencies) { { guardian: user.guardian } }
+ let(:text) { "A beautiful sunset over the ocean" }
+
+ before do
+ enable_current_plugin
+ assign_fake_provider_to(:ai_default_llm_model)
+ SiteSetting.ai_helper_post_illustrator_persona = post_illustrator_persona.id
+
+ # Configure PostIllustrator persona with the image tool
+ post_illustrator_persona.update!(tools: [["custom-#{image_tool.id}", nil, true]])
+ end
+
+ context "when text parameter is missing" do
+ let(:text) { nil }
+
+ it { is_expected.to fail_a_contract }
+ end
+
+ context "when text parameter exceeds maximum length" do
+ let(:text) { "a" * 10_001 }
+
+ it { is_expected.to fail_a_contract }
+ end
+
+ context "when persona is not found" do
+ before { SiteSetting.ai_helper_post_illustrator_persona = 99_999 }
+
+ it { is_expected.to fail_to_find_a_model(:persona) }
+ end
+
+ context "when persona has no image generation tool" do
+ before do
+ # Remove tools from persona
+ post_illustrator_persona.update!(tools: [])
+ end
+
+ it { is_expected.to fail_a_policy(:has_image_generation_tool) }
+ end
+
+ context "when image generation succeeds" do
+ before do
+ # Mock the bot reply to return custom_raw with upload URL
+ allow_any_instance_of(DiscourseAi::Personas::Bot).to receive(
+ :reply,
+ ) do |_bot, _context, &block|
+ block.call("", "![test](#{upload.short_url})", :partial_invoke)
+ end
+ end
+
+ it { is_expected.to run_successfully }
+
+ it "generates and returns thumbnails" do
+ expect(result[:thumbnails]).to be_present
+ expect(result[:thumbnails].length).to eq(1)
+ expect(result[:thumbnails].first[:id]).to eq(upload.id)
+ expect(result[:thumbnails].first[:short_url]).to eq(upload.short_url)
+ end
+ end
+
+ context "when bot returns no custom_raw" do
+ before do
+ allow_any_instance_of(DiscourseAi::Personas::Bot).to receive(:reply).and_return(nil)
+ end
+
+ it { is_expected.to fail_a_step(:generate_images) }
+ end
+
+ context "when bot returns custom_raw without upload URLs" do
+ before do
+ allow_any_instance_of(DiscourseAi::Personas::Bot).to receive(
+ :reply,
+ ) do |_bot, _context, &block|
+ block.call("Some text without uploads", nil, :custom_raw)
+ end
+ end
+
+ it { is_expected.to fail_a_step(:parse_uploads) }
+ end
+
+ context "when upload is not found" do
+ before do
+ allow_any_instance_of(DiscourseAi::Personas::Bot).to receive(
+ :reply,
+ ) do |_bot, _context, &block|
+ block.call("", "![test](upload://nonexistentsha1234567890123456789012)", :partial_invoke)
+ end
+ end
+
+ it "returns empty thumbnails array" do
+ expect(result).to run_successfully
+ expect(result[:thumbnails]).to eq([])
+ end
+ end
+ end
+end
diff --git a/plugins/discourse-ai/spec/system/ai_bot/tool_list_editor_spec.rb b/plugins/discourse-ai/spec/system/ai_bot/tool_list_editor_spec.rb
new file mode 100644
index 00000000000..34aa58f8e25
--- /dev/null
+++ b/plugins/discourse-ai/spec/system/ai_bot/tool_list_editor_spec.rb
@@ -0,0 +1,141 @@
+# frozen_string_literal: true
+
+describe "AI Tool List Editor Dropdown", type: :system do
+ fab!(:admin)
+
+ before do
+ enable_current_plugin
+ SiteSetting.ai_embeddings_enabled = true
+ sign_in(admin)
+ end
+
+ it "shows main menu presets and can navigate to image generation category" do
+ visit "/admin/plugins/discourse-ai/ai-tools"
+ expect(page).to have_content("Tools")
+
+ find(".ai-tool-list-editor__new-button").click
+ tool_menu = PageObjects::Components::DMenu.new(find(".ai-tool-list-editor__new-button"))
+
+ expect(tool_menu).to have_css(".btn[data-option='browse_web_jina']")
+ expect(tool_menu).to have_css(".btn[data-option='exchange_rate']")
+ expect(tool_menu).to have_css(".btn[data-option='stock_quote']")
+ expect(tool_menu).to have_css(".btn[data-option='image_generation_category']")
+ expect(tool_menu).to have_css(".btn[data-option='empty_tool']")
+
+ expect(page).not_to have_css(".ai-tool-preset-item[data-option='image_generation_openai']")
+
+ tool_menu.option(".btn[data-option='image_generation_category']").click
+
+ expect(page).to have_css(".ai-tool-preset-item[data-option='image_generation_openai']")
+ expect(page).to have_css(".ai-tool-preset-item[data-option='image_generation_gemini']")
+ expect(page).to have_css(".ai-tool-preset-item[data-option='image_generation_flux']")
+ expect(page).to have_css(".btn[data-option='image_generation_custom']")
+
+ expect(page).not_to have_css(".btn[data-option='browse_web_jina']")
+
+ expect(page).to have_css(".btn-transparent .d-icon-chevron-left")
+ end
+
+ it "can navigate back from image generation category to main menu" do
+ visit "/admin/plugins/discourse-ai/ai-tools"
+
+ find(".ai-tool-list-editor__new-button").click
+ tool_menu = PageObjects::Components::DMenu.new(find(".ai-tool-list-editor__new-button"))
+
+ tool_menu.option(".btn[data-option='image_generation_category']").click
+
+ expect(page).to have_css(".ai-tool-preset-item[data-option='image_generation_openai']")
+
+ find(".btn-transparent .d-icon-chevron-left").ancestor(".btn-transparent").click
+
+ expect(page).to have_css(".btn[data-option='browse_web_jina']")
+ expect(page).to have_css(".btn[data-option='exchange_rate']")
+ expect(page).to have_css(".btn[data-option='image_generation_category']")
+
+ expect(page).not_to have_css(".ai-tool-preset-item[data-option='image_generation_openai']")
+ end
+
+ it "navigates to new tool page when clicking image generation preset" do
+ visit "/admin/plugins/discourse-ai/ai-tools"
+
+ find(".ai-tool-list-editor__new-button").click
+ tool_menu = PageObjects::Components::DMenu.new(find(".ai-tool-list-editor__new-button"))
+
+ tool_menu.option(".btn[data-option='image_generation_category']").click
+
+ find(".ai-tool-preset-item[data-option='image_generation_openai']").click
+
+ expect(page).to have_current_path(
+ %r{/admin/plugins/discourse-ai/ai-tools/new\?presetId=image_generation_openai},
+ )
+
+ expect(page).to have_field("tool_name", with: "image_generation_openai")
+ expect(page).to have_field("name", with: "GPT Image")
+ end
+
+ it "navigates to new tool page when clicking non-category preset" do
+ visit "/admin/plugins/discourse-ai/ai-tools"
+
+ find(".ai-tool-list-editor__new-button").click
+ tool_menu = PageObjects::Components::DMenu.new(find(".ai-tool-list-editor__new-button"))
+
+ tool_menu.option(".btn[data-option='exchange_rate']").click
+
+ expect(page).to have_current_path(
+ %r{/admin/plugins/discourse-ai/ai-tools/new\?presetId=exchange_rate},
+ )
+
+ expect(page).to have_field("tool_name", with: "exchange_rate")
+ expect(page).to have_field("name", with: "Exchange Rate")
+ end
+
+ it "displays image generation presets sorted by provider" do
+ visit "/admin/plugins/discourse-ai/ai-tools"
+
+ find(".ai-tool-list-editor__new-button").click
+ tool_menu = PageObjects::Components::DMenu.new(find(".ai-tool-list-editor__new-button"))
+
+ tool_menu.option(".btn[data-option='image_generation_category']").click
+
+ preset_items = page.all(".ai-tool-preset-item")
+
+ provider_order = preset_items.map { |item| item.find(".ai-tool-preset-provider").text }
+
+ expect(provider_order).to eq(provider_order.sort)
+ end
+
+ it "shows custom preset at the bottom separated by divider" do
+ visit "/admin/plugins/discourse-ai/ai-tools"
+
+ find(".ai-tool-list-editor__new-button").click
+ tool_menu = PageObjects::Components::DMenu.new(find(".ai-tool-list-editor__new-button"))
+
+ tool_menu.option(".btn[data-option='image_generation_category']").click
+
+ expect(page).to have_css(".btn[data-option='image_generation_custom']")
+
+ dividers = page.all(".dropdown-menu__divider")
+ expect(dividers.count).to eq(2)
+
+ custom_preset_items = page.all(".btn[data-option='image_generation_custom']")
+ expect(custom_preset_items.count).to eq(1)
+ end
+
+ it "resets menu state when closing dropdown" do
+ visit "/admin/plugins/discourse-ai/ai-tools"
+
+ find(".ai-tool-list-editor__new-button").click
+ tool_menu = PageObjects::Components::DMenu.new(find(".ai-tool-list-editor__new-button"))
+
+ tool_menu.option(".btn[data-option='image_generation_category']").click
+
+ expect(page).to have_css(".ai-tool-preset-item[data-option='image_generation_openai']")
+
+ page.find("body").click
+
+ find(".ai-tool-list-editor__new-button").click
+
+ expect(page).to have_css(".btn[data-option='browse_web_jina']")
+ expect(page).not_to have_css(".ai-tool-preset-item[data-option='image_generation_openai']")
+ end
+end