Skip to content

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

FEATURE: AI-generated queries using user-filled descriptions (#39095)

Natalie Tay97400099a5ca
diff --git a/plugins/discourse-ai/spec/lib/agents/agent_spec.rb b/plugins/discourse-ai/spec/lib/agents/agent_spec.rb
index 0f9e00ee6a3..4c6dd728791 100644
--- a/plugins/discourse-ai/spec/lib/agents/agent_spec.rb
+++ b/plugins/discourse-ai/spec/lib/agents/agent_spec.rb
@@ -341,10 +341,16 @@ RSpec.describe DiscourseAi::Agents::Agent do
described_class.instance_variable_set(:@external_tools_by_name, nil)
end
+ before do
+ # reset cache so sync runs fresh
+ reset_external_registry!
+ end
+
after do
DiscoursePluginRegistry._raw_external_ai_features.reject! do |entry|
entry[:value][:module_name] == :test_module
end
+ # remove fake entries from the registry
reset_external_registry!
end
diff --git a/plugins/discourse-data-explorer/admin/assets/javascripts/admin/templates/admin-plugins/show/explorer/details.gjs b/plugins/discourse-data-explorer/admin/assets/javascripts/admin/templates/admin-plugins/show/explorer/details.gjs
index 231004485aa..dac3975825d 100644
--- a/plugins/discourse-data-explorer/admin/assets/javascripts/admin/templates/admin-plugins/show/explorer/details.gjs
+++ b/plugins/discourse-data-explorer/admin/assets/javascripts/admin/templates/admin-plugins/show/explorer/details.gjs
@@ -96,6 +96,13 @@ export default class QueriesDetails extends Component {
<div class="clear"></div>
+ {{#if @controller.aiGenerating}}
+ <div class="query-ai-generating">
+ <ConditionalLoadingSpinner @condition={{true}} @size="small" />
+ <span>{{i18n "explorer.ai.generating"}}</span>
+ </div>
+ {{/if}}
+
{{#if @controller.editingQuery}}
<div class="query-editor {{if @controller.hideSchema 'no-schema'}}">
<div class="panels-flex">
@@ -105,7 +112,7 @@ export default class QueriesDetails extends Component {
@content={{@controller.model.sql}}
@onChange={{fn (mut @controller.model.sql)}}
@mode="sql"
- @disabled={{@controller.model.destroyed}}
+ @disabled={{@controller.editorDisabled}}
@save={{@controller.save}}
@submit={{@controller.saveAndRun}}
/>
@@ -208,6 +215,7 @@ export default class QueriesDetails extends Component {
@action={{@controller.destroyQuery}}
@icon="trash-can"
@label="explorer.delete"
+ @disabled={{@controller.aiGenerating}}
class="btn-danger"
/>
{{/if}}
diff --git a/plugins/discourse-data-explorer/admin/assets/javascripts/admin/templates/admin-plugins/show/explorer/new.gjs b/plugins/discourse-data-explorer/admin/assets/javascripts/admin/templates/admin-plugins/show/explorer/new.gjs
index 0b1e5624888..53c51e40f65 100644
--- a/plugins/discourse-data-explorer/admin/assets/javascripts/admin/templates/admin-plugins/show/explorer/new.gjs
+++ b/plugins/discourse-data-explorer/admin/assets/javascripts/admin/templates/admin-plugins/show/explorer/new.gjs
@@ -1,5 +1,6 @@
import BackButton from "discourse/components/back-button";
import Form from "discourse/components/form";
+import icon from "discourse/helpers/d-icon";
import { i18n } from "discourse-i18n";
export default <template>
@@ -17,7 +18,7 @@ export default <template>
>
<form.Field
@name="name"
- @title={{i18n "explorer.create_placeholder"}}
+ @title={{i18n "explorer.query_name"}}
@validation="required"
@format="large"
@type="input"
@@ -38,5 +39,40 @@ export default <template>
<form.Submit @label="explorer.create" @icon="plus" />
</form.Actions>
</Form>
+
+ {{#if @controller.aiQueriesEnabled}}
+ <div class="query-new__or-divider">
+ <span>{{i18n "explorer.ai.or_divider"}}</span>
+ </div>
+
+ <Form
+ @data={{@controller.aiFormData}}
+ @onSubmit={{@controller.createWithAi}}
+ class="query-new query-new--ai"
+ as |form|
+ >
+ <label class="form-kit__label query-new__ai-label">
+ <span>{{i18n "explorer.ai.description_title"}}</span>
+ {{icon "discourse-sparkles"}}
+ </label>
+ <form.Field
+ @name="ai_description"
+ @title={{i18n "explorer.ai.description_title"}}
+ @description={{i18n "explorer.ai.description_hint"}}
+ @showTitle={{false}}
+ @validation="required"
+ @format="large"
+ @type="textarea"
+ as |field|
+ >
+ <field.Control
+ placeholder={{i18n "explorer.ai.description_placeholder"}}
+ />
+ </form.Field>
+ <form.Actions>
+ <form.Submit @label="explorer.ai.generate" />
+ </form.Actions>
+ </Form>
+ {{/if}}
</div>
</template>
diff --git a/plugins/discourse-data-explorer/app/controllers/discourse_data_explorer/query_controller.rb b/plugins/discourse-data-explorer/app/controllers/discourse_data_explorer/query_controller.rb
index dd5fd59c9e1..1de65640556 100644
--- a/plugins/discourse-data-explorer/app/controllers/discourse_data_explorer/query_controller.rb
+++ b/plugins/discourse-data-explorer/app/controllers/discourse_data_explorer/query_controller.rb
@@ -154,15 +154,21 @@ module DiscourseDataExplorer
end
def create
+ permitted = %i[name description sql]
+ permitted << :ai_description if AiQueryEnqueuer.enabled?
+
+ query_params = params.require(:query).permit(*permitted)
+ ai_description = query_params.delete(:ai_description)&.strip
+ group_ids = params.require(:query)[:group_ids]
+
query =
- Query.create!(
- params
- .require(:query)
- .permit(:name, :description, :sql)
- .merge(user_id: current_user.id, last_run_at: Time.now),
+ QueryCreator.create(
+ query_params: query_params,
+ ai_description: ai_description,
+ group_ids: group_ids,
+ user: current_user,
)
- group_ids = params.require(:query)[:group_ids]
- group_ids&.each { |group_id| query.query_groups.find_or_create_by!(group_id: group_id) }
+
render_serialized query, QueryDetailsSerializer, root: "query"
end
diff --git a/plugins/discourse-data-explorer/app/jobs/regular/generate_de_query_with_ai.rb b/plugins/discourse-data-explorer/app/jobs/regular/generate_de_query_with_ai.rb
new file mode 100644
index 00000000000..72d3c316f78
--- /dev/null
+++ b/plugins/discourse-data-explorer/app/jobs/regular/generate_de_query_with_ai.rb
@@ -0,0 +1,113 @@
+# frozen_string_literal: true
+
+module Jobs
+ class GenerateDeQueryWithAi < ::Jobs::Base
+ sidekiq_options retry: false
+
+ CHANNEL_PREFIX = "/discourse-data-explorer/queries/ai-generation"
+
+ def execute(args)
+ @query_id = args[:query_id]
+
+ return unless SiteSetting.data_explorer_enabled
+ return unless SiteSetting.data_explorer_ai_queries_enabled
+
+ query = DiscourseDataExplorer::Query.find_by(id: @query_id)
+ user = User.find_by(id: args[:user_id])
+ return if query.nil? || user.nil?
+
+ agent_id =
+ DiscourseAi::Agents::Agent.external_agent_id(DiscourseDataExplorer::AiQueryGenerator)
+ agent_record = AiAgent.find_by(id: agent_id)
+ if agent_record.nil?
+ return(
+ publish_error(
+ query,
+ user,
+ I18n.t("discourse_data_explorer.ai.error_agent_not_configured"),
+ )
+ )
+ end
+
+ agent_klass = agent_record.class_instance
+ bot = DiscourseAi::Agents::Bot.as(Discourse.system_user, agent: agent_klass.new)
+
+ context =
+ DiscourseAi::Agents::BotContext.new(
+ messages: [{ type: :user, content: args[:ai_description] }],
+ user: user,
+ feature_name: "data_explorer_query_generation",
+ )
+
+ structured_output = nil
+ result = +""
+ bot.reply(context) do |partial, _, type|
+ if type == :structured_output
+ structured_output = partial
+ elsif type.blank? && partial.is_a?(String)
+ result << partial
+ end
+ end
+ parsed = parse_structured_response(structured_output, result)
+
+ if parsed[:sql].blank?
+ return(
+ publish_error(query, user, I18n.t("discourse_data_explorer.ai.error_no_sql_returned"))
+ )
+ end
+
+ query.update!(
+ sql: parsed[:sql].chomp(";").strip,
+ name: parsed[:name].presence || args[:ai_description].to_s.truncate(60, separator: " "),
+ description: parsed[:description].presence || args[:ai_description],
+ )
+
+ publish_complete(query, user)
+ rescue => e
+ publish_error(query, user, e.message) if query && user
+ ensure
+ cleanup_redis
+ end
+
+ private
+
+ def cleanup_redis
+ Discourse.redis.del(DiscourseDataExplorer::AiQueryEnqueuer.redis_key(@query_id)) if @query_id
+ end
+
+ def parse_structured_response(structured_output, text)
+ if structured_output
+ {
+ sql: structured_output.read_buffered_property(:sql),
+ name: structured_output.read_buffered_property(:name),
+ description: structured_output.read_buffered_property(:description),
+ }
+ else
+ parsed = JSON.parse(text.strip).symbolize_keys
+ parsed.slice(:sql, :name, :description)
+ end
+ rescue JSON::ParserError
+ { sql: text.strip, name: nil, description: nil }
+ end
+
+ def publish_complete(query, user)
+ MessageBus.publish(
+ "#{CHANNEL_PREFIX}/#{query.id}",
+ { status: "complete", sql: query.sql, name: query.name, description: query.description },
+ user_ids: [user.id],
+ max_backlog_age: DiscourseDataExplorer::AiQueryEnqueuer::REDIS_TTL,
+ )
+ end
+
+ def publish_error(query, user, message)
+ return if query.nil? || user.nil?
+
+ MessageBus.publish(
+ "#{CHANNEL_PREFIX}/#{query.id}",
+ { status: "error", error: message },
+ user_ids: [user.id],
+ max_backlog_age: DiscourseDataExplorer::AiQueryEnqueuer::REDIS_TTL,
+ )
+ end
+ end
+end
diff --git a/plugins/discourse-data-explorer/app/serializers/discourse_data_explorer/query_details_serializer.rb b/plugins/discourse-data-explorer/app/serializers/discourse_data_explorer/query_details_serializer.rb
index 8abb2eabd4a..18cc41f8582 100644
--- a/plugins/discourse-data-explorer/app/serializers/discourse_data_explorer/query_details_serializer.rb
+++ b/plugins/discourse-data-explorer/app/serializers/discourse_data_explorer/query_details_serializer.rb
@@ -7,5 +7,15 @@ module DiscourseDataExplorer
def param_info
object&.params&.uniq { |p| p.identifier }&.map(&:to_hash)
end
+
+ attribute :ai_generating
+
+ def include_ai_generating?
+ SiteSetting.data_explorer_ai_queries_enabled
+ end
+
+ def ai_generating
+ Discourse.redis.exists?(DiscourseDataExplorer::AiQueryEnqueuer.redis_key(object.id))
+ end
end
end
diff --git a/plugins/discourse-data-explorer/assets/javascripts/discourse/controllers/admin-plugins/show/explorer/details.js b/plugins/discourse-data-explorer/assets/javascripts/discourse/controllers/admin-plugins/show/explorer/details.js
index b3d6879a364..13916f25a36 100644
--- a/plugins/discourse-data-explorer/assets/javascripts/discourse/controllers/admin-plugins/show/explorer/details.js
+++ b/plugins/discourse-data-explorer/assets/javascripts/discourse/controllers/admin-plugins/show/explorer/details.js
@@ -7,14 +7,22 @@ import { ajax } from "discourse/lib/ajax";
import { popupAjaxError } from "discourse/lib/ajax-error";
import { AUTO_GROUPS } from "discourse/lib/constants";
import { bind } from "discourse/lib/decorators";
+import { i18n } from "discourse-i18n";
import QueryHelp from "discourse/plugins/discourse-data-explorer/discourse/components/modal/query-help";
import { ParamValidationError } from "discourse/plugins/discourse-data-explorer/discourse/components/param-input-form";
import Query from "discourse/plugins/discourse-data-explorer/discourse/models/query";
+const AI_GENERATION_CHANNEL_PREFIX =
+ "/discourse-data-explorer/queries/ai-generation";
+const AI_GENERATION_TIMEOUT_MS = 60000;
+
export default class PluginsExplorerController extends Controller {
@service modal;
@service appEvents;
@service router;
+ @service messageBus;
+ @service siteSettings;
+ @service toasts;
@tracked params;
@tracked editingName = false;
@@ -24,19 +32,21 @@ export default class PluginsExplorerController extends Controller {
@tracked hideSchema = false;
@tracked results = this.model.results;
@tracked dirty = false;
+ @tracked aiGenerating = false;
queryParams = ["params"];
explain = false;
order = null;
form = null;
shouldAutoRun = false;
+ _aiGenerationTimer = null;
get saveDisabled() {
- return !this.dirty;
+ return this.aiGenerating || !this.dirty;
}
get runDisabled() {
- return this.dirty;
+ return this.aiGenerating || this.dirty;
}
get parsedParams() {
@@ -44,7 +54,65 @@ export default class PluginsExplorerController extends Controller {
}
get editDisabled() {
- return this.model.is_default;
+ return this.model.is_default || this.aiGenerating;
+ }
+
+ get editorDisabled() {
+ return this.model.destroyed || this.aiGenerating;
+ }
+
+ setupAiGeneration() {
+ if (
+ !this.siteSettings.data_explorer_ai_queries_enabled ||
+ !this.model.ai_generating
+ ) {
+ return;
+ }
+
+ this.aiGenerating = true;
+ this.editingQuery = true;
+ const channel = `${AI_GENERATION_CHANNEL_PREFIX}/${this.model.id}`;
+
+ this.messageBus.subscribe(channel, this._onAiGenerationMessage, -1);
+
+ this._aiGenerationTimer = setTimeout(() => {
+ this._stopAiGeneration();
+ this.toasts.error({
+ data: { message: i18n("explorer.ai.generation_timeout") },
+ });
+ }, AI_GENERATION_TIMEOUT_MS);
+ }
+
+ teardownAiGeneration() {
+ if (this.model?.id) {
+ const channel = `${AI_GENERATION_CHANNEL_PREFIX}/${this.model.id}`;
+ this.messageBus.unsubscribe(channel, this._onAiGenerationMessage);
+ }
+ if (this._aiGenerationTimer) {
+ clearTimeout(this._aiGenerationTimer);
+ this._aiGenerationTimer = null;
+ }
+ }
+
+ @bind
+ _onAiGenerationMessage(data) {
+ if (data.status === "complete") {
+ this.model.set("sql", data.sql);
+ this.model.set("name", data.name);
+ this.model.set("description", data.description);
+ this.dirty = false;
+ this._stopAiGeneration();
+ } else if (data.status === "error") {
+ this._stopAiGeneration();
+ this.toasts.error({
+ data: { message: data.error || i18n("explorer.ai.generation_error") },
+ });
+ }
+ }
+
+ _stopAiGeneration() {
+ this.aiGenerating = false;
+ this.teardownAiGeneration();
}
get groupOptions() {
diff --git a/plugins/discourse-data-explorer/assets/javascripts/discourse/controllers/admin-plugins/show/explorer/new.js b/plugins/discourse-data-explorer/assets/javascripts/discourse/controllers/admin-plugins/show/explorer/new.js
index 7648cf8fcf1..b46a5b0caca 100644
--- a/plugins/discourse-data-explorer/assets/javascripts/discourse/controllers/admin-plugins/show/explorer/new.js
+++ b/plugins/discourse-data-explorer/assets/javascripts/discourse/controllers/admin-plugins/show/explorer/new.js
@@ -9,19 +9,35 @@ export default class AdminPluginsExplorerNew extends Controller {
@service store;
@service router;
@service toasts;
+ @service siteSettings;
@tracked loading = false;
+ aiFormData = { ai_description: "" };
+
+ get aiQueriesEnabled() {
+ return this.siteSettings.data_explorer_ai_queries_enabled;
+ }
@action
async create({ name, description }) {
+ await this._createQuery({
+ name: name.trim(),
+ description: description?.trim(),
+ });
+ }
+
+ @action
+ async createWithAi({ ai_description }) {
+ await this._createQuery({
+ name: i18n("explorer.ai.generating_name"),
+ ai_description: ai_description.trim(),
+ });
+ }
+
+ async _createQuery(data) {
try {
this.loading = true;
- const result = await this.store
- .createRecord("query", {
- name: name.trim(),
- description: description?.trim(),
- })
- .save();
+ const result = await this.store.createRecord("query", data).save();
this.toasts.success({
data: { message: i18n("explorer.query_created") },
});
diff --git a/plugins/discourse-data-explorer/assets/javascripts/discourse/models/query.js b/plugins/discourse-data-explorer/assets/javascripts/discourse/models/query.js
index 8a70a8b135f..ed06717e43b 100644
--- a/plugins/discourse-data-explorer/assets/javascripts/discourse/models/query.js
+++ b/plugins/discourse-data-explorer/assets/javascripts/discourse/models/query.js
@@ -77,6 +77,10 @@ export default class Query extends RestModel {
// Importing
return this.updateProperties();
}
- return this.getProperties("name", "description");
+ const props = this.getProperties("name", "description");
+ if (this.ai_description) {
+ props.ai_description = this.ai_description;
+ }
+ return props;
}
}
diff --git a/plugins/discourse-data-explorer/assets/javascripts/discourse/routes/admin-plugins/show/explorer/details.js b/plugins/discourse-data-explorer/assets/javascripts/discourse/routes/admin-plugins/show/explorer/details.js
index 934e4606ff1..c83ba419dba 100644
--- a/plugins/discourse-data-explorer/assets/javascripts/discourse/routes/admin-plugins/show/explorer/details.js
+++ b/plugins/discourse-data-explorer/assets/javascripts/discourse/routes/admin-plugins/show/explorer/details.js
@@ -44,12 +44,19 @@ export default class AdminPluginsExplorerQueriesDetails extends DiscourseRoute {
}
setupController(controller, model, transition) {
+ controller.teardownAiGeneration();
controller.setProperties({
...model,
results: null,
showResults: false,
dirty: false,
+ aiGenerating: false,
shouldAutoRun: !!transition.to.queryParams.run,
});
+ controller.setupAiGeneration();
+ }
+
+ resetController(controller) {
+ controller.teardownAiGeneration();
}
}
diff --git a/plugins/discourse-data-explorer/assets/stylesheets/explorer.scss b/plugins/discourse-data-explorer/assets/stylesheets/explorer.scss
index 01e6e21a6ad..a866482c38c 100644
--- a/plugins/discourse-data-explorer/assets/stylesheets/explorer.scss
+++ b/plugins/discourse-data-explorer/assets/stylesheets/explorer.scss
@@ -336,6 +336,7 @@ table.group-reports {
}
.disscourse-data-explorer-query-list,
+.query-create,
.query-edit,
.query-results,
.query-params,
@@ -343,6 +344,45 @@ table.group-reports {
margin: 10px 0;
}
+.query-new__or-divider {
+ display: flex;
+ align-items: center;
+ gap: 1em;
+ width: var(--form-kit-large-input);
+ margin: 1.5em 0;
+ color: var(--primary-medium);
+ font-size: var(--font-down-1);
+ text-transform: uppercase;
+ letter-spacing: 0.1em;
+
+ &::before,
+ &::after {
+ content: "";
+ flex: 1;
+ border-top: 1px solid var(--primary-low-mid);
+ }
+}
+
+.query-new__ai-label {
+ display: flex;
+ align-items: center;
+ gap: 0.35em;
+ font-weight: 700;
+}
+
+.query-ai-generating {
+ display: flex;
+ align-items: center;
+ gap: 0.5em;
+ padding: 0.75em 1em;
+ margin-bottom: 0.75em;
+ background: var(--tertiary-very-low);
+ border: 1px solid var(--tertiary-low);
+ border-radius: var(--d-border-radius);
+ font-size: var(--font-down-1);
+ color: var(--tertiary);
+}
+
.query-results {
section {
width: 100%;
diff --git a/plugins/discourse-data-explorer/config/locales/client.en.yml b/plugins/discourse-data-explorer/config/locales/client.en.yml
index 6876f096c25..56d64629b48 100644
--- a/plugins/discourse-data-explorer/config/locales/client.en.yml
+++ b/plugins/discourse-data-explorer/config/locales/client.en.yml
@@ -22,6 +22,16 @@ en:
create: "Create"
create_placeholder: "Query name..."
description_placeholder: "Enter a description here"
+ ai:
+ or_divider: "OR"
+ description_title: "Generate with AI"
+ description_hint: "Describe what you want in plain language. We'll generate the SQL, name, and description for you."
+ description_placeholder: "e.g. Show me signups across time"
+ generate: "Generate"
+ generating_name: "Generating..."
+ generating: "Generating query with AI..."
+ generation_timeout: "AI query generation timed out. You can write the SQL manually."
+ generation_error: "Something went wrong generating the query."
import:
label: "Import"
unparseable_json: "Unparseable JSON file."
diff --git a/plugins/discourse-data-explorer/config/locales/server.en.yml b/plugins/discourse-data-explorer/config/locales/server.en.yml
index 01013dc71ce..cf87e720ccd 100644
--- a/plugins/discourse-data-explorer/config/locales/server.en.yml
+++ b/plugins/discourse-data-explorer/config/locales/server.en.yml
@@ -17,6 +17,11 @@ en:
tool_description:
validate_sql: "Validated SQL query"
run_sql: "Ran SQL query"
+ discourse_data_explorer:
+ ai:
+ generating_name: "Generating..."
+ error_agent_not_configured: "AI agent is not configured. Please check the AI features settings."
+ error_no_sql_returned: "AI did not return a valid SQL query. Please try again or write the query manually."
discourse_automation:
scriptables:
recurring_data_explorer_result_pm:
diff --git a/plugins/discourse-data-explorer/lib/discourse_data_explorer/ai_query_enqueuer.rb b/plugins/discourse-data-explorer/lib/discourse_data_explorer/ai_query_enqueuer.rb
new file mode 100644
index 00000000000..79c7b3c4143
--- /dev/null
+++ b/plugins/discourse-data-explorer/lib/discourse_data_explorer/ai_query_enqueuer.rb
@@ -0,0 +1,27 @@
+# frozen_string_literal: true
+
+module DiscourseDataExplorer
+ class AiQueryEnqueuer
+ REDIS_TTL = 360
+
+ def self.enabled?
+ SiteSetting.data_explorer_ai_queries_enabled && defined?(DiscourseAi)
+ end
+
+ def self.redis_key(query_id)
+ "data_explorer_ai_generating:#{query_id}"
+ end
+
+ def self.enqueue(query:, user:, ai_description:)
+ return if !enabled? || ai_description.blank?
+
+ Discourse.redis.setex(redis_key(query.id), REDIS_TTL, user.id)
+ Jobs.enqueue(
+ :generate_de_query_with_ai,
+ query_id: query.id,
+ user_id: user.id,
+ ai_description: ai_description,
+ )
+ end
+ end
+end
diff --git a/plugins/discourse-data-explorer/lib/discourse_data_explorer/query_creator.rb b/plugins/discourse-data-explorer/lib/discourse_data_explorer/query_creator.rb
new file mode 100644
index 00000000000..5c99d577f32
--- /dev/null
+++ b/plugins/discourse-data-explorer/lib/discourse_data_explorer/query_creator.rb
@@ -0,0 +1,28 @@
+# frozen_string_literal: true
+
+module DiscourseDataExplorer
+ class QueryCreator
+ def self.create(query_params:, ai_description:, group_ids:, user:)
+ name = query_params[:name].presence
+ if name.blank?
+ if AiQueryEnqueuer.enabled? && ai_description.present?
+ name = I18n.t("discourse_data_explorer.ai.generating_name")
+ else
+ raise Discourse::InvalidParameters.new(:name)
+ end
+ end
+
+ attrs = { name: name, user_id: user.id, last_run_at: Time.now }
+ attrs[:description] = query_params[:description] if query_params[:description].present?
+ attrs[:sql] = query_params[:sql] if query_params[:sql].present?
+
+ query = Query.create!(attrs)
+
+ group_ids&.each { |group_id| query.query_groups.find_or_create_by!(group_id: group_id) }
+
+ AiQueryEnqueuer.enqueue(query: query, user: user, ai_description: ai_description)
+
+ query
+ end
+ end
+end
diff --git a/plugins/discourse-data-explorer/spec/system/ai_query_generation_spec.rb b/plugins/discourse-data-explorer/spec/system/ai_query_generation_spec.rb
new file mode 100644
index 00000000000..a5e807d80ea
--- /dev/null
+++ b/plugins/discourse-data-explorer/spec/system/ai_query_generation_spec.rb
@@ -0,0 +1,58 @@
+# frozen_string_literal: true
+
+RSpec.describe "Data Explorer AI query generation" do
+ fab!(:admin)
+
+ before do
+ SiteSetting.data_explorer_enabled = true
+ sign_in admin
+ end
+
+ # background job publishes this when generation completes.
+ # it's internals, but allows us to test re-enablement of the buttons
+ def simulate_finish_generating(query, user)
+ MessageBus.publish(
+ "/discourse-data-explorer/queries/ai-generation/#{query.id}",
+ { status: "complete", sql: "SELECT 1", name: "Test Query", description: "A test" },
+ user_ids: [user.id],
+ )
+ end
+
+ context "when ai queries setting is disabled" do
+ before { SiteSetting.data_explorer_ai_queries_enabled = false }
+
+ it "does not show the AI description field in the create form" do
+ visit("/admin/plugins/discourse-data-explorer/queries/new")
+
+ expect(page).to have_css(".query-new")
+ expect(page).to have_no_field("Generate with AI")
+ end
+ end
+
+ context "when ai queries setting is enabled" do
+ before { SiteSetting.data_explorer_ai_queries_enabled = true }
+
+ it "shows the AI description field and creates a query with generating state" do
+ visit("/admin/plugins/discourse-data-explorer/queries/new")
+
+ expect(page).to have_css(".query-new--ai")
+
+ find(".query-new--ai textarea[name='ai_description']").fill_in(
+ with: "show me users who signed up in the last 7 days",
+ )
+
+ find(".query-new--ai .form-kit__actions .btn-primary").click
+
+ expect(page).to have_current_path(%r{/admin/plugins/discourse-data-explorer/queries/\d+})
+ expect(page).to have_css(".query-ai-generating")
+ expect(page).to have_button("Run", disabled: true)
+ expect(page).to have_button("Delete", disabled: true)
+
+ simulate_finish_generating(DiscourseDataExplorer::Query.last, admin)
+
+ expect(page).to have_no_css(".query-ai-generating")
+ expect(page).to have_button("Run", disabled: false)
+ expect(page).to have_button("Delete", disabled: false)
+ end
+ end
+end