A platform for community discussion. Free, open, simple.
FEATURE: Allow admins to duplicate AI agents (#42298)
Natalie Tay06e652a1e255
diff --git a/frontend/discourse/app/form-kit/components/fk/form.gjs b/frontend/discourse/app/form-kit/components/fk/form.gjsindex a3fe82a7581..bdd19d0d397 100644--- a/frontend/discourse/app/form-kit/components/fk/form.gjs+++ b/frontend/discourse/app/form-kit/components/fk/form.gjs@@ -51,6 +51,7 @@ class FKForm extends Component {set: this.set,setProperties: this.setProperties,get: this.get,+ commit: this.commit,commitField: this.commitField,submit: this.onSubmit,reset: this.onReset,@@ -197,6 +198,11 @@ class FKForm extends Component {}}+ @action+ commit() {+ this.formData.save();+ }+@actioncommitField(name) {this.formData.commitField(name);@@ -270,7 +276,9 @@ class FKForm extends Component {await this.validate([...this.fields.values()]);if (this.formData.isValid) {- this.formData.save();+ if (this.args.commitOnSubmit !== false) {+ this.formData.save();+ }await this.args.onSubmit?.(this.formData.draftData);} else {@@ -393,6 +401,7 @@ const Form = <template>{{#each (array @data) as |data|}}<FKForm@data={{data}}+ @commitOnSubmit={{@commitOnSubmit}}@onSubmit={{@onSubmit}}@validate={{@validate}}@validateOn={{@validateOn}}diff --git a/frontend/discourse/tests/integration/components/form-kit/form-test.gjs b/frontend/discourse/tests/integration/components/form-kit/form-test.gjsindex f884675cee7..ff4d95a14d8 100644--- a/frontend/discourse/tests/integration/components/form-kit/form-test.gjs+++ b/frontend/discourse/tests/integration/components/form-kit/form-test.gjs@@ -21,6 +21,32 @@ module("Integration | Component | FormKit | Form", function (hooks) {await formKit().submit();});+ test("@onSubmit keeps changes dirty when submission fails", async function (assert) {+ let formApi;+ const registerApi = (api) => (formApi = api);+ const onSubmit = () => Promise.reject(new Error("save failed"));++ await render(+ <template>+ <Form+ @data={{hash foo=1}}+ @commitOnSubmit={{false}}+ @onSubmit={{onSubmit}}+ @onRegisterApi={{registerApi}}+ />+ </template>+ );++ await formApi.set("foo", 2);++ await assert.rejects(formApi.submit(), /save failed/);+ assert.true(formApi.isDirty, "the failed change remains dirty");++ await formApi.reset();++ assert.strictEqual(formApi.get("foo"), 1, "the failed change can be reset");+ });+test("@onSet", async function (assert) {const calls = [];const onSet = (name, value, data) => {@@ -205,6 +231,27 @@ module("Integration | Component | FormKit | Form", function (hooks) {}, 0);});+ test("@onRegisterApi - commit", async function (assert) {+ let formApi;+ const registerApi = (api) => (formApi = api);++ await render(+ <template>+ <Form @data={{hash foo=1}} @onRegisterApi={{registerApi}} />+ </template>+ );++ await formApi.set("foo", 2);+ formApi.commit();++ assert.false(formApi.isDirty, "the committed form is pristine");++ await formApi.set("foo", 3);+ await formApi.reset();++ assert.strictEqual(formApi.get("foo"), 2, "reset uses the committed value");+ });+test("@onRegisterApi - commitField", async function (assert) {let formApi;const model = { foo: "a", bar: "b" };diff --git a/plugins/discourse-ai/admin/assets/javascripts/discourse/components/ai-agent-editor.gjs b/plugins/discourse-ai/admin/assets/javascripts/discourse/components/ai-agent-editor.gjsindex d71cdb2f8a1..e11d1e53525 100644--- a/plugins/discourse-ai/admin/assets/javascripts/discourse/components/ai-agent-editor.gjs+++ b/plugins/discourse-ai/admin/assets/javascripts/discourse/components/ai-agent-editor.gjs@@ -24,6 +24,7 @@ import { and, eq, gt, not, or } from "discourse/truth-helpers";import DButton from "discourse/ui-kit/d-button";import dBoundAvatarTemplate from "discourse/ui-kit/helpers/d-bound-avatar-template";import dIcon from "discourse/ui-kit/helpers/d-icon";+import dOnResize from "discourse/ui-kit/modifiers/d-on-resize";import { i18n } from "discourse-i18n";import AiAgentMcpToolSelectorModal from "../components/modal/ai-agent-mcp-tool-selector-modal";import AiAgentResponseFormatEditor from "../components/modal/ai-agent-response-format-editor";@@ -51,34 +52,46 @@ export default class AgentEditor extends Component {@tracked allGroups = [];@tracked isSaving = false;+ @tracked formApi = null;- dirtyFormData = null;+ formDataModel = null;+ formDataCache = null;@cachedget formData() {- // This is to recover a dirty state after persisting a single form field.- // It's meant to be consumed only once.- if (this.dirtyFormData) {- const data = this.dirtyFormData;- this.dirtyFormData = null;- return data;- } else {- const data = this.args.model.toPOJO();-- if (data.tools) {- data.toolOptions = this.mapToolOptions(data.toolOptions, data.tools);- }+ const model = this.args.model;+ if (this.formDataModel === model) {+ return this.formDataCache;+ }++ const data = this.formDataFor(model);++ this.formDataModel = model;+ this.formDataCache = data;- data.compression_threshold ??= 80;+ return data;+ }++ formDataFor(model) {+ const data = model.toPOJO();- return data;+ if (data.tools) {+ data.toolOptions = this.mapToolOptions(data.toolOptions, data.tools);}++ data.compression_threshold ??= 80;++ return data;}get chatPluginEnabled() {return this.siteSettings.chat_enabled;}+ get hasFloatingActions() {+ return this.args.model.isNew || this.formApi?.isDirty;+ }+get allTools() {return this.args.agents.resultSetMeta.tools;}@@ -148,6 +161,11 @@ export default class AgentEditor extends Component {this.allGroups = groups;}+ @action+ registerFormApi(api) {+ this.formApi = api;+ }+@actionasync save(data) {const isNew = this.args.model.isNew;@@ -160,9 +178,11 @@ export default class AgentEditor extends Component {);await agentToSave.save();+ await this.formApi.setProperties(this.formDataFor(agentToSave));+ this.formApi.commit();this.#sortAgents();- if (isNew && this.args.model.rag_uploads.length === 0) {+ if (isNew) {addUniqueValueToArray(this.args.agents.content, agentToSave);await this.router.replaceWith("adminPlugins.show.discourse-ai-agents.edit",@@ -205,15 +225,15 @@ export default class AgentEditor extends Component {}@action- async toggleEnabled(dirtyData, value, { set }) {- set("enabled", value);- await this.persistField(dirtyData, "enabled", value);+ async toggleEnabled(form, value, { set }) {+ await set("enabled", value);+ await this.persistField(form, "enabled", value);}@action- async togglePriority(dirtyData, value, { set }) {- set("priority", value);- await this.persistField(dirtyData, "priority", value, true);+ async togglePriority(form, value, { set }) {+ await set("priority", value);+ await this.persistField(form, "priority", value, true);}@action@@ -236,15 +256,15 @@ export default class AgentEditor extends Component {}@action- async removeUpload(form, dirtyData, currentUploads, upload) {+ async removeUpload(form, currentUploads, upload) {const updatedUploads = currentUploads.filter((file) => file.id !== upload.id);- form.set("rag_uploads", updatedUploads);+ await form.set("rag_uploads", updatedUploads);if (!this.args.model.isNew) {- await this.persistField(dirtyData, "rag_uploads", updatedUploads);+ await this.persistField(form, "rag_uploads", updatedUploads);}}@@ -574,17 +594,14 @@ export default class AgentEditor extends Component {return updatedOptions;}- async persistField(dirtyData, field, newValue, sortAgents) {+ async persistField(form, field, newValue, sortAgents) {if (!this.args.model.isNew) {- const updatedDirtyData = Object.assign({}, dirtyData);- updatedDirtyData[field] = newValue;-try {const args = {};args[field] = newValue;- this.dirtyFormData = updatedDirtyData;await this.args.model.update(args);+ form.commitField(field);if (sortAgents) {this.#sortAgents();}@@ -613,13 +630,47 @@ export default class AgentEditor extends Component {window.location.href = getURL(exportUrl);}+ @action+ duplicateAgent() {+ this.router.transitionTo("adminPlugins.show.discourse-ai-agents.new", {+ queryParams: { copyFrom: this.args.model.id },+ });+ }++ @action+ positionActions([entry]) {+ const editorElement = entry.target.closest(".ai-agent-editor");+ const formElement = editorElement?.querySelector(".form-kit");+ const actionsElement = formElement?.querySelector(".form-kit__actions");++ if (!formElement || !actionsElement) {+ return;+ }++ const { width } = formElement.getBoundingClientRect();+ const { height } = actionsElement.getBoundingClientRect();+ actionsElement.style.width = `${width}px`;+ formElement.style.setProperty("--ai-agent-actions-height", `${height}px`);+ }+<template><BackButton@route="adminPlugins.show.discourse-ai-agents"@label="discourse_ai.ai_agent.back"/>- <div class="ai-agent-editor" {{didInsert this.updateAllGroups @model.id}}>- <Form @onSubmit={{this.save}} @data={{this.formData}} as |form data|>+ <div+ class="ai-agent-editor"+ {{didInsert this.updateAllGroups @model.id}}+ {{dOnResize this.positionActions}}+ >+ <Form+ class={{if this.hasFloatingActions "has-floating-actions"}}+ @commitOnSubmit={{false}}+ @onSubmit={{this.save}}+ @onRegisterApi={{this.registerFormApi}}+ @data={{this.formData}}+ as |form data|+ ><form.Field@name="name"@title={{i18n "discourse_ai.ai_agent.name"}}@@ -635,7 +686,7 @@ export default class AgentEditor extends Component {<form.Field@name="description"@title={{i18n "discourse_ai.ai_agent.description"}}- @validation="required|length:1,100"+ @validation="required|length:1,2000"@disabled={{data.system}}@format="large"@type="textarea"@@ -1165,7 +1216,7 @@ export default class AgentEditor extends Component {@target={{data}}@targetName="AiAgent"@updateUploads={{fn this.updateUploads form}}- @onRemove={{fn this.removeUpload form data field.value}}+ @onRemove={{fn this.removeUpload form field.value}}@allowImages={{@agents.resultSetMeta.settings.rag_images_enabled}}/></field.Control>@@ -1197,7 +1248,7 @@ export default class AgentEditor extends Component {<form.Field@name="enabled"@title={{i18n "discourse_ai.ai_agent.enabled"}}- @onSet={{fn this.toggleEnabled data}}+ @onSet={{fn this.toggleEnabled form}}@type="toggle"as |field|>@@ -1207,7 +1258,7 @@ export default class AgentEditor extends Component {<form.Field@name="priority"@title={{i18n "discourse_ai.ai_agent.priority"}}- @onSet={{fn this.togglePriority data}}+ @onSet={{fn this.togglePriority form}}@tooltip={{i18n "discourse_ai.ai_agent.priority_help"}}@type="toggle"as |field|@@ -1304,9 +1355,21 @@ export default class AgentEditor extends Component {{{/if}}</form.Section>- <form.Actions>+ <form.Actions+ class={{if this.hasFloatingActions "is-floating"}}+ {{dOnResize this.positionActions}}+ ><form.Submit />+ {{#unless @model.isNew}}+ <form.Button+ @label="discourse_ai.ai_agent.duplicate"+ @action={{this.duplicateAgent}}+ @icon="copy"+ class="btn-default ai-agent-editor__duplicate"+ />+ {{/unless}}+{{#unless (or @model.isNew @model.system)}}<form.Button@label="discourse_ai.ai_agent.export"diff --git a/plugins/discourse-ai/admin/assets/javascripts/discourse/components/ai-agent-list-editor.gjs b/plugins/discourse-ai/admin/assets/javascripts/discourse/components/ai-agent-list-editor.gjsindex 30a4fc49cdf..f18c485d10d 100644--- a/plugins/discourse-ai/admin/assets/javascripts/discourse/components/ai-agent-list-editor.gjs+++ b/plugins/discourse-ai/admin/assets/javascripts/discourse/components/ai-agent-list-editor.gjs@@ -1,6 +1,6 @@import Component from "@glimmer/component";import { tracked } from "@glimmer/tracking";-import { concat, fn } from "@ember/helper";+import { concat, fn, hash } from "@ember/helper";import { action } from "@ember/object";import { LinkTo } from "@ember/routing";import { service } from "@ember/service";@@ -12,8 +12,10 @@ import { removeValueFromArray } from "discourse/lib/array-tools";import { gt } from "discourse/truth-helpers";import DBreadcrumbsItem from "discourse/ui-kit/d-breadcrumbs-item";import DButton from "discourse/ui-kit/d-button";+import DComboButton from "discourse/ui-kit/d-combo-button";import DDropdownMenu from "discourse/ui-kit/d-dropdown-menu";import DFilterControls from "discourse/ui-kit/d-filter-controls";+import DFilterInput from "discourse/ui-kit/d-filter-input";import DPageSubheader from "discourse/ui-kit/d-page-subheader";import dAvatar from "discourse/ui-kit/helpers/d-avatar";import dConcatClass from "discourse/ui-kit/helpers/d-concat-class";@@ -40,8 +42,11 @@ export default class AiAgentListEditor extends Component {@service keyValueStore;@service capabilities;@service dialog;+ @service router;+ @service site;@tracked currentLayout = LAYOUT_BUTTONS[0];+ @tracked duplicateFilter = "";constructor() {super(...arguments);@@ -58,6 +63,31 @@ export default class AiAgentListEditor extends Component {return ["name", "description"];}+ get hasAgents() {+ return (this.args.agents?.content?.length || 0) > 0;+ }++ get filteredDuplicateAgents() {+ const filter = this.duplicateFilter.trim().toLocaleLowerCase();+ const agents = [...(this.args.agents?.content || [])].sort((a, b) =>+ a.name.localeCompare(b.name)+ );++ if (!filter) {+ return agents;+ }++ return agents.filter((agent) =>+ agent.name.toLocaleLowerCase().includes(filter)+ );+ }++ get newAgentButtonClasses() {+ return this.site.mobileView+ ? "btn-transparent"+ : "btn-primary btn-small d-page-action-button";+ }+get dropdownOptions() {let features = [];(this.args.agents?.content || []).forEach((agent) => {@@ -117,6 +147,36 @@ export default class AiAgentListEditor extends Component {this.dMenu.close();}+ @action+ newAgent() {+ this.router.transitionTo("adminPlugins.show.discourse-ai-agents.new", {+ queryParams: { copyFrom: null },+ });+ }++ @action+ registerDuplicateMenu(api) {+ this.duplicateMenu = api;+ }++ @action+ filterDuplicateAgents(event) {+ this.duplicateFilter = event.target.value;+ }++ @action+ clearDuplicateFilter() {+ this.duplicateFilter = "";+ }++ @action+ async duplicateAgent(agent) {+ await this.duplicateMenu.close();+ this.router.transitionTo("adminPlugins.show.discourse-ai-agents.new", {+ queryParams: { copyFrom: agent.id },+ });+ }+@actionimportAgent() {const fileInput = document.createElement("input");@@ -210,12 +270,83 @@ export default class AiAgentListEditor extends Component {@icon="upload"class="ai-agent-list-editor__import-button"/>- <actions.Primary- @label="discourse_ai.ai_agent.new"- @route="adminPlugins.show.discourse-ai-agents.new"- @icon="plus"- class="ai-agent-list-editor__new-button"- />+ <actions.Wrapped>+ <DComboButton+ class={{dConcatClass+ "ai-agent-list-editor__new-combo"+ (if this.hasAgents "--has-menu")+ }}+ aria-label={{i18n "discourse_ai.ai_agent.new_group"}}+ as |combo|+ >+ <combo.Button+ @label="discourse_ai.ai_agent.new"+ @ariaLabel="discourse_ai.ai_agent.new"+ @action={{this.newAgent}}+ @icon="plus"+ class={{dConcatClass+ this.newAgentButtonClasses+ "ai-agent-list-editor__new-button"+ }}+ />+ {{#if this.hasAgents}}+ <combo.Menu+ @identifier="duplicate-agent-menu"+ @title={{i18n "discourse_ai.ai_agent.duplicate"}}+ @placement="bottom-end"+ @modalForMobile={{true}}+ @autofocus={{true}}+ @onRegisterApi={{this.registerDuplicateMenu}}+ @onClose={{this.clearDuplicateFilter}}+ @triggerClass={{dConcatClass+ this.newAgentButtonClasses+ "ai-agent-list-editor__duplicate-menu"+ }}+ aria-label={{i18n "discourse_ai.ai_agent.duplicate"}}+ >+ <div class="ai-agent-list-editor__duplicate-picker">+ <DFilterInput+ @value={{this.duplicateFilter}}+ @filterAction={{this.filterDuplicateAgents}}+ @onClearInput={{this.clearDuplicateFilter}}+ @icons={{hash left="magnifying-glass"}}+ placeholder={{i18n+ "discourse_ai.ai_agent.duplicate_search"+ }}+ aria-label={{i18n+ "discourse_ai.ai_agent.duplicate_search"+ }}+ data-test-duplicate-agent-filter+ autofocus+ />+ <DDropdownMenu+ class="ai-agent-list-editor__duplicate-results"+ as |dropdown|+ >+ {{#each this.filteredDuplicateAgents as |agent|}}+ <dropdown.item>+ <DButton+ @action={{fn this.duplicateAgent agent}}+ @translatedLabel={{agent.name}}+ @icon="copy"+ class="btn-transparent"+ data-test-duplicate-agent-option+ />+ </dropdown.item>+ {{else}}+ <li+ class="ai-agent-list-editor__duplicate-empty"+ role="status"+ >+ {{i18n "discourse_ai.ai_agent.filters.no_results"}}+ </li>+ {{/each}}+ </DDropdownMenu>+ </div>+ </combo.Menu>+ {{/if}}+ </DComboButton>+ </actions.Wrapped></:actions></DPageSubheader>{{#if @agents.content}}@@ -350,7 +481,7 @@ export default class AiAgentListEditor extends Component {{{else}}<AdminConfigAreaEmptyList@ctaLabel="discourse_ai.ai_agent.new"- @ctaRoute="adminPlugins.show.discourse-ai-agents.new"+ @ctaAction={{this.newAgent}}@ctaClass="ai-agent-list-editor__empty-new-button"@emptyLabel="discourse_ai.ai_agent.no_agents"/>diff --git a/plugins/discourse-ai/admin/assets/javascripts/discourse/routes/admin-plugins/show/discourse-ai-agents/new.js b/plugins/discourse-ai/admin/assets/javascripts/discourse/routes/admin-plugins/show/discourse-ai-agents/new.jsindex 96a635a4683..7dc90089618 100644--- a/plugins/discourse-ai/admin/assets/javascripts/discourse/routes/admin-plugins/show/discourse-ai-agents/new.js+++ b/plugins/discourse-ai/admin/assets/javascripts/discourse/routes/admin-plugins/show/discourse-ai-agents/new.js@@ -1,8 +1,29 @@import { AUTO_GROUPS } from "discourse/lib/constants";import DiscourseRoute from "discourse/routes/discourse";+import { i18n } from "discourse-i18n";export default class AdminPluginsShowDiscourseAiAgentsNew extends DiscourseRoute {- async model() {+ queryParams = {+ copyFrom: { refreshModel: true },+ };++ async model({ copyFrom }) {+ const sourceAgent = this.#findSourceAgent(copyFrom);+ if (sourceAgent) {+ const data = sourceAgent.toPOJO();+ data.id = null;+ data.name = i18n("discourse_ai.ai_agent.copy_name", {+ name: sourceAgent.name,+ });+ data.enabled = false;+ data.system = false;+ data.user = null;+ data.user_id = null;++ const duplicate = sourceAgent.fromPOJO(data);+ return this.store.createRecord("ai-agent", duplicate.createProperties());+ }+const record = this.store.createRecord("ai-agent");record.set("allowed_group_ids", [AUTO_GROUPS.trust_level_0.id]);record.set("tools", []);@@ -16,6 +37,17 @@ export default class AdminPluginsShowDiscourseAiAgentsNew extends DiscourseRoutereturn record;}+ #findSourceAgent(copyFrom) {+ if (!copyFrom) {+ return;+ }++ const id = parseInt(copyFrom, 10);+ return this.modelFor("adminPlugins.show.discourse-ai-agents").content.find(+ (agent) => agent.id === id+ );+ }+setupController(controller, model) {super.setupController(controller, model);controller.set(diff --git a/plugins/discourse-ai/assets/stylesheets/modules/ai-bot/common/ai-agent.scss b/plugins/discourse-ai/assets/stylesheets/modules/ai-bot/common/ai-agent.scssindex 198d07aa6a4..6861a819e41 100644--- a/plugins/discourse-ai/assets/stylesheets/modules/ai-bot/common/ai-agent.scss+++ b/plugins/discourse-ai/assets/stylesheets/modules/ai-bot/common/ai-agent.scss@@ -4,6 +4,30 @@margin-top: 0;}+.ai-agent-list-editor__duplicate-picker {+ inline-size: min(24em, calc(100vw - var(--space-8)));+ padding: var(--space-2);++ .filter-input-container {+ margin-block-end: var(--space-2);+ }+}++.ai-agent-list-editor__duplicate-results {+ max-block-size: min(24em, 50vh);+ overflow-y: auto;++ .btn {+ inline-size: 100%;+ justify-content: flex-start;+ }+}++.ai-agent-list-editor__duplicate-empty {+ padding: var(--space-3);+ color: var(--primary-medium);+}+.ai-agent-list-editor {@include viewport.until(md) {td {@@ -215,6 +239,24 @@.ai-agent-editor {padding-left: 0.5em;+ .form-kit {+ --ai-agent-actions-offset: var(--space-3);+ padding-block-end: var(--space-8);++ &.has-floating-actions {+ padding-block-end: calc(+ var(--ai-agent-actions-height, 4em) + var(--ai-agent-actions-offset) ++ var(--space-4)+ );+ }++ .footer-nav-visible & {+ --ai-agent-actions-offset: calc(+ var(--footer-nav-height) + env(safe-area-inset-bottom) + var(--space-4)+ );+ }+ }+.select-kit.multi-select.is-disabled {height: auto;@@ -466,6 +508,19 @@color: var(--danger);}}++ .form-kit__actions.is-floating {+ box-sizing: border-box;+ position: fixed;+ inset-block-end: var(--ai-agent-actions-offset);+ z-index: 1;+ flex-wrap: wrap;+ padding: var(--space-3);+ background-color: var(--secondary);+ border: 1px solid var(--primary-300);+ border-radius: var(--d-border-radius);+ box-shadow: var(--shadow-card);+ }}.ai-agent-mcp-tools-modal {diff --git a/plugins/discourse-ai/config/locales/client.en.yml b/plugins/discourse-ai/config/locales/client.en.ymlindex f565644ef3d..bcf84d6a5a0 100644--- a/plugins/discourse-ai/config/locales/client.en.yml+++ b/plugins/discourse-ai/config/locales/client.en.yml@@ -750,6 +750,10 @@ en:allowed_groups: "Allowed groups"confirm_delete: "Are you sure you want to delete this agent?"new: "New agent"+ new_group: "New or duplicate agent"+ duplicate: "Duplicate"+ duplicate_search: "Duplicate an agent"+ copy_name: "Copy of %{name}"no_agents: "You have not created any agents yet"manage_agents: "Manage agents"title: "Agents"diff --git a/plugins/discourse-ai/spec/system/admin_ai_agent_spec.rb b/plugins/discourse-ai/spec/system/admin_ai_agent_spec.rbindex 3a93b73643d..3c917933cd2 100644--- a/plugins/discourse-ai/spec/system/admin_ai_agent_spec.rb+++ b/plugins/discourse-ai/spec/system/admin_ai_agent_spec.rb@@ -4,6 +4,7 @@ RSpec.describe "Admin AI agent configuration" dofab!(:admin)let(:page_header) { PageObjects::Components::DPageHeader.new }let(:form) { PageObjects::Components::FormKit.new("form") }+ let(:dialog) { PageObjects::Components::Dialog.new }let(:agent_editor_page) { PageObjects::Pages::AdminAiAgent.new }let(:mcp_tool_selector_modal) { PageObjects::Modals::AiAgentMcpToolSelector.new }@@ -71,6 +72,118 @@ RSpec.describe "Admin AI agent configuration" doexpect(form.field("system_prompt")).to be_disabledend+ it "starts an unsaved custom agent by duplicating a system agent" do+ source_agent =+ AiAgent.find(DiscourseAi::Agents::Agent.system_agents[DiscourseAi::Agents::PostRawTranslator])++ agent_editor_page.visit_edit(source_agent).duplicate++ expect(page).to have_current_path("/admin/plugins/discourse-ai/ai-agents/new?copyFrom=-28")+ expect(agent_editor_page).to have_form_field_value("name", "Copy of #{source_agent.name}")+ expect(agent_editor_page).to have_form_field_value("description", source_agent.description)+ expect(agent_editor_page).to have_form_field_value("system_prompt", source_agent.system_prompt)+ expect(agent_editor_page).to have_agent_enabled_state(false)+ expect(form.field("system_prompt")).not_to be_disabled++ find(".back-button").click++ expect(page).not_to have_selector(".ai-agent-list__name", text: "Copy of #{source_agent.name}")++ find(".ai-agent-list-editor__new-button").click++ expect(page).to have_current_path("/admin/plugins/discourse-ai/ai-agents/new")+ expect(agent_editor_page).to have_form_field_value("name", "")+ end++ it "starts a duplicate from the searchable agent list" do+ source_agent = Fabricate(:ai_agent, name: "猫 Translator", enabled: true)+ other_agent = Fabricate(:ai_agent, name: "Unrelated custom agent")++ agent_editor_page.visit_list.open_duplicate_menu.filter_duplicates("猫")++ expect(agent_editor_page).to have_duplicate_option(source_agent.name)+ expect(agent_editor_page).to have_no_duplicate_option(other_agent.name)++ agent_editor_page.duplicate_from_list(source_agent.name)++ expect(page).to have_current_path(+ "/admin/plugins/discourse-ai/ai-agents/new?copyFrom=#{source_agent.id}",+ )+ expect(agent_editor_page).to have_form_field_value("name", "Copy of #{source_agent.name}")+ expect(agent_editor_page).to have_agent_enabled_state(false)+ end++ it "opens a saved duplicate containing RAG uploads on its edit route" do+ embedding_definition = Fabricate(:embedding_definition)+ SiteSetting.ai_embeddings_selected_model = embedding_definition.id+ SiteSetting.ai_embeddings_enabled = true+ source_agent = Fabricate(:ai_agent, description: "a" * 2000)+ upload = Fabricate(:upload, user: admin)+ UploadReference.ensure_exist!(upload_ids: [upload.id], target: source_agent)++ agent_editor_page.visit_edit(source_agent).duplicate++ expect(page).to have_content(upload.original_filename)++ form.submit++ expect(page).to have_current_path(%r{/admin/plugins/discourse-ai/ai-agents/\d+/edit})+ expect(page).to have_content(upload.original_filename)+ end++ it "creates a distinct user when a saved duplicate needs one" do+ llm_model = Fabricate(:llm_model)+ source_agent =+ Fabricate(+ :ai_agent,+ name: "Mention helper",+ allow_topic_mentions: true,+ default_llm_id: llm_model.id,+ )+ source_user = source_agent.create_user!++ agent_editor_page.visit_edit(source_agent).duplicate++ expect(agent_editor_page).to have_no_agent_user++ form.submit++ expect(page).to have_current_path(%r{/admin/plugins/discourse-ai/ai-agents/\d+/edit})+ expect(agent_editor_page).to have_agent_user+ expect(agent_editor_page).to have_no_agent_user(source_user.username)+ end++ it "floats the actions after an existing agent is changed" do+ agent = Fabricate(:ai_agent, enabled: false)++ agent_editor_page.visit_edit(agent)++ expect(agent_editor_page).to have_no_floating_actions++ form.field("enabled").toggle++ expect(agent_editor_page).to have_no_floating_actions++ form.field("name").fill_in("Updated agent")++ expect(agent_editor_page).to have_floating_actions+ end++ it "keeps the actions floating when saving fails" do+ agent = Fabricate(:ai_agent)+ existing_agent = Fabricate(:ai_agent, name: "Existing agent")++ agent_editor_page.visit_edit(agent)+ form.field("name").fill_in(existing_agent.name)+ form.submit++ expect(dialog).to be_open+ expect(dialog).to have_content(+ I18n.t("js.generic_error_with_reason", error: "Name has already been taken"),+ )+ expect(agent_editor_page).to have_floating_actions+ end+it "will enable agent right away when you click on enable but does not save side effects" doagent = Fabricate(:ai_agent, enabled: false)diff --git a/plugins/discourse-ai/spec/system/page_objects/pages/admin_ai_agent.rb b/plugins/discourse-ai/spec/system/page_objects/pages/admin_ai_agent.rbindex 49938d3fcec..b19c03e58ea 100644--- a/plugins/discourse-ai/spec/system/page_objects/pages/admin_ai_agent.rb+++ b/plugins/discourse-ai/spec/system/page_objects/pages/admin_ai_agent.rb@@ -3,11 +3,73 @@module PageObjectsmodule Pagesclass AdminAiAgent < PageObjects::Pages::Base+ def visit_list+ page.visit("/admin/plugins/discourse-ai/ai-agents")+ self+ end+def visit_edit(agent)page.visit("/admin/plugins/discourse-ai/ai-agents/#{agent.id}/edit")selfend+ def open_duplicate_menu+ page.find("button.duplicate-agent-menu-trigger").click+ self+ end++ def filter_duplicates(value)+ page.find("[data-test-duplicate-agent-filter]").fill_in(with: value)+ self+ end++ def duplicate_from_list(name)+ page.find("[data-test-duplicate-agent-option]", text: name).click+ self+ end++ def has_duplicate_option?(name)+ page.has_css?("[data-test-duplicate-agent-option]", text: name)+ end++ def has_no_duplicate_option?(name)+ page.has_no_css?("[data-test-duplicate-agent-option]", text: name)+ end++ def duplicate+ page.find(".ai-agent-editor__duplicate").click+ self+ end++ def has_floating_actions?+ page.has_css?(".form-kit__actions.is-floating")+ end++ def has_no_floating_actions?+ page.has_no_css?(".form-kit__actions.is-floating")+ end++ def has_form_field_value?(name, value)+ page.has_field?(name, with: value)+ end++ def has_agent_enabled_state?(enabled)+ page.has_css?(+ ".form-kit__field[data-name='enabled'] button[role='switch'][aria-checked='#{enabled}']",+ visible: :all,+ )+ end++ def has_agent_user?(username = nil)+ options = username ? { text: username } : {}+ page.has_css?(".ai-agent-editor__ai_bot_user a", **options)+ end++ def has_no_agent_user?(username = nil)+ options = username ? { text: username } : {}+ page.has_no_css?(".ai-agent-editor__ai_bot_user a", **options)+ end+def form@form ||= PageObjects::Components::FormKit.new("form")end