diff --git a/agent/src/main/java/org/openremote/agent/protocol/modbus/ModbusAgentLink.java b/agent/src/main/java/org/openremote/agent/protocol/modbus/ModbusAgentLink.java index 77b4d6b987..3d3c7f567a 100644 --- a/agent/src/main/java/org/openremote/agent/protocol/modbus/ModbusAgentLink.java +++ b/agent/src/main/java/org/openremote/agent/protocol/modbus/ModbusAgentLink.java @@ -23,11 +23,15 @@ import jakarta.validation.constraints.Min; import java.math.BigInteger; import org.openremote.model.asset.agent.AgentLink; +import org.openremote.model.util.JSONSchemaUtil.JsonSchemaTemplateParameter; +import org.openremote.model.util.JSONSchemaUtil.JsonSchemaTitle; public class ModbusAgentLink extends AgentLink { @JsonPropertyDescription( "Modbus unit ID (1-255). Required for Serial, optional for TCP (defaults to 1)") + @JsonSchemaTitle("Unit ID") + @JsonSchemaTemplateParameter @Min(1) private Integer unitId; @JsonPropertyDescription( diff --git a/agent/src/test/groovy/org/openremote/agent/protocol/modbus/ModbusAgentLinkTest.groovy b/agent/src/test/groovy/org/openremote/agent/protocol/modbus/ModbusAgentLinkTest.groovy new file mode 100644 index 0000000000..42a04e5c88 --- /dev/null +++ b/agent/src/test/groovy/org/openremote/agent/protocol/modbus/ModbusAgentLinkTest.groovy @@ -0,0 +1,38 @@ +/* + * Copyright 2026, OpenRemote Inc. + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see . + * + * SPDX-License-Identifier: AGPL-3.0-or-later + */ +package org.openremote.agent.protocol.modbus + +import org.openremote.model.asset.agent.AgentLink +import org.openremote.model.util.ValueUtil +import spock.lang.Specification + +class ModbusAgentLinkTest extends Specification { + + def setupSpec() { + ValueUtil.initialise(null) + } + + def "schema marks the unit id of a Modbus agent link as a template parameter"() { + when: + def properties = ValueUtil.getSchema(AgentLink).at("/definitions/ModbusAgentLink/properties") + + then: + properties.at("/unitId/templateParameter").asBoolean() + } +} diff --git a/model/src/main/java/org/openremote/model/asset/agent/AgentLink.java b/model/src/main/java/org/openremote/model/asset/agent/AgentLink.java index db09deac20..e4099d7ba4 100644 --- a/model/src/main/java/org/openremote/model/asset/agent/AgentLink.java +++ b/model/src/main/java/org/openremote/model/asset/agent/AgentLink.java @@ -45,7 +45,9 @@ @TsIgnoreTypeParams public abstract class AgentLink> implements Serializable { + @JsonSchemaTitle("Agent ID") @JsonSchemaFormat("or-agent-id") + @JsonSchemaTemplateParameter protected String id; @JsonSchemaDescription( diff --git a/model/src/main/java/org/openremote/model/util/JSONSchemaUtil.java b/model/src/main/java/org/openremote/model/util/JSONSchemaUtil.java index c6247e0919..7c443881c7 100644 --- a/model/src/main/java/org/openremote/model/util/JSONSchemaUtil.java +++ b/model/src/main/java/org/openremote/model/util/JSONSchemaUtil.java @@ -211,6 +211,19 @@ public static ObjectNode getSuppliedNode(JsonSchemaSupplier annotation) String supplier(); } + /** + * Marks a field whose value a configuration template asks for on import, such as the agent of an + * agent link. Only mark fields that the standard JSON Forms renderers can render, as the import + * renders them outside of their custom renderers. + */ + @Retention(RetentionPolicy.RUNTIME) + @Target(ElementType.FIELD) + public @interface JsonSchemaTemplateParameter { + String keyword() default "templateParameter"; + + String value() default "true"; + } + private static class CustomModule implements Module { private final ObjectMapper mapper; @@ -338,6 +351,7 @@ public String getDefinitionNameForKey( applyFieldAnnotation(fieldScope, JsonSchemaFormat.class, attrs); applyFieldAnnotation(fieldScope, JsonSchemaDefault.class, attrs); applyFieldAnnotation(fieldScope, JsonSchemaExamples.class, attrs); + applyFieldAnnotation(fieldScope, JsonSchemaTemplateParameter.class, attrs); String key = getCanonicalMemberKey(fieldScope); if (!applyI18nAnnotation( diff --git a/model/src/test/groovy/org/openremote/model/util/JSONSchemaUtilTest.groovy b/model/src/test/groovy/org/openremote/model/util/JSONSchemaUtilTest.groovy index 6e2ce1c7e4..e622d312c6 100644 --- a/model/src/test/groovy/org/openremote/model/util/JSONSchemaUtilTest.groovy +++ b/model/src/test/groovy/org/openremote/model/util/JSONSchemaUtilTest.groovy @@ -19,6 +19,7 @@ package org.openremote.model.util import com.fasterxml.jackson.annotation.* +import org.openremote.model.asset.agent.AgentLink import org.openremote.model.util.JSONSchemaUtil.* import org.openremote.model.value.ValueType import org.reflections.Reflections @@ -146,6 +147,7 @@ class JSONSchemaUtilTest extends Specification { @JsonSchemaFormat("test") @JsonSchemaDefault("false") @JsonSchemaExamples(["test"]) + @JsonSchemaTemplateParameter public Boolean all } @@ -300,6 +302,15 @@ class JSONSchemaUtilTest extends Specification { schemaMatchesSnapshot(ReflectedPolymorphicType) } + def "schema marks the agent id of an agent link as a template parameter"() { + when: + def properties = ValueUtil.getSchema(AgentLink).at("/definitions/DefaultAgentLink/properties") + + then: + properties.at("/id/templateParameter").asBoolean() + !properties.at("/type").has("templateParameter") + } + def "schemas do not use allOf"() { expect: reflections.getTypesAnnotatedWith(JsonTypeInfo).each { clazz -> diff --git a/model/src/test/resources/snapshots/org/openremote/model/util/JSONSchemaUtilTest/schema_applies_custom_annotations_to_fields.json b/model/src/test/resources/snapshots/org/openremote/model/util/JSONSchemaUtilTest/schema_applies_custom_annotations_to_fields.json index d1fdd2cb32..ed38b1b339 100644 --- a/model/src/test/resources/snapshots/org/openremote/model/util/JSONSchemaUtilTest/schema_applies_custom_annotations_to_fields.json +++ b/model/src/test/resources/snapshots/org/openremote/model/util/JSONSchemaUtilTest/schema_applies_custom_annotations_to_fields.json @@ -7,6 +7,7 @@ "format" : "test", "default" : false, "examples" : [ "test" ], + "templateParameter" : true, "title" : "test", "description" : "test" } diff --git a/ui/app/manager/test/configuration-template.test.ts b/ui/app/manager/test/configuration-template.test.ts index 2573cf2a68..06f47b3592 100644 --- a/ui/app/manager/test/configuration-template.test.ts +++ b/ui/app/manager/test/configuration-template.test.ts @@ -16,13 +16,15 @@ * * SPDX-License-Identifier: AGPL-3.0-or-later */ -import { expect, type Page } from "@openremote/test"; +import { expect, type Locator, type Page } from "@openremote/test"; +import type { Asset } from "@openremote/model"; import type { AssetViewer } from "../../../component/or-asset-viewer/test/fixtures"; import { test, userStatePath } from "./fixtures/manager.js"; import { agent } from "./fixtures/data/assets.js"; import { configuredLight, lightTemplate, + linkedLightTemplate, partlyImportableTemplate, pumpTemplate, targetLight, @@ -248,6 +250,105 @@ test("should go back to the file selection from a template that cannot be import await expect(assetViewer.getConfigurationTemplateAttribute(matched, "Dimmer")).toBeVisible(); }); +/** + * Continue from what an import would do to the parameters of its agent links. + * @param page The page showing the import + * @param assetViewer The asset viewer fixture + */ +async function continueToParameters(page: Page, assetViewer: AssetViewer) { + const matched = assetViewer.getConfigurationTemplateSection("Matched attributes"); + await expect(assetViewer.getConfigurationTemplateAttribute(matched, "Power")).toBeVisible(); + await page.getByRole("dialog").getByRole("button", { name: "Next", exact: true }).click(); +} + +/** + * Pick an agent for a parameter of the configuration template import. + * @param parameter The parameter + * @param agent The agent to pick + */ +async function pickAgent(parameter: Locator, agent: Asset) { + await parameter.getByLabel("Agent ID").click(); + // A closing select still shows its options, so look them up in this parameter only + await parameter.getByRole("option", { name: `${agent.name} (${agent.id})` }).click(); +} + +/** + * @given A simulator agent and a light to import into are set up in the "smartcity" realm + * @when Importing a template whose agent links point at two agents of another instance + * @then An agent is asked for once per template agent, listing the attributes that share it + * @and Import is blocked, as the template's agents do not exist here + * @when Picking the simulator agent for both, importing and saving the light + * @then Every agent link of the light points at the simulator agent + */ +test("should ask for an agent for each agent of the template", async ({ page, manager, assetsPage, assetViewer }) => { + await manager.setup("smartcity", { assets: [agent, targetLight] }); + const simulator = manager.assets.find(({ type }) => type === agent.type)!; + const light = manager.assets.find(({ name }) => name === targetLight.name)!; + await assetsPage.gotoAssetId("smartcity", light.id!, true); + await selectTemplateFile(page, assetViewer, "linked.json", JSON.stringify(linkedLightTemplate)); + await continueToParameters(page, assetViewer); + + const shared = assetViewer.getConfigurationTemplateParameter("Dimmer"); + const single = assetViewer.getConfigurationTemplateParameter("Power"); + await expect(shared).toContainText("White tone"); + await expect(single).not.toContainText("Dimmer"); + const importButton = page.getByRole("dialog").getByRole("button", { name: "Import", exact: true }); + for (const parameter of [shared, single]) { + await expect(parameter.getByText("The template's agent does not exist here. Pick another one.")).toBeVisible(); + } + await expect(importButton).toBeDisabled(); + + await pickAgent(shared, simulator); + await pickAgent(single, simulator); + await expect(importButton).toBeEnabled(); + await importButton.click(); + const saveButton = page.getByRole("button", { name: "Save" }); + await saveButton.click(); + await expect(saveButton).toBeDisabled(); + + const { data: saved } = await manager.api.AssetResource.get(light.id!, await manager.adminConfig()); + for (const name of ["brightness", "colourTemperature", "onOff"]) { + expect(saved.attributes![name].meta!.agentLink).toMatchObject({ type: "SimulatorAgentLink", id: simulator.id }); + } +}); + +/** + * @given A light to import into is set up in the "smartcity" realm, without a simulator agent + * @when Importing a template with simulator agent links + * @then Import is blocked, saying that an agent of the link type is needed + * @when A simulator agent is added elsewhere + * @then It can be picked and the template imported + */ +test("should block import until an agent of the link type exists", async ({ + page, + manager, + assetsPage, + assetViewer, +}) => { + await manager.setup("smartcity", { assets: [targetLight] }); + await assetsPage.gotoAssetId("smartcity", manager.assets[0].id!, true); + await selectTemplateFile(page, assetViewer, "linked.json", JSON.stringify(linkedLightTemplate)); + await continueToParameters(page, assetViewer); + + const parameters = [ + assetViewer.getConfigurationTemplateParameter("Dimmer"), + assetViewer.getConfigurationTemplateParameter("Power"), + ]; + const importButton = page.getByRole("dialog").getByRole("button", { name: "Import", exact: true }); + for (const parameter of parameters) { + await expect(parameter.getByText(/^There is no agent for a .+ yet/)).toBeVisible(); + } + await expect(importButton).toBeDisabled(); + + await manager.setup("smartcity", { assets: [agent] }); + const simulator = manager.assets.find(({ type }) => type === agent.type)!; + for (const parameter of parameters) { + await expect(parameter.getByText(/^There is no agent for a .+ yet/)).toHaveCount(0); + await pickAgent(parameter, simulator); + } + await expect(importButton).toBeEnabled(); +}); + /** * @given An agent is set up in the "smartcity" realm * @when Opening the agent in modify mode diff --git a/ui/app/manager/test/fixtures/data/configuration-template.ts b/ui/app/manager/test/fixtures/data/configuration-template.ts index e030236556..c505583b03 100644 --- a/ui/app/manager/test/fixtures/data/configuration-template.ts +++ b/ui/app/manager/test/fixtures/data/configuration-template.ts @@ -107,3 +107,26 @@ export const pumpTemplate = { flowRate: { type: "number", meta: { label: "Flow rate" } }, }, }; + +/** + * A template whose agent links point at agents of another instance, as the links of the config template setup's pump + * do: Dimmer and White tone share an agent, Power uses another one. + */ +export const linkedLightTemplate = { + version: 1, + assetType: "LightAsset", + attributes: { + brightness: { + type: "positiveInteger", + meta: { label: "Dimmer", agentLink: { type: "SimulatorAgentLink", id: "templateAgentA00000001" } }, + }, + colourTemperature: { + type: "positiveInteger", + meta: { label: "White tone", agentLink: { type: "SimulatorAgentLink", id: "templateAgentA00000001" } }, + }, + onOff: { + type: "boolean", + meta: { label: "Power", agentLink: { type: "SimulatorAgentLink", id: "templateAgentB00000001" } }, + }, + }, +}; diff --git a/ui/app/shared/locales/ar/or.json b/ui/app/shared/locales/ar/or.json index 3d479255d4..a9bb0747e2 100644 --- a/ui/app/shared/locales/ar/or.json +++ b/ui/app/shared/locales/ar/or.json @@ -550,6 +550,9 @@ }, "writeValueFilters": { "description": "" + }, + "id": { + "label": "" } } } @@ -577,6 +580,13 @@ } } } + }, + "modbus": { + "ModbusAgentLink": { + "unitId": { + "label": "" + } + } } } } diff --git a/ui/app/shared/locales/cn/or.json b/ui/app/shared/locales/cn/or.json index 30b9318aab..7f2b7cbd62 100644 --- a/ui/app/shared/locales/cn/or.json +++ b/ui/app/shared/locales/cn/or.json @@ -599,6 +599,9 @@ }, "writeValueFilters": { "description": "" + }, + "id": { + "label": "" } } } @@ -626,6 +629,13 @@ } } } + }, + "modbus": { + "ModbusAgentLink": { + "unitId": { + "label": "" + } + } } } } diff --git a/ui/app/shared/locales/cs/or.json b/ui/app/shared/locales/cs/or.json index 1f78bcfff6..637600fb1f 100644 --- a/ui/app/shared/locales/cs/or.json +++ b/ui/app/shared/locales/cs/or.json @@ -1295,6 +1295,9 @@ }, "writeValueFilters": { "description": "Podobné jako valueFilter, ale použije se na odchozí hodnoty, což umožňuje inverzní filtrování." + }, + "id": { + "label": "" } } } @@ -1322,6 +1325,13 @@ } } } + }, + "modbus": { + "ModbusAgentLink": { + "unitId": { + "label": "" + } + } } } } diff --git a/ui/app/shared/locales/de/or.json b/ui/app/shared/locales/de/or.json index 653dc8cefc..1b7b92f856 100644 --- a/ui/app/shared/locales/de/or.json +++ b/ui/app/shared/locales/de/or.json @@ -645,6 +645,9 @@ }, "writeValueFilters": { "description": "" + }, + "id": { + "label": "" } } } @@ -672,6 +675,13 @@ } } } + }, + "modbus": { + "ModbusAgentLink": { + "unitId": { + "label": "" + } + } } } } diff --git a/ui/app/shared/locales/en/or.json b/ui/app/shared/locales/en/or.json index d32f6ff112..a1b6fe350d 100644 --- a/ui/app/shared/locales/en/or.json +++ b/ui/app/shared/locales/en/or.json @@ -322,6 +322,7 @@ "linkedUsers": "Linked users", "setup": "Setup", "selectFile": "Select file", + "selectAgent": "Select an agent", "file": "File", "discoverAssets": "Discover assets", "discovering": "Discovering", @@ -1306,6 +1307,9 @@ }, "writeValueFilters": { "description": "Similar to valueFilter but will be applied to outgoing values allowing for inverse filtering." + }, + "id": { + "label": "Agent ID" } } } @@ -1333,6 +1337,13 @@ } } } + }, + "modbus": { + "ModbusAgentLink": { + "unitId": { + "label": "Unit ID" + } + } } } } @@ -1358,6 +1369,10 @@ "back": "Back", "next": "Next", "json": "JSON", + "parametersDescription": "Choose which Agent Link parameter values to use", + "parametersHeading": "{{type}} parameters", + "unknownAgent": "The template's agent does not exist here. Pick another one.", + "noAgentOfType": "There is no agent for a {{type}} yet. Add one to continue; this list updates once it exists.", "forbidden": "You are not allowed to import a configuration template into this asset.", "failure": { "INVALID_JSON": "The selected file does not hold valid JSON.", diff --git a/ui/app/shared/locales/es/or.json b/ui/app/shared/locales/es/or.json index 5e6e8ec75a..7030c65bda 100644 --- a/ui/app/shared/locales/es/or.json +++ b/ui/app/shared/locales/es/or.json @@ -602,6 +602,9 @@ }, "writeValueFilters": { "description": "" + }, + "id": { + "label": "" } } } @@ -629,6 +632,13 @@ } } } + }, + "modbus": { + "ModbusAgentLink": { + "unitId": { + "label": "" + } + } } } } diff --git a/ui/app/shared/locales/fr/or.json b/ui/app/shared/locales/fr/or.json index 8cf57ae36c..2766bf8d4d 100644 --- a/ui/app/shared/locales/fr/or.json +++ b/ui/app/shared/locales/fr/or.json @@ -605,6 +605,9 @@ }, "writeValueFilters": { "description": "" + }, + "id": { + "label": "" } } } @@ -632,6 +635,13 @@ } } } + }, + "modbus": { + "ModbusAgentLink": { + "unitId": { + "label": "" + } + } } } } diff --git a/ui/app/shared/locales/it/or.json b/ui/app/shared/locales/it/or.json index 8b18b526c2..bdce047f4e 100644 --- a/ui/app/shared/locales/it/or.json +++ b/ui/app/shared/locales/it/or.json @@ -599,6 +599,9 @@ }, "writeValueFilters": { "description": "" + }, + "id": { + "label": "" } } } @@ -626,6 +629,13 @@ } } } + }, + "modbus": { + "ModbusAgentLink": { + "unitId": { + "label": "" + } + } } } } diff --git a/ui/app/shared/locales/nl/or.json b/ui/app/shared/locales/nl/or.json index 0c40efbfc3..04e5f1dd10 100644 --- a/ui/app/shared/locales/nl/or.json +++ b/ui/app/shared/locales/nl/or.json @@ -317,6 +317,7 @@ "linkedUsers": "Gekoppelde gebruikers", "setup": "Instellingen", "selectFile": "Kies bestand", + "selectAgent": "Selecteer een agent", "file": "Bestand", "discoverAssets": "Haal assets op", "discovering": "Assets ophalen", @@ -1291,6 +1292,9 @@ }, "writeValueFilters": { "description": "" + }, + "id": { + "label": "" } } } @@ -1318,6 +1322,13 @@ } } } + }, + "modbus": { + "ModbusAgentLink": { + "unitId": { + "label": "" + } + } } } } @@ -1343,6 +1354,10 @@ "back": "Terug", "next": "Volgende", "json": "JSON", + "parametersDescription": "Kies welke Agent Link parameterwaarden je wilt gebruiken", + "parametersHeading": "{{type}} parameters", + "unknownAgent": "De agent uit de template bestaat hier niet. Kies een andere.", + "noAgentOfType": "Er is nog geen agent voor een {{type}}. Voeg er een toe om verder te gaan; deze lijst werkt bij zodra die bestaat.", "forbidden": "Je hebt geen rechten om een configuratie template in dit asset te importeren.", "failure": { "INVALID_JSON": "Het geselecteerde bestand bevat geen geldige JSON.", diff --git a/ui/app/shared/locales/pl/or.json b/ui/app/shared/locales/pl/or.json index ef42a3ced8..7fb6fadf8f 100644 --- a/ui/app/shared/locales/pl/or.json +++ b/ui/app/shared/locales/pl/or.json @@ -1505,6 +1505,9 @@ }, "writeValueFilters": { "description": "Podobnie jak valueFilter, ale stosowany do wartości wychodzących - umożliwia odwrotne filtrowanie." + }, + "id": { + "label": "" } } } @@ -1532,6 +1535,13 @@ } } } + }, + "modbus": { + "ModbusAgentLink": { + "unitId": { + "label": "" + } + } } } } diff --git a/ui/app/shared/locales/pt/or.json b/ui/app/shared/locales/pt/or.json index 0555e122d2..870d20bdfd 100644 --- a/ui/app/shared/locales/pt/or.json +++ b/ui/app/shared/locales/pt/or.json @@ -600,6 +600,9 @@ }, "writeValueFilters": { "description": "" + }, + "id": { + "label": "" } } } @@ -627,6 +630,13 @@ } } } + }, + "modbus": { + "ModbusAgentLink": { + "unitId": { + "label": "" + } + } } } } diff --git a/ui/app/shared/locales/ro/or.json b/ui/app/shared/locales/ro/or.json index 0d6e8949fd..2b478b4c1f 100644 --- a/ui/app/shared/locales/ro/or.json +++ b/ui/app/shared/locales/ro/or.json @@ -841,6 +841,9 @@ }, "writeValueFilters": { "description": "" + }, + "id": { + "label": "" } } } @@ -868,6 +871,13 @@ } } } + }, + "modbus": { + "ModbusAgentLink": { + "unitId": { + "label": "" + } + } } } } diff --git a/ui/app/shared/locales/uk/or.json b/ui/app/shared/locales/uk/or.json index a605e5b9fa..609f0154e7 100644 --- a/ui/app/shared/locales/uk/or.json +++ b/ui/app/shared/locales/uk/or.json @@ -1313,6 +1313,9 @@ }, "writeValueFilters": { "description": "Аналогічно valueFilter, але застосовується до вихідних значень, забезпечуючи зворотну фільтрацію." + }, + "id": { + "label": "" } } } @@ -1340,6 +1343,13 @@ } } } + }, + "modbus": { + "ModbusAgentLink": { + "unitId": { + "label": "" + } + } } } } diff --git a/ui/component/or-asset-viewer/src/configuration-template.ts b/ui/component/or-asset-viewer/src/configuration-template.ts index 211d20bb77..1170d1e937 100644 --- a/ui/component/or-asset-viewer/src/configuration-template.ts +++ b/ui/component/or-asset-viewer/src/configuration-template.ts @@ -24,6 +24,9 @@ import { AssetModelUtil, ConfigurationTemplateImportFailure, WellknownMetaItems, + WellknownValueTypes, + type Agent, + type AgentDescriptor, type Asset, type Attribute, type ConfigurationTemplateImportFailureLocation, @@ -31,6 +34,12 @@ import { type ValueConstraint, type ValueFormat, } from "@openremote/model"; +import { + addAgentsChangedListener, + getAgentOptions, + jsonFormsAttributeRenderers, + loadAgents, +} from "@openremote/or-attribute-input"; import { i18next } from "@openremote/or-translate"; import "@openremote/or-icon"; import "@openremote/or-translate"; @@ -39,6 +48,7 @@ import "@openremote/or-vaadin-components/or-vaadin-badge"; import "@openremote/or-vaadin-components/or-vaadin-button"; import "@openremote/or-vaadin-components/or-vaadin-checkbox"; import "@openremote/or-vaadin-components/or-vaadin-dialog"; +import "@openremote/or-vaadin-components/or-vaadin-select"; import "@openremote/or-vaadin-components/or-vaadin-text-field"; import type { OrVaadinButton } from "@openremote/or-vaadin-components/or-vaadin-button"; import type { OrVaadinCheckbox } from "@openremote/or-vaadin-components/or-vaadin-checkbox"; @@ -61,6 +71,39 @@ interface ConfigurationItemView { json?: string; } +/** The part of a JSON schema that the dialogs read. */ +interface ParameterSchema { + title?: string; + i18n?: string; + required?: string[]; + properties?: { [property: string]: ParameterSchema & { templateParameter?: boolean } }; + definitions?: { [name: string]: ParameterSchema }; +} + +/** + * A field of an agent link that the agent link schema marks as a template parameter. Fields of the same agent link + * type holding the same value share one parameter, which applies its value to all of their attributes. + */ +interface SharedParameter { + property: string; + schema: ParameterSchema; + required: boolean; + /** The value the template holds, which the parameter starts with. */ + templateValue: unknown; + value: unknown; + valid: boolean; + attributes: Attribute[]; + /** The data of the JSON Forms input, kept so that a dialog update does not reset it. */ + data?: { [property: string]: unknown }; +} + +/** The shared parameters of one agent link type. */ +interface ParameterGroup { + linkType: string; + title: string; + parameters: SharedParameter[]; +} + const DIALOG_WIDTH = "550px"; // language=CSS @@ -222,6 +265,47 @@ const dialogStyle = html` justify-content: space-between; width: 100%; } + .ac-group { + display: flex; + flex-direction: column; + gap: var(--lumo-space-m); + background-color: var(--lumo-contrast-5pct); + border-radius: var(--lumo-border-radius-l); + padding: var(--lumo-space-m); + } + .ac-group-header { + display: flex; + align-items: center; + justify-content: space-between; + font-size: var(--lumo-font-size-l); + font-weight: 600; + color: var(--lumo-body-text-color); + cursor: pointer; + } + .ac-group-details { + display: none; + flex-direction: column; + gap: var(--lumo-space-s); + } + .ac-expanded > .ac-group-details { + display: flex; + } + .ac-parameter { + display: flex; + flex-direction: column; + gap: var(--lumo-space-s); + background-color: var(--lumo-base-color); + border-radius: var(--lumo-border-radius-m); + padding: var(--lumo-space-m); + } + .ac-parameter or-vaadin-select { + width: 100%; + } + .ac-badges { + display: flex; + flex-wrap: wrap; + gap: var(--lumo-space-xs); + } `; @@ -440,19 +524,24 @@ async function previewImport( draft: asset, document: configuration, }); - showImportPreviewDialog(host, asset, fileName, configuration, response.data, onImported, onBack); + const parameters = await getParameterGroups(response.data); + showImportPreviewDialog(host, asset, fileName, configuration, response.data, parameters, onImported, onBack); } catch (error) { showImportFailureDialog(host, asset, configuration, error, onBack); } } -/** Reports what the import would change and warns that it overwrites the metadata of matched attributes. */ +/** + * Reports what the import would change and warns that it overwrites the metadata of matched attributes. With + * parameters, the import continues on the parameter step. + */ function showImportPreviewDialog( host: Node, asset: Asset, fileName: string, configuration: string, preview: ConfigurationTemplateImportPreview, + parameters: ParameterGroup[], onImported: (attributes: AssetAttributes) => void, onBack: () => void ) { @@ -502,10 +591,18 @@ function showImportPreviewDialog( theme="primary" @click=${() => { dialog?.close(); - onImported(patchedAttributes); + if (parameters.length > 0) { + showImportParametersDialog(host, asset, fileName, preview, parameters, onImported, () => + showImportPreviewDialog(host, asset, fileName, configuration, preview, parameters, onImported, onBack) + ); + } else { + onImported(patchedAttributes); + } }} > - + 0 ? "configurationTemplate.next" : "configurationTemplate.import"} + > @@ -513,6 +610,298 @@ function showImportPreviewDialog( ); } +/** + * Asks for the value of each shared parameter, prefilled from the template, and applies them to the patched + * attributes. Agent ids only offer agents of their link type, and the import is blocked while a value is missing or + * invalid, including while no agent of a needed type exists. + */ +function showImportParametersDialog( + host: Node, + asset: Asset, + fileName: string, + preview: ConfigurationTemplateImportPreview, + groups: ParameterGroup[], + onImported: (attributes: AssetAttributes) => void, + onBack: () => void +) { + const parameters = groups.flatMap((group) => group.parameters); + const dialog: Ref = createRef(); + const importBtn: Ref = createRef(); + let agents: Agent[] | undefined; + + // Renders the dialog again into the container that showDialog made for it + const update = () => { + if (dialog.value?.parentElement) { + render(getDialogTemplate(), dialog.value.parentElement); + } + }; + + const updateImportBtn = () => { + if (importBtn.value) { + importBtn.value.disabled = !agents || !parameters.every((parameter) => parameter.valid); + } + }; + + const refreshAgents = async () => { + agents = [...(await loadAgents())]; + groups.forEach((group) => + group.parameters + .filter((parameter) => isAgentIdParameter(parameter)) + .forEach((parameter) => resolveAgentId(parameter, getAgentsOfLinkType(agents!, group.linkType))) + ); + update(); + updateImportBtn(); + }; + + const getDialogTemplate = () => html` + + ${dialogStyle} ${getHeaderTemplate("configurationTemplate.importHeading", () => dialog.value?.close())} +
+ ${fileName} + + ${groups.map( + (group) => html` +
+
+ ${i18next.t("configurationTemplate.parametersHeading", { type: group.title })} + + + +
+
+ ${group.parameters.map((parameter) => + getParameterTemplate(asset, group, parameter, agents, updateImportBtn) + )} +
+
+ ` + )} +
+
+ { + dialog.value?.close(); + onBack(); + }} + > + + + parameter.valid)} + ${ref(importBtn)} + @click=${() => { + dialog.value?.close(); + onImported(applyParameters((preview.patchedAttributes || {}) as AssetAttributes, parameters)); + }} + > + + +
+
+ `; + + showDialog(host, getDialogTemplate()); + + // Agents added or removed elsewhere, such as in another tab, update the options while the step is open + const removeListener = addAgentsChangedListener(() => refreshAgents()); + dialog.value?.addEventListener("closed", () => removeListener()); + refreshAgents(); +} + +/** The input of a shared parameter, with the attributes it applies to. */ +function getParameterTemplate( + asset: Asset, + group: ParameterGroup, + parameter: SharedParameter, + agents: Agent[] | undefined, + onChange: () => void +): TemplateResult { + const label = fieldLabel(parameter.property, parameter.schema); + + return html` +
+
+ ${parameter.attributes.map((attribute) => html`${attributeLabel(asset, attribute)}`)} +
+ ${ + isAgentIdParameter(parameter) + ? getAgentIdTemplate(group, parameter, label, agents, onChange) + : getJsonFormsTemplate(parameter, label, onChange) + } +
+ `; +} + +/** Picks one of the agents of the link type, the only agents that can resolve the other fields of the link. */ +function getAgentIdTemplate( + group: ParameterGroup, + parameter: SharedParameter, + label: string, + agents: Agent[] | undefined, + onChange: () => void +): TemplateResult { + const options = agents ? getAgentOptions(getAgentsOfLinkType(agents, group.linkType)) : []; + const noAgentOfType = !!agents && options.length === 0; + // Only while no agent is picked, as the field is required + const unknownAgent = !!agents && parameter.templateValue !== undefined && parameter.value === undefined; + let errorMessage = ""; + + if (noAgentOfType) { + errorMessage = i18next.t("configurationTemplate.noAgentOfType", { type: group.title }); + } else if (unknownAgent) { + errorMessage = i18next.t("configurationTemplate.unknownAgent"); + } + + return html` + ({ value, label: optionLabel }))} + .value=${live((parameter.value as string | undefined) ?? "")} + @value-changed=${(ev: CustomEvent<{ value: string }>) => { + parameter.value = ev.detail.value || undefined; + parameter.valid = options.some(([id]) => id === parameter.value); + onChange(); + }} + > + `; +} + +/** Renders the field with JSON Forms from its schema, which also validates the value. */ +function getJsonFormsTemplate(parameter: SharedParameter, label: string, onChange: () => void): TemplateResult { + parameter.data ??= parameter.value === undefined ? {} : { [parameter.property]: parameter.value }; + + return html` + { + parameter.data = data; + parameter.value = data?.[parameter.property]; + parameter.valid = !errors?.length; + onChange(); + }} + > + `; +} + +/** + * The shared parameters of the agent links of the importable attributes, grouped by agent link type in order of + * appearance. Every field the agent link schema marks as a template parameter becomes one, and fields of the same type + * holding the same value share it. + */ +async function getParameterGroups(preview: ConfigurationTemplateImportPreview): Promise { + const patchedAttributes = (preview.patchedAttributes || {}) as AssetAttributes; + const links = (preview.importableAttributes || []) + .map((summary) => ({ ...patchedAttributes[summary.name!], name: summary.name })) + .map((attribute) => ({ attribute, link: attribute.meta?.[WellknownMetaItems.AGENTLINK] })) + .filter(({ link }) => typeof link?.type === "string"); + + if (links.length === 0) { + return []; + } + + const definitions = await getAgentLinkSchemas(); + const groups = new Map(); + const parameters = new Map(); + + links.forEach(({ attribute, link }) => { + const definition = definitions[link.type]; + + Object.entries(definition?.properties || {}) + .filter(([property, schema]) => schema.templateParameter && property !== "type") + .forEach(([property, schema]) => { + const value = link[property] ?? undefined; + const key = JSON.stringify([link.type, property, value ?? null]); + let parameter = parameters.get(key); + + if (!parameter) { + parameter = { + property, + schema, + required: property === "id" || !!definition!.required?.includes(property), + templateValue: value, + value, + valid: true, + attributes: [], + }; + parameters.set(key, parameter); + + let group = groups.get(link.type); + if (!group) { + group = { linkType: link.type, title: fieldLabel(link.type, definition), parameters: [] }; + groups.set(link.type, group); + } + group.parameters.push(parameter); + } + + parameter.attributes.push(attribute); + }); + }); + + // Agent ids before the other fields, as the agent decides what the other fields mean + groups.forEach((group) => + group.parameters.sort((a, b) => Number(isAgentIdParameter(b)) - Number(isAgentIdParameter(a))) + ); + return [...groups.values()]; +} + +/** The patched attributes with the value of every shared parameter applied to the agent links holding it. */ +function applyParameters(patchedAttributes: AssetAttributes, parameters: SharedParameter[]): AssetAttributes { + const attributes = JSON.parse(JSON.stringify(patchedAttributes)) as AssetAttributes; + + parameters.forEach((parameter) => + parameter.attributes.forEach((attribute) => { + const link = attributes[attribute.name!]?.meta?.[WellknownMetaItems.AGENTLINK]; + + if (!link) { + return; + } + if (parameter.value === undefined || parameter.value === null || parameter.value === "") { + delete link[parameter.property]; + } else { + link[parameter.property] = parameter.value; + } + }) + ); + + return attributes; +} + +function isAgentIdParameter(parameter: SharedParameter): boolean { + return parameter.property === "id"; +} + +/** The agents whose agent links have the given type. */ +function getAgentsOfLinkType(agents: Agent[], linkType: string): Agent[] { + return agents.filter( + (agent) => + (AssetModelUtil.getAssetDescriptor(agent.type) as AgentDescriptor | undefined)?.agentLinkType === linkType + ); +} + +/** Keeps the picked agent while it is one of the given agents, and otherwise falls back to the template's agent. */ +function resolveAgentId(parameter: SharedParameter, agents: Agent[]) { + const isOption = (id: unknown) => agents.some((agent) => agent.id === id); + + if (!isOption(parameter.value)) { + parameter.value = isOption(parameter.templateValue) ? parameter.templateValue : undefined; + } + parameter.valid = isOption(parameter.value); +} + /** * Reports a document that cannot be imported, with whatever the server could tell about it. A rejected file can be * swapped for another one by going back. @@ -810,3 +1199,18 @@ function getNames(names: string[]): string { function toggleJson(ev: Event) { (ev.currentTarget as HTMLElement).closest(".ac-item")?.classList.toggle("ac-json-shown"); } + +/** The label of a schema field, translated through the i18n key its JSON Schema annotations give it. */ +function fieldLabel(property: string, schema?: ParameterSchema): string { + const defaultValue = schema?.title || Util.camelCaseToSentenceCase(property); + const key = schema?.i18n ? `${schema.i18n}.label` : undefined; + return (key && (i18next.t(key, { defaultValue }) || i18next.t(key, { defaultValue, lng: "en" }))) || defaultValue; +} + +/** The JSON schema of every agent link type, keyed by link type. */ +async function getAgentLinkSchemas(): Promise<{ [linkType: string]: ParameterSchema }> { + const response = await manager.rest.api.AssetModelResource.getValueDescriptorSchema({ + name: WellknownValueTypes.AGENTLINK, + }); + return (response.data as ParameterSchema).definitions || {}; +} diff --git a/ui/component/or-asset-viewer/test/fixtures/index.ts b/ui/component/or-asset-viewer/test/fixtures/index.ts index 9b9a3a6b4e..8a22f93022 100644 --- a/ui/component/or-asset-viewer/test/fixtures/index.ts +++ b/ui/component/or-asset-viewer/test/fixtures/index.ts @@ -154,6 +154,15 @@ export class AssetViewer { // The name carries the label and value type as its title, e.g. "Dimmer (Positive integer)" return section.getByTitle(new RegExp(`^${label} \\(`)); } + + /** + * Get a locator to a parameter of the configuration template import by the label of an attribute it applies to. + * @param attributeLabel The attribute label, e.g. "Dimmer" + */ + getConfigurationTemplateParameter(attributeLabel: string): Locator { + // A parameter lists the attributes it applies to by label and value type, e.g. "Dimmer (Positive integer)" + return this.page.getByRole("dialog").locator(".ac-parameter", { hasText: new RegExp(`${attributeLabel} \\(`) }); + } } interface ComponentFixtures extends SharedComponentTestFixtures { diff --git a/ui/component/or-attribute-input/src/index.ts b/ui/component/or-attribute-input/src/index.ts index 089b6234e0..3a566a4874 100644 --- a/ui/component/or-attribute-input/src/index.ts +++ b/ui/component/or-attribute-input/src/index.ts @@ -66,6 +66,8 @@ import { agentIdRendererRegistryEntry } from "./renderers/agent-link"; import { schedulerRendererRegistryEntry } from "./renderers/scheduler"; import { replayDataRendererRegistryEntry } from "./renderers/replay-data"; +export { addAgentsChangedListener, getAgentOptions, loadAgents } from "./renderers/agent-link"; + export class OrAttributeInputChangedEvent extends CustomEvent { public static readonly NAME = "or-attribute-input-changed"; diff --git a/ui/component/or-attribute-input/src/renderers/agent-link.ts b/ui/component/or-attribute-input/src/renderers/agent-link.ts index d89840f97e..afb1348cf5 100644 --- a/ui/component/or-attribute-input/src/renderers/agent-link.ts +++ b/ui/component/or-attribute-input/src/renderers/agent-link.ts @@ -45,8 +45,24 @@ let agents: Agent[] | undefined; let loadingPromise: Promise | undefined; let subscribed = false; const timeout = 2000; +const changeListeners = new Set<() => void>(); -function loadAgents(): PromiseLike { +/** + * Calls the listener whenever the agents of {@link loadAgents} may have changed, until the returned function is + * called. Agents are only watched once they have been loaded. + */ +export function addAgentsChangedListener(listener: () => void): () => void { + changeListeners.add(listener); + return () => changeListeners.delete(listener); +} + +function onAgentsChanged() { + agents = undefined; + loadingPromise = undefined; + changeListeners.forEach((listener) => listener()); +} + +export function loadAgents(): PromiseLike { if (agents) { return Promise.resolve(agents); } @@ -59,16 +75,14 @@ function loadAgents(): PromiseLike { manager.addListener((ev: OREvent) => { switch (ev) { case OREvent.DISPLAY_REALM_CHANGED: - agents = undefined; - loadingPromise = undefined; + onAgentsChanged(); break; } }); manager.events!.subscribeAssetEvents(undefined, false, (assetEvent) => { if (assetEvent.asset && assetEvent.asset.type!.endsWith("Agent")) { - agents = undefined; - loadingPromise = undefined; + onAgentsChanged(); } }); @@ -93,6 +107,11 @@ function loadAgents(): PromiseLike { return loadingPromise; } +/** The agents to pick from for an agent link, as value and label pairs. */ +export function getAgentOptions(agents: Agent[]): [string, string][] { + return agents.map((agent) => [agent.id!, agent.name + " (" + agent.id + ")"]); +} + const agentIdTester: RankedTester = rankWith(6, and(uiTypeIs("Control"), formatIs("or-agent-id"))); const agentIdRenderer = (state: JsonFormsStateContext, props: ControlProps) => { props = { @@ -118,7 +137,7 @@ const agentIdRenderer = (state: JsonFormsStateContext, props: ControlProps) => { }; const loadedTemplatePromise = loadAgents().then((agents) => { - const options: [string, string][] = agents.map((agent) => [agent.id!, agent.name + " (" + agent.id + ")"]); + const options = getAgentOptions(agents); return html`