Skip to content

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

FEATURE: generate SQL of data-explorer node with AI (#42607)

Joffrey JAFFEUXb69b97442e85
diff --git a/plugins/discourse-data-explorer/admin/assets/javascripts/discourse/initializers/register-workflow-ai-query.js b/plugins/discourse-data-explorer/admin/assets/javascripts/discourse/initializers/register-workflow-ai-query.js
new file mode 100644
index 00000000000..a3d3d548fc2
--- /dev/null
+++ b/plugins/discourse-data-explorer/admin/assets/javascripts/discourse/initializers/register-workflow-ai-query.js
@@ -0,0 +1,33 @@
+import { withPluginApi } from "discourse/lib/plugin-api";
+import DataExplorerWorkflowAiQuery from "discourse/plugins/discourse-data-explorer/discourse/components/data-explorer-workflow-ai-query";
+
+export default {
+ name: "data-explorer-register-workflow-ai-query",
+
+ initialize(container) {
+ const siteSettings = container.lookup("service:site-settings");
+ if (!siteSettings.enable_discourse_workflows) {
+ return;
+ }
+
+ withPluginApi((api) => {
+ api.registerValueTransformer(
+ "workflow-field-control",
+ ({ value, context }) => {
+ if (
+ context.node?.type !== "action:sql" ||
+ context.fieldName !== "query" ||
+ context.nodeParameters?.operation !== "raw"
+ ) {
+ return value;
+ }
+
+ return {
+ ...value,
+ addons: [...(value.addons || []), DataExplorerWorkflowAiQuery],
+ };
+ }
+ );
+ });
+ },
+};
diff --git a/plugins/discourse-data-explorer/assets/javascripts/discourse/components/data-explorer-workflow-ai-query.gjs b/plugins/discourse-data-explorer/assets/javascripts/discourse/components/data-explorer-workflow-ai-query.gjs
new file mode 100644
index 00000000000..d1c55b67285
--- /dev/null
+++ b/plugins/discourse-data-explorer/assets/javascripts/discourse/components/data-explorer-workflow-ai-query.gjs
@@ -0,0 +1,151 @@
+import Component from "@glimmer/component";
+import { tracked } from "@glimmer/tracking";
+import { action } from "@ember/object";
+import { service } from "@ember/service";
+import { ajax } from "discourse/lib/ajax";
+import { popupAjaxError } from "discourse/lib/ajax-error";
+import dIcon from "discourse/ui-kit/helpers/d-icon";
+import { i18n } from "discourse-i18n";
+import { subscribeToAiGeneration } from "discourse/plugins/discourse-data-explorer/discourse/lib/ai-generation";
+import { dataExplorerAiQueriesEnabled } from "discourse/plugins/discourse-data-explorer/discourse/lib/ai-query-availability";
+import QueryAiPrompt from "./query-ai-prompt";
+
+export default class DataExplorerWorkflowAiQuery extends Component {
+ @service messageBus;
+ @service siteSettings;
+ @service toasts;
+
+ @tracked prompt = "";
+ @tracked generating = false;
+
+ #teardownAiGeneration = null;
+
+ willDestroy() {
+ super.willDestroy(...arguments);
+ this.#teardownAiGeneration?.();
+ }
+
+ get shouldRender() {
+ return (
+ dataExplorerAiQueriesEnabled(this.siteSettings) &&
+ this.args.node?.type === "action:sql" &&
+ this.args.fieldName === "query" &&
+ this.args.nodeParameters?.operation === "raw"
+ );
+ }
+
+ get sql() {
+ return this.args.field.value?.toString() || "";
+ }
+
+ get actionLabel() {
+ return this.sql.trim() ? "explorer.ai.regenerate" : "explorer.ai.generate";
+ }
+
+ get placeholder() {
+ return this.sql.trim()
+ ? i18n("explorer.ai.regenerate_placeholder")
+ : i18n("explorer.ai.description_placeholder");
+ }
+
+ get generateDisabled() {
+ return this.disabled || !this.prompt.trim();
+ }
+
+ get disabled() {
+ return this.generating || this.args.field.disabled;
+ }
+
+ @action
+ updatePrompt(event) {
+ this.prompt = event.target.value;
+ }
+
+ @action
+ async generate() {
+ if (this.generateDisabled) {
+ return;
+ }
+
+ this.generating = true;
+
+ try {
+ const { generation_id: generationId } = await ajax(
+ "/admin/plugins/discourse-data-explorer/queries/generate.json",
+ {
+ type: "POST",
+ data: {
+ ai_description: this.prompt.trim(),
+ existing_sql: this.sql.trim() || undefined,
+ },
+ }
+ );
+
+ if (this.isDestroying || this.isDestroyed) {
+ return;
+ }
+
+ this.#teardownAiGeneration = subscribeToAiGeneration({
+ messageBus: this.messageBus,
+ generationId,
+ onComplete: ({ sql }) => {
+ this.args.field.set(sql);
+ this.generating = false;
+ },
+ onError: ({ error }) => {
+ this.#showGenerationError(
+ error || i18n("explorer.ai.generation_error")
+ );
+ },
+ onTimeout: () => {
+ this.#showGenerationError(i18n("explorer.ai.generation_timeout"));
+ },
+ });
+ } catch (error) {
+ if (this.isDestroying || this.isDestroyed) {
+ return;
+ }
+
+ this.generating = false;
+ popupAjaxError(error);
+ }
+ }
+
+ #showGenerationError(message) {
+ this.generating = false;
+ this.toasts.error({ data: { message } });
+ }
+
+ <template>
+ {{#if this.shouldRender}}
+ <section
+ class="data-explorer-workflow-ai-query"
+ aria-labelledby="data-explorer-workflow-ai-query-title"
+ >
+ <header class="data-explorer-workflow-ai-query__header">
+ <span class="data-explorer-workflow-ai-query__icon">
+ {{dIcon "discourse-sparkles"}}
+ </span>
+ <h3
+ id="data-explorer-workflow-ai-query-title"
+ class="data-explorer-workflow-ai-query__title"
+ >
+ {{i18n "explorer.ai.workflow_title"}}
+ </h3>
+ </header>
+ <QueryAiPrompt
+ @value={{this.prompt}}
+ @onChange={{this.updatePrompt}}
+ @onRegenerate={{this.generate}}
+ @regenerateDisabled={{this.generateDisabled}}
+ @generating={{this.generating}}
+ @disabled={{this.disabled}}
+ @actionLabel={{this.actionLabel}}
+ @actionClass="btn-primary"
+ @placeholder={{this.placeholder}}
+ class="data-explorer-workflow-ai-query__prompt"
+ />
+ </section>
+ {{/if}}
+ </template>
+}
diff --git a/plugins/discourse-data-explorer/assets/javascripts/discourse/components/query-ai-prompt.gjs b/plugins/discourse-data-explorer/assets/javascripts/discourse/components/query-ai-prompt.gjs
index 2ff8c014e8d..8c1a2baf494 100644
--- a/plugins/discourse-data-explorer/assets/javascripts/discourse/components/query-ai-prompt.gjs
+++ b/plugins/discourse-data-explorer/assets/javascripts/discourse/components/query-ai-prompt.gjs
@@ -1,18 +1,22 @@
import { on } from "@ember/modifier";
+import { or } from "discourse/truth-helpers";
import DButton from "discourse/ui-kit/d-button";
-import DConditionalLoadingSpinner from "discourse/ui-kit/d-conditional-loading-spinner";
import DTextarea from "discourse/ui-kit/d-textarea";
+import dConcatClass from "discourse/ui-kit/helpers/d-concat-class";
import { i18n } from "discourse-i18n";
const QueryAiPrompt = <template>
- <div class="query-ai-prompt">
+ <div class="query-ai-prompt" ...attributes>
<label class="query-ai-prompt__label" for="query-ai-prompt-input">
{{i18n "explorer.ai.prompt_label"}}
</label>
<DTextarea
@value={{@value}}
{{on "input" @onChange}}
- placeholder={{i18n "explorer.ai.regenerate_placeholder"}}
+ placeholder={{or
+ @placeholder
+ (i18n "explorer.ai.regenerate_placeholder")
+ }}
id="query-ai-prompt-input"
class="query-ai-prompt__input"
disabled={{@disabled}}
@@ -21,20 +25,15 @@ const QueryAiPrompt = <template>
<DButton
@action={{@onRegenerate}}
@icon="arrows-rotate"
- @label="explorer.ai.regenerate"
+ @label={{or @actionLabel "explorer.ai.regenerate"}}
@disabled={{@regenerateDisabled}}
- class="btn-default query-ai-prompt__regenerate"
+ @isLoading={{@generating}}
+ aria-busy={{@generating}}
+ class={{dConcatClass
+ (or @actionClass "btn-default")
+ "query-ai-prompt__regenerate"
+ }}
/>
- {{#if @generating}}
- <span
- class="query-ai-prompt__generating"
- role="status"
- aria-live="polite"
- >
- <DConditionalLoadingSpinner @condition={{true}} @size="small" />
- <span>{{i18n "explorer.ai.generating"}}</span>
- </span>
- {{/if}}
</div>
</div>
</template>;
diff --git a/plugins/discourse-data-explorer/assets/stylesheets/explorer.scss b/plugins/discourse-data-explorer/assets/stylesheets/explorer.scss
index 61a7a956b18..45c06db7345 100644
--- a/plugins/discourse-data-explorer/assets/stylesheets/explorer.scss
+++ b/plugins/discourse-data-explorer/assets/stylesheets/explorer.scss
@@ -527,30 +527,71 @@ table.group-reports {
.query-ai-prompt {
display: flex;
flex-direction: column;
- gap: 0.5em;
+ gap: var(--space-1);
margin: 1em 0;
&__label {
- font-weight: 700;
+ margin: 0;
+ color: var(--primary);
+ font-size: var(--font-down-1-rem);
+ font-weight: 600;
+ line-height: var(--line-height-medium);
}
&__input {
width: 100%;
+ height: auto;
min-height: 4em;
}
&__actions {
display: flex;
align-items: center;
- gap: 0.75em;
+ margin-block-start: var(--space-1);
+ }
+}
+
+.data-explorer-workflow-ai-query {
+ display: flex;
+ flex-direction: column;
+ gap: var(--space-3);
+ align-self: stretch;
+ min-width: 0;
+ margin-block: var(--space-3) 0;
+ padding: var(--space-3);
+ background: var(--primary-very-low);
+ border: 1px solid var(--primary-low);
+ border-inline-start: 3px solid var(--tertiary);
+ border-radius: var(--d-border-radius);
+
+ &__header {
+ display: flex;
+ align-items: center;
+ gap: var(--space-2);
}
- &__generating {
+ &__icon {
display: inline-flex;
align-items: center;
- gap: 0.35em;
- color: var(--primary-medium);
- font-size: var(--font-down-1);
+ justify-content: center;
+ flex: 0 0 auto;
+ width: 2rem;
+ height: 2rem;
+ color: var(--tertiary);
+ background: var(--secondary);
+ border: 1px solid var(--primary-low);
+ border-radius: var(--d-border-radius-pill);
+ }
+
+ &__title {
+ margin: 0;
+ color: var(--primary);
+ font-size: var(--font-up-1);
+ line-height: var(--line-height-medium);
+ }
+
+ &__prompt {
+ margin: 0;
}
}
diff --git a/plugins/discourse-data-explorer/config/locales/client.en.yml b/plugins/discourse-data-explorer/config/locales/client.en.yml
index b9b780a718c..d219312c52b 100644
--- a/plugins/discourse-data-explorer/config/locales/client.en.yml
+++ b/plugins/discourse-data-explorer/config/locales/client.en.yml
@@ -43,8 +43,9 @@ en:
description_placeholder: "e.g. Show me signups across time"
regenerate_placeholder: "e.g. Update the query to limit to 50 results"
prompt_label: "Prompt"
+ workflow_title: "AI query assistant"
generate: "Generate"
- regenerate: "Update query"
+ regenerate: "Generate query"
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."
@@ -177,14 +178,13 @@ en:
sql:
operation: "Operation"
operation_description: "How to run the query"
- queries: "Queries"
- raw: "Raw SQL"
+ operation_queries: "Predefined queries"
+ operation_raw: "Raw SQL query"
query_id: "Query"
query_id_description: "Select a saved query to run"
query_params: "Query parameters"
query_params_description: "Fill in the parameters for the selected query"
query: "SQL query"
- query_description: "Write a read-only SQL query. Declare parameters with Data Explorer syntax and map their values below."
params: "Query parameters"
params_description: "Parameters can be used as :my_param in the SQL query."
add_param: "Add parameter"
diff --git a/plugins/discourse-data-explorer/test/javascripts/integration/components/data-explorer-workflow-ai-query-test.gjs b/plugins/discourse-data-explorer/test/javascripts/integration/components/data-explorer-workflow-ai-query-test.gjs
new file mode 100644
index 00000000000..09c716d96d5
--- /dev/null
+++ b/plugins/discourse-data-explorer/test/javascripts/integration/components/data-explorer-workflow-ai-query-test.gjs
@@ -0,0 +1,323 @@
+import { tracked } from "@glimmer/tracking";
+import { action } from "@ember/object";
+import {
+ clearRender,
+ click,
+ fillIn,
+ render,
+ settled,
+} from "@ember/test-helpers";
+import { module, test } from "qunit";
+import sinon from "sinon";
+import { setupRenderingTest } from "discourse/tests/helpers/component-test";
+import pretender, { response } from "discourse/tests/helpers/create-pretender";
+import { publishToMessageBus } from "discourse/tests/helpers/qunit-helpers";
+import { i18n } from "discourse-i18n";
+import DataExplorerWorkflowAiQuery from "discourse/plugins/discourse-data-explorer/discourse/components/data-explorer-workflow-ai-query";
+import { AI_GENERATION_TIMEOUT_MS } from "discourse/plugins/discourse-data-explorer/discourse/lib/ai-generation";
+
+const GENERATION_ID = "workflow-query-generation";
+const CHANNEL = `/discourse-data-explorer/queries/ai-generation/${GENERATION_ID}`;
+
+class QueryState {
+ @tracked value;
+ disabled = false;
+
+ constructor(value) {
+ this.value = value;
+ }
+
+ @action
+ set(value) {
+ this.value = value;
+ }
+}
+
+module(
+ "Integration | Component | DataExplorerWorkflowAiQuery",
+ function (hooks) {
+ setupRenderingTest(hooks);
+
+ hooks.beforeEach(function () {
+ this.siteSettings.data_explorer_ai_queries_enabled = true;
+ this.siteSettings.discourse_ai_enabled = true;
+ this.queryState = new QueryState("SELECT 1");
+ this.node = { type: "action:sql" };
+ this.nodeParameters = { operation: "raw" };
+ this.schema = { control_options: { lang: "sql" } };
+ this.fieldName = "query";
+
+ pretender.post(
+ "/admin/plugins/discourse-data-explorer/queries/generate.json",
+ () => response({ generation_id: GENERATION_ID, status: "generating" })
+ );
+ });
+
+ hooks.afterEach(function () {
+ sinon.restore();
+ });
+
+ async function renderComponent(context) {
+ await render(
+ <template>
+ <DataExplorerWorkflowAiQuery
+ @field={{context.queryState}}
+ @fieldName={{context.fieldName}}
+ @schema={{context.schema}}
+ @node={{context.node}}
+ @nodeParameters={{context.nodeParameters}}
+ />
+ </template>
+ );
+ }
+
+ async function startGeneration(prompt) {
+ await fillIn(".query-ai-prompt__input", prompt);
+ await click(".query-ai-prompt__regenerate");
+ }
+
+ test("renders only for an available Raw SQL query field", async function (assert) {
+ await renderComponent(this);
+
+ assert
+ .dom(".data-explorer-workflow-ai-query")
+ .exists("renders for the Raw SQL query field");
+ assert
+ .dom(".query-ai-prompt__regenerate")
+ .hasText("Generate query", "offers to regenerate existing SQL");
+
+ this.set("nodeParameters", { operation: "queries" });
+ await settled();
+ assert
+ .dom(".data-explorer-workflow-ai-query")
+ .doesNotExist("does not render for saved queries");
+
+ this.set("nodeParameters", { operation: "raw" });
+ this.set("fieldName", "code");
+ await settled();
+ assert
+ .dom(".data-explorer-workflow-ai-query")
+ .doesNotExist("does not render for unrelated code fields");
+
+ this.set("fieldName", "query");
+ this.set("node", { type: "action:code" });
+ await settled();
+ assert
+ .dom(".data-explorer-workflow-ai-query")
+ .doesNotExist("does not render for unrelated code nodes");
+
+ this.set("node", { type: "action:sql" });
+ this.siteSettings.discourse_ai_enabled = false;
+ await settled();
+ assert
+ .dom(".data-explorer-workflow-ai-query")
+ .doesNotExist("does not render when Discourse AI is unavailable");
+
+ this.siteSettings.discourse_ai_enabled = true;
+ this.siteSettings.data_explorer_ai_queries_enabled = false;
+ await settled();
+ assert
+ .dom(".data-explorer-workflow-ai-query")
+ .doesNotExist("does not render when AI query generation is disabled");
+ });
+
+ test("uses Generate for an empty SQL field", async function (assert) {
+ this.queryState = new QueryState("");
+ await renderComponent(this);
+
+ assert
+ .dom(".query-ai-prompt__regenerate")
+ .hasText("Generate", "offers to generate an initial query");
+ assert
+ .dom(".query-ai-prompt__input")
+ .hasAttribute(
+ "placeholder",
+ i18n("explorer.ai.description_placeholder"),
+ "uses the initial query prompt"
+ );
+ });
+
+ test("presents generation as a distinct AI area", async function (assert) {
+ await renderComponent(this);
+
+ assert
+ .dom(".data-explorer-workflow-ai-query")
+ .hasAttribute(
+ "aria-labelledby",
+ "data-explorer-workflow-ai-query-title",
+ "labels the AI section"
+ );
+ assert
+ .dom(".data-explorer-workflow-ai-query__title")
+ .hasText(
+ i18n("explorer.ai.workflow_title"),
+ "identifies the AI assistant"
+ );
+ assert
+ .dom(".data-explorer-workflow-ai-query__description")
+ .doesNotExist("keeps the AI area concise");
+ assert
+ .dom(
+ ".data-explorer-workflow-ai-query__icon .d-icon-discourse-sparkles"
+ )
+ .exists("shows the standard AI icon");
+ assert
+ .dom(".query-ai-prompt__regenerate")
+ .hasClass("btn-primary", "emphasizes the AI action");
+ assert
+ .dom(".query-ai-prompt__regenerate .d-icon-arrows-rotate")
+ .exists("shows the query generation icon");
+ });
+
+ test("sends the current SQL and applies a completed generation", async function (assert) {
+ let requestParams;
+ pretender.post(
+ "/admin/plugins/discourse-data-explorer/queries/generate.json",
+ (request) => {
+ requestParams = new URLSearchParams(request.requestBody);
+ return response({
+ generation_id: GENERATION_ID,
+ status: "generating",
+ });
+ }
+ );
+ await renderComponent(this);
+
+ await startGeneration("Show active users");
+
+ assert.strictEqual(
+ requestParams.get("ai_description"),
+ "Show active users",
+ "sends the natural-language prompt"
+ );
+ assert.strictEqual(
+ requestParams.get("existing_sql"),
+ "SELECT 1",
+ "sends the current SQL as refinement context"
+ );
+ assert.false(
+ requestParams.has("llm_model_id"),
+ "uses the site-wide default instead of a per-request override"
+ );
+ assert
+ .dom(".query-ai-prompt__regenerate")
+ .isDisabled("prevents repeat submissions while generating");
+ assert
+ .dom(".query-ai-prompt__regenerate")
+ .hasClass("is-loading", "uses the button loading state");
+ assert
+ .dom(".query-ai-prompt__regenerate .loading-icon")
+ .exists("shows the loading spinner inside the button");
+ assert
+ .dom(".query-ai-prompt__generating")
+ .doesNotExist("does not render a separate loading indicator");
+
+ await publishToMessageBus(CHANNEL, {
+ generation_id: GENERATION_ID,
+ status: "complete",
+ sql: "SELECT id FROM users",
+ });
+ await settled();
+
+ assert.strictEqual(
+ this.queryState.value,
+ "SELECT id FROM users",
+ "applies the verified SQL to the field"
+ );
+ assert
+ .dom(".query-ai-prompt__regenerate")
+ .isEnabled("allows the generated SQL to be refined again");
+ });
+
+ test("preserves SQL and restores the prompt after a generation error", async function (assert) {
+ await renderComponent(this);
+ await startGeneration("Show active users");
+
+ await publishToMessageBus(CHANNEL, {
+ generation_id: GENERATION_ID,
+ status: "error",
+ error: "The model is unavailable",
+ });
+ await settled();
+
+ assert.strictEqual(
+ this.queryState.value,
+ "SELECT 1",
+ "does not replace SQL after an error"
+ );
+ assert
+ .dom(".query-ai-prompt__regenerate")
+ .isEnabled("allows the prompt to be retried");
+ assert.strictEqual(
+ this.owner.lookup("service:toasts").activeToasts.at(-1).options.data
+ .message,
+ "The model is unavailable",
+ "shows the generation error"
+ );
+ });
+
+ test("preserves SQL and restores the prompt after a request error", async function (assert) {
+ pretender.post(
+ "/admin/plugins/discourse-data-explorer/queries/generate.json",
+ () => response(500, { errors: ["Request failed"] })
+ );
+ await renderComponent(this);
+ await startGeneration("Show active users");
+
+ assert.strictEqual(
+ this.queryState.value,
+ "SELECT 1",
+ "does not replace SQL after a request error"
+ );
+ assert
+ .dom(".query-ai-prompt__regenerate")
+ .isEnabled("allows the request to be retried");
+ });
+
+ test("preserves SQL and restores the prompt after a timeout", async function (assert) {
+ let timeoutCallback;
+ const originalSetTimeout = window.setTimeout;
+ sinon.stub(window, "setTimeout").callsFake((callback, delay, ...args) => {
+ if (delay === AI_GENERATION_TIMEOUT_MS) {
+ timeoutCallback = callback;
+ return 123;
+ }
+ return originalSetTimeout(callback, delay, ...args);
+ });
+
+ await renderComponent(this);
+ await startGeneration("Show active users");
+ timeoutCallback();
+ await settled();
+
+ assert.strictEqual(
+ this.queryState.value,
+ "SELECT 1",
+ "does not replace SQL after a timeout"
+ );
+ assert
+ .dom(".query-ai-prompt__regenerate")
+ .isEnabled("allows the prompt to be retried");
+ assert.strictEqual(
+ this.owner.lookup("service:toasts").activeToasts.at(-1).options.data
+ .message,
+ i18n("explorer.ai.generation_timeout"),
+ "shows the timeout error"
+ );
+ });
+
+ test("unsubscribes from an in-flight generation when destroyed", async function (assert) {
+ const messageBus = this.owner.lookup("service:message-bus");
+ const unsubscribe = sinon.spy(messageBus, "unsubscribe");
+ await renderComponent(this);
+ await startGeneration("Show active users");
+
+ await clearRender();
+
+ assert.true(
+ unsubscribe.calledWith(CHANNEL),
+ "removes the generation subscription"
+ );
+ });
+ }
+);
diff --git a/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/configurators/field.gjs b/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/configurators/field.gjs
index 5b471f33d6d..623de433579 100644
--- a/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/configurators/field.gjs
+++ b/plugins/discourse-workflows/admin/assets/javascripts/admin/components/workflows/configurators/field.gjs
@@ -1,5 +1,6 @@
import Component from "@glimmer/component";
import { trustHTML } from "@ember/template";
+import { applyValueTransformer } from "discourse/lib/transformer";
import { eq } from "discourse/truth-helpers";
import { i18n } from "discourse-i18n";
import FIELD_CONTROL_REGISTRY from "../../../lib/workflows/field-control-registry";
@@ -48,9 +49,16 @@ export default class Field extends Component {
}
get entry() {
- return (
- FIELD_CONTROL_REGISTRY[this.control] || FIELD_CONTROL_REGISTRY.default
- );
+ const entry =
+ FIELD_CONTROL_REGISTRY[this.control] || FIELD_CONTROL_REGISTRY.default;
+
+ return applyValueTransformer("workflow-field-control", entry, {
+ control: this.control,
+ fieldName: this.args.fieldName,
+ node: this.args.node,
+ nodeParameters: this.args.nodeParameters,
+ schema: this.args.schema,
+ });
}
get renderer() {
@@ -254,6 +262,15 @@ export default class Field extends Component {
@onBeforeStartTestSession={{@onBeforeStartTestSession}}
/>
{{/if}}
+ {{#each this.entry.addons as |Addon|}}
+ <Addon
+ @field={{field}}
+ @fieldName={{@fieldName}}
+ @node={{@node}}
+ @nodeParameters={{@nodeParameters}}
+ @schema={{@schema}}
+ />
+ {{/each}}
</@form.Field>
{{/if}}
</template>
diff --git a/plugins/discourse-workflows/assets/javascripts/discourse/pre-initializers/workflow-transformers.js b/plugins/discourse-workflows/assets/javascripts/discourse/pre-initializers/workflow-transformers.js
index d73ae4d256a..814a1676571 100644
--- a/plugins/discourse-workflows/assets/javascripts/discourse/pre-initializers/workflow-transformers.js
+++ b/plugins/discourse-workflows/assets/javascripts/discourse/pre-initializers/workflow-transformers.js
@@ -7,6 +7,7 @@ export default {
withPluginApi((api) => {
api.addValueTransformerName("workflow-node-defaults");
api.addValueTransformerName("workflow-node-icons");
+ api.addValueTransformerName("workflow-field-control");
});
},
};
diff --git a/plugins/discourse-workflows/test/javascripts/integration/components/workflows/field-control-addon-test.gjs b/plugins/discourse-workflows/test/javascripts/integration/components/workflows/field-control-addon-test.gjs
new file mode 100644
index 00000000000..c9e2fb63968
--- /dev/null
+++ b/plugins/discourse-workflows/test/javascripts/integration/components/workflows/field-control-addon-test.gjs
@@ -0,0 +1,97 @@
+import Component from "@glimmer/component";
+import { hash } from "@ember/helper";
+import { action } from "@ember/object";
+import { click, render } from "@ember/test-helpers";
+import { module, test } from "qunit";
+import Form from "discourse/components/form";
+import { withPluginApi } from "discourse/lib/plugin-api";
+import { setupRenderingTest } from "discourse/tests/helpers/component-test";
+import DButton from "discourse/ui-kit/d-button";
+import Field from "discourse/plugins/discourse-workflows/admin/components/workflows/configurators/field";
+
+class FieldControlAddonProbe extends Component {
+ @action
+ updateValue() {
+ this.args.field.set("SELECT 2");
+ }
+
+ <template>
+ <DButton
+ @action={{this.updateValue}}
+ @translatedLabel={{@field.value}}
+ class="btn-default field-control-addon-probe"
+ />
+ </template>
+}
+
+module(
+ "Integration | Component | Workflows | FieldControlAddon",
+ function (hooks) {
+ setupRenderingTest(hooks);
+
+ hooks.beforeEach(function () {
+ withPluginApi((api) => {
+ api.registerValueTransformer(
+ "workflow-field-control",
+ ({ value, context }) => {
+ if (
+ context.node?.type !== "action:sql" ||
+ context.fieldName !== "query"
+ ) {
+ return value;
+ }
+
+ return {
+ ...value,
+ addons: [...(value.addons || []), FieldControlAddonProbe],
+ };
+ }
+ );
+ });
+ });
+
+ test("renders registered add-ons and updates through the FormKit field", async function (assert) {
+ this.configuration = { query: "SELECT 1" };
+ this.formApi = null;
+ this.registerApi = (api) => {
+ this.formApi = api;
+ };
+
+ await render(
+ <template>
+ <Form
+ @data={{this.configuration}}
+ @onRegisterApi={{this.registerApi}}
+ as |form transientData|
+ >
+ <Field
+ @form={{form}}
+ @configuration={{transientData}}
+ @fieldName="query"
+ @label="Query"
+ @node={{hash type="action:sql"}}
+ @nodeParameters={{transientData}}
+ @schema={{hash
+ type="string"
+ no_data_expression=true
+ ui=(hash control="code")
+ }}
+ />
+ </Form>
+ </template>
+ );
+
+ assert
+ .dom(".field-control-addon-probe")
+ .hasText("SELECT 1", "the add-on receives the field value");
+
+ await click(".field-control-addon-probe");
+
+ assert.strictEqual(
+ this.formApi.get("query"),
+ "SELECT 2",
+ "the add-on updates the FormKit field"
+ );
+ });
+ }
+);