diff --git a/application/pom.xml b/application/pom.xml index c9a29755f2..82ab4cd113 100644 --- a/application/pom.xml +++ b/application/pom.xml @@ -10,7 +10,7 @@ 4.0.0 org.thingsboard - 4.4.1-SNAPSHOT + 4.4.2-SNAPSHOT thingsboard application diff --git a/application/src/main/java/org/thingsboard/server/controller/AiChatController.java b/application/src/main/java/org/thingsboard/server/controller/AiChatController.java index bbd9366776..6c05737fb3 100644 --- a/application/src/main/java/org/thingsboard/server/controller/AiChatController.java +++ b/application/src/main/java/org/thingsboard/server/controller/AiChatController.java @@ -65,6 +65,15 @@ class AiChatController extends BaseController { aiChatService.updateChat(chatId, request, user); } + @PreAuthorize("hasAuthority('TENANT_ADMIN')") + @PostMapping("/{chatId}/stop") + @ResponseStatus(HttpStatus.NO_CONTENT) + public void stopChat(@PathVariable UUID chatId) throws ThingsboardException { + SecurityUser user = getCurrentUser(); + accessControlService.checkPermission(user, Resource.AI, Operation.WRITE); + aiChatService.stopChat(chatId, user); + } + @PreAuthorize("hasAuthority('TENANT_ADMIN')") @GetMapping public JsonNode listChats() throws ThingsboardException { @@ -73,6 +82,14 @@ class AiChatController extends BaseController { return aiChatService.listChats(user); } + @PreAuthorize("hasAuthority('TENANT_ADMIN')") + @GetMapping("/status") + public JsonNode listChatStatuses() throws ThingsboardException { + SecurityUser user = getCurrentUser(); + accessControlService.checkPermission(user, Resource.AI, Operation.READ); + return aiChatService.listChatStatuses(user); + } + @PreAuthorize("hasAuthority('TENANT_ADMIN')") @GetMapping("/{chatId}/messages") public JsonNode getChatMessages(@PathVariable UUID chatId) throws ThingsboardException { diff --git a/application/src/main/java/org/thingsboard/server/controller/AiSolutionController.java b/application/src/main/java/org/thingsboard/server/controller/AiSolutionController.java index 3bc73f3428..14fc76ee3a 100644 --- a/application/src/main/java/org/thingsboard/server/controller/AiSolutionController.java +++ b/application/src/main/java/org/thingsboard/server/controller/AiSolutionController.java @@ -92,6 +92,14 @@ public class AiSolutionController extends BaseController { return aiSolutionService.createSolution(solutionId, user); } + @PreAuthorize("hasAuthority('TENANT_ADMIN')") + @PostMapping("/{solutionId}/stop") + public JsonNode stopSolution(@PathVariable UUID solutionId) throws ThingsboardException { + SecurityUser user = getCurrentUser(); + accessControlService.checkPermission(user, Resource.AI, Operation.WRITE); + return aiSolutionService.stopSolution(solutionId, user); + } + @PreAuthorize("hasAuthority('TENANT_ADMIN')") @PutMapping("/{solutionId}/{dataKey}") public JsonNode updateData(@PathVariable UUID solutionId, @@ -110,6 +118,22 @@ public class AiSolutionController extends BaseController { aiSolutionService.clearStep(solutionId, step, user); } + @PreAuthorize("hasAuthority('TENANT_ADMIN')") + @PostMapping(value = "/{solutionId}/update", consumes = MediaType.APPLICATION_JSON_VALUE) + public void updateSolution(@PathVariable UUID solutionId, @RequestBody JsonNode request) throws ThingsboardException { + SecurityUser user = getCurrentUser(); + accessControlService.checkPermission(user, Resource.AI, Operation.WRITE); + aiSolutionService.updateSolution(solutionId, request, user); + } + + @PreAuthorize("hasAuthority('TENANT_ADMIN')") + @GetMapping("/{solutionId}/progress") + public JsonNode getInstallProgress(@PathVariable UUID solutionId) throws ThingsboardException { + SecurityUser user = getCurrentUser(); + accessControlService.checkPermission(user, Resource.AI, Operation.READ); + return aiSolutionService.getInstallProgress(solutionId, user); + } + @PreAuthorize("hasAuthority('TENANT_ADMIN')") @PostMapping("/{solutionId}/install") public JsonNode installSolution(@PathVariable UUID solutionId, diff --git a/application/src/main/java/org/thingsboard/server/controller/IotHubController.java b/application/src/main/java/org/thingsboard/server/controller/IotHubController.java index 287c50b84d..5dc2a0ba9c 100644 --- a/application/src/main/java/org/thingsboard/server/controller/IotHubController.java +++ b/application/src/main/java/org/thingsboard/server/controller/IotHubController.java @@ -31,7 +31,6 @@ import java.util.Map; import java.util.UUID; import org.thingsboard.server.common.data.id.IotHubInstalledItemId; import org.thingsboard.server.common.data.permission.Operation; -import org.thingsboard.server.common.data.permission.Resource; import org.thingsboard.server.dao.device.DeviceConnectivityHostSource; import org.thingsboard.server.dao.device.DeviceConnectivityService; import org.thingsboard.server.dao.iot_hub.IotHubInstalledItemService; @@ -224,7 +223,7 @@ public class IotHubController extends BaseController { } private void checkAllPermissions() throws ThingsboardException { - if (!getCurrentUser().getUserPermissions().hasGenericPermission(Resource.ALL, Operation.ALL)) { + if (!getCurrentUser().getUserPermissions().hasGenericPermissionExceptAi(Operation.ALL)) { throw new ThingsboardException("You don't have permissions to use solution templates!", ThingsboardErrorCode.PERMISSION_DENIED); } diff --git a/application/src/main/java/org/thingsboard/server/controller/NotificationController.java b/application/src/main/java/org/thingsboard/server/controller/NotificationController.java index 7c43c82422..9d2781c3bc 100644 --- a/application/src/main/java/org/thingsboard/server/controller/NotificationController.java +++ b/application/src/main/java/org/thingsboard/server/controller/NotificationController.java @@ -22,6 +22,7 @@ import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import org.thingsboard.rule.engine.api.NotificationCenter; import org.thingsboard.server.common.data.EntityType; +import org.thingsboard.server.common.data.Tenant; import org.thingsboard.server.common.data.User; import org.thingsboard.server.common.data.exception.ThingsboardException; import org.thingsboard.server.common.data.id.CustomerId; @@ -38,6 +39,7 @@ import org.thingsboard.server.common.data.notification.NotificationRequestPrevie import org.thingsboard.server.common.data.notification.NotificationType; import org.thingsboard.server.common.data.notification.info.AddonAccessErrorNotificationInfo; import org.thingsboard.server.common.data.notification.info.AddonAccessRequestNotificationInfo; +import org.thingsboard.server.common.data.notification.info.AiCreditsLimitIncreaseRequestNotificationInfo; import org.thingsboard.server.common.data.notification.info.EntitiesLimitIncreaseRequestNotificationInfo; import org.thingsboard.server.common.data.notification.info.NotificationInfo; import org.thingsboard.server.common.data.notification.info.PlanUpgradeRequestNotificationInfo; @@ -72,15 +74,20 @@ import org.thingsboard.server.service.security.model.SecurityUser; import org.thingsboard.server.service.security.system.SystemSecurityService; import org.thingsboard.server.service.translation.TranslationService; +import java.time.ZoneOffset; +import java.time.ZonedDateTime; +import java.time.temporal.ChronoUnit; import java.util.Comparator; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.LinkedHashSet; import java.util.List; import java.util.Map; +import java.util.Objects; import java.util.Optional; import java.util.Set; import java.util.UUID; +import java.util.concurrent.ConcurrentHashMap; import java.util.stream.Collectors; import static org.thingsboard.server.common.data.permission.Resource.NOTIFICATION; @@ -114,6 +121,8 @@ public class NotificationController extends BaseController { private final SystemSecurityService systemSecurityService; private final SubscriptionService subscriptionService; + private final Map aiCreditsRequests = new ConcurrentHashMap<>(); + @ApiOperation(value = "Get notifications (getNotifications)", notes = "Returns the page of notifications for current user." + NEW_LINE + PAGE_DATA_PARAMETERS + @@ -499,6 +508,53 @@ public class NotificationController extends BaseController { } } + @ApiOperation(value = "Send AI credits limit increase request notification to System administrators (sendAiCreditsLimitIncreaseRequest)", + notes = "Send AI credits limit increase request notification by Tenant Administrator to System administrators. " + + "TENANT asks for a higher monthly limit of the tenant, POOL for more AI credits for the whole installation. " + + "A request for the same limit is sent once a month." + TENANT_AUTHORITY_PARAGRAPH) + @PostMapping("/notification/aiCreditsLimitIncreaseRequest") + @PreAuthorize("hasAnyAuthority('TENANT_ADMIN')") + public void sendAiCreditsLimitIncreaseRequest(@Parameter(description = "Limit to increase", schema = @Schema(allowableValues = {"TENANT", "POOL"})) + @RequestParam(defaultValue = "TENANT") String limitType, + @AuthenticationPrincipal SecurityUser user, + HttpServletRequest request) throws Exception { + boolean pool = "POOL".equals(limitType); + if (!pool && !"TENANT".equals(limitType)) { + throw new IllegalArgumentException("Unsupported limit type: " + limitType); + } + long month = ZonedDateTime.now(ZoneOffset.UTC).truncatedTo(ChronoUnit.DAYS).withDayOfMonth(1).toInstant().toEpochMilli(); + String requestKey = user.getTenantId().getId() + ":" + limitType; + if (Objects.equals(aiCreditsRequests.put(requestKey, month), month)) { + return; + } + try { + NotificationTarget sysAdmins = notificationTargetService.findNotificationTargetsByTenantIdAndUsersFilterType(TenantId.SYS_TENANT_ID, UsersFilterType.SYSTEM_ADMINISTRATORS) + .stream().findFirst() + .orElseThrow(() -> new IllegalArgumentException("Notification target for 'System administrators' not found")); + String baseUrl = systemSecurityService.getBaseUrl(TenantId.SYS_TENANT_ID, new CustomerId(EntityId.NULL_UUID), request); + Tenant tenant = tenantService.findTenantById(user.getTenantId()); + String limitDescription; + if (pool) { + limitDescription = "all AI credits of this installation's license"; + } else { + long limit = tenantProfileCache.get(user.getTenantId()).getDefaultProfileConfiguration().getMaxAiCredits(); + limitDescription = String.format("its monthly limit of %,d AI credits", limit); + } + NotificationInfo info = AiCreditsLimitIncreaseRequestNotificationInfo.builder() + .userEmail(user.getEmail()) + .tenantName(tenant != null ? tenant.getName() : user.getTenantId().toString()) + .limitDescription(limitDescription) + .increaseLimitActionLabel(pool ? "Add credits" : "Set new limit") + .increaseLimitLink(pool ? "/license" : "/tenants/" + user.getTenantId()) + .baseUrl(baseUrl) + .build(); + notificationCenter.sendSystemNotification(TenantId.SYS_TENANT_ID, sysAdmins.getId(), NotificationType.AI_CREDITS_LIMIT_INCREASE_REQUEST, info); + } catch (Exception e) { + aiCreditsRequests.remove(requestKey, month); + throw e; + } + } + @ApiOperation(value = "Get notification request preview (getNotificationRequestPreview)", notes = "Returns preview for notification request." + NEW_LINE + "`processedTemplates` shows how the notifications for each delivery method will look like " + diff --git a/application/src/main/java/org/thingsboard/server/controller/UsageInfoController.java b/application/src/main/java/org/thingsboard/server/controller/UsageInfoController.java index 7196fe5c92..2bf6be25da 100644 --- a/application/src/main/java/org/thingsboard/server/controller/UsageInfoController.java +++ b/application/src/main/java/org/thingsboard/server/controller/UsageInfoController.java @@ -12,7 +12,6 @@ import org.springframework.web.bind.annotation.RestController; import org.thingsboard.server.common.data.UsageInfo; import org.thingsboard.server.common.data.exception.ThingsboardException; import org.thingsboard.server.common.data.permission.Operation; -import org.thingsboard.server.common.data.permission.Resource; import org.thingsboard.server.dao.usage.UsageInfoService; import org.thingsboard.server.queue.util.TbCoreComponent; @@ -30,7 +29,7 @@ public class UsageInfoController extends BaseController { @PreAuthorize("hasAuthority('TENANT_ADMIN')") @GetMapping(value = "/usage") public UsageInfo getTenantUsageInfo() throws ThingsboardException { - if (!getMergedUserPermissions(getCurrentUser(), false).hasGenericPermission(Resource.ALL, Operation.READ)) { + if (!getMergedUserPermissions(getCurrentUser(), false).hasGenericPermissionExceptAi(Operation.READ)) { throw new ThingsboardException("You don't have permission to read UsageInfo!", PERMISSION_DENIED); } return checkNotNull(usageInfoService.getUsageInfo(getCurrentUser().getTenantId())); diff --git a/application/src/main/java/org/thingsboard/server/exception/AiCreditsExceededException.java b/application/src/main/java/org/thingsboard/server/exception/AiCreditsExceededException.java new file mode 100644 index 0000000000..643def19d2 --- /dev/null +++ b/application/src/main/java/org/thingsboard/server/exception/AiCreditsExceededException.java @@ -0,0 +1,20 @@ +// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: BUSL-1.1 +package org.thingsboard.server.exception; + +import lombok.Getter; +import org.thingsboard.server.common.data.exception.ThingsboardErrorCode; + +@Getter +public class AiCreditsExceededException extends ThingsboardRuntimeException { + + public static final String TENANT_LIMIT = "TENANT"; + + private final String limitType; + + public AiCreditsExceededException(String limitType) { + super("Out of AI credits", ThingsboardErrorCode.TOO_MANY_REQUESTS); + this.limitType = limitType; + } + +} diff --git a/application/src/main/java/org/thingsboard/server/exception/ThingsboardAiCreditsExceededResponse.java b/application/src/main/java/org/thingsboard/server/exception/ThingsboardAiCreditsExceededResponse.java new file mode 100644 index 0000000000..19996a2c73 --- /dev/null +++ b/application/src/main/java/org/thingsboard/server/exception/ThingsboardAiCreditsExceededResponse.java @@ -0,0 +1,28 @@ +// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: BUSL-1.1 +package org.thingsboard.server.exception; + +import io.swagger.v3.oas.annotations.media.Schema; +import org.springframework.http.HttpStatus; +import org.thingsboard.server.common.data.exception.ThingsboardErrorCode; + +@Schema +public class ThingsboardAiCreditsExceededResponse extends ThingsboardErrorResponse { + + private final String aiCreditsLimit; + + protected ThingsboardAiCreditsExceededResponse(String message, String aiCreditsLimit) { + super(message, ThingsboardErrorCode.TOO_MANY_REQUESTS, HttpStatus.TOO_MANY_REQUESTS); + this.aiCreditsLimit = aiCreditsLimit; + } + + public static ThingsboardAiCreditsExceededResponse of(String message, String aiCreditsLimit) { + return new ThingsboardAiCreditsExceededResponse(message, aiCreditsLimit); + } + + @Schema(description = "Which AI credits limit is used up: TENANT for the tenant's monthly limit", accessMode = Schema.AccessMode.READ_ONLY) + public String getAiCreditsLimit() { + return aiCreditsLimit; + } + +} diff --git a/application/src/main/java/org/thingsboard/server/exception/ThingsboardErrorResponseHandler.java b/application/src/main/java/org/thingsboard/server/exception/ThingsboardErrorResponseHandler.java index d0fb672d12..4923bbb451 100644 --- a/application/src/main/java/org/thingsboard/server/exception/ThingsboardErrorResponseHandler.java +++ b/application/src/main/java/org/thingsboard/server/exception/ThingsboardErrorResponseHandler.java @@ -93,6 +93,7 @@ public class ThingsboardErrorResponseHandler extends ResponseEntityExceptionHand errorCodeToStatusMap.put(ThingsboardErrorCode.ENTITIES_LIMIT_EXCEEDED, HttpStatus.FORBIDDEN); errorCodeToStatusMap.put(ThingsboardErrorCode.VERSION_CONFLICT, HttpStatus.CONFLICT); errorCodeToStatusMap.put(ThingsboardErrorCode.SETUP_INCOMPLETE, HttpStatus.LOCKED); + errorCodeToStatusMap.put(ThingsboardErrorCode.SERVICE_UNAVAILABLE, HttpStatus.SERVICE_UNAVAILABLE); } private static ThingsboardErrorCode statusToErrorCode(HttpStatus status) { @@ -198,6 +199,12 @@ public class ThingsboardErrorResponseHandler extends ResponseEntityExceptionHand } private void handleThingsboardRuntimeException(ThingsboardRuntimeException thingsboardRuntimeException, HttpServletResponse response) throws IOException { + if (thingsboardRuntimeException instanceof AiCreditsExceededException aiCreditsExceeded) { + response.setStatus(HttpStatus.TOO_MANY_REQUESTS.value()); + JacksonUtil.writeValue(response.getWriter(), + ThingsboardAiCreditsExceededResponse.of(aiCreditsExceeded.getMessage(), aiCreditsExceeded.getLimitType())); + return; + } ThingsboardErrorCode errorCode = thingsboardRuntimeException.getErrorCode(); HttpStatus status = errorCodeToStatus(errorCode); response.setStatus(status.value()); diff --git a/application/src/main/java/org/thingsboard/server/service/ai/DefaultTbAiService.java b/application/src/main/java/org/thingsboard/server/service/ai/DefaultTbAiService.java index f3b60383eb..174fe9cb85 100644 --- a/application/src/main/java/org/thingsboard/server/service/ai/DefaultTbAiService.java +++ b/application/src/main/java/org/thingsboard/server/service/ai/DefaultTbAiService.java @@ -17,6 +17,7 @@ import org.thingsboard.server.common.data.ApiUsageRecordKey; import org.thingsboard.server.common.data.User; import org.thingsboard.server.common.data.exception.ThingsboardErrorCode; import org.thingsboard.server.common.stats.TbApiUsageReportClient; +import org.thingsboard.server.exception.AiCreditsExceededException; import org.thingsboard.server.exception.ThingsboardRuntimeException; import org.thingsboard.server.queue.util.TbCoreComponent; import org.thingsboard.server.service.ai.transport.TbAiChannelRejectedException; @@ -152,9 +153,9 @@ class DefaultTbAiService implements TbAiService { private static String toUserFriendlyMessage(Throwable e) { if (e instanceof TimeoutException) { - return "Request timed out"; + return TbAiOperations.TIMED_OUT_MESSAGE; } else if (e instanceof TbAiChannelUnavailableException) { - return "Service unavailable"; + return TbAiOperations.UNAVAILABLE_MESSAGE; } else if (e instanceof TbAiChannelRejectedException || e instanceof ThingsboardRuntimeException) { return e.getMessage(); } @@ -176,13 +177,15 @@ class DefaultTbAiService implements TbAiService { case 404 -> ThingsboardErrorCode.ITEM_NOT_FOUND; case 409 -> ThingsboardErrorCode.VERSION_CONFLICT; case 429 -> ThingsboardErrorCode.TOO_MANY_REQUESTS; + case 401, 403 -> ThingsboardErrorCode.PERMISSION_DENIED; + case 502, 503, 504 -> ThingsboardErrorCode.SERVICE_UNAVAILABLE; default -> ThingsboardErrorCode.GENERAL; }; } private void checkApiUsage(SecurityUser user) { if (!apiUsageStateService.getApiUsageState(user.getTenantId()).isAiEnabled()) { - throw new ThingsboardRuntimeException("Out of AI credits", ThingsboardErrorCode.TOO_MANY_REQUESTS); + throw new AiCreditsExceededException(AiCreditsExceededException.TENANT_LIMIT); } } diff --git a/application/src/main/java/org/thingsboard/server/service/ai/chat/AiChatService.java b/application/src/main/java/org/thingsboard/server/service/ai/chat/AiChatService.java index 2eae20227a..c355f38b05 100644 --- a/application/src/main/java/org/thingsboard/server/service/ai/chat/AiChatService.java +++ b/application/src/main/java/org/thingsboard/server/service/ai/chat/AiChatService.java @@ -15,8 +15,12 @@ public interface AiChatService { void updateChat(UUID chatId, JsonNode request, SecurityUser user); + void stopChat(UUID chatId, SecurityUser user); + JsonNode listChats(SecurityUser user); + JsonNode listChatStatuses(SecurityUser user); + JsonNode getChatMessages(UUID chatId, SecurityUser user); void deleteChat(UUID chatId, SecurityUser user); diff --git a/application/src/main/java/org/thingsboard/server/service/ai/chat/DefaultAiChatService.java b/application/src/main/java/org/thingsboard/server/service/ai/chat/DefaultAiChatService.java index 1b15fc8045..0fff311678 100644 --- a/application/src/main/java/org/thingsboard/server/service/ai/chat/DefaultAiChatService.java +++ b/application/src/main/java/org/thingsboard/server/service/ai/chat/DefaultAiChatService.java @@ -9,6 +9,8 @@ import org.springframework.stereotype.Service; import org.thingsboard.ai.common.channel.ChannelProtocol; import org.thingsboard.ai.common.channel.ChatOperationRequest; import org.thingsboard.common.util.JacksonUtil; +import org.thingsboard.server.cache.limits.RateLimitService; +import org.thingsboard.server.common.data.limit.LimitedApi; import org.thingsboard.server.queue.util.TbCoreComponent; import org.thingsboard.server.service.ai.TbAiService; import org.thingsboard.server.service.ai.transport.TbAiOperation; @@ -27,15 +29,17 @@ import java.util.UUID; class DefaultAiChatService implements AiChatService { private static final JsonNode TOOL_CARDS = JacksonUtil.newObjectNode().put("toolCards", true); + static final String RATE_LIMITED = "RATE_LIMITED"; private final TbAiService tbAiService; private final TbAiTransport tbAiTransport; private final TbAiOperations operations; + private final RateLimitService rateLimitService; @Override public JsonNode createChat(JsonNode request, SecurityUser user) { return tbAiService.process(tokenProvider -> operations.execute( - new TbAiOperation(ChannelProtocol.CHAT_CREATE, new ChatOperationRequest(null, request)), user, tokenProvider), user, false); + new TbAiOperation(ChannelProtocol.CHAT_CREATE, new ChatOperationRequest(null, request)), user, tokenProvider), user, true); } @Override @@ -50,12 +54,24 @@ class DefaultAiChatService implements AiChatService { new TbAiOperation(ChannelProtocol.CHAT_LIST, null), user, tokenProvider), user, false); } + @Override + public JsonNode listChatStatuses(SecurityUser user) { + return tbAiService.process(tokenProvider -> operations.execute( + new TbAiOperation(ChannelProtocol.CHAT_STATUS, null), user, tokenProvider), user, false); + } + @Override public JsonNode getChatMessages(UUID chatId, SecurityUser user) { return tbAiService.process(tokenProvider -> operations.execute( new TbAiOperation(ChannelProtocol.CHAT_MESSAGES, new ChatOperationRequest(chatId, TOOL_CARDS)), user, tokenProvider), user, false); } + @Override + public void stopChat(UUID chatId, SecurityUser user) { + tbAiService.process(tokenProvider -> operations.execute( + new TbAiOperation(ChannelProtocol.CHAT_STOP, new ChatOperationRequest(chatId, null)), user, tokenProvider), user, false); + } + @Override public void deleteChat(UUID chatId, SecurityUser user) { tbAiService.process(tokenProvider -> operations.execute( @@ -67,6 +83,14 @@ class DefaultAiChatService implements AiChatService { UUID chatId, JsonNode request, String tbAccessToken, String acceptLanguage, String clientOrigin, SecurityUser user ) { + if (!rateLimitService.checkRateLimit(LimitedApi.AI_CHAT_REQUESTS, user.getTenantId())) { + return Flux.just(ServerSentEvent.builder() + .event("error") + .data(JacksonUtil.toString(JacksonUtil.newObjectNode() + .put("message", "Rate limit exceeded") + .put("code", RATE_LIMITED))) + .build()); + } var link = new TbAiTurnLink(); return tbAiService.processStream(chatId, tokenProvider -> { var context = new TbAiTurnContext(user, tbAccessToken, acceptLanguage, tokenProvider, clientOrigin); diff --git a/application/src/main/java/org/thingsboard/server/service/ai/solution/AiSolutionService.java b/application/src/main/java/org/thingsboard/server/service/ai/solution/AiSolutionService.java index b0f7763131..5e5582df98 100644 --- a/application/src/main/java/org/thingsboard/server/service/ai/solution/AiSolutionService.java +++ b/application/src/main/java/org/thingsboard/server/service/ai/solution/AiSolutionService.java @@ -25,10 +25,16 @@ public interface AiSolutionService { void clearStep(UUID solutionId, SolutionStep step, SecurityUser user); + JsonNode stopSolution(UUID solutionId, SecurityUser user); + JsonNode installSolution(UUID solutionId, String tbAccessToken, String clientOrigin, SecurityUser user); JsonNode uninstallSolution(UUID solutionId, String tbAccessToken, String clientOrigin, SecurityUser user); void deleteSolution(UUID solutionId, SecurityUser user); + void updateSolution(UUID solutionId, JsonNode request, SecurityUser user); + + JsonNode getInstallProgress(UUID solutionId, SecurityUser user); + } diff --git a/application/src/main/java/org/thingsboard/server/service/ai/solution/DefaultAiSolutionService.java b/application/src/main/java/org/thingsboard/server/service/ai/solution/DefaultAiSolutionService.java index c110699cbd..91d8297daa 100644 --- a/application/src/main/java/org/thingsboard/server/service/ai/solution/DefaultAiSolutionService.java +++ b/application/src/main/java/org/thingsboard/server/service/ai/solution/DefaultAiSolutionService.java @@ -10,12 +10,15 @@ import org.thingsboard.ai.common.data.solution.SolutionStep; import org.thingsboard.server.common.data.exception.ThingsboardErrorCode; import org.thingsboard.server.exception.ThingsboardRuntimeException; import org.thingsboard.server.common.data.util.CollectionsUtil; +import org.thingsboard.server.cache.limits.RateLimitService; +import org.thingsboard.server.common.data.limit.LimitedApi; import org.thingsboard.server.queue.util.TbCoreComponent; import org.thingsboard.ai.common.channel.ChannelProtocol; import org.thingsboard.ai.common.channel.SolutionChatRequest; import org.thingsboard.ai.common.channel.SolutionDataRequest; import org.thingsboard.ai.common.channel.SolutionOperationRequest; import org.thingsboard.ai.common.channel.SolutionStepRequest; +import org.thingsboard.ai.common.channel.SolutionUpdateRequest; import org.thingsboard.server.service.ai.TbAiService; import org.thingsboard.server.service.ai.transport.TbAiOperation; import org.thingsboard.server.service.ai.transport.TbAiOperations; @@ -32,11 +35,12 @@ public class DefaultAiSolutionService implements AiSolutionService { private final TbAiService tbAiService; private final TbAiOperations operations; + private final RateLimitService rateLimitService; @Override public JsonNode startNew(SecurityUser user) { return tbAiService.process(tokenProvider -> operations.execute( - new TbAiOperation(ChannelProtocol.SOLUTION_START, null), user, tokenProvider), user, false); + new TbAiOperation(ChannelProtocol.SOLUTION_START, null), user, tokenProvider), user); } @Override @@ -58,6 +62,9 @@ public class DefaultAiSolutionService implements AiSolutionService { if (StringUtils.isBlank(text) && attached == null) { throw new ThingsboardRuntimeException("Message cannot be blank", ThingsboardErrorCode.BAD_REQUEST_PARAMS); } + if (!rateLimitService.checkRateLimit(LimitedApi.AI_CHAT_REQUESTS, user.getTenantId())) { + throw new ThingsboardRuntimeException("Rate limit exceeded", ThingsboardErrorCode.TOO_MANY_REQUESTS); + } return tbAiService.process(tokenProvider -> operations.execute( new TbAiOperation(ChannelProtocol.SOLUTION_CHAT, new SolutionChatRequest(solutionId, step, text, attached)), user, tokenProvider), user); } @@ -80,6 +87,12 @@ public class DefaultAiSolutionService implements AiSolutionService { new TbAiOperation(ChannelProtocol.SOLUTION_STEP_CLEAR, new SolutionStepRequest(solutionId, step)), user, tokenProvider), user, false); } + @Override + public JsonNode stopSolution(UUID solutionId, SecurityUser user) { + return tbAiService.process(tokenProvider -> operations.execute( + new TbAiOperation(ChannelProtocol.SOLUTION_STOP, new SolutionOperationRequest(solutionId)), user, tokenProvider), user, false); + } + @Override public JsonNode installSolution(UUID solutionId, String tbAccessToken, String clientOrigin, SecurityUser user) { return tbAiService.process(tokenProvider -> operations.execute( @@ -100,4 +113,16 @@ public class DefaultAiSolutionService implements AiSolutionService { new TbAiOperation(ChannelProtocol.SOLUTION_DELETE, new SolutionOperationRequest(solutionId)), user, tokenProvider), user, false); } + @Override + public void updateSolution(UUID solutionId, JsonNode request, SecurityUser user) { + tbAiService.process(tokenProvider -> operations.execute( + new TbAiOperation(ChannelProtocol.SOLUTION_UPDATE, new SolutionUpdateRequest(solutionId, request)), user, tokenProvider), user, false); + } + + @Override + public JsonNode getInstallProgress(UUID solutionId, SecurityUser user) { + return tbAiService.process(tokenProvider -> operations.execute( + new TbAiOperation(ChannelProtocol.SOLUTION_PROGRESS, new SolutionOperationRequest(solutionId)), user, tokenProvider), user, false); + } + } diff --git a/application/src/main/java/org/thingsboard/server/service/ai/transport/ChannelTbAiOperations.java b/application/src/main/java/org/thingsboard/server/service/ai/transport/ChannelTbAiOperations.java index 5d6b1c4846..f336bc1c4a 100644 --- a/application/src/main/java/org/thingsboard/server/service/ai/transport/ChannelTbAiOperations.java +++ b/application/src/main/java/org/thingsboard/server/service/ai/transport/ChannelTbAiOperations.java @@ -52,7 +52,7 @@ class ChannelTbAiOperations { } catch (NotStartedException e) { if (attempt >= 2) { log.warn("AI channel operation '{}' was refused twice: {}", operation.type(), e.getMessage()); - return failure("Service unavailable"); + return failure(HttpStatus.SERVICE_UNAVAILABLE, TbAiOperations.UNAVAILABLE_MESSAGE); } log.debug("AI channel operation '{}' was not started ({}), retrying on a new channel", operation.type(), e.getMessage()); fresh = true; @@ -76,8 +76,8 @@ class ChannelTbAiOperations { } } - static TbAiResponse failure(String message) { - return TbAiResponse.builder().success(false).error(message).build(); + static TbAiResponse failure(HttpStatus status, String message) { + return TbAiResponse.builder().success(false).status(status.value()).error(message).build(); } static TbAiResponse toResponse(OperationResult result) { @@ -136,15 +136,15 @@ class ChannelTbAiOperations { return result.get(OPERATION_TIMEOUT.toMillis(), TimeUnit.MILLISECONDS); } catch (InterruptedException e) { Thread.currentThread().interrupt(); - return failure("Request interrupted"); + return failure(HttpStatus.SERVICE_UNAVAILABLE, "Request interrupted"); } catch (TimeoutException e) { - return failure("Request timed out"); + return failure(HttpStatus.GATEWAY_TIMEOUT, TbAiOperations.TIMED_OUT_MESSAGE); } catch (ExecutionException e) { if (e.getCause() instanceof NotStartedException notStarted) { throw notStarted; } log.warn("AI channel operation '{}' failed: {}", operation.type(), ExceptionUtils.getRootCauseMessage(e)); - return failure("Service unavailable"); + return failure(HttpStatus.SERVICE_UNAVAILABLE, TbAiOperations.UNAVAILABLE_MESSAGE); } finally { finish(); } diff --git a/application/src/main/java/org/thingsboard/server/service/ai/transport/ChannelTbAiTransport.java b/application/src/main/java/org/thingsboard/server/service/ai/transport/ChannelTbAiTransport.java index c8e49e4797..9cedb4a509 100644 --- a/application/src/main/java/org/thingsboard/server/service/ai/transport/ChannelTbAiTransport.java +++ b/application/src/main/java/org/thingsboard/server/service/ai/transport/ChannelTbAiTransport.java @@ -25,7 +25,7 @@ import java.util.concurrent.atomic.AtomicBoolean; /** * Runs a chat turn on a pooled channel and re-emits its events as SSE. A turn the channel did not start (refused, or * closed with 1001 before any frame for it) is retried once on a new channel; a channel that cannot be opened fails - * the turn with "Service unavailable". + * the turn with {@link TbAiOperations#UNAVAILABLE_MESSAGE}. */ @Slf4j @Component @@ -166,7 +166,7 @@ class ChannelTbAiTransport implements TbAiTransport { end(null); } else { log.warn("[{}] AI channel closed during the turn [{}] {}", chatId, code, reason); - end(errorEvent("Service unavailable")); + end(errorEvent(TbAiOperations.UNAVAILABLE_MESSAGE)); } } diff --git a/application/src/main/java/org/thingsboard/server/service/ai/transport/TbAiChannelPool.java b/application/src/main/java/org/thingsboard/server/service/ai/transport/TbAiChannelPool.java index 9cb93f24d1..a5875c01df 100644 --- a/application/src/main/java/org/thingsboard/server/service/ai/transport/TbAiChannelPool.java +++ b/application/src/main/java/org/thingsboard/server/service/ai/transport/TbAiChannelPool.java @@ -2,6 +2,8 @@ // SPDX-License-Identifier: BUSL-1.1 package org.thingsboard.server.service.ai.transport; +import com.auth0.jwt.JWT; +import com.auth0.jwt.exceptions.JWTDecodeException; import io.netty.handler.codec.http.websocketx.WebSocketClientHandshakeException; import jakarta.annotation.PreDestroy; import lombok.extern.slf4j.Slf4j; @@ -13,6 +15,7 @@ import org.springframework.http.HttpStatus; import org.springframework.stereotype.Component; import org.thingsboard.ai.common.channel.ChannelProtocol; import org.thingsboard.ai.common.channel.TbAiChannelClient; +import org.thingsboard.ai.common.client.TbAiClaims; import org.thingsboard.ai.common.client.TbAiClient; import org.thingsboard.ai.common.client.TbAiHeaders; import org.thingsboard.common.util.ThingsBoardThreadFactory; @@ -120,11 +123,17 @@ class TbAiChannelPool { PoolKey key = new PoolKey(context.tenantId(), context.userId()); CompletableFuture pending = null; if (!fresh) { + String limits = limitsOf(currentToken(context)); Group group = groups.computeIfAbsent(key, k -> new Group()); synchronized (group) { long now = nanoClock.getAsLong(); for (int i = group.connections.size() - 1; i >= 0; i--) { TbAiPooledConnection connection = group.connections.get(i); + if (connection.isStaleFor(limits)) { + log.debug("[{}] Retiring an AI channel opened with other limits", key); + connection.retire(); + continue; + } if (connection.tryReserve(now)) { return CompletableFuture.completedFuture(connection); } @@ -185,7 +194,9 @@ class TbAiChannelPool { private CompletableFuture connect(TbAiTurnContext context, PoolKey key, boolean pooled) { var connection = new TbAiPooledConnection(key, context.clientOrigin(), pooled, maxOperationsPerConnection, channelClient.codec(), this, nanoClock.getAsLong()); - channelClient.connect(handshakeTokenProvider(context), connection) + String token = currentToken(context); + connection.handshakeLimits(limitsOf(token)); + channelClient.connect(handshakeTokenProvider(context, token), connection) .subscribeOn(Schedulers.boundedElastic()) .subscribe(connection::opened, error -> connection.failed(toConnectError(error))); return connection.ready() @@ -298,13 +309,32 @@ class TbAiChannelPool { return true; } - private TbAiClient.TokenProvider handshakeTokenProvider(TbAiTurnContext context) { + private static String currentToken(TbAiTurnContext context) { + try { + return context.tokenProvider() != null ? context.tokenProvider().getToken() : null; + } catch (RuntimeException e) { + return null; + } + } + + static String limitsOf(String token) { + if (token == null) { + return null; + } + try { + return JWT.decode(token).getClaim(TbAiClaims.PROFILE_CONFIG).asString(); + } catch (JWTDecodeException e) { + return null; + } + } + + private TbAiClient.TokenProvider handshakeTokenProvider(TbAiTurnContext context, String token) { TbAiClient.TokenProvider delegate = context.tokenProvider(); String acceptLanguage = context.acceptLanguage(); return new TbAiClient.TokenProvider() { @Override public String getToken() { - return delegate.getToken(); + return token != null ? token : delegate.getToken(); } @Override @@ -324,7 +354,7 @@ class TbAiChannelPool { if (cause instanceof WebSocketClientHandshakeException handshake && handshake.response() != null) { int status = handshake.response().status().code(); if (status == HttpStatus.UNAUTHORIZED.value() || status == HttpStatus.FORBIDDEN.value()) { - return new TbAiChannelRejectedException(HttpStatus.valueOf(status).getReasonPhrase()); + return new TbAiChannelRejectedException(HttpStatus.valueOf(status)); } } if (cause instanceof TbAiChannelRejectedException || cause instanceof TbAiChannelUnavailableException) { diff --git a/application/src/main/java/org/thingsboard/server/service/ai/transport/TbAiChannelRejectedException.java b/application/src/main/java/org/thingsboard/server/service/ai/transport/TbAiChannelRejectedException.java index b0dc2324a7..2b63861a53 100644 --- a/application/src/main/java/org/thingsboard/server/service/ai/transport/TbAiChannelRejectedException.java +++ b/application/src/main/java/org/thingsboard/server/service/ai/transport/TbAiChannelRejectedException.java @@ -2,13 +2,20 @@ // SPDX-License-Identifier: BUSL-1.1 package org.thingsboard.server.service.ai.transport; +import lombok.Getter; +import org.springframework.http.HttpStatus; + /** * TB AI refused the channel handshake with 401 or 403; the reason phrase is shown to the user. */ +@Getter public class TbAiChannelRejectedException extends RuntimeException { - public TbAiChannelRejectedException(String reason) { - super(reason); + private final HttpStatus status; + + public TbAiChannelRejectedException(HttpStatus status) { + super(status.getReasonPhrase()); + this.status = status; } } diff --git a/application/src/main/java/org/thingsboard/server/service/ai/transport/TbAiOperations.java b/application/src/main/java/org/thingsboard/server/service/ai/transport/TbAiOperations.java index 32052870c1..80fa6a1e23 100644 --- a/application/src/main/java/org/thingsboard/server/service/ai/transport/TbAiOperations.java +++ b/application/src/main/java/org/thingsboard/server/service/ai/transport/TbAiOperations.java @@ -4,6 +4,7 @@ package org.thingsboard.server.service.ai.transport; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; +import org.springframework.http.HttpStatus; import org.springframework.stereotype.Component; import org.thingsboard.ai.common.client.TbAiClient; import org.thingsboard.ai.common.client.TbAiClient.TbAiResponse; @@ -17,6 +18,9 @@ import org.thingsboard.server.service.security.system.SystemSecurityService; @RequiredArgsConstructor public class TbAiOperations { + public static final String UNAVAILABLE_MESSAGE = "The AI service is unavailable. Try again."; + public static final String TIMED_OUT_MESSAGE = "The AI service did not answer in time. Try again."; + private final ChannelTbAiOperations channelOperations; private final SystemSecurityService systemSecurityService; @@ -33,9 +37,9 @@ public class TbAiOperations { return channelOperations.execute(operation, context); } catch (TbAiChannelUnavailableException e) { log.warn("[{}][{}] AI channel unavailable for '{}': {}", context.tenantId(), context.userId(), operation.type(), e.getMessage()); - return ChannelTbAiOperations.failure("Service unavailable"); + return ChannelTbAiOperations.failure(HttpStatus.SERVICE_UNAVAILABLE, UNAVAILABLE_MESSAGE); } catch (TbAiChannelRejectedException e) { - return ChannelTbAiOperations.failure(e.getMessage()); + return ChannelTbAiOperations.failure(e.getStatus(), e.getMessage()); } } diff --git a/application/src/main/java/org/thingsboard/server/service/ai/transport/TbAiPooledConnection.java b/application/src/main/java/org/thingsboard/server/service/ai/transport/TbAiPooledConnection.java index 3b77aad205..b5f0b606d1 100644 --- a/application/src/main/java/org/thingsboard/server/service/ai/transport/TbAiPooledConnection.java +++ b/application/src/main/java/org/thingsboard/server/service/ai/transport/TbAiPooledConnection.java @@ -32,7 +32,7 @@ final class TbAiPooledConnection implements ChannelFrameListener { // Protocol version 1 is the baseline. A later feature that this ThingsBoard handles goes here, so TB AI can tell // before using it that this ThingsBoard understands it. - static final List CLIENT_CAPABILITIES = List.of(); + static final List CLIENT_CAPABILITIES = List.of(ChannelProtocol.CHAT_KIT_CAPABILITY); private final TbAiChannelPool.PoolKey key; private final String origin; @@ -54,6 +54,7 @@ final class TbAiPooledConnection implements ChannelFrameListener { private volatile ChannelSession session; private volatile int maxFrameBytes = TbAiChannelClient.DEFAULT_MAX_FRAME_BYTES; private volatile List serverCapabilities = List.of(); + private volatile String handshakeLimits; /** * Created with one reservation for the caller that opens it, so callers waiting on the same handshake cannot @@ -198,6 +199,20 @@ final class TbAiPooledConnection implements ChannelFrameListener { } } + void handshakeLimits(String limits) { + this.handshakeLimits = limits; + } + + /** + * True when the channel shook hands with other limits than the caller's current token carries (the tenant + * profile's rate limits among them): its view of the user is out of date, so it should take no new work. Claims + * that change on every signing, such as the client address or the issue time, do not count. + */ + boolean isStaleFor(String currentLimits) { + String limits = handshakeLimits; + return currentLimits != null && limits != null && !limits.equals(currentLimits); + } + void retire() { boolean close; synchronized (lock) { diff --git a/application/src/main/java/org/thingsboard/server/service/entitiy/user/DefaultTbUserSettingsService.java b/application/src/main/java/org/thingsboard/server/service/entitiy/user/DefaultTbUserSettingsService.java index ddb154c88a..a045db3b86 100644 --- a/application/src/main/java/org/thingsboard/server/service/entitiy/user/DefaultTbUserSettingsService.java +++ b/application/src/main/java/org/thingsboard/server/service/entitiy/user/DefaultTbUserSettingsService.java @@ -1,5 +1,6 @@ // SPDX-FileCopyrightText: Copyright The ThingsBoard Authors -// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Modifications Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: Apache-2.0 AND BUSL-1.1 package org.thingsboard.server.service.entitiy.user; import com.fasterxml.jackson.databind.JsonNode; @@ -39,7 +40,7 @@ import java.util.stream.Collectors; @Slf4j public class DefaultTbUserSettingsService implements TbUserSettingsService { - private static final int MAX_DASHBOARD_INFO_LIST_SIZE = 10; + private static final int MAX_DASHBOARD_INFO_LIST_SIZE = 50; private static final Predicate EMPTY_TITLE = i -> StringUtils.isEmpty(i.getTitle()); private final UserSettingsService settingsService; diff --git a/application/src/main/java/org/thingsboard/server/service/install/lts/V4_4_2_0Migration.java b/application/src/main/java/org/thingsboard/server/service/install/lts/V4_4_2_0Migration.java new file mode 100644 index 0000000000..4c7a4dbeb4 --- /dev/null +++ b/application/src/main/java/org/thingsboard/server/service/install/lts/V4_4_2_0Migration.java @@ -0,0 +1,41 @@ +// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: BUSL-1.1 +package org.thingsboard.server.service.install.lts; + +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.stereotype.Component; +import org.thingsboard.server.common.data.id.TenantId; +import org.thingsboard.server.common.data.notification.NotificationType; +import org.thingsboard.server.dao.notification.DefaultNotifications; +import org.thingsboard.server.dao.notification.NotificationSettingsService; +import org.thingsboard.server.queue.util.TbCoreComponent; + +@Slf4j +@Component +@TbCoreComponent +@RequiredArgsConstructor +public class V4_4_2_0Migration implements Migration { + + private final NotificationSettingsService notificationSettingsService; + private final DefaultNotifications defaultNotifications; + + @Override + public String getVersion() { + return "4.4.2.0"; + } + + @Override + public void apply() { + createAiCreditsLimitIncreaseRequestTemplate(); + } + + private void createAiCreditsLimitIncreaseRequestTemplate() { + if (notificationSettingsService.isNotificationConfigured(TenantId.SYS_TENANT_ID, NotificationType.AI_CREDITS_LIMIT_INCREASE_REQUEST)) { + log.debug("The AI credits limit increase request notification template already exists"); + return; + } + defaultNotifications.create(TenantId.SYS_TENANT_ID, DefaultNotifications.aiCreditsLimitIncreaseRequest); + log.info("Created the AI credits limit increase request notification template"); + } +} diff --git a/application/src/main/java/org/thingsboard/server/service/iot_hub/DefaultDevicePackageService.java b/application/src/main/java/org/thingsboard/server/service/iot_hub/DefaultDevicePackageService.java index bd51048bca..e025d41fe0 100644 --- a/application/src/main/java/org/thingsboard/server/service/iot_hub/DefaultDevicePackageService.java +++ b/application/src/main/java/org/thingsboard/server/service/iot_hub/DefaultDevicePackageService.java @@ -9,6 +9,8 @@ import com.fasterxml.jackson.databind.node.TextNode; import com.google.gson.JsonParser; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; +import org.apache.commons.lang3.exception.ExceptionUtils; +import org.springframework.http.HttpStatus; import org.springframework.stereotype.Service; import org.springframework.transaction.support.TransactionTemplate; import org.springframework.web.client.RestClientException; @@ -69,6 +71,8 @@ import org.thingsboard.server.dao.subscription.PlatformFeature; import org.thingsboard.server.dao.subscription.SubscriptionService; import org.thingsboard.server.exception.DataValidationException; import org.thingsboard.server.exception.EntitiesLimitExceededException; +import org.thingsboard.server.exception.ThingsboardEntitiesLimitExceededResponse; +import org.thingsboard.server.exception.ThingsboardErrorResponse; import org.thingsboard.server.queue.util.TbCoreComponent; import org.thingsboard.server.service.entitiy.AbstractTbEntityService; import org.thingsboard.server.service.entitiy.integration.TbIntegrationService; @@ -242,7 +246,7 @@ public class DefaultDevicePackageService extends AbstractTbEntityService impleme applied = change.apply(); } catch (StepFailure e) { log.warn("[{}] Device package {} failed on step [{}], nothing was changed", tenantId, operation, e.stepKey, e.getCause()); - return DevicePackageResult.error(userMessage(e.getCause()), e.stepKey); + return DevicePackageResult.error(userMessage(e.getCause()), e.stepKey, limitOf(e.getCause())); } catch (RestClientException e) { log.error("[{}] IoT Hub request failed during the device package {}", tenantId, operation, e); return DevicePackageResult.error("IoT Hub is unavailable. Try again later.", null); @@ -1068,6 +1072,17 @@ public class DefaultDevicePackageService extends AbstractTbEntityService impleme * The message the wizard shows: the ones validation and limits give, as they are; anything else, e.g. a database * error, as a common message, with the details in the log. */ + static JsonNode limitOf(Throwable e) { + SubscriptionException subscription = ExceptionUtils.throwableOfType(e, SubscriptionException.class); + if (subscription != null) { + return JacksonUtil.valueToTree(ThingsboardErrorResponse.ofSubscriptionViolation(subscription.getMessage(), subscription.getErrorCode(), + subscription.getEntry(), subscription.getValue(), HttpStatus.FORBIDDEN)); + } + EntitiesLimitExceededException entities = ExceptionUtils.throwableOfType(e, EntitiesLimitExceededException.class); + return entities == null ? null + : JacksonUtil.valueToTree(ThingsboardEntitiesLimitExceededResponse.of(entities.getMessage(), entities.getEntityType(), entities.getLimit())); + } + static String userMessage(Throwable e) { if (e instanceof EntityVersionMismatchException) { return "Someone changed it meanwhile. Check the package again."; diff --git a/application/src/main/java/org/thingsboard/server/service/iot_hub/DevicePackageResult.java b/application/src/main/java/org/thingsboard/server/service/iot_hub/DevicePackageResult.java index d07a51d839..f7d75ff652 100644 --- a/application/src/main/java/org/thingsboard/server/service/iot_hub/DevicePackageResult.java +++ b/application/src/main/java/org/thingsboard/server/service/iot_hub/DevicePackageResult.java @@ -2,6 +2,7 @@ // SPDX-License-Identifier: BUSL-1.1 package org.thingsboard.server.service.iot_hub; +import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.node.ObjectNode; import lombok.AllArgsConstructor; import lombok.Data; @@ -25,13 +26,19 @@ public class DevicePackageResult { private DeviceInstalledItemDescriptor descriptor; // By install state key of the step: what the install instructions resolve, e.g. ${integration.httpEndpoint}, ${device.token} private Map outputs; + // When a step failed on an entity or subscription limit: the same body ThingsBoard answers such a request with (403) + private JsonNode limit; public static DevicePackageResult success(DeviceInstalledItemDescriptor descriptor, Map outputs) { - return new DevicePackageResult(true, null, null, descriptor, outputs); + return new DevicePackageResult(true, null, null, descriptor, outputs, null); } public static DevicePackageResult error(String errorMessage, String failedStep) { - return new DevicePackageResult(false, errorMessage, failedStep, null, null); + return error(errorMessage, failedStep, null); + } + + public static DevicePackageResult error(String errorMessage, String failedStep, JsonNode limit) { + return new DevicePackageResult(false, errorMessage, failedStep, null, null, limit); } } diff --git a/application/src/main/java/org/thingsboard/server/service/notification/provider/DefaultFirebaseService.java b/application/src/main/java/org/thingsboard/server/service/notification/provider/DefaultFirebaseService.java index fdee2f9c41..a4dc0125ea 100644 --- a/application/src/main/java/org/thingsboard/server/service/notification/provider/DefaultFirebaseService.java +++ b/application/src/main/java/org/thingsboard/server/service/notification/provider/DefaultFirebaseService.java @@ -1,5 +1,6 @@ // SPDX-FileCopyrightText: Copyright The ThingsBoard Authors -// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Modifications Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: Apache-2.0 AND BUSL-1.1 package org.thingsboard.server.service.notification.provider; import com.github.benmanes.caffeine.cache.Cache; @@ -52,8 +53,11 @@ public class DefaultFirebaseService implements FirebaseService { } }); + // mutable-content lets the iOS app's notification service extension + // add the template icon to the push before iOS shows it Aps.Builder apsConfig = Aps.builder() - .setSound("default"); + .setSound("default") + .setMutableContent(true); if (badge != null) { apsConfig.setBadge(badge); } diff --git a/application/src/main/java/org/thingsboard/server/service/subscription/DefaultTbEntityDataSubscriptionService.java b/application/src/main/java/org/thingsboard/server/service/subscription/DefaultTbEntityDataSubscriptionService.java index 742f9b22ec..4e8467cba5 100644 --- a/application/src/main/java/org/thingsboard/server/service/subscription/DefaultTbEntityDataSubscriptionService.java +++ b/application/src/main/java/org/thingsboard/server/service/subscription/DefaultTbEntityDataSubscriptionService.java @@ -422,7 +422,13 @@ public class DefaultTbEntityDataSubscriptionService implements TbEntityDataSubsc List entities = ctx.getEntitiesData(); ctx.cancelTasks(); ctx.clearEntitySubscriptions(); - if (entities.isEmpty()) { + if (ctx.isOwnerScoped()) { + ctx.fetchAlarms(); + TbAlarmDataSubCtx finalCtx = ctx; + ScheduledFuture task = scheduler.scheduleWithFixedDelay( + () -> refreshAlarmQuery(finalCtx), dynamicPageLinkRefreshInterval, dynamicPageLinkRefreshInterval, TimeUnit.SECONDS); + finalCtx.setRefreshTask(task); + } else if (entities.isEmpty()) { AlarmDataUpdate update = new AlarmDataUpdate(cmd.getCmdId(), new PageData<>(), null, 0, 0); ctx.sendWsMsg(update); } else { diff --git a/application/src/main/java/org/thingsboard/server/service/subscription/TbAbstractDataSubCtx.java b/application/src/main/java/org/thingsboard/server/service/subscription/TbAbstractDataSubCtx.java index 6306ad7ab3..10db008227 100644 --- a/application/src/main/java/org/thingsboard/server/service/subscription/TbAbstractDataSubCtx.java +++ b/application/src/main/java/org/thingsboard/server/service/subscription/TbAbstractDataSubCtx.java @@ -66,6 +66,9 @@ public abstract class TbAbstractDataSubCtx newDataMap) { + } + @Override protected synchronized void update() { PageData newData = findEntityData(); @@ -78,6 +81,7 @@ public abstract class TbAbstractDataSubCtx newDataMap = newData.getData().stream().collect(Collectors.toMap(EntityData::getEntityId, Function.identity(), (a, b) -> a)); if (oldDataMap.size() == newDataMap.size() && oldDataMap.keySet().equals(newDataMap.keySet())) { log.trace("[{}][{}] No updates to entity data found", sessionRef.getSessionId(), cmdId); + onSameEntities(newDataMap); } else { this.data = newData; doUpdate(newDataMap); diff --git a/application/src/main/java/org/thingsboard/server/service/subscription/TbAlarmDataSubCtx.java b/application/src/main/java/org/thingsboard/server/service/subscription/TbAlarmDataSubCtx.java index 3b7c0824c1..fb2bef81ef 100644 --- a/application/src/main/java/org/thingsboard/server/service/subscription/TbAlarmDataSubCtx.java +++ b/application/src/main/java/org/thingsboard/server/service/subscription/TbAlarmDataSubCtx.java @@ -101,7 +101,10 @@ public class TbAlarmDataSubCtx extends TbAbstractDataSubCtx { return; } AlarmDataUpdate update; - if (!entitiesMap.isEmpty()) { + if (isOwnerScoped()) { + setAndMergeAlarmsData(findOwnerAlarms()); + update = new AlarmDataUpdate(cmdId, alarms, null, maxEntitiesPerAlarmSubscription, 0); + } else if (!entitiesMap.isEmpty()) { long start = System.currentTimeMillis(); PageData alarms = alarmService.findAlarmDataByQueryForEntities(getTenantId(), getMergedUserPermissions(), query, getOrderedEntityIds()); @@ -116,9 +119,39 @@ public class TbAlarmDataSubCtx extends TbAbstractDataSubCtx { sendWsMsg(update); } + public boolean isOwnerScoped() { + return query != null && query.getEntityFilter() == null; + } + + private PageData findOwnerAlarms() { + long start = System.currentTimeMillis(); + PageData result = alarmService.findAlarmDataByQuery(getTenantId(), getCustomerId(), getMergedUserPermissions(), query); + stats.getAlarmQueryInvocationCnt().incrementAndGet(); + stats.getAlarmQueryTimeSpent().addAndGet(System.currentTimeMillis() - start); + return result; + } + + private void refreshOwnerAlarms() { + if (stopped) { + return; + } + PageData fresh = findOwnerAlarms(); + if (alarms != null && alarms.getTotalElements() == fresh.getTotalElements() && alarms.getData().equals(fresh.getData())) { + return; + } + setAndMergeAlarmsData(fresh); + sendWsMsg(new AlarmDataUpdate(cmdId, alarms, null, maxEntitiesPerAlarmSubscription, 0)); + } + public void fetchData() { resetInvocationCounter(); log.trace("[{}] Fetching data: {}", cmdId, alarmInvocationAttempts); + if (isOwnerScoped()) { + data = PageData.emptyPageData(); + entitiesMap.clear(); + tooManyEntities = false; + return; + } super.fetchData(); entitiesMap.clear(); tooManyEntities = data.hasNext(); @@ -232,6 +265,9 @@ public class TbAlarmDataSubCtx extends TbAbstractDataSubCtx { } public void cleanupOldAlarms() { + if (query.getPageLink().getTimeWindow() <= 0) { + return; + } long expTime = System.currentTimeMillis() - query.getPageLink().getTimeWindow(); boolean shouldRefresh = false; for (AlarmData alarmData : alarms.getData()) { @@ -248,7 +284,7 @@ public class TbAlarmDataSubCtx extends TbAbstractDataSubCtx { private boolean filter(Alarm alarm) { AlarmDataPageLink filter = query.getPageLink(); long startTs = System.currentTimeMillis() - filter.getTimeWindow(); - if (alarm.getCreatedTime() < startTs) { + if (filter.getTimeWindow() > 0 && alarm.getCreatedTime() < startTs) { //Skip update that does not match time window. return false; } @@ -292,6 +328,11 @@ public class TbAlarmDataSubCtx extends TbAbstractDataSubCtx { } public synchronized void checkAndResetInvocationCounter() { + if (isOwnerScoped()) { + resetInvocationCounter(); + refreshOwnerAlarms(); + return; + } boolean fetchNeeded = this.alarmInvocationAttempts > maxAlarmQueriesPerRefreshInterval; resetInvocationCounter(); if (fetchNeeded) { diff --git a/application/src/main/java/org/thingsboard/server/service/subscription/TbEntityDataSubCtx.java b/application/src/main/java/org/thingsboard/server/service/subscription/TbEntityDataSubCtx.java index 1197da0d09..fa599ecac0 100644 --- a/application/src/main/java/org/thingsboard/server/service/subscription/TbEntityDataSubCtx.java +++ b/application/src/main/java/org/thingsboard/server/service/subscription/TbEntityDataSubCtx.java @@ -3,6 +3,7 @@ // SPDX-License-Identifier: Apache-2.0 AND BUSL-1.1 package org.thingsboard.server.service.subscription; +import java.util.Objects; import lombok.Getter; import lombok.Setter; import lombok.extern.slf4j.Slf4j; @@ -177,6 +178,38 @@ public class TbEntityDataSubCtx extends TbAbstractDataSubCtx { }); } + @Override + protected void onSameEntities(Map newDataMap) { + List changed = new ArrayList<>(); + for (EntityData current : data.getData()) { + EntityData fresh = newDataMap.get(current.getEntityId()); + Map freshFields = fresh != null && fresh.getLatest() != null ? fresh.getLatest().get(EntityKeyType.ENTITY_FIELD) : null; + if (freshFields == null || freshFields.isEmpty() || current.getLatest() == null) { + continue; + } + if (!sameFieldValues(current.getLatest().get(EntityKeyType.ENTITY_FIELD), freshFields)) { + current.getLatest().put(EntityKeyType.ENTITY_FIELD, freshFields); + changed.add(new EntityData(current.getEntityId(), false, false, Map.of(EntityKeyType.ENTITY_FIELD, freshFields), null)); + } + } + if (!changed.isEmpty()) { + sendWsMsg(new EntityDataUpdate(cmdId, null, changed, maxEntitiesPerDataSubscription)); + } + } + + private static boolean sameFieldValues(Map current, Map fresh) { + if (current == null || current.size() != fresh.size()) { + return false; + } + for (Map.Entry entry : fresh.entrySet()) { + TsValue value = current.get(entry.getKey()); + if (value == null || !Objects.equals(value.getValue(), entry.getValue().getValue())) { + return false; + } + } + return true; + } + @Override public synchronized void doUpdate(Map newDataMap) { this.updateLatestTsData(this.data); diff --git a/application/src/main/resources/thingsboard.yml b/application/src/main/resources/thingsboard.yml index be1959f081..35ba0f140d 100644 --- a/application/src/main/resources/thingsboard.yml +++ b/application/src/main/resources/thingsboard.yml @@ -2556,7 +2556,7 @@ queue: # Statistics printing interval for Edge services print-interval-ms: "${TB_QUEUE_EDGE_STATS_PRINT_INTERVAL_MS:60000}" integration: - # Name of hash function used for consistent hash ring in Cluster Mode. See architecture docs for more details. Valid values - murmur3_32, murmur3_128 or sha256 + # Number of partitions in each integration queue; there is one queue per integration type. Must match TB_QUEUE_INTEGRATION_PARTITIONS on the Integration Executors, otherwise downlinks, integration validation and Check connection may not reach the executor that runs the integration. partitions: "${TB_QUEUE_INTEGRATION_PARTITIONS:3}" # For high-priority notifications that require minimum latency and processing time notifications_topic: "${TB_QUEUE_INTEGRATION_NOTIFICATIONS_TOPIC:tb_integration_executor.notifications}" diff --git a/application/src/test/java/org/thingsboard/server/service/ai/DefaultTbAiServiceTest.java b/application/src/test/java/org/thingsboard/server/service/ai/DefaultTbAiServiceTest.java index 4f48e5c6c2..245760f276 100644 --- a/application/src/test/java/org/thingsboard/server/service/ai/DefaultTbAiServiceTest.java +++ b/application/src/test/java/org/thingsboard/server/service/ai/DefaultTbAiServiceTest.java @@ -4,6 +4,7 @@ package org.thingsboard.server.service.ai; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.node.ObjectNode; +import org.springframework.http.HttpStatus; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; @@ -170,8 +171,9 @@ class DefaultTbAiServiceTest { } @ParameterizedTest - @CsvSource({"400, BAD_REQUEST_PARAMS", "413, BAD_REQUEST_PARAMS", "403, GENERAL", "404, ITEM_NOT_FOUND", - "409, VERSION_CONFLICT", "429, TOO_MANY_REQUESTS", "401, GENERAL", "500, GENERAL", "0, GENERAL"}) + @CsvSource({"400, BAD_REQUEST_PARAMS", "413, BAD_REQUEST_PARAMS", "403, PERMISSION_DENIED", "404, ITEM_NOT_FOUND", + "409, VERSION_CONFLICT", "429, TOO_MANY_REQUESTS", "401, PERMISSION_DENIED", "500, GENERAL", "0, GENERAL", + "502, SERVICE_UNAVAILABLE", "503, SERVICE_UNAVAILABLE", "504, SERVICE_UNAVAILABLE"}) void shouldKeepTheStatusOfTheAiService_whenProcessAndResponseIsFailure(int status, ThingsboardErrorCode errorCode) { // GIVEN given(apiUsageStateService.getApiUsageState(tenantId)).willReturn(enabledApiUsageState()); @@ -189,7 +191,7 @@ class DefaultTbAiServiceTest { void shouldReportCreditsThenThrowGeneral_whenProcessAndResponseIsFailure() { // GIVEN given(apiUsageStateService.getApiUsageState(tenantId)).willReturn(enabledApiUsageState()); - given(call.apply(any())).willReturn(TbAiResponse.builder().success(false).error("Upstream rejected").creditsUsed(42).build()); + given(call.apply(any())).willReturn(TbAiResponse.builder().success(false).status(500).error("Upstream rejected").creditsUsed(42).build()); // WHEN Throwable thrown = catchThrowable(() -> service.process(call, user, true)); @@ -493,12 +495,12 @@ class DefaultTbAiServiceTest { static List upstreamErrors() { return List.of( // PE-side inactivity timeout from the .timeout(...) operator - arguments(new TimeoutException("inactivity"), "Request timed out"), + arguments(new TimeoutException("inactivity"), TbAiOperations.TIMED_OUT_MESSAGE), // the AI channel cannot be opened or closed before the turn started - arguments(new TbAiChannelUnavailableException("Connection refused", null), "Service unavailable"), + arguments(new TbAiChannelUnavailableException("Connection refused", null), TbAiOperations.UNAVAILABLE_MESSAGE), // the channel handshake was refused: the reason phrase is shown - arguments(new TbAiChannelRejectedException("Unauthorized"), "Unauthorized"), - arguments(new TbAiChannelRejectedException("Forbidden"), "Forbidden"), + arguments(new TbAiChannelRejectedException(HttpStatus.UNAUTHORIZED), "Unauthorized"), + arguments(new TbAiChannelRejectedException(HttpStatus.FORBIDDEN), "Forbidden"), // any other unexpected throwable arguments(new RuntimeException("boom"), "Internal error") ); diff --git a/application/src/test/java/org/thingsboard/server/service/ai/chat/DefaultAiChatServiceTest.java b/application/src/test/java/org/thingsboard/server/service/ai/chat/DefaultAiChatServiceTest.java index a5606a95bf..1ea3dcd21c 100644 --- a/application/src/test/java/org/thingsboard/server/service/ai/chat/DefaultAiChatServiceTest.java +++ b/application/src/test/java/org/thingsboard/server/service/ai/chat/DefaultAiChatServiceTest.java @@ -17,6 +17,9 @@ import org.thingsboard.ai.common.channel.ChannelProtocol; import org.thingsboard.ai.common.channel.ChatOperationRequest; import org.thingsboard.ai.common.client.TbAiClient; import org.thingsboard.common.util.JacksonUtil; +import org.thingsboard.server.cache.limits.RateLimitService; +import org.thingsboard.server.common.data.id.TenantId; +import org.thingsboard.server.common.data.limit.LimitedApi; import org.thingsboard.server.service.ai.TbAiService; import org.thingsboard.server.service.ai.transport.TbAiTransport; import org.thingsboard.server.service.ai.transport.TbAiTurnContext; @@ -53,23 +56,25 @@ class DefaultAiChatServiceTest { TbAiOperations operations; @Mock TbAiTransport tbAiTransport; + @Mock + RateLimitService rateLimitService; DefaultAiChatService service; @BeforeEach void setUp() { - service = new DefaultAiChatService(tbAiService, tbAiTransport, operations); + service = new DefaultAiChatService(tbAiService, tbAiTransport, operations, rateLimitService); lenient().when(operations.execute(any(TbAiOperation.class), any(SecurityUser.class), any(TbAiClient.TokenProvider.class))) .thenReturn(tbAiResponse); } @Test - void shouldProcessWithoutCreditCheckAndDelegateToClient_whenCreateChatCalled() { + void shouldProcessWithCreditCheckAndDelegateToClient_whenCreateChatCalled() { // GIVEN JsonNode request = createChatRequest("New chat"); UUID chatId = UUID.randomUUID(); JsonNode expectedResponse = TextNode.valueOf(chatId.toString()); - given(tbAiService.process(any(), same(user), eq(false))).willReturn(expectedResponse); + given(tbAiService.process(any(), same(user), eq(true))).willReturn(expectedResponse); // WHEN JsonNode result = service.createChat(request, user); @@ -77,7 +82,7 @@ class DefaultAiChatServiceTest { // THEN assertThat(result).isSameAs(expectedResponse); - assertThat(captureProcessCall().apply(tokenProvider)).isSameAs(tbAiResponse); + assertThat(captureProcessCall(true).apply(tokenProvider)).isSameAs(tbAiResponse); then(operations).should().execute(argThat(operation -> ChannelProtocol.CHAT_CREATE.equals(operation.type()) && Objects.equals(new ChatOperationRequest(null, request), operation.payload())), same(user), same(tokenProvider)); then(tbAiService).shouldHaveNoMoreInteractions(); @@ -94,7 +99,7 @@ class DefaultAiChatServiceTest { service.updateChat(chatId, request, user); // THEN - assertThat(captureProcessCall().apply(tokenProvider)).isSameAs(tbAiResponse); + assertThat(captureProcessCall(false).apply(tokenProvider)).isSameAs(tbAiResponse); then(operations).should().execute(argThat(operation -> ChannelProtocol.CHAT_UPDATE.equals(operation.type()) && Objects.equals(new ChatOperationRequest(chatId, request), operation.payload())), same(user), same(tokenProvider)); then(tbAiService).shouldHaveNoMoreInteractions(); @@ -113,7 +118,7 @@ class DefaultAiChatServiceTest { // THEN assertThat(result).isSameAs(expectedResponse); - assertThat(captureProcessCall().apply(tokenProvider)).isSameAs(tbAiResponse); + assertThat(captureProcessCall(false).apply(tokenProvider)).isSameAs(tbAiResponse); then(operations).should().execute(argThat(operation -> ChannelProtocol.CHAT_LIST.equals(operation.type()) && Objects.equals(null, operation.payload())), same(user), same(tokenProvider)); then(tbAiService).shouldHaveNoMoreInteractions(); @@ -132,7 +137,7 @@ class DefaultAiChatServiceTest { // THEN assertThat(result).isSameAs(expectedResponse); - assertThat(captureProcessCall().apply(tokenProvider)).isSameAs(tbAiResponse); + assertThat(captureProcessCall(false).apply(tokenProvider)).isSameAs(tbAiResponse); then(operations).should().execute(argThat(operation -> ChannelProtocol.CHAT_MESSAGES.equals(operation.type()) && Objects.equals(new ChatOperationRequest(chatId, JacksonUtil.newObjectNode().put("toolCards", true)), operation.payload())), same(user), same(tokenProvider)); @@ -149,12 +154,28 @@ class DefaultAiChatServiceTest { service.deleteChat(chatId, user); // THEN - assertThat(captureProcessCall().apply(tokenProvider)).isSameAs(tbAiResponse); + assertThat(captureProcessCall(false).apply(tokenProvider)).isSameAs(tbAiResponse); then(operations).should().execute(argThat(operation -> ChannelProtocol.CHAT_DELETE.equals(operation.type()) && Objects.equals(new ChatOperationRequest(chatId, null), operation.payload())), same(user), same(tokenProvider)); then(tbAiService).shouldHaveNoMoreInteractions(); } + @Test + void shouldProcessWithoutCreditCheckAndDelegateToClient_whenStopChatCalled() { + // GIVEN + UUID chatId = UUID.randomUUID(); + given(tbAiService.process(any(), same(user), eq(false))).willReturn(null); + + // WHEN + service.stopChat(chatId, user); + + // THEN + assertThat(captureProcessCall(false).apply(tokenProvider)).isSameAs(tbAiResponse); + then(operations).should().execute(argThat(operation -> ChannelProtocol.CHAT_STOP.equals(operation.type()) + && Objects.equals(new ChatOperationRequest(chatId, null), operation.payload())), same(user), same(tokenProvider)); + then(tbAiService).shouldHaveNoMoreInteractions(); + } + @Test void shouldProcessStreamAndDelegateToTransportWithTurnContext_whenSendChatMessageWithClientContextCalled() { // GIVEN @@ -166,6 +187,9 @@ class DefaultAiChatServiceTest { .event("assistantMessage") .data("{\"message\":\"ok\"}") .build()); + TenantId tenantId = TenantId.fromUUID(UUID.randomUUID()); + given(user.getTenantId()).willReturn(tenantId); + given(rateLimitService.checkRateLimit(LimitedApi.AI_CHAT_REQUESTS, tenantId)).willReturn(true); given(tbAiService.processStream(eq(chatId), any(), same(user), any(TbAiTurnLink.class), eq(true))).willReturn(expectedStream); var clientOrigin = "https://tb.example.com"; var expectedContext = new TbAiTurnContext(user, tbAccessToken, acceptLanguage, tokenProvider, clientOrigin); @@ -184,6 +208,26 @@ class DefaultAiChatServiceTest { then(tbAiService).shouldHaveNoMoreInteractions(); } + @Test + void shouldAnswerWithRateLimitedError_whenTenantExceedsAiChatRequestsLimit() { + // GIVEN + UUID chatId = UUID.randomUUID(); + TenantId tenantId = TenantId.fromUUID(UUID.randomUUID()); + given(user.getTenantId()).willReturn(tenantId); + given(rateLimitService.checkRateLimit(LimitedApi.AI_CHAT_REQUESTS, tenantId)).willReturn(false); + + // WHEN + var events = service.sendChatMessage(chatId, sendMessageBody("And how many assets?", "DEVICE_LIST"), + "tb-access-token", "en-US", "https://tb.example.com", user).collectList().block(); + + // THEN + assertThat(events).hasSize(1); + assertThat(events.get(0).event()).isEqualTo("error"); + assertThat(events.get(0).data()).isEqualTo("{\"message\":\"Rate limit exceeded\",\"code\":\"RATE_LIMITED\"}"); + then(tbAiService).shouldHaveNoInteractions(); + then(tbAiTransport).shouldHaveNoInteractions(); + } + @Test void shouldFollowTheRunningTurnWithoutCreditCheck_whenResumeChatCalled() { // GIVEN @@ -211,9 +255,9 @@ class DefaultAiChatServiceTest { } @SuppressWarnings({"rawtypes", "unchecked"}) - private TbAiService.TbAiCall captureProcessCall() { + private TbAiService.TbAiCall captureProcessCall(boolean checkCredits) { ArgumentCaptor callCaptor = ArgumentCaptor.forClass(TbAiService.TbAiCall.class); - then(tbAiService).should().process(callCaptor.capture(), same(user), eq(false)); + then(tbAiService).should().process(callCaptor.capture(), same(user), eq(checkCredits)); return callCaptor.getValue(); } diff --git a/application/src/test/java/org/thingsboard/server/service/ai/solution/DefaultAiSolutionServiceTest.java b/application/src/test/java/org/thingsboard/server/service/ai/solution/DefaultAiSolutionServiceTest.java index 723dc0131e..1ca652aff1 100644 --- a/application/src/test/java/org/thingsboard/server/service/ai/solution/DefaultAiSolutionServiceTest.java +++ b/application/src/test/java/org/thingsboard/server/service/ai/solution/DefaultAiSolutionServiceTest.java @@ -22,7 +22,10 @@ import org.thingsboard.ai.common.channel.SolutionStepRequest; import org.thingsboard.ai.common.client.TbAiClient; import org.thingsboard.ai.common.data.solution.SolutionStep; import org.thingsboard.common.util.JacksonUtil; +import org.thingsboard.server.cache.limits.RateLimitService; import org.thingsboard.server.common.data.exception.ThingsboardErrorCode; +import org.thingsboard.server.common.data.id.TenantId; +import org.thingsboard.server.common.data.limit.LimitedApi; import org.thingsboard.server.exception.ThingsboardRuntimeException; import org.thingsboard.server.service.ai.TbAiService; import org.thingsboard.server.service.ai.transport.TbAiOperation; @@ -58,6 +61,10 @@ class DefaultAiSolutionServiceTest { TbAiOperations operations; @Mock SecurityUser user; + @Mock + RateLimitService rateLimitService; + + TenantId tenantId = TenantId.fromUUID(UUID.randomUUID()); String clientOrigin = "https://tb.example.com"; @@ -65,16 +72,18 @@ class DefaultAiSolutionServiceTest { @BeforeEach void setUp() { - service = new DefaultAiSolutionService(tbAiService, operations); + service = new DefaultAiSolutionService(tbAiService, operations, rateLimitService); + lenient().when(user.getTenantId()).thenReturn(tenantId); + lenient().when(rateLimitService.checkRateLimit(LimitedApi.AI_CHAT_REQUESTS, tenantId)).thenReturn(true); lenient().when(operations.execute(any(TbAiOperation.class), any(SecurityUser.class), any(TbAiClient.TokenProvider.class))) .thenReturn(tbAiResponse); } @Test - void shouldProcessWithoutCreditCheckAndDelegateToClient_whenStartNewCalled() { + void shouldProcessWithCreditCheckAndDelegateToClient_whenStartNewCalled() { // GIVEN JsonNode expectedResponse = solutionResponse(UUID.randomUUID(), "Energy Monitoring", false, false); - given(tbAiService.process(any(), same(user), eq(false))).willReturn(expectedResponse); + given(tbAiService.process(any(), same(user))).willReturn(expectedResponse); // WHEN JsonNode result = service.startNew(user); @@ -82,7 +91,7 @@ class DefaultAiSolutionServiceTest { // THEN assertThat(result).isSameAs(expectedResponse); - assertThat(captureProcessCallWithoutCreditCheck().apply(tokenProvider)).isSameAs(tbAiResponse); + assertThat(captureProcessCallWithCreditCheck().apply(tokenProvider)).isSameAs(tbAiResponse); then(operations).should().execute(argThat(operation -> ChannelProtocol.SOLUTION_START.equals(operation.type()) && Objects.equals(null, operation.payload())), same(user), same(tokenProvider)); then(tbAiService).shouldHaveNoMoreInteractions(); @@ -136,6 +145,20 @@ class DefaultAiSolutionServiceTest { then(tbAiService).shouldHaveNoInteractions(); } + @Test + void shouldRefuseWithTooManyRequestsWithoutCallingTheAiService_whenTheTenantIsOverTheChatRequestsLimit() { + // GIVEN + given(rateLimitService.checkRateLimit(LimitedApi.AI_CHAT_REQUESTS, tenantId)).willReturn(false); + + // WHEN + Throwable thrown = catchThrowable(() -> service.chat(UUID.randomUUID(), SolutionStep.INITIAL_CONFIGURATION, "Add humidity", List.of(), user)); + + // THEN + assertThat(thrown).isInstanceOf(ThingsboardRuntimeException.class).hasMessage("Rate limit exceeded"); + assertThat(((ThingsboardRuntimeException) thrown).getErrorCode()).isEqualTo(ThingsboardErrorCode.TOO_MANY_REQUESTS); + then(tbAiService).shouldHaveNoInteractions(); + } + @ParameterizedTest @EnumSource(SolutionStep.class) void shouldProcessWithCreditCheckAndDelegateToClient_whenChatCalled(SolutionStep step) { @@ -214,6 +237,22 @@ class DefaultAiSolutionServiceTest { then(tbAiService).shouldHaveNoMoreInteractions(); } + @Test + void shouldProcessWithoutCreditCheckAndDelegateToClient_whenStopSolutionCalled() { + // GIVEN + UUID solutionId = UUID.randomUUID(); + given(tbAiService.process(any(), same(user), eq(false))).willReturn(null); + + // WHEN + service.stopSolution(solutionId, user); + + // THEN + assertThat(captureProcessCallWithoutCreditCheck().apply(tokenProvider)).isSameAs(tbAiResponse); + then(operations).should().execute(argThat(operation -> ChannelProtocol.SOLUTION_STOP.equals(operation.type()) + && Objects.equals(new SolutionOperationRequest(solutionId), operation.payload())), same(user), same(tokenProvider)); + then(tbAiService).shouldHaveNoMoreInteractions(); + } + @Test void shouldProcessWithoutCreditCheckAndDelegateToClient_whenInstallSolutionCalled() { // GIVEN diff --git a/application/src/test/java/org/thingsboard/server/service/ai/transport/ChannelTbAiOperationsTest.java b/application/src/test/java/org/thingsboard/server/service/ai/transport/ChannelTbAiOperationsTest.java index c5771a6b26..3665c2476c 100644 --- a/application/src/test/java/org/thingsboard/server/service/ai/transport/ChannelTbAiOperationsTest.java +++ b/application/src/test/java/org/thingsboard/server/service/ai/transport/ChannelTbAiOperationsTest.java @@ -189,7 +189,8 @@ class ChannelTbAiOperationsTest { // THEN assertThat(response.isSuccess()).isFalse(); - assertThat(response.getError()).isEqualTo("Service unavailable"); + assertThat(response.getStatus()).isEqualTo(503); + assertThat(response.getError()).isEqualTo(TbAiOperations.UNAVAILABLE_MESSAGE); assertThat(server.received(ChannelProtocol.SOLUTION_INSTALL)).hasSize(1); } @@ -239,7 +240,8 @@ class ChannelTbAiOperationsTest { // THEN assertThat(response.isSuccess()).isFalse(); - assertThat(response.getError()).isEqualTo("Service unavailable"); + assertThat(response.getStatus()).isEqualTo(503); + assertThat(response.getError()).isEqualTo(TbAiOperations.UNAVAILABLE_MESSAGE); assertThat(server.received(ChannelProtocol.SOLUTION_INSTALL)).hasSize(1); assertThat(server.connections.get()).isEqualTo(1); } diff --git a/application/src/test/java/org/thingsboard/server/service/ai/transport/ChannelTbAiTransportTest.java b/application/src/test/java/org/thingsboard/server/service/ai/transport/ChannelTbAiTransportTest.java index a7095f83e3..7635a173e1 100644 --- a/application/src/test/java/org/thingsboard/server/service/ai/transport/ChannelTbAiTransportTest.java +++ b/application/src/test/java/org/thingsboard/server/service/ai/transport/ChannelTbAiTransportTest.java @@ -72,7 +72,7 @@ class ChannelTbAiTransportTest { assertThat(second).hasSize(3); assertThat(server.connections.get()).isEqualTo(1); ChannelHello hello = server.codec.fromPayload(server.received(ChannelProtocol.HELLO).getFirst().payload(), ChannelHello.class); - assertThat(hello).isEqualTo(new ChannelHello(1, TbAiPooledConnection.CLIENT_CAPABILITIES, "https://tb.example.com", null)); + assertThat(hello).isEqualTo(new ChannelHello(1, List.of("chat.kit"), "https://tb.example.com", null)); ChannelFrame send = server.received(ChannelProtocol.CHAT_SEND).getFirst(); ChatTurnRequest turnRequest = server.codec.fromPayload(send.payload(), ChatTurnRequest.class); assertThat(turnRequest.request()).isEqualTo(request); diff --git a/application/src/test/java/org/thingsboard/server/service/ai/transport/TbAiChannelPoolTest.java b/application/src/test/java/org/thingsboard/server/service/ai/transport/TbAiChannelPoolTest.java index 4b5a5e41df..fcf55c4214 100644 --- a/application/src/test/java/org/thingsboard/server/service/ai/transport/TbAiChannelPoolTest.java +++ b/application/src/test/java/org/thingsboard/server/service/ai/transport/TbAiChannelPoolTest.java @@ -7,17 +7,24 @@ import org.junit.jupiter.api.Test; import org.springframework.http.HttpHeaders; import org.thingsboard.ai.common.channel.ChannelProtocol; import org.thingsboard.ai.common.client.TbAiHeaders; +import org.thingsboard.ai.common.client.TbAiTokenFactory; +import org.thingsboard.ai.common.data.usage.RateLimitScope; +import org.thingsboard.ai.common.data.usage.RateLimitedApi; +import org.thingsboard.ai.common.data.user.ProfileConfig; import org.thingsboard.server.common.data.id.TenantId; import org.thingsboard.server.common.data.id.UserId; import org.thingsboard.server.service.security.model.SecurityUser; +import java.nio.charset.StandardCharsets; import java.time.Duration; +import java.util.Base64; import java.util.List; import java.util.Map; import java.util.UUID; import java.util.concurrent.CompletableFuture; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicLong; +import java.util.concurrent.atomic.AtomicReference; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; @@ -28,6 +35,8 @@ import static org.mockito.Mockito.mock; class TbAiChannelPoolTest { static final String TB_VERSION = "4.4.0"; + static final TbAiTokenFactory TOKEN_FACTORY = new TbAiTokenFactory("test", Base64.getEncoder() + .encodeToString("tb-ai-channel-pool-test-signing-key-".repeat(2).getBytes(StandardCharsets.UTF_8)), Duration.ofMinutes(60)); AtomicLong now = new AtomicLong(1_000_000_000L); FakeTbAiServer server = FakeTbAiServer.start((connection, frame) -> {}); @@ -246,6 +255,68 @@ class TbAiChannelPoolTest { await().atMost(5, TimeUnit.SECONDS).until(() -> pool.pooledConnections() == 0); } + @Test + void shouldRetireIdleChannel_whenTheTokenCarriesOtherLimits() { + // GIVEN + pool = pool(10); + SecurityUser user = user(); + AtomicReference token = new AtomicReference<>(token("10:60", "198.51.100.10")); + TbAiTurnContext context = context(user, token); + TbAiPooledConnection before = join(pool.acquire(context, false)); + before.unreserve(now.get()); + + // WHEN + token.set(token("1:60", "198.51.100.10")); + TbAiPooledConnection after = join(pool.acquire(context, false)); + + // THEN + assertThat(after).isNotSameAs(before); + assertThat(server.connections.get()).isEqualTo(2); + await().atMost(5, TimeUnit.SECONDS).until(() -> server.openConnections.get() == 1); + } + + @Test + void shouldFinishTheRunningCallOnAStaleChannel_thenCloseIt() { + // GIVEN + pool = pool(10); + AtomicReference token = new AtomicReference<>(token("10:60", "198.51.100.10")); + TbAiTurnContext context = context(user(), token); + TbAiPooledConnection busy = join(pool.acquire(context, false)); + + // WHEN + token.set(token("1:60", "198.51.100.10")); + TbAiPooledConnection next = join(pool.acquire(context, false)); + int openWhileBusy = server.openConnections.get(); + busy.unreserve(now.get()); + + // THEN + assertThat(next).isNotSameAs(busy); + assertThat(openWhileBusy).isEqualTo(2); + await().atMost(5, TimeUnit.SECONDS).until(() -> server.openConnections.get() == 1); + } + + @Test + void shouldKeepChannel_whenOnlyTheClientAddressChanged() { + // GIVEN + pool = pool(10); + AtomicReference token = new AtomicReference<>(token("10:60", "198.51.100.10")); + TbAiTurnContext context = context(user(), token); + TbAiPooledConnection desktop = join(pool.acquire(context, false)); + desktop.unreserve(now.get()); + + // WHEN + token.set(token("10:60", "203.0.113.20")); + TbAiPooledConnection mobile = join(pool.acquire(context, false)); + mobile.unreserve(now.get()); + token.set(token("10:60", "198.51.100.10")); + TbAiPooledConnection desktopAgain = join(pool.acquire(context, false)); + + // THEN + assertThat(mobile).isSameAs(desktop); + assertThat(desktopAgain).isSameAs(desktop); + assertThat(server.connections.get()).isEqualTo(1); + } + TbAiChannelPool pool(int maxConnections) { return new TbAiChannelPool(server.client(), TB_VERSION, maxConnections, 20, Duration.ofSeconds(60), Duration.ofMinutes(10), now::get, false); } @@ -265,4 +336,14 @@ class TbAiChannelPoolTest { return new TbAiTurnContext(user, null, null, () -> "token", origin); } + static TbAiTurnContext context(SecurityUser user, AtomicReference token) { + return new TbAiTurnContext(user, null, null, token::get, "https://tb.example.com"); + } + + static String token(String chatRequestsLimit, String clientAddress) { + ProfileConfig profileConfig = new ProfileConfig(); + profileConfig.setRateLimits(Map.of(RateLimitedApi.AI_CHAT_REQUESTS, Map.of(RateLimitScope.TENANT, chatRequestsLimit))); + return TOKEN_FACTORY.createToken(UUID.randomUUID().toString(), profileConfig, Map.of("clientAddress", clientAddress)); + } + } diff --git a/application/src/test/java/org/thingsboard/server/service/ai/transport/TbAiOperationsTest.java b/application/src/test/java/org/thingsboard/server/service/ai/transport/TbAiOperationsTest.java index eb751dba12..c0217ea02f 100644 --- a/application/src/test/java/org/thingsboard/server/service/ai/transport/TbAiOperationsTest.java +++ b/application/src/test/java/org/thingsboard/server/service/ai/transport/TbAiOperationsTest.java @@ -2,6 +2,7 @@ // SPDX-License-Identifier: BUSL-1.1 package org.thingsboard.server.service.ai.transport; +import org.springframework.http.HttpStatus; import org.junit.jupiter.api.Test; import org.mockito.ArgumentCaptor; import org.thingsboard.ai.common.channel.ChannelProtocol; @@ -50,19 +51,21 @@ class TbAiOperationsTest { // THEN assertThat(response.isSuccess()).isFalse(); - assertThat(response.getError()).isEqualTo("Service unavailable"); + assertThat(response.getStatus()).isEqualTo(503); + assertThat(response.getError()).isEqualTo(TbAiOperations.UNAVAILABLE_MESSAGE); } @Test void shouldReturnRejection_whenChannelHandshakeIsRefused() { // GIVEN - given(channel.execute(operation, context)).willThrow(new TbAiChannelRejectedException("Unauthorized")); + given(channel.execute(operation, context)).willThrow(new TbAiChannelRejectedException(HttpStatus.UNAUTHORIZED)); // WHEN TbAiResponse response = operations.execute(operation, context); // THEN assertThat(response.isSuccess()).isFalse(); + assertThat(response.getStatus()).isEqualTo(401); assertThat(response.getError()).isEqualTo("Unauthorized"); } diff --git a/application/src/test/java/org/thingsboard/server/service/ai/transport/TbAiPooledConnectionTest.java b/application/src/test/java/org/thingsboard/server/service/ai/transport/TbAiPooledConnectionTest.java index b77252bf94..028c865290 100644 --- a/application/src/test/java/org/thingsboard/server/service/ai/transport/TbAiPooledConnectionTest.java +++ b/application/src/test/java/org/thingsboard/server/service/ai/transport/TbAiPooledConnectionTest.java @@ -14,7 +14,6 @@ import org.thingsboard.server.common.data.id.TenantId; import org.thingsboard.server.common.data.id.UserId; import java.time.Duration; -import java.util.List; import java.util.UUID; import java.util.concurrent.TimeoutException; @@ -71,7 +70,7 @@ class TbAiPooledConnectionTest { } @Test - void shouldSendHelloWithoutCapabilities_whenSessionOpens() { + void shouldSendHelloWithItsCapabilities_whenSessionOpens() { // GIVEN TbAiPooledConnection connection = connection(); ChannelSession session = openSession(); @@ -83,12 +82,30 @@ class TbAiPooledConnectionTest { // THEN then(session).should().send(ChannelFrame.of(ChannelProtocol.HELLO, - codec.toPayload(new ChannelHello(ChannelProtocol.VERSION, List.of(), "https://tb.example.com", null)))); + codec.toPayload(new ChannelHello(ChannelProtocol.VERSION, TbAiPooledConnection.CLIENT_CAPABILITIES, "https://tb.example.com", null)))); then(session).should(never()).close(anyInt(), anyString()); assertThat(connection.ready()).isCompletedWithValue(connection); assertThat(connection.maxFrameBytes()).isEqualTo(1024); } + @Test + void shouldBeStale_whenTheCallerHoldsOtherLimits() { + // GIVEN + TbAiPooledConnection connection = connection(); + connection.handshakeLimits("limits-before-the-profile-change"); + + // WHEN-THEN + assertThat(connection.isStaleFor("limits-after-the-profile-change")).isTrue(); + assertThat(connection.isStaleFor("limits-before-the-profile-change")).isFalse(); + assertThat(connection.isStaleFor(null)).isFalse(); + } + + @Test + void shouldNotBeStale_whenItsHandshakeLimitsAreUnknown() { + // WHEN-THEN + assertThat(connection().isStaleFor("any-limits")).isFalse(); + } + TbAiPooledConnection connection() { return new TbAiPooledConnection(key, "https://tb.example.com", false, 20, codec, pool, System.nanoTime()); } diff --git a/application/src/test/java/org/thingsboard/server/service/install/lts/MigrationIntegrationTest.java b/application/src/test/java/org/thingsboard/server/service/install/lts/MigrationIntegrationTest.java index bbdb95c466..0d557be89b 100644 --- a/application/src/test/java/org/thingsboard/server/service/install/lts/MigrationIntegrationTest.java +++ b/application/src/test/java/org/thingsboard/server/service/install/lts/MigrationIntegrationTest.java @@ -57,9 +57,9 @@ public class MigrationIntegrationTest extends AbstractControllerTest { private static final String SCHEMA_UPDATE_SQL = "schema_update.sql"; // Versions with a registered bean but no schema_update.sql, because their whole change is programmatic: - // 4.3.1.5 rewrites one JSON column through the DAO. Entries here opt out of the dir/bean check below, + // 4.3.1.5 rewrites one JSON column through the DAO, 4.4.2.0 adds a notification template. Entries here opt out of the dir/bean check below, // so add one only when the version genuinely ships no SQL. - private static final Set SQL_LESS_ALLOWED = Set.of("4.3.1.5"); + private static final Set SQL_LESS_ALLOWED = Set.of("4.3.1.5", "4.4.2.0"); @Autowired private MigrationService migrationService; diff --git a/application/src/test/java/org/thingsboard/server/service/install/lts/V4_4_2_0MigrationTest.java b/application/src/test/java/org/thingsboard/server/service/install/lts/V4_4_2_0MigrationTest.java new file mode 100644 index 0000000000..37dc7bd57e --- /dev/null +++ b/application/src/test/java/org/thingsboard/server/service/install/lts/V4_4_2_0MigrationTest.java @@ -0,0 +1,56 @@ +// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: BUSL-1.1 +package org.thingsboard.server.service.install.lts; + +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; +import org.thingsboard.server.common.data.id.TenantId; +import org.thingsboard.server.common.data.notification.NotificationType; +import org.thingsboard.server.dao.notification.DefaultNotifications; +import org.thingsboard.server.dao.notification.NotificationSettingsService; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +@ExtendWith(MockitoExtension.class) +class V4_4_2_0MigrationTest { + + @Mock + private NotificationSettingsService notificationSettingsService; + @Mock + private DefaultNotifications defaultNotifications; + + @InjectMocks + private V4_4_2_0Migration migration; + + @Test + void hasItsVersion() { + assertEquals("4.4.2.0", migration.getVersion()); + } + + @Test + void createsAiCreditsLimitIncreaseRequestTemplateWhenMissing() { + when(notificationSettingsService.isNotificationConfigured(TenantId.SYS_TENANT_ID, NotificationType.AI_CREDITS_LIMIT_INCREASE_REQUEST)) + .thenReturn(false); + + migration.apply(); + + verify(defaultNotifications).create(TenantId.SYS_TENANT_ID, DefaultNotifications.aiCreditsLimitIncreaseRequest); + } + + @Test + void keepsAiCreditsLimitIncreaseRequestTemplateWhenPresent() { + when(notificationSettingsService.isNotificationConfigured(TenantId.SYS_TENANT_ID, NotificationType.AI_CREDITS_LIMIT_INCREASE_REQUEST)) + .thenReturn(true); + + migration.apply(); + + verify(defaultNotifications, never()).create(any(), any()); + } +} diff --git a/application/src/test/java/org/thingsboard/server/service/iot_hub/DefaultDevicePackageServiceTest.java b/application/src/test/java/org/thingsboard/server/service/iot_hub/DefaultDevicePackageServiceTest.java index 16dc4c3f19..a53d9f8dff 100644 --- a/application/src/test/java/org/thingsboard/server/service/iot_hub/DefaultDevicePackageServiceTest.java +++ b/application/src/test/java/org/thingsboard/server/service/iot_hub/DefaultDevicePackageServiceTest.java @@ -47,6 +47,7 @@ import org.thingsboard.server.common.data.integration.Integration; import org.thingsboard.server.common.data.page.PageData; import org.thingsboard.server.common.data.security.DeviceCredentials; import org.thingsboard.server.common.data.subscription.SubscriptionErrorCode; +import org.thingsboard.server.common.data.subscription.SubscriptionEntry; import org.thingsboard.server.common.data.subscription.SubscriptionException; import org.thingsboard.rule.engine.api.AttributesSaveRequest; import org.thingsboard.server.common.data.iot_hub.DeviceInstalledItemDescriptor; @@ -69,6 +70,7 @@ import org.thingsboard.server.service.entitiy.integration.TbIntegrationService; import org.thingsboard.server.service.install.ProjectInfo; import org.thingsboard.server.service.security.model.SecurityUser; import org.thingsboard.server.service.telemetry.TelemetrySubscriptionService; +import org.thingsboard.server.exception.EntitiesLimitExceededException; import java.util.ArrayList; import java.util.List; @@ -870,6 +872,32 @@ class DefaultDevicePackageServiceTest { .isEqualTo("Failed to save the device package"); } + @Test + void limitOf_givesTheLimitResponseBody_whenAStepHitsASubscriptionLimit() { + JsonNode limit = DefaultDevicePackageService.limitOf(new RuntimeException("step failed", new SubscriptionException( + "Maximum allowed devices limit reached!", SubscriptionErrorCode.LIMIT_REACHED, SubscriptionEntry.DEVICE_COUNT, 5))); + + assertThat(limit.get("errorCode").asInt()).isEqualTo(40); + assertThat(limit.get("message").asText()).isEqualTo("Maximum allowed devices limit reached!"); + assertThat(limit.get("subscriptionErrorCode").asText()).isEqualTo("LIMIT_REACHED"); + assertThat(limit.get("subscriptionEntry").asText()).isEqualTo("DEVICE_COUNT"); + assertThat(limit.at("/subscriptionValue/value").asLong()).isEqualTo(5); + } + + @Test + void limitOf_givesTheLimitResponseBody_whenAStepHitsATenantProfileLimit() { + JsonNode limit = DefaultDevicePackageService.limitOf(new EntitiesLimitExceededException(TenantId.SYS_TENANT_ID, EntityType.DASHBOARD, 10)); + + assertThat(limit.get("errorCode").asInt()).isEqualTo(41); + assertThat(limit.get("entityType").asText()).isEqualTo("DASHBOARD"); + assertThat(limit.get("limit").asLong()).isEqualTo(10); + } + + @Test + void limitOf_givesNothing_whenTheFailureIsNotALimit() { + assertThat(DefaultDevicePackageService.limitOf(new DataValidationException("Device with such name already exists!"))).isNull(); + } + @Test void resolvePlaceholders_leavesUnknownAliasesAsTheyAre() { ObjectNode device = JacksonUtil.newObjectNode().put("id", "123"); diff --git a/application/src/test/java/org/thingsboard/server/service/subscription/TbAlarmDataSubCtxTest.java b/application/src/test/java/org/thingsboard/server/service/subscription/TbAlarmDataSubCtxTest.java new file mode 100644 index 0000000000..a27ad861f8 --- /dev/null +++ b/application/src/test/java/org/thingsboard/server/service/subscription/TbAlarmDataSubCtxTest.java @@ -0,0 +1,137 @@ +// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: BUSL-1.1 +package org.thingsboard.server.service.subscription; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.ArgumentCaptor; +import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; +import org.thingsboard.server.common.data.alarm.Alarm; +import org.thingsboard.server.common.data.id.AlarmId; +import org.thingsboard.server.common.data.id.DeviceId; +import org.thingsboard.server.common.data.id.TenantId; +import org.thingsboard.server.common.data.page.PageData; +import org.thingsboard.server.common.data.query.AlarmData; +import org.thingsboard.server.common.data.query.AlarmDataPageLink; +import org.thingsboard.server.common.data.query.AlarmDataQuery; +import org.thingsboard.server.common.data.query.SingleEntityFilter; +import org.thingsboard.server.dao.alarm.AlarmService; +import org.thingsboard.server.service.security.model.SecurityUser; +import org.thingsboard.server.service.ws.WebSocketService; +import org.thingsboard.server.service.ws.WebSocketSessionRef; +import org.thingsboard.server.service.ws.telemetry.cmd.v2.AlarmDataUpdate; +import org.thingsboard.server.service.ws.telemetry.cmd.v2.CmdUpdate; + +import java.util.ArrayList; +import java.util.List; +import java.util.UUID; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.ArgumentMatchers.same; +import static org.mockito.BDDMockito.given; +import static org.mockito.BDDMockito.then; +import static org.mockito.Mockito.lenient; +import static org.mockito.Mockito.mock; + +@ExtendWith(MockitoExtension.class) +public class TbAlarmDataSubCtxTest { + + private final String sessionId = "session"; + private final int cmdId = 7; + private final int maxEntitiesPerAlarmSubscription = 100; + private final TenantId tenantId = TenantId.fromUUID(UUID.randomUUID()); + private final DeviceId deviceId = new DeviceId(UUID.randomUUID()); + + @Mock + private WebSocketService webSocketService; + @Mock + private AlarmService alarmService; + @Mock + private WebSocketSessionRef sessionRef; + @Mock + private SecurityUser securityUser; + + private TbAlarmDataSubCtx subCtx; + + @BeforeEach + public void setUp() { + lenient().when(sessionRef.getSessionId()).thenReturn(sessionId); + lenient().when(sessionRef.getSecurityCtx()).thenReturn(securityUser); + lenient().when(securityUser.getTenantId()).thenReturn(tenantId); + subCtx = new TbAlarmDataSubCtx("service", webSocketService, mock(), mock(), mock(), new SubscriptionServiceStatistics(), + alarmService, sessionRef, cmdId, maxEntitiesPerAlarmSubscription, 10); + } + + @Test + public void shouldBeOwnerScoped_onlyWhenQueryHasNoEntityFilter() { + assertThat(subCtx.isOwnerScoped()).isFalse(); + + subCtx.setQuery(query(null, 0)); + assertThat(subCtx.isOwnerScoped()).isTrue(); + + subCtx.setQuery(query(new SingleEntityFilter(), 0)); + assertThat(subCtx.isOwnerScoped()).isFalse(); + } + + @Test + public void shouldSendNothing_whenOwnerScopedRefreshReturnsTheSamePage() { + AlarmDataQuery query = query(null, 0); + subCtx.setQuery(query); + List alarms = List.of(alarmData(), alarmData()); + subCtx.setAlarms(new PageData<>(alarms, 1, 2, false)); + given(alarmService.findAlarmDataByQuery(eq(tenantId), any(), any(), same(query))) + .willReturn(new PageData<>(new ArrayList<>(alarms), 1, 2, false)); + + subCtx.checkAndResetInvocationCounter(); + + then(alarmService).should().findAlarmDataByQuery(eq(tenantId), any(), any(), same(query)); + then(webSocketService).shouldHaveNoInteractions(); + } + + @Test + public void shouldSendTheFreshPage_whenOwnerScopedRefreshReturnsAChangedPage() { + AlarmDataQuery query = query(null, 0); + subCtx.setQuery(query); + subCtx.setAlarms(new PageData<>(List.of(alarmData()), 1, 1, false)); + PageData fresh = new PageData<>(List.of(alarmData(), alarmData()), 1, 2, false); + given(alarmService.findAlarmDataByQuery(eq(tenantId), any(), any(), same(query))).willReturn(fresh); + + subCtx.checkAndResetInvocationCounter(); + + ArgumentCaptor updateCaptor = ArgumentCaptor.forClass(CmdUpdate.class); + then(webSocketService).should().sendUpdate(eq(sessionId), updateCaptor.capture()); + AlarmDataUpdate update = (AlarmDataUpdate) updateCaptor.getValue(); + assertThat(update.getCmdId()).isEqualTo(cmdId); + assertThat(update.getData()).isSameAs(fresh); + assertThat(update.getUpdate()).isNull(); + assertThat(update.getAllowedEntities()).isEqualTo(maxEntitiesPerAlarmSubscription); + assertThat(subCtx.getAlarms()).isSameAs(fresh); + assertThat(subCtx.getAlarmsMap()).hasSize(2); + } + + @Test + public void shouldNotTouchAlarms_whenCleanupCalledWithoutTimeWindow() { + subCtx.setQuery(query(new SingleEntityFilter(), 0)); + + subCtx.cleanupOldAlarms(); + + then(alarmService).shouldHaveNoInteractions(); + then(webSocketService).shouldHaveNoInteractions(); + } + + private static AlarmDataQuery query(SingleEntityFilter entityFilter, long timeWindow) { + AlarmDataPageLink pageLink = new AlarmDataPageLink(10, 0, null, null, false, false, 0, 0, timeWindow, null, null, null, null); + return new AlarmDataQuery(entityFilter, pageLink, null, null, null, null); + } + + private AlarmData alarmData() { + Alarm alarm = new Alarm(new AlarmId(UUID.randomUUID())); + alarm.setOriginator(deviceId); + return new AlarmData(alarm, deviceId); + } + +} diff --git a/application/src/test/java/org/thingsboard/server/service/subscription/TbEntityDataSubCtxTest.java b/application/src/test/java/org/thingsboard/server/service/subscription/TbEntityDataSubCtxTest.java index d104f8d4f4..8a50384edc 100644 --- a/application/src/test/java/org/thingsboard/server/service/subscription/TbEntityDataSubCtxTest.java +++ b/application/src/test/java/org/thingsboard/server/service/subscription/TbEntityDataSubCtxTest.java @@ -1,5 +1,6 @@ // SPDX-FileCopyrightText: Copyright The ThingsBoard Authors -// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Modifications Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: Apache-2.0 AND BUSL-1.1 package org.thingsboard.server.service.subscription; import org.apache.commons.lang3.RandomStringUtils; @@ -32,10 +33,12 @@ import java.util.Map; import java.util.UUID; import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.BDDMockito.then; +import static org.mockito.Mockito.lenient; import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; +import static org.mockito.Mockito.never; @ExtendWith(MockitoExtension.class) public class TbEntityDataSubCtxTest { @@ -57,7 +60,7 @@ public class TbEntityDataSubCtxTest { @BeforeEach public void setUp() { - when(webSocketSessionRef.getSessionId()).thenReturn(sessionId); + lenient().when(webSocketSessionRef.getSessionId()).thenReturn(sessionId); subCtx = new TbEntityDataSubCtx(serviceId, webSocketService, mock(), mock(), mock(), mock(), webSocketSessionRef, cmdId, maxEntitiesPerDataSubscription); Map subToEntityIdMap = new HashMap<>(); @@ -114,4 +117,64 @@ public class TbEntityDataSubCtxTest { assertThat(entityDataUpdate.getAllowedEntities()).isEqualTo(maxEntitiesPerDataSubscription); } + @Test + public void shouldSendOnlyChangedEntity_whenEntityFieldValueChanged() { + DeviceId otherId = new DeviceId(UUID.randomUUID()); + setCurrentData(entityWithFields(deviceId, "name", "Thermostat"), entityWithFields(otherId, "name", "Pump")); + Map changedFields = Map.of("name", new TsValue(2L, "Thermostat 2")); + + subCtx.onSameEntities(Map.of( + deviceId, new EntityData(deviceId, false, false, Map.of(EntityKeyType.ENTITY_FIELD, changedFields), null), + otherId, entityWithFields(otherId, "name", "Pump"))); + + ArgumentCaptor cmdUpdateCaptor = ArgumentCaptor.forClass(CmdUpdate.class); + then(webSocketService).should().sendUpdate(eq(sessionId), cmdUpdateCaptor.capture()); + EntityDataUpdate update = (EntityDataUpdate) cmdUpdateCaptor.getValue(); + assertThat(update.getCmdId()).isEqualTo(cmdId); + assertThat(update.getData()).isNull(); + assertThat(update.getUpdate()).singleElement().satisfies(entityData -> { + assertThat(entityData.getEntityId()).isEqualTo(deviceId); + assertThat(entityData.getLatest()).isEqualTo(Map.of(EntityKeyType.ENTITY_FIELD, changedFields)); + }); + assertThat(currentFields(deviceId)).isEqualTo(changedFields); + } + + @Test + public void shouldSendNothing_whenEntityFieldValuesUnchanged() { + setCurrentData(entityWithFields(deviceId, "name", "Thermostat")); + + subCtx.onSameEntities(Map.of(deviceId, entityWithFields(deviceId, "name", "Thermostat"))); + + then(webSocketService).should(never()).sendUpdate(any(), any()); + } + + @Test + public void shouldSkipEntity_whenFreshEntityFieldsMissingOrEmpty() { + DeviceId otherId = new DeviceId(UUID.randomUUID()); + setCurrentData(entityWithFields(deviceId, "name", "Thermostat"), entityWithFields(otherId, "name", "Pump")); + + subCtx.onSameEntities(Map.of(otherId, new EntityData(otherId, false, false, new HashMap<>(Map.of(EntityKeyType.ENTITY_FIELD, Map.of())), null))); + + then(webSocketService).should(never()).sendUpdate(any(), any()); + assertThat(currentFields(deviceId)).containsOnlyKeys("name"); + assertThat(currentFields(otherId)).containsOnlyKeys("name"); + } + + private void setCurrentData(EntityData... entities) { + ReflectionTestUtils.setField(subCtx, "data", new PageData<>(List.of(entities), 1, entities.length, false)); + } + + @SuppressWarnings("unchecked") + private Map currentFields(EntityId entityId) { + PageData data = (PageData) ReflectionTestUtils.getField(subCtx, "data"); + return data.getData().stream().filter(entityData -> entityData.getEntityId().equals(entityId)) + .findFirst().orElseThrow().getLatest().get(EntityKeyType.ENTITY_FIELD); + } + + private static EntityData entityWithFields(EntityId entityId, String key, String value) { + Map> latest = new HashMap<>(); + latest.put(EntityKeyType.ENTITY_FIELD, new HashMap<>(Map.of(key, new TsValue(1L, value)))); + return new EntityData(entityId, false, false, latest, null); + } + } diff --git a/common/actor/pom.xml b/common/actor/pom.xml index fa3037517c..d4932cd35d 100644 --- a/common/actor/pom.xml +++ b/common/actor/pom.xml @@ -10,7 +10,7 @@ 4.0.0 org.thingsboard - 4.4.1-SNAPSHOT + 4.4.2-SNAPSHOT common org.thingsboard.common diff --git a/common/agent-api/pom.xml b/common/agent-api/pom.xml index 4b52297231..c6dbbc1d89 100644 --- a/common/agent-api/pom.xml +++ b/common/agent-api/pom.xml @@ -9,7 +9,7 @@ 4.0.0 org.thingsboard - 4.4.1-SNAPSHOT + 4.4.2-SNAPSHOT common org.thingsboard.common diff --git a/common/cache/pom.xml b/common/cache/pom.xml index 0c4ca035a0..d6608c3fe3 100644 --- a/common/cache/pom.xml +++ b/common/cache/pom.xml @@ -10,7 +10,7 @@ 4.0.0 org.thingsboard - 4.4.1-SNAPSHOT + 4.4.2-SNAPSHOT common org.thingsboard.common diff --git a/common/cluster-api/pom.xml b/common/cluster-api/pom.xml index eee7fa9f3f..334d47c32c 100644 --- a/common/cluster-api/pom.xml +++ b/common/cluster-api/pom.xml @@ -10,7 +10,7 @@ 4.0.0 org.thingsboard - 4.4.1-SNAPSHOT + 4.4.2-SNAPSHOT common org.thingsboard.common diff --git a/common/coap-server/pom.xml b/common/coap-server/pom.xml index be18ecd519..19109218ea 100644 --- a/common/coap-server/pom.xml +++ b/common/coap-server/pom.xml @@ -12,7 +12,7 @@ 4.0.0 org.thingsboard - 4.4.1-SNAPSHOT + 4.4.2-SNAPSHOT common org.thingsboard.common diff --git a/common/dao-api/pom.xml b/common/dao-api/pom.xml index aec399929c..0df941cff1 100644 --- a/common/dao-api/pom.xml +++ b/common/dao-api/pom.xml @@ -10,7 +10,7 @@ 4.0.0 org.thingsboard - 4.4.1-SNAPSHOT + 4.4.2-SNAPSHOT common org.thingsboard.common diff --git a/common/dao-api/src/main/java/org/thingsboard/server/dao/alarm/AlarmService.java b/common/dao-api/src/main/java/org/thingsboard/server/dao/alarm/AlarmService.java index eec419f9ef..a89f5a32b3 100644 --- a/common/dao-api/src/main/java/org/thingsboard/server/dao/alarm/AlarmService.java +++ b/common/dao-api/src/main/java/org/thingsboard/server/dao/alarm/AlarmService.java @@ -109,6 +109,8 @@ public interface AlarmService extends EntityDaoService { PageData findAlarmDataByQueryForEntities(TenantId tenantId, MergedUserPermissions mergedUserPermissions, AlarmDataQuery query, Collection orderedEntityIds); + PageData findAlarmDataByQuery(TenantId tenantId, CustomerId customerId, MergedUserPermissions mergedUserPermissions, AlarmDataQuery query); + Set getPropagationEntityIds(Alarm alarm); Set getPropagationEntityIds(Alarm alarm, List types); diff --git a/common/data/pom.xml b/common/data/pom.xml index 3bb8c137d1..c92b144a3e 100644 --- a/common/data/pom.xml +++ b/common/data/pom.xml @@ -10,7 +10,7 @@ 4.0.0 org.thingsboard - 4.4.1-SNAPSHOT + 4.4.2-SNAPSHOT common org.thingsboard.common diff --git a/common/data/src/main/java/org/thingsboard/server/common/data/exception/ThingsboardErrorCode.java b/common/data/src/main/java/org/thingsboard/server/common/data/exception/ThingsboardErrorCode.java index f6228df527..bb24122330 100644 --- a/common/data/src/main/java/org/thingsboard/server/common/data/exception/ThingsboardErrorCode.java +++ b/common/data/src/main/java/org/thingsboard/server/common/data/exception/ThingsboardErrorCode.java @@ -22,7 +22,8 @@ public enum ThingsboardErrorCode { ENTITIES_LIMIT_EXCEEDED(41), PASSWORD_VIOLATION(45), DATABASE(46), - SETUP_INCOMPLETE(47); + SETUP_INCOMPLETE(47), + SERVICE_UNAVAILABLE(48); private int errorCode; diff --git a/common/data/src/main/java/org/thingsboard/server/common/data/limit/LimitedApi.java b/common/data/src/main/java/org/thingsboard/server/common/data/limit/LimitedApi.java index a04ba1bd9c..88531dc13f 100644 --- a/common/data/src/main/java/org/thingsboard/server/common/data/limit/LimitedApi.java +++ b/common/data/src/main/java/org/thingsboard/server/common/data/limit/LimitedApi.java @@ -57,7 +57,7 @@ public enum LimitedApi { WS_SUBSCRIPTIONS("WS subscriptions", false), CALCULATED_FIELD_DEBUG_EVENTS("calculated field debug events", true), TRENDZ_PUBLIC_SYNC("Trendz sync from public endpoint", false), - AI_CHAT_REQUESTS("AI chat requests", true); + AI_CHAT_REQUESTS(DefaultTenantProfileConfiguration::getAiChatRequestsPerTenantRateLimit, "AI chat requests", true, true); private final Function configExtractor; private final boolean perTenant; diff --git a/common/data/src/main/java/org/thingsboard/server/common/data/notification/NotificationType.java b/common/data/src/main/java/org/thingsboard/server/common/data/notification/NotificationType.java index 3708bd0eb8..43ca459aaa 100644 --- a/common/data/src/main/java/org/thingsboard/server/common/data/notification/NotificationType.java +++ b/common/data/src/main/java/org/thingsboard/server/common/data/notification/NotificationType.java @@ -24,6 +24,7 @@ public enum NotificationType { ADDON_ACCESS_REQUEST(true), ADDON_ACCESS_ERROR(true), PLAN_UPGRADE_REQUEST(true), + AI_CREDITS_LIMIT_INCREASE_REQUEST(true), API_USAGE_LIMIT, RULE_NODE, INTEGRATION_LIFECYCLE_EVENT, diff --git a/common/data/src/main/java/org/thingsboard/server/common/data/notification/info/AiCreditsLimitIncreaseRequestNotificationInfo.java b/common/data/src/main/java/org/thingsboard/server/common/data/notification/info/AiCreditsLimitIncreaseRequestNotificationInfo.java new file mode 100644 index 0000000000..dee1b1378f --- /dev/null +++ b/common/data/src/main/java/org/thingsboard/server/common/data/notification/info/AiCreditsLimitIncreaseRequestNotificationInfo.java @@ -0,0 +1,40 @@ +// SPDX-FileCopyrightText: Copyright The ThingsBoard Authors +// SPDX-FileCopyrightText: Modifications Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: Apache-2.0 AND BUSL-1.1 +package org.thingsboard.server.common.data.notification.info; + +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Data; +import lombok.NoArgsConstructor; + +import java.util.Map; + +import static org.thingsboard.server.common.data.util.CollectionsUtil.mapOf; + +@Data +@NoArgsConstructor +@AllArgsConstructor +@Builder +public class AiCreditsLimitIncreaseRequestNotificationInfo implements NotificationInfo { + + private String userEmail; + private String tenantName; + private String limitDescription; + private String increaseLimitActionLabel; + private String increaseLimitLink; + private String baseUrl; + + @Override + public Map getTemplateData() { + return mapOf( + "userEmail", userEmail, + "tenantName", tenantName, + "limitDescription", limitDescription, + "increaseLimitActionLabel", increaseLimitActionLabel, + "increaseLimitLink", increaseLimitLink, + "baseUrl", baseUrl + ); + } + +} diff --git a/common/data/src/main/java/org/thingsboard/server/common/data/notification/info/NotificationInfo.java b/common/data/src/main/java/org/thingsboard/server/common/data/notification/info/NotificationInfo.java index ad8b61402d..32ba0d43dd 100644 --- a/common/data/src/main/java/org/thingsboard/server/common/data/notification/info/NotificationInfo.java +++ b/common/data/src/main/java/org/thingsboard/server/common/data/notification/info/NotificationInfo.java @@ -35,6 +35,7 @@ import java.util.Map; @DiscriminatorMapping(value = "org.thingsboard.server.common.data.notification.info.IntegrationLifecycleEventNotificationInfo", schema = IntegrationLifecycleEventNotificationInfo.class), @DiscriminatorMapping(value = "org.thingsboard.server.common.data.notification.info.NewPlatformVersionNotificationInfo", schema = NewPlatformVersionNotificationInfo.class), @DiscriminatorMapping(value = "org.thingsboard.server.common.data.notification.info.PlanUpgradeRequestNotificationInfo", schema = PlanUpgradeRequestNotificationInfo.class), + @DiscriminatorMapping(value = "org.thingsboard.server.common.data.notification.info.AiCreditsLimitIncreaseRequestNotificationInfo", schema = AiCreditsLimitIncreaseRequestNotificationInfo.class), @DiscriminatorMapping(value = "org.thingsboard.server.common.data.notification.info.RateLimitsNotificationInfo", schema = RateLimitsNotificationInfo.class), @DiscriminatorMapping(value = "org.thingsboard.server.common.data.notification.info.ReportGeneratedNotificationInfo", schema = ReportGeneratedNotificationInfo.class), @DiscriminatorMapping(value = "org.thingsboard.server.common.data.notification.info.ResourcesShortageNotificationInfo", schema = ResourcesShortageNotificationInfo.class), @@ -64,6 +65,7 @@ import java.util.Map; @JsonSubTypes.Type(IntegrationLifecycleEventNotificationInfo.class), @JsonSubTypes.Type(NewPlatformVersionNotificationInfo.class), @JsonSubTypes.Type(PlanUpgradeRequestNotificationInfo.class), + @JsonSubTypes.Type(AiCreditsLimitIncreaseRequestNotificationInfo.class), @JsonSubTypes.Type(RateLimitsNotificationInfo.class), @JsonSubTypes.Type(ReportGeneratedNotificationInfo.class), @JsonSubTypes.Type(ResourcesShortageNotificationInfo.class), diff --git a/common/data/src/main/java/org/thingsboard/server/common/data/permission/MergedUserPermissions.java b/common/data/src/main/java/org/thingsboard/server/common/data/permission/MergedUserPermissions.java index 7244289778..12afeed071 100644 --- a/common/data/src/main/java/org/thingsboard/server/common/data/permission/MergedUserPermissions.java +++ b/common/data/src/main/java/org/thingsboard/server/common/data/permission/MergedUserPermissions.java @@ -12,6 +12,7 @@ import org.thingsboard.server.common.data.id.EntityGroupId; import java.io.Serializable; import java.util.ArrayList; +import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.List; @@ -40,6 +41,8 @@ public final class MergedUserPermissions implements Serializable { @Schema(description = "Map of read entity time-series permissions per resource. Used on the UI to enable/disable certain tabs.") private final Map readTsPermissions; + public static final Set AI_RESOURCES = Set.of(Resource.AI, Resource.AI_MODEL); + public static final MergedUserPermissions ALL = new MergedUserPermissions(Map.of(Resource.ALL, Set.of(Operation.ALL)), Collections.emptyMap()); @JsonCreator @@ -134,6 +137,32 @@ public final class MergedUserPermissions implements Serializable { return hasGenericResourcePermission(resource, operation) || hasGenericAllPermission(operation); } + /** + * True when the user has the operation on every resource except the AI ones ({@link #AI_RESOURCES}): either through + * {@link Resource#ALL}, or resource by resource, as a role that allows everything but excludes AI is merged. + */ + public boolean hasGenericPermissionExceptAi(Operation operation) { + if (hasGenericAllPermission(operation)) { + return true; + } + return Arrays.stream(Resource.values()) + .filter(resource -> resource != Resource.ALL && !AI_RESOURCES.contains(resource)) + .allMatch(resource -> hasEveryOperation(resource, operation)); + } + + private boolean hasEveryOperation(Resource resource, Operation operation) { + Set valid = Resource.operationsByResource.get(resource); + if (valid == null) { + return true; + } + if (operation != Operation.ALL) { + return !valid.contains(operation) || hasGenericResourcePermission(resource, operation); + } + List required = valid.stream().filter(op -> op != Operation.ALL).toList(); + return required.isEmpty() ? hasGenericResourcePermission(resource, Operation.ALL) + : required.stream().allMatch(op -> hasGenericResourcePermission(resource, op)); + } + private boolean hasGenericAllPermission(Operation operation) { Set operations = genericPermissions.get(Resource.ALL); return operations != null && checkOperation(operations, operation); diff --git a/common/data/src/test/java/org/thingsboard/server/common/data/limit/LimitedApiTest.java b/common/data/src/test/java/org/thingsboard/server/common/data/limit/LimitedApiTest.java index b9a8c2525a..3e92803c92 100644 --- a/common/data/src/test/java/org/thingsboard/server/common/data/limit/LimitedApiTest.java +++ b/common/data/src/test/java/org/thingsboard/server/common/data/limit/LimitedApiTest.java @@ -80,7 +80,9 @@ class LimitedApiTest { Map.entry(LimitedApi.INTEGRATION_MSGS_PER_DEVICE, () -> verify(config).getIntegrationMsgsPerDeviceRateLimit()), Map.entry(LimitedApi.INTEGRATION_MSGS_PER_ASSET, () -> - verify(config).getIntegrationMsgsPerAssetRateLimit()) + verify(config).getIntegrationMsgsPerAssetRateLimit()), + Map.entry(LimitedApi.AI_CHAT_REQUESTS, () -> + verify(config).getAiChatRequestsPerTenantRateLimit()) ); Set expected = verifierMap.keySet(); diff --git a/common/data/src/test/java/org/thingsboard/server/common/data/permission/MergedUserPermissionsTest.java b/common/data/src/test/java/org/thingsboard/server/common/data/permission/MergedUserPermissionsTest.java new file mode 100644 index 0000000000..d606067a43 --- /dev/null +++ b/common/data/src/test/java/org/thingsboard/server/common/data/permission/MergedUserPermissionsTest.java @@ -0,0 +1,75 @@ +// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: BUSL-1.1 +package org.thingsboard.server.common.data.permission; + +import org.junit.jupiter.api.Test; + +import java.util.Collections; +import java.util.HashMap; +import java.util.HashSet; +import java.util.Map; +import java.util.Set; + +import static org.assertj.core.api.Assertions.assertThat; + +class MergedUserPermissionsTest { + + @Test + void shouldAllowEverythingExceptAi_whenTheRoleAllowsAll() { + MergedUserPermissions permissions = new MergedUserPermissions(Map.of(Resource.ALL, Set.of(Operation.ALL)), Collections.emptyMap()); + + assertThat(permissions.hasGenericPermissionExceptAi(Operation.ALL)).isTrue(); + assertThat(permissions.hasGenericPermissionExceptAi(Operation.READ)).isTrue(); + } + + @Test + void shouldAllowEverythingExceptAi_whenAllIsAllowedAndTheAiResourcesAreExcluded() { + MergedUserPermissions permissions = new MergedUserPermissions(expandedExceptAi(Operation.ALL), Collections.emptyMap()); + + assertThat(permissions.hasGenericPermission(Resource.ALL, Operation.ALL)).isFalse(); + assertThat(permissions.hasGenericPermissionExceptAi(Operation.ALL)).isTrue(); + assertThat(permissions.hasGenericPermissionExceptAi(Operation.READ)).isTrue(); + } + + @Test + void shouldNotAllowEverything_whenAnotherResourceIsExcluded() { + Map> generic = expandedExceptAi(Operation.ALL); + generic.get(Resource.DEVICE).remove(Operation.WRITE); + + MergedUserPermissions permissions = new MergedUserPermissions(generic, Collections.emptyMap()); + + assertThat(permissions.hasGenericPermissionExceptAi(Operation.ALL)).isFalse(); + assertThat(permissions.hasGenericPermissionExceptAi(Operation.READ)).isTrue(); + } + + @Test + void shouldAllowReadOnly_whenReadIsAllowedOnEverythingExceptAi() { + MergedUserPermissions permissions = new MergedUserPermissions(expandedExceptAi(Operation.READ), Collections.emptyMap()); + + assertThat(permissions.hasGenericPermissionExceptAi(Operation.READ)).isTrue(); + assertThat(permissions.hasGenericPermissionExceptAi(Operation.ALL)).isFalse(); + } + + static Map> expandedExceptAi(Operation allowed) { + Map> generic = new HashMap<>(); + for (Resource resource : Resource.values()) { + Set valid = Resource.operationsByResource.get(resource); + if (resource == Resource.ALL || MergedUserPermissions.AI_RESOURCES.contains(resource) || valid == null) { + continue; + } + Set operations = new HashSet<>(valid); + if (allowed == Operation.ALL) { + if (operations.size() > 1) { + operations.remove(Operation.ALL); + } + } else { + operations.retainAll(Set.of(allowed)); + } + if (!operations.isEmpty()) { + generic.put(resource, operations); + } + } + return generic; + } + +} diff --git a/common/discovery-api/pom.xml b/common/discovery-api/pom.xml index aba7b8e3b7..777b87dda0 100644 --- a/common/discovery-api/pom.xml +++ b/common/discovery-api/pom.xml @@ -10,7 +10,7 @@ 4.0.0 org.thingsboard - 4.4.1-SNAPSHOT + 4.4.2-SNAPSHOT common org.thingsboard.common diff --git a/common/edge-api/pom.xml b/common/edge-api/pom.xml index b4249cb28f..94c1d060cd 100644 --- a/common/edge-api/pom.xml +++ b/common/edge-api/pom.xml @@ -10,7 +10,7 @@ 4.0.0 org.thingsboard - 4.4.1-SNAPSHOT + 4.4.2-SNAPSHOT common org.thingsboard.common diff --git a/common/edge-api/src/main/proto/edge.proto b/common/edge-api/src/main/proto/edge.proto index e2001ba7fb..b502f01dad 100644 --- a/common/edge-api/src/main/proto/edge.proto +++ b/common/edge-api/src/main/proto/edge.proto @@ -44,6 +44,7 @@ enum EdgeVersion { V_4_2_2_7 = 4227; V_4_2_2_8 = 4228; V_4_2_2_9 = 4229; + V_4_2_2_10 = 42210; V_4_3_0_1 = 15; V_4_3_1 = 4310; V_4_3_1_1 = 4311; @@ -55,10 +56,12 @@ enum EdgeVersion { V_4_3_1_7 = 4317; V_4_3_1_8 = 4318; V_4_3_1_9 = 4319; + V_4_3_1_10 = 43110; V_4_4_0 = 4400; V_4_4_0_1 = 4401; V_4_4_0_2 = 4402; V_4_4_1 = 4410; + V_4_4_2 = 4420; V_LATEST = 99999; } diff --git a/common/edqs/pom.xml b/common/edqs/pom.xml index 3fd8967034..53de0d7fd3 100644 --- a/common/edqs/pom.xml +++ b/common/edqs/pom.xml @@ -10,7 +10,7 @@ 4.0.0 org.thingsboard - 4.4.1-SNAPSHOT + 4.4.2-SNAPSHOT common org.thingsboard.common diff --git a/common/integration/apache-pulsar/pom.xml b/common/integration/apache-pulsar/pom.xml index af67298a14..5a29905333 100644 --- a/common/integration/apache-pulsar/pom.xml +++ b/common/integration/apache-pulsar/pom.xml @@ -11,7 +11,7 @@ 4.0.0 org.thingsboard.common - 4.4.1-SNAPSHOT + 4.4.2-SNAPSHOT integration org.thingsboard.common.integration diff --git a/common/integration/aws-integrations/pom.xml b/common/integration/aws-integrations/pom.xml index 759218c775..ad590eaa00 100644 --- a/common/integration/aws-integrations/pom.xml +++ b/common/integration/aws-integrations/pom.xml @@ -9,7 +9,7 @@ 4.0.0 org.thingsboard.common - 4.4.1-SNAPSHOT + 4.4.2-SNAPSHOT integration org.thingsboard.common.integration diff --git a/common/integration/azure-integrations/pom.xml b/common/integration/azure-integrations/pom.xml index 682887a6cb..d9ddee4e1a 100644 --- a/common/integration/azure-integrations/pom.xml +++ b/common/integration/azure-integrations/pom.xml @@ -9,7 +9,7 @@ 4.0.0 org.thingsboard.common - 4.4.1-SNAPSHOT + 4.4.2-SNAPSHOT integration org.thingsboard.common.integration diff --git a/common/integration/cluster-integration-api/pom.xml b/common/integration/cluster-integration-api/pom.xml index 1d4596b74d..5d9c43df9c 100644 --- a/common/integration/cluster-integration-api/pom.xml +++ b/common/integration/cluster-integration-api/pom.xml @@ -9,7 +9,7 @@ 4.0.0 org.thingsboard.common - 4.4.1-SNAPSHOT + 4.4.2-SNAPSHOT integration org.thingsboard.common.integration diff --git a/common/integration/coap-integrations/pom.xml b/common/integration/coap-integrations/pom.xml index 1f81a26785..b76cf5bbee 100644 --- a/common/integration/coap-integrations/pom.xml +++ b/common/integration/coap-integrations/pom.xml @@ -10,7 +10,7 @@ 4.0.0 org.thingsboard.common - 4.4.1-SNAPSHOT + 4.4.2-SNAPSHOT integration org.thingsboard.common.integration diff --git a/common/integration/gcloud-integrations/pom.xml b/common/integration/gcloud-integrations/pom.xml index 825d2f79a9..cc169746c0 100644 --- a/common/integration/gcloud-integrations/pom.xml +++ b/common/integration/gcloud-integrations/pom.xml @@ -9,7 +9,7 @@ 4.0.0 org.thingsboard.common - 4.4.1-SNAPSHOT + 4.4.2-SNAPSHOT integration org.thingsboard.common.integration diff --git a/common/integration/http-integrations/pom.xml b/common/integration/http-integrations/pom.xml index f8fde4d5bf..343522df6f 100644 --- a/common/integration/http-integrations/pom.xml +++ b/common/integration/http-integrations/pom.xml @@ -9,7 +9,7 @@ 4.0.0 org.thingsboard.common - 4.4.1-SNAPSHOT + 4.4.2-SNAPSHOT integration org.thingsboard.common.integration diff --git a/common/integration/integration-api/pom.xml b/common/integration/integration-api/pom.xml index 3b97d0bacc..fcbfac5d49 100644 --- a/common/integration/integration-api/pom.xml +++ b/common/integration/integration-api/pom.xml @@ -9,7 +9,7 @@ 4.0.0 org.thingsboard.common - 4.4.1-SNAPSHOT + 4.4.2-SNAPSHOT integration org.thingsboard.common.integration diff --git a/common/integration/kafka-integrations/pom.xml b/common/integration/kafka-integrations/pom.xml index 2a4a855a2f..72903d57d5 100644 --- a/common/integration/kafka-integrations/pom.xml +++ b/common/integration/kafka-integrations/pom.xml @@ -9,7 +9,7 @@ 4.0.0 org.thingsboard.common - 4.4.1-SNAPSHOT + 4.4.2-SNAPSHOT integration org.thingsboard.common.integration diff --git a/common/integration/mqtt-integrations/pom.xml b/common/integration/mqtt-integrations/pom.xml index 55806bba46..62368cdaf3 100644 --- a/common/integration/mqtt-integrations/pom.xml +++ b/common/integration/mqtt-integrations/pom.xml @@ -9,7 +9,7 @@ 4.0.0 org.thingsboard.common - 4.4.1-SNAPSHOT + 4.4.2-SNAPSHOT integration org.thingsboard.common.integration diff --git a/common/integration/opcua-integrations/pom.xml b/common/integration/opcua-integrations/pom.xml index e72308f862..3a7e8adc58 100644 --- a/common/integration/opcua-integrations/pom.xml +++ b/common/integration/opcua-integrations/pom.xml @@ -9,7 +9,7 @@ 4.0.0 org.thingsboard.common - 4.4.1-SNAPSHOT + 4.4.2-SNAPSHOT integration org.thingsboard.common.integration diff --git a/common/integration/pom.xml b/common/integration/pom.xml index 3ee67d5101..767aedcbaa 100644 --- a/common/integration/pom.xml +++ b/common/integration/pom.xml @@ -9,7 +9,7 @@ 4.0.0 org.thingsboard - 4.4.1-SNAPSHOT + 4.4.2-SNAPSHOT common org.thingsboard.common diff --git a/common/integration/rabbitmq-integrations/pom.xml b/common/integration/rabbitmq-integrations/pom.xml index 05174c76dd..ab0891c19b 100644 --- a/common/integration/rabbitmq-integrations/pom.xml +++ b/common/integration/rabbitmq-integrations/pom.xml @@ -9,7 +9,7 @@ 4.0.0 org.thingsboard.common - 4.4.1-SNAPSHOT + 4.4.2-SNAPSHOT integration org.thingsboard.common.integration diff --git a/common/integration/remote-integration-api/pom.xml b/common/integration/remote-integration-api/pom.xml index f0d93a0f5d..79b3773494 100644 --- a/common/integration/remote-integration-api/pom.xml +++ b/common/integration/remote-integration-api/pom.xml @@ -9,7 +9,7 @@ 4.0.0 org.thingsboard.common - 4.4.1-SNAPSHOT + 4.4.2-SNAPSHOT integration org.thingsboard.common.integration diff --git a/common/integration/tuya-integrations/pom.xml b/common/integration/tuya-integrations/pom.xml index 5355f7a31f..239c2767b1 100644 --- a/common/integration/tuya-integrations/pom.xml +++ b/common/integration/tuya-integrations/pom.xml @@ -9,7 +9,7 @@ 4.0.0 org.thingsboard.common - 4.4.1-SNAPSHOT + 4.4.2-SNAPSHOT integration org.thingsboard.common.integration diff --git a/common/message/pom.xml b/common/message/pom.xml index 05f4d7a4ea..e048cd5802 100644 --- a/common/message/pom.xml +++ b/common/message/pom.xml @@ -10,7 +10,7 @@ 4.0.0 org.thingsboard - 4.4.1-SNAPSHOT + 4.4.2-SNAPSHOT common org.thingsboard.common diff --git a/common/pom.xml b/common/pom.xml index ecef58c721..82668ff2a9 100644 --- a/common/pom.xml +++ b/common/pom.xml @@ -10,7 +10,7 @@ 4.0.0 org.thingsboard - 4.4.1-SNAPSHOT + 4.4.2-SNAPSHOT thingsboard common diff --git a/common/proto/pom.xml b/common/proto/pom.xml index 45b19bf13b..aae9f9c406 100644 --- a/common/proto/pom.xml +++ b/common/proto/pom.xml @@ -10,7 +10,7 @@ 4.0.0 org.thingsboard - 4.4.1-SNAPSHOT + 4.4.2-SNAPSHOT common org.thingsboard.common diff --git a/common/queue/pom.xml b/common/queue/pom.xml index 7b5351abba..001ae31e66 100644 --- a/common/queue/pom.xml +++ b/common/queue/pom.xml @@ -10,7 +10,7 @@ 4.0.0 org.thingsboard - 4.4.1-SNAPSHOT + 4.4.2-SNAPSHOT common org.thingsboard.common diff --git a/common/report/pom.xml b/common/report/pom.xml index 1da8aeca10..34f19c64d1 100644 --- a/common/report/pom.xml +++ b/common/report/pom.xml @@ -9,7 +9,7 @@ 4.0.0 org.thingsboard - 4.4.1-SNAPSHOT + 4.4.2-SNAPSHOT common org.thingsboard.common diff --git a/common/script/pom.xml b/common/script/pom.xml index 2fa3adae61..bd93302014 100644 --- a/common/script/pom.xml +++ b/common/script/pom.xml @@ -10,7 +10,7 @@ 4.0.0 org.thingsboard - 4.4.1-SNAPSHOT + 4.4.2-SNAPSHOT common org.thingsboard.common diff --git a/common/script/remote-js-client/pom.xml b/common/script/remote-js-client/pom.xml index 98f78fa69e..9868dceaea 100644 --- a/common/script/remote-js-client/pom.xml +++ b/common/script/remote-js-client/pom.xml @@ -10,7 +10,7 @@ 4.0.0 org.thingsboard.common - 4.4.1-SNAPSHOT + 4.4.2-SNAPSHOT script org.thingsboard.common.script diff --git a/common/script/script-api/pom.xml b/common/script/script-api/pom.xml index 044fc57553..f7318222fd 100644 --- a/common/script/script-api/pom.xml +++ b/common/script/script-api/pom.xml @@ -10,7 +10,7 @@ 4.0.0 org.thingsboard.common - 4.4.1-SNAPSHOT + 4.4.2-SNAPSHOT script org.thingsboard.common.script diff --git a/common/stats/pom.xml b/common/stats/pom.xml index 2873f94f9c..95d485d3c6 100644 --- a/common/stats/pom.xml +++ b/common/stats/pom.xml @@ -12,7 +12,7 @@ 4.0.0 org.thingsboard - 4.4.1-SNAPSHOT + 4.4.2-SNAPSHOT common org.thingsboard.common diff --git a/common/transport/coap/pom.xml b/common/transport/coap/pom.xml index 9a28d7c95c..7b2057706d 100644 --- a/common/transport/coap/pom.xml +++ b/common/transport/coap/pom.xml @@ -10,7 +10,7 @@ 4.0.0 org.thingsboard.common - 4.4.1-SNAPSHOT + 4.4.2-SNAPSHOT transport org.thingsboard.common.transport diff --git a/common/transport/http/pom.xml b/common/transport/http/pom.xml index e479006913..e12c064ae0 100644 --- a/common/transport/http/pom.xml +++ b/common/transport/http/pom.xml @@ -10,7 +10,7 @@ 4.0.0 org.thingsboard.common - 4.4.1-SNAPSHOT + 4.4.2-SNAPSHOT transport org.thingsboard.common.transport diff --git a/common/transport/lwm2m/pom.xml b/common/transport/lwm2m/pom.xml index ccc051900f..d122e6b529 100644 --- a/common/transport/lwm2m/pom.xml +++ b/common/transport/lwm2m/pom.xml @@ -10,7 +10,7 @@ 4.0.0 org.thingsboard.common - 4.4.1-SNAPSHOT + 4.4.2-SNAPSHOT transport org.thingsboard.common.transport diff --git a/common/transport/mqtt/pom.xml b/common/transport/mqtt/pom.xml index b499a5f591..bd6affb863 100644 --- a/common/transport/mqtt/pom.xml +++ b/common/transport/mqtt/pom.xml @@ -10,7 +10,7 @@ 4.0.0 org.thingsboard.common - 4.4.1-SNAPSHOT + 4.4.2-SNAPSHOT transport org.thingsboard.common.transport diff --git a/common/transport/pom.xml b/common/transport/pom.xml index 103dde135d..de208689cf 100644 --- a/common/transport/pom.xml +++ b/common/transport/pom.xml @@ -10,7 +10,7 @@ 4.0.0 org.thingsboard - 4.4.1-SNAPSHOT + 4.4.2-SNAPSHOT common org.thingsboard.common diff --git a/common/transport/snmp/pom.xml b/common/transport/snmp/pom.xml index d3a02e9848..bfa14cdd91 100644 --- a/common/transport/snmp/pom.xml +++ b/common/transport/snmp/pom.xml @@ -11,7 +11,7 @@ org.thingsboard.common - 4.4.1-SNAPSHOT + 4.4.2-SNAPSHOT transport diff --git a/common/transport/transport-api/pom.xml b/common/transport/transport-api/pom.xml index 939bf62614..1e86888779 100644 --- a/common/transport/transport-api/pom.xml +++ b/common/transport/transport-api/pom.xml @@ -10,7 +10,7 @@ 4.0.0 org.thingsboard.common - 4.4.1-SNAPSHOT + 4.4.2-SNAPSHOT transport org.thingsboard.common.transport diff --git a/common/util/pom.xml b/common/util/pom.xml index 0fe6b896a4..970c553e91 100644 --- a/common/util/pom.xml +++ b/common/util/pom.xml @@ -10,7 +10,7 @@ 4.0.0 org.thingsboard - 4.4.1-SNAPSHOT + 4.4.2-SNAPSHOT common org.thingsboard.common diff --git a/common/version-control/pom.xml b/common/version-control/pom.xml index d59741949a..9f68f11d8e 100644 --- a/common/version-control/pom.xml +++ b/common/version-control/pom.xml @@ -10,7 +10,7 @@ 4.0.0 org.thingsboard - 4.4.1-SNAPSHOT + 4.4.2-SNAPSHOT common org.thingsboard.common diff --git a/dao/pom.xml b/dao/pom.xml index 38027a5a7b..ed9386f4df 100644 --- a/dao/pom.xml +++ b/dao/pom.xml @@ -10,7 +10,7 @@ 4.0.0 org.thingsboard - 4.4.1-SNAPSHOT + 4.4.2-SNAPSHOT thingsboard dao diff --git a/dao/src/main/java/org/thingsboard/server/dao/alarm/AlarmDao.java b/dao/src/main/java/org/thingsboard/server/dao/alarm/AlarmDao.java index d600e84f15..276e5a044c 100644 --- a/dao/src/main/java/org/thingsboard/server/dao/alarm/AlarmDao.java +++ b/dao/src/main/java/org/thingsboard/server/dao/alarm/AlarmDao.java @@ -73,6 +73,8 @@ public interface AlarmDao extends Dao { PageData findAlarmDataByQueryForEntities(TenantId tenantId, MergedUserPermissions mergedUserPermissions, AlarmDataQuery query, Collection orderedEntityIds); + PageData findAlarmDataByQuery(TenantId tenantId, CustomerId customerId, MergedUserPermissions mergedUserPermissions, AlarmDataQuery query); + Set findAlarmSeverities(TenantId tenantId, EntityId entityId, AlarmStatusFilter asf, String assigneeId); /** diff --git a/dao/src/main/java/org/thingsboard/server/dao/alarm/BaseAlarmService.java b/dao/src/main/java/org/thingsboard/server/dao/alarm/BaseAlarmService.java index fba8bcefc0..154e4df5b2 100644 --- a/dao/src/main/java/org/thingsboard/server/dao/alarm/BaseAlarmService.java +++ b/dao/src/main/java/org/thingsboard/server/dao/alarm/BaseAlarmService.java @@ -217,6 +217,13 @@ public class BaseAlarmService extends AbstractCachedEntityService findAlarmDataByQuery(TenantId tenantId, CustomerId customerId, MergedUserPermissions mergedUserPermissions, AlarmDataQuery query) { + validateId(tenantId, id -> INCORRECT_TENANT_ID + id); + validateEntityDataPageLink(query.getPageLink()); + return alarmDao.findAlarmDataByQuery(tenantId, customerId, mergedUserPermissions, query); + } + @Override @Transactional public AlarmApiCallResult delAlarm(TenantId tenantId, EntityId originator, AlarmId alarmId) { diff --git a/dao/src/main/java/org/thingsboard/server/dao/notification/DefaultNotificationSettingsService.java b/dao/src/main/java/org/thingsboard/server/dao/notification/DefaultNotificationSettingsService.java index 9f876d3401..57ed4409bc 100644 --- a/dao/src/main/java/org/thingsboard/server/dao/notification/DefaultNotificationSettingsService.java +++ b/dao/src/main/java/org/thingsboard/server/dao/notification/DefaultNotificationSettingsService.java @@ -158,6 +158,7 @@ public class DefaultNotificationSettingsService implements NotificationSettingsS defaultNotifications.create(tenantId, DefaultNotifications.addonAccessRequest, sysAdmins.getId()); defaultNotifications.create(tenantId, DefaultNotifications.addonAccessError, sysAdmins.getId()); defaultNotifications.create(tenantId, DefaultNotifications.planUpgradeRequest, sysAdmins.getId()); + defaultNotifications.create(tenantId, DefaultNotifications.aiCreditsLimitIncreaseRequest, sysAdmins.getId()); defaultNotifications.create(tenantId, DefaultNotifications.apiFeatureWarningForSysadmin, sysAdmins.getId()); defaultNotifications.create(tenantId, DefaultNotifications.apiFeatureWarningForTenant, affectedTenantAdmins.getId()); defaultNotifications.create(tenantId, DefaultNotifications.apiFeatureDisabledForSysadmin, sysAdmins.getId()); @@ -220,6 +221,9 @@ public class DefaultNotificationSettingsService implements NotificationSettingsS if (!isNotificationConfigured(tenantId, NotificationType.PLAN_UPGRADE_REQUEST)) { defaultNotifications.create(tenantId, DefaultNotifications.planUpgradeRequest, sysAdmins.getId()); } + if (!isNotificationConfigured(tenantId, NotificationType.AI_CREDITS_LIMIT_INCREASE_REQUEST)) { + defaultNotifications.create(tenantId, DefaultNotifications.aiCreditsLimitIncreaseRequest, sysAdmins.getId()); + } } else { NotificationTarget tenantAdmins = notificationTargetService.findNotificationTargetsByTenantIdAndUsersFilterType(tenantId, UsersFilterType.TENANT_ADMINISTRATORS) .stream().findFirst() diff --git a/dao/src/main/java/org/thingsboard/server/dao/notification/DefaultNotifications.java b/dao/src/main/java/org/thingsboard/server/dao/notification/DefaultNotifications.java index 9a200d263a..3ffa3f46a4 100644 --- a/dao/src/main/java/org/thingsboard/server/dao/notification/DefaultNotifications.java +++ b/dao/src/main/java/org/thingsboard/server/dao/notification/DefaultNotifications.java @@ -230,6 +230,41 @@ public class DefaultNotifications { """) .build()) .build(); + public static final DefaultNotification aiCreditsLimitIncreaseRequest = DefaultNotification.builder() + .name("AI credits limit increase request") + .type(NotificationType.AI_CREDITS_LIMIT_INCREASE_REQUEST) + .subject("AI credits limit increase request") + .text("${userEmail} from tenant ${tenantName} has used ${limitDescription} and is requesting more AI credits.") + .icon("auto_awesome") + .button("${increaseLimitActionLabel}").link("${increaseLimitLink}") + .emailTemplate(DefaultEmailTemplate.builder() + .subject("AI credits limit increase request") + .body(""" + + + + + + +
+ + + + + + + + + + + + +
AI credits limit increase request
${userEmail} from tenant ${tenantName} has used ${limitDescription} and is requesting more AI credits.
+ ${increaseLimitActionLabel} +
+
""") + .build()) + .build(); public static final DefaultNotification apiFeatureWarningForSysadmin = DefaultNotification.builder() .name("API feature warning notification for sysadmin") .type(NotificationType.API_USAGE_LIMIT) diff --git a/dao/src/main/java/org/thingsboard/server/dao/sql/alarm/JpaAlarmDao.java b/dao/src/main/java/org/thingsboard/server/dao/sql/alarm/JpaAlarmDao.java index f8c990657a..6d7aa5fb6b 100644 --- a/dao/src/main/java/org/thingsboard/server/dao/sql/alarm/JpaAlarmDao.java +++ b/dao/src/main/java/org/thingsboard/server/dao/sql/alarm/JpaAlarmDao.java @@ -12,6 +12,8 @@ import org.springframework.data.domain.Page; import org.springframework.data.domain.PageRequest; import org.springframework.data.domain.Pageable; import org.springframework.data.domain.Slice; +import org.springframework.data.domain.Sort; +import org.springframework.data.jpa.domain.JpaSort; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.stereotype.Component; import org.springframework.util.CollectionUtils; @@ -145,6 +147,25 @@ public class JpaAlarmDao extends JpaAbstractDao implements A return findByIdAsync(tenantId, key); } + private static final String SEVERITY_PROPERTY = "severity"; + + private static final String SEVERITY_RANK = "(case a.severity" + + Arrays.stream(AlarmSeverity.values()) + .map(severity -> " when " + AlarmSeverity.class.getName() + "." + severity.name() + " then " + severity.ordinal()) + .collect(Collectors.joining()) + + " else " + AlarmSeverity.values().length + " end)"; + + private static Pageable toAlarmPageable(PageLink pageLink) { + Pageable pageable = DaoUtil.toPageable(pageLink); + if (pageable.getSort().getOrderFor(SEVERITY_PROPERTY) == null) { + return pageable; + } + List orders = pageable.getSort().stream() + .map(order -> SEVERITY_PROPERTY.equals(order.getProperty()) ? JpaSort.unsafe(order.getDirection(), SEVERITY_RANK).iterator().next() : order) + .toList(); + return PageRequest.of(pageable.getPageNumber(), pageable.getPageSize(), Sort.by(orders)); + } + @Override public PageData findAlarms(TenantId tenantId, AlarmQuery query) { log.trace("Try to find alarms by entity [{}], status [{}] and pageLink [{}]", query.getAffectedEntityId(), query.getStatus(), query.getPageLink()); @@ -164,7 +185,7 @@ public class JpaAlarmDao extends JpaAbstractDao implements A asf.hasAckFilter() && asf.getAckFilter(), DaoUtil.getId(query.getAssigneeId()), query.getPageLink().getTextSearch(), - DaoUtil.toPageable(query.getPageLink()) + toAlarmPageable(query.getPageLink()) ) ); } else { @@ -179,7 +200,7 @@ public class JpaAlarmDao extends JpaAbstractDao implements A asf.hasAckFilter() && asf.getAckFilter(), DaoUtil.getId(query.getAssigneeId()), query.getPageLink().getTextSearch(), - DaoUtil.toPageable(query.getPageLink()) + toAlarmPageable(query.getPageLink()) ) ); } @@ -201,7 +222,7 @@ public class JpaAlarmDao extends JpaAbstractDao implements A asf.hasAckFilter() && asf.getAckFilter(), DaoUtil.getId(query.getAssigneeId()), query.getPageLink().getTextSearch(), - DaoUtil.toPageable(query.getPageLink()) + toAlarmPageable(query.getPageLink()) ) ); } @@ -230,7 +251,7 @@ public class JpaAlarmDao extends JpaAbstractDao implements A asf.hasAckFilter() && asf.getAckFilter(), DaoUtil.getId(query.getAssigneeId()), query.getPageLink().getTextSearch(), - DaoUtil.toPageable(query.getPageLink()) + toAlarmPageable(query.getPageLink()) ) ); } else { @@ -247,7 +268,7 @@ public class JpaAlarmDao extends JpaAbstractDao implements A asf.hasAckFilter() && asf.getAckFilter(), DaoUtil.getId(query.getAssigneeId()), query.getPageLink().getTextSearch(), - DaoUtil.toPageable(query.getPageLink()) + toAlarmPageable(query.getPageLink()) ) ); } @@ -273,7 +294,7 @@ public class JpaAlarmDao extends JpaAbstractDao implements A asf.hasAckFilter() && asf.getAckFilter(), DaoUtil.getId(query.getAssigneeId()), query.getPageLink().getTextSearch(), - DaoUtil.toPageable(query.getPageLink()) + toAlarmPageable(query.getPageLink()) ) ); } @@ -309,6 +330,11 @@ public class JpaAlarmDao extends JpaAbstractDao implements A return alarmQueryRepository.findAlarmDataByQueryForEntities(tenantId, mergedUserPermissions, query, orderedEntityIds); } + @Override + public PageData findAlarmDataByQuery(TenantId tenantId, CustomerId customerId, MergedUserPermissions mergedUserPermissions, AlarmDataQuery query) { + return alarmQueryRepository.findAlarmDataByQuery(tenantId, customerId, mergedUserPermissions, query); + } + @Override public Set findAlarmSeverities(TenantId tenantId, EntityId entityId, AlarmStatusFilter asf, String assigneeId) { return alarmRepository.findAlarmSeverities(tenantId.getId(), entityId.getId(), entityId.getEntityType().name(), diff --git a/dao/src/main/java/org/thingsboard/server/dao/sql/query/AlarmDataAdapter.java b/dao/src/main/java/org/thingsboard/server/dao/sql/query/AlarmDataAdapter.java index 51a421ca3e..fabefaa6b2 100644 --- a/dao/src/main/java/org/thingsboard/server/dao/sql/query/AlarmDataAdapter.java +++ b/dao/src/main/java/org/thingsboard/server/dao/sql/query/AlarmDataAdapter.java @@ -36,7 +36,8 @@ public class AlarmDataAdapter { public static PageData createAlarmData(EntityDataPageLink pageLink, List> rows, int totalElements, Collection orderedEntityIds) { - Map entityIdMap = orderedEntityIds.stream().collect(Collectors.toMap(EntityId::getId, Function.identity())); + Map entityIdMap = orderedEntityIds == null ? Collections.emptyMap() + : orderedEntityIds.stream().collect(Collectors.toMap(EntityId::getId, Function.identity())); int totalPages = pageLink.getPageSize() > 0 ? (int) Math.ceil((float) totalElements / pageLink.getPageSize()) : 1; int startIndex = pageLink.getPageSize() * pageLink.getPage(); boolean hasNext = pageLink.getPageSize() > 0 && totalElements > startIndex + rows.size(); @@ -101,7 +102,7 @@ public class AlarmDataAdapter { alarm.setPropagateRelationTypes(Collections.emptyList()); } UUID entityUuid = (UUID) row.get(ModelConstants.ENTITY_ID_COLUMN); - EntityId entityId = entityIdMap.get(entityUuid); + EntityId entityId = entityIdMap.isEmpty() ? alarm.getOriginator() : entityIdMap.get(entityUuid); Object originatorNameObj = row.get(ModelConstants.ALARM_ORIGINATOR_NAME_PROPERTY); String originatorName = originatorNameObj != null ? originatorNameObj.toString() : null; Object originatorLabelObj = row.get(ModelConstants.ALARM_ORIGINATOR_LABEL_PROPERTY); diff --git a/dao/src/main/java/org/thingsboard/server/dao/sql/query/AlarmQueryRepository.java b/dao/src/main/java/org/thingsboard/server/dao/sql/query/AlarmQueryRepository.java index de0a7e4ab9..74bbb0246e 100644 --- a/dao/src/main/java/org/thingsboard/server/dao/sql/query/AlarmQueryRepository.java +++ b/dao/src/main/java/org/thingsboard/server/dao/sql/query/AlarmQueryRepository.java @@ -19,6 +19,8 @@ public interface AlarmQueryRepository { PageData findAlarmDataByQueryForEntities(TenantId tenantId, MergedUserPermissions mergedUserPermissions, AlarmDataQuery query, Collection orderedEntityIds); + PageData findAlarmDataByQuery(TenantId tenantId, CustomerId customerId, MergedUserPermissions mergedUserPermissions, AlarmDataQuery query); + long countAlarmsByQuery(TenantId tenantId, CustomerId customerId, MergedUserPermissions mergedUserPermissions, AlarmCountQuery query, Collection orderedEntityIds); } diff --git a/dao/src/main/java/org/thingsboard/server/dao/sql/query/DefaultAlarmQueryRepository.java b/dao/src/main/java/org/thingsboard/server/dao/sql/query/DefaultAlarmQueryRepository.java index c6487d3532..31ed47cd88 100644 --- a/dao/src/main/java/org/thingsboard/server/dao/sql/query/DefaultAlarmQueryRepository.java +++ b/dao/src/main/java/org/thingsboard/server/dao/sql/query/DefaultAlarmQueryRepository.java @@ -31,12 +31,14 @@ import org.thingsboard.server.dao.model.ModelConstants; import org.thingsboard.server.dao.sql.citus.CitusSettings; import java.util.ArrayList; +import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Objects; +import java.util.Set; import java.util.stream.Collectors; @Repository @@ -45,6 +47,18 @@ public class DefaultAlarmQueryRepository implements AlarmQueryRepository { private static final Map alarmFieldColumnMap = new HashMap<>(); + private static final String SEVERITY_RANK = "case a." + ModelConstants.ALARM_SEVERITY_PROPERTY + + Arrays.stream(AlarmSeverity.values()) + .map(severity -> " when '" + severity.name() + "' then " + severity.ordinal()) + .collect(Collectors.joining()) + + " else " + AlarmSeverity.values().length + " end"; + + private static final Set ALARM_TABLE_SORT_COLUMNS = Set.of(ModelConstants.CREATED_TIME_PROPERTY, ModelConstants.ALARM_ACK_TS_PROPERTY, + ModelConstants.ALARM_CLEAR_TS_PROPERTY, ModelConstants.ALARM_ASSIGN_TS_PROPERTY, ModelConstants.ALARM_END_TS_PROPERTY, + ModelConstants.ALARM_START_TS_PROPERTY, ModelConstants.ALARM_ACKNOWLEDGED_PROPERTY, ModelConstants.ALARM_CLEARED_PROPERTY, + ModelConstants.ALARM_TYPE_PROPERTY, ModelConstants.ALARM_SEVERITY_PROPERTY, ModelConstants.ALARM_ORIGINATOR_ID_PROPERTY, + ModelConstants.ALARM_ORIGINATOR_TYPE_PROPERTY, ModelConstants.ALARM_ASSIGNEE_ID_PROPERTY); + private static final String ASSIGNEE_EMAIL_KEY = "assigneeEmail"; private static final String ASSIGNEE_LAST_NAME_KEY = "assigneeLastName"; private static final String ASSIGNEE_FIRST_NAME_KEY = "assigneeFirstName"; @@ -133,20 +147,40 @@ public class DefaultAlarmQueryRepository implements AlarmQueryRepository { @Override public PageData findAlarmDataByQueryForEntities(TenantId tenantId, MergedUserPermissions mergedUserPermissions, AlarmDataQuery query, Collection orderedEntityIds) { + return findAlarmData(tenantId, null, mergedUserPermissions, query, orderedEntityIds); + } + + @Override + public PageData findAlarmDataByQuery(TenantId tenantId, CustomerId customerId, MergedUserPermissions mergedUserPermissions, AlarmDataQuery query) { + return findAlarmData(tenantId, customerId, mergedUserPermissions, query, null); + } + + private PageData findAlarmData(TenantId tenantId, CustomerId customerId, MergedUserPermissions mergedUserPermissions, + AlarmDataQuery query, Collection orderedEntityIds) { if (!mergedUserPermissions.hasGenericPermission(Resource.ALARM, Operation.READ)) { return PageData.emptyPageData(); } + boolean ownerScoped = orderedEntityIds == null; return transactionTemplate.execute(trStatus -> { AlarmDataPageLink pageLink = query.getPageLink(); + boolean searchPropagatedAlarms = !ownerScoped && pageLink.isSearchPropagatedAlarms(); SqlQueryContext ctx = new SqlQueryContext(new QueryContext(tenantId, null, EntityType.ALARM, mergedUserPermissions, null), citusSettings.isEnabled()); - ctx.addUuidListParameter("entity_ids", orderedEntityIds.stream().map(EntityId::getId).collect(Collectors.toList())); StringBuilder selectPart = new StringBuilder(FIELDS_SELECTION); StringBuilder fromPart = new StringBuilder(" from alarm_info a "); StringBuilder wherePart = new StringBuilder(" where "); StringBuilder sortPart = new StringBuilder(" order by "); StringBuilder joinPart = new StringBuilder(); boolean addAnd = false; - if (pageLink.isSearchPropagatedAlarms()) { + if (ownerScoped) { + selectPart.append(" a.originator_id as entity_id "); + ctx.addUuidParameter("owner_tenant_id", tenantId.getId()); + wherePart.append(" a.tenant_id = :owner_tenant_id"); + if (customerId != null && !customerId.isNullUid()) { + ctx.addUuidParameter("owner_customer_id", customerId.getId()); + wherePart.append(" and a.customer_id = :owner_customer_id"); + } + addAnd = true; + } else if (searchPropagatedAlarms) { selectPart.append(" ea.entity_id as entity_id "); fromPart.append(JOIN_ENTITY_ALARMS); wherePart.append(buildPermissionsQuery(tenantId, ctx, mergedUserPermissions)); @@ -154,7 +188,13 @@ public class DefaultAlarmQueryRepository implements AlarmQueryRepository { } else { selectPart.append(" a.originator_id as entity_id "); } + if (!ownerScoped) { + ctx.addUuidListParameter("entity_ids", orderedEntityIds.stream().map(EntityId::getId).collect(Collectors.toList())); + } EntityDataSortOrder sortOrder = pageLink.getSortOrder(); + if (ownerScoped && (sortOrder == null || !EntityKeyType.ALARM_FIELD.equals(sortOrder.getKey().getType()))) { + sortOrder = new EntityDataSortOrder(new EntityKey(EntityKeyType.ALARM_FIELD, "createdTime"), EntityDataSortOrder.Direction.DESC); + } if (sortOrder != null && EntityKeyType.ALARM_FIELD.equals(sortOrder.getKey().getType()) && ASSIGNEE_KEY.equalsIgnoreCase(sortOrder.getKey().getKey())) { sortOrder = new EntityDataSortOrder(new EntityKey(EntityKeyType.ALARM_FIELD, ASSIGNEE_EMAIL_KEY), sortOrder.getDirection()); @@ -178,9 +218,12 @@ public class DefaultAlarmQueryRepository implements AlarmQueryRepository { if ("status".equalsIgnoreCase(sortOrderKey)) { selectPart.append(", a.status as status "); } - sortPart.append(alarmFieldColumnMap.getOrDefault(sortOrderKey, sortOrderKey)) + String sortColumn = alarmFieldColumnMap.getOrDefault(sortOrderKey, sortOrderKey); + sortPart.append(ModelConstants.ALARM_SEVERITY_PROPERTY.equals(sortColumn) ? SEVERITY_RANK : sortColumn) .append(" ").append(sortOrder.getDirection().name()); - if (pageLink.isSearchPropagatedAlarms()) { + if (ownerScoped) { + sortPart.append(", a.created_time desc, a.id desc"); + } else if (searchPropagatedAlarms) { wherePart.append(" and ea.entity_id in (:entity_ids)"); } else { addAndIfNeeded(wherePart, addAnd); @@ -201,7 +244,7 @@ public class DefaultAlarmQueryRepository implements AlarmQueryRepository { entityIdIdx++; } joinPart.append(" as e(id, priority)) e "); - if (pageLink.isSearchPropagatedAlarms()) { + if (searchPropagatedAlarms) { if (textSearchQuery.isEmpty()) { joinPart.append("on ea.entity_id = e.id"); } else { @@ -233,7 +276,7 @@ public class DefaultAlarmQueryRepository implements AlarmQueryRepository { addAnd = true; ctx.addLongParameter("startTime", startTs); wherePart.append("a.created_time >= :startTime"); - if (pageLink.isSearchPropagatedAlarms()) { + if (searchPropagatedAlarms) { wherePart.append(" and ea.created_time >= :startTime"); } } @@ -243,7 +286,7 @@ public class DefaultAlarmQueryRepository implements AlarmQueryRepository { addAnd = true; ctx.addLongParameter("endTime", endTs); wherePart.append("a.created_time <= :endTime"); - if (pageLink.isSearchPropagatedAlarms()) { + if (searchPropagatedAlarms) { wherePart.append(" and ea.created_time <= :endTime"); } } @@ -253,7 +296,7 @@ public class DefaultAlarmQueryRepository implements AlarmQueryRepository { addAnd = true; ctx.addStringListParameter("alarmTypes", pageLink.getTypeList()); wherePart.append("a.type in (:alarmTypes)"); - if (pageLink.isSearchPropagatedAlarms()) { + if (searchPropagatedAlarms) { wherePart.append(" and ea.alarm_type in (:alarmTypes)"); } } @@ -294,7 +337,9 @@ public class DefaultAlarmQueryRepository implements AlarmQueryRepository { } else { mainQuery = String.format("select * from (%s%s) a %s WHERE %s", mainQuery, wherePart, joinPart, textSearchQuery); } - String countQuery = String.format("select count(*) from (%s) result", mainQuery); + String countQuery = ownerScoped && textSearchQuery.isEmpty() + ? String.format("select count(*) from alarm a %s", wherePart) + : String.format("select count(*) from (%s) result", mainQuery); long queryTs = System.currentTimeMillis(); int totalElements; try { @@ -309,8 +354,11 @@ public class DefaultAlarmQueryRepository implements AlarmQueryRepository { String dataQuery = mainQuery + sortPart; int startIndex = pageLink.getPageSize() * pageLink.getPage(); - if (pageLink.getPageSize() > 0) { - dataQuery = String.format("%s limit %s offset %s", dataQuery, pageLink.getPageSize(), startIndex); + String limitPart = pageLink.getPageSize() > 0 ? String.format(" limit %s offset %s", pageLink.getPageSize(), startIndex) : ""; + if (ownerScoped && textSearchQuery.isEmpty() && ALARM_TABLE_SORT_COLUMNS.contains(alarmFieldColumnMap.getOrDefault(sortOrder.getKey().getKey(), sortOrder.getKey().getKey()))) { + dataQuery = String.format("%s%s where a.id in (select a.id from alarm a %s%s%s)%s", selectPart, fromPart, wherePart, sortPart, limitPart, sortPart); + } else { + dataQuery = dataQuery + limitPart; } queryTs = System.currentTimeMillis(); List> rows; diff --git a/dao/src/test/java/org/thingsboard/server/dao/service/AlarmServiceTest.java b/dao/src/test/java/org/thingsboard/server/dao/service/AlarmServiceTest.java index 069f7d07b2..38397e2069 100644 --- a/dao/src/test/java/org/thingsboard/server/dao/service/AlarmServiceTest.java +++ b/dao/src/test/java/org/thingsboard/server/dao/service/AlarmServiceTest.java @@ -64,14 +64,17 @@ import org.thingsboard.server.dao.user.UserService; import org.thingsboard.server.exception.DataValidationException; import java.util.ArrayList; +import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.ExecutionException; +import java.util.concurrent.TimeUnit; import static org.assertj.core.api.Assertions.assertThat; +import static org.awaitility.Awaitility.await; @DaoSqlTest public class AlarmServiceTest extends AbstractServiceTest { @@ -729,6 +732,131 @@ public class AlarmServiceTest extends AbstractServiceTest { Assert.assertEquals(customerAlarm, new AlarmInfo(customerAlarms.getData().get(0))); } + @Test + public void testFindAlarmDataByQueryWithoutEntityFilter() { + Customer customer = new Customer(); + customer.setTitle("TestCustomer"); + customer.setTenantId(tenantId); + customer = customerService.saveCustomer(customer); + + Device tenantDevice = new Device(); + tenantDevice.setName("TestTenantDevice"); + tenantDevice.setType("default"); + tenantDevice.setTenantId(tenantId); + tenantDevice = deviceService.saveDevice(tenantDevice); + + Device customerDevice = new Device(); + customerDevice.setName("TestCustomerDevice"); + customerDevice.setType("default"); + customerDevice.setTenantId(tenantId); + customerDevice.setCustomerId(customer.getId()); + customerDevice = deviceService.saveDevice(customerDevice); + + long ts = System.currentTimeMillis(); + AlarmInfo tenantAlarm = alarmService.createAlarm(AlarmCreateOrUpdateActiveRequest.builder() + .tenantId(tenantId) + .originator(tenantDevice.getId()) + .type(TEST_ALARM) + .severity(AlarmSeverity.CRITICAL) + .startTs(ts).build()).getAlarm(); + AlarmInfo clearedAlarm = alarmService.createAlarm(AlarmCreateOrUpdateActiveRequest.builder() + .tenantId(tenantId) + .originator(tenantDevice.getId()) + .type("Cleared Alarm") + .severity(AlarmSeverity.MAJOR) + .startTs(ts).build()).getAlarm(); + alarmService.clearAlarm(tenantId, clearedAlarm.getOriginator(), clearedAlarm.getId(), System.currentTimeMillis(), null, true); + await().atMost(1, TimeUnit.SECONDS).until(() -> System.currentTimeMillis() > tenantAlarm.getCreatedTime() + 1); + AlarmInfo customerAlarm = alarmService.createAlarm(AlarmCreateOrUpdateActiveRequest.builder() + .tenantId(tenantId) + .customerId(customer.getId()) + .originator(customerDevice.getId()) + .type(TEST_ALARM) + .severity(AlarmSeverity.MAJOR) + .startTs(ts).build()).getAlarm(); + + AlarmDataPageLink pageLink = new AlarmDataPageLink(); + pageLink.setPage(0); + pageLink.setPageSize(10); + pageLink.setStatusList(List.of(AlarmSearchStatus.ACTIVE)); + AlarmDataQuery query = new AlarmDataQuery(null, pageLink, null, null, null, Collections.emptyList()); + + PageData tenantAlarms = alarmService.findAlarmDataByQuery(tenantId, null, mergedUserPermissions, query); + Assert.assertEquals(2, tenantAlarms.getTotalElements()); + Assert.assertEquals(List.of(customerAlarm.getId(), tenantAlarm.getId()), tenantAlarms.getData().stream().map(AlarmData::getId).toList()); + Assert.assertEquals(List.of(customerDevice.getId(), tenantDevice.getId()), tenantAlarms.getData().stream().map(AlarmData::getEntityId).toList()); + + PageData customerAlarms = alarmService.findAlarmDataByQuery(tenantId, customer.getId(), mergedUserPermissions, query); + Assert.assertEquals(List.of(customerAlarm.getId()), customerAlarms.getData().stream().map(AlarmData::getId).toList()); + + pageLink.setSeverityList(List.of(AlarmSeverity.CRITICAL)); + PageData criticalAlarms = alarmService.findAlarmDataByQuery(tenantId, null, mergedUserPermissions, query); + Assert.assertEquals(List.of(tenantAlarm.getId()), criticalAlarms.getData().stream().map(AlarmData::getId).toList()); + + pageLink.setSeverityList(null); + pageLink.setPageSize(1); + PageData firstPage = alarmService.findAlarmDataByQuery(tenantId, null, mergedUserPermissions, query); + Assert.assertEquals(1, firstPage.getData().size()); + Assert.assertEquals(2, firstPage.getTotalElements()); + Assert.assertTrue(firstPage.hasNext()); + } + + @Test + public void testSortAlarmDataBySeverityPriority() { + Device device = new Device(); + device.setName("TestSeverityDevice"); + device.setType("default"); + device.setTenantId(tenantId); + device = deviceService.saveDevice(device); + + long ts = System.currentTimeMillis(); + List ids = new ArrayList<>(); + for (AlarmSeverity severity : List.of(AlarmSeverity.INDETERMINATE, AlarmSeverity.CRITICAL, AlarmSeverity.WARNING, AlarmSeverity.MAJOR, AlarmSeverity.MINOR)) { + ids.add(alarmService.createAlarm(AlarmCreateOrUpdateActiveRequest.builder() + .tenantId(tenantId) + .originator(device.getId()) + .type("Severity " + severity) + .severity(severity) + .startTs(ts).build()).getAlarm().getId()); + } + List byPriority = List.of(ids.get(1), ids.get(3), ids.get(4), ids.get(2), ids.get(0)); + + AlarmDataPageLink pageLink = new AlarmDataPageLink(); + pageLink.setPage(0); + pageLink.setPageSize(10); + pageLink.setSortOrder(new EntityDataSortOrder(new EntityKey(EntityKeyType.ALARM_FIELD, "severity"), EntityDataSortOrder.Direction.ASC)); + AlarmDataQuery ownerQuery = new AlarmDataQuery(null, pageLink, null, null, null, Collections.emptyList()); + + Assert.assertEquals(byPriority, alarmService.findAlarmDataByQuery(tenantId, null, mergedUserPermissions, ownerQuery) + .getData().stream().map(AlarmData::getId).toList()); + Assert.assertEquals(byPriority, alarmService.findAlarmDataByQueryForEntities(tenantId, mergedUserPermissions, toQuery(pageLink), List.of(device.getId())) + .getData().stream().map(AlarmData::getId).toList()); + + pageLink.setSortOrder(new EntityDataSortOrder(new EntityKey(EntityKeyType.ALARM_FIELD, "severity"), EntityDataSortOrder.Direction.DESC)); + Assert.assertEquals(byPriority.reversed(), alarmService.findAlarmDataByQuery(tenantId, null, mergedUserPermissions, ownerQuery) + .getData().stream().map(AlarmData::getId).toList()); + + pageLink.setSortOrder(new EntityDataSortOrder(new EntityKey(EntityKeyType.ALARM_FIELD, "severity"), EntityDataSortOrder.Direction.ASC)); + pageLink.setTextSearch("Severity"); + Assert.assertEquals(byPriority, alarmService.findAlarmDataByQuery(tenantId, null, mergedUserPermissions, ownerQuery) + .getData().stream().map(AlarmData::getId).toList()); + Assert.assertEquals(byPriority, alarmService.findAlarmDataByQueryForEntities(tenantId, mergedUserPermissions, toQuery(pageLink), List.of(device.getId())) + .getData().stream().map(AlarmData::getId).toList()); + + List types = Arrays.stream(AlarmSeverity.values()).map(severity -> "Severity " + severity).toList(); + for (SortOrder.Direction direction : SortOrder.Direction.values()) { + List expected = direction == SortOrder.Direction.ASC ? byPriority : byPriority.reversed(); + TimePageLink timePageLink = new TimePageLink(10, 0, null, new SortOrder("severity", direction), null, null); + Assert.assertEquals(expected, alarmService.findAlarmsV2(tenantId, AlarmQueryV2.builder() + .affectedEntityId(device.getId()).pageLink(timePageLink).build()).getData().stream().map(AlarmInfo::getId).toList()); + Assert.assertEquals(expected, alarmService.findAlarmsV2(tenantId, AlarmQueryV2.builder() + .typeList(types).pageLink(timePageLink).build()).getData().stream().map(AlarmInfo::getId).toList()); + Assert.assertEquals(expected, alarmService.findAlarms(tenantId, AlarmQuery.builder() + .affectedEntityId(device.getId()).pageLink(new TimePageLink(10, 0, "Severity", new SortOrder("severity", direction), null, null)).build()) + .getData().stream().map(AlarmInfo::getId).toList()); + } + } + private AlarmDataQuery toQuery(AlarmDataPageLink pageLink) { return toQuery(pageLink, Collections.emptyList()); } diff --git a/edqs/pom.xml b/edqs/pom.xml index 7f777ffdc0..5cb4791033 100644 --- a/edqs/pom.xml +++ b/edqs/pom.xml @@ -10,7 +10,7 @@ 4.0.0 org.thingsboard - 4.4.1-SNAPSHOT + 4.4.2-SNAPSHOT thingsboard edqs diff --git a/integration/apache-pulsar/pom.xml b/integration/apache-pulsar/pom.xml index c72b5bbb55..68c29c0ad4 100644 --- a/integration/apache-pulsar/pom.xml +++ b/integration/apache-pulsar/pom.xml @@ -9,7 +9,7 @@ 4.0.0 org.thingsboard - 4.4.1-SNAPSHOT + 4.4.2-SNAPSHOT integration org.thingsboard.integration diff --git a/integration/aws/pom.xml b/integration/aws/pom.xml index a45b4b95fe..907bb0a5a3 100644 --- a/integration/aws/pom.xml +++ b/integration/aws/pom.xml @@ -9,7 +9,7 @@ 4.0.0 org.thingsboard - 4.4.1-SNAPSHOT + 4.4.2-SNAPSHOT integration org.thingsboard.integration diff --git a/integration/azure/pom.xml b/integration/azure/pom.xml index 26b09e3e8e..8f50f0c2f4 100644 --- a/integration/azure/pom.xml +++ b/integration/azure/pom.xml @@ -9,7 +9,7 @@ 4.0.0 org.thingsboard - 4.4.1-SNAPSHOT + 4.4.2-SNAPSHOT integration org.thingsboard.integration diff --git a/integration/coap/pom.xml b/integration/coap/pom.xml index c85e6d3c51..7b3a1c14a8 100644 --- a/integration/coap/pom.xml +++ b/integration/coap/pom.xml @@ -9,7 +9,7 @@ 4.0.0 org.thingsboard - 4.4.1-SNAPSHOT + 4.4.2-SNAPSHOT integration org.thingsboard.integration diff --git a/integration/executor/pom.xml b/integration/executor/pom.xml index 9afdaecb85..8c846481dc 100644 --- a/integration/executor/pom.xml +++ b/integration/executor/pom.xml @@ -9,7 +9,7 @@ 4.0.0 org.thingsboard - 4.4.1-SNAPSHOT + 4.4.2-SNAPSHOT integration org.thingsboard.integration diff --git a/integration/executor/src/main/resources/tb-integration-executor.yml b/integration/executor/src/main/resources/tb-integration-executor.yml index 171efc630e..fad781696b 100644 --- a/integration/executor/src/main/resources/tb-integration-executor.yml +++ b/integration/executor/src/main/resources/tb-integration-executor.yml @@ -334,7 +334,7 @@ queue: pause-between-retries: "${TB_QUEUE_RE_SQ_PROCESSING_STRATEGY_RETRY_PAUSE:5}" # Time in seconds to wait in consumer thread before retries; max-pause-between-retries: "${TB_QUEUE_RE_SQ_PROCESSING_STRATEGY_MAX_RETRY_PAUSE:5}" # Max allowed time in seconds for pause between retries. integration: - # Name of hash function used for consistent hash ring in Cluster Mode. See architecture docs for more details. Valid values - murmur3_32, murmur3_128 or sha256 + # Number of partitions in each integration queue; there is one queue per integration type. Integrations that run on only one executor at a time (MQTT, OPC-UA, Kafka and similar) are distributed across executors by partition, so executors above this number stay idle for those types. When you add executors, set it to at least the number of executors that run the same integration types, and use the same value on the ThingsBoard nodes. partitions: "${TB_QUEUE_INTEGRATION_PARTITIONS:3}" # For high-priority notifications that require minimum latency and processing time notifications_topic: "${TB_QUEUE_INTEGRATION_NOTIFICATIONS_TOPIC:tb_integration_executor.notifications}" diff --git a/integration/http/pom.xml b/integration/http/pom.xml index 2dede382c0..4879370975 100644 --- a/integration/http/pom.xml +++ b/integration/http/pom.xml @@ -9,7 +9,7 @@ 4.0.0 org.thingsboard - 4.4.1-SNAPSHOT + 4.4.2-SNAPSHOT integration org.thingsboard.integration diff --git a/integration/kafka/pom.xml b/integration/kafka/pom.xml index f245c9395f..b746be4460 100644 --- a/integration/kafka/pom.xml +++ b/integration/kafka/pom.xml @@ -9,7 +9,7 @@ 4.0.0 org.thingsboard - 4.4.1-SNAPSHOT + 4.4.2-SNAPSHOT integration org.thingsboard.integration diff --git a/integration/mqtt/pom.xml b/integration/mqtt/pom.xml index 8e9ac8fadf..e4db54d60e 100644 --- a/integration/mqtt/pom.xml +++ b/integration/mqtt/pom.xml @@ -9,7 +9,7 @@ 4.0.0 org.thingsboard - 4.4.1-SNAPSHOT + 4.4.2-SNAPSHOT integration org.thingsboard.integration diff --git a/integration/opc-ua/pom.xml b/integration/opc-ua/pom.xml index cb71e15a8d..6767a9e531 100644 --- a/integration/opc-ua/pom.xml +++ b/integration/opc-ua/pom.xml @@ -9,7 +9,7 @@ 4.0.0 org.thingsboard - 4.4.1-SNAPSHOT + 4.4.2-SNAPSHOT integration org.thingsboard.integration diff --git a/integration/pom.xml b/integration/pom.xml index e4df184899..d640754f6a 100644 --- a/integration/pom.xml +++ b/integration/pom.xml @@ -9,7 +9,7 @@ 4.0.0 org.thingsboard - 4.4.1-SNAPSHOT + 4.4.2-SNAPSHOT thingsboard integration diff --git a/integration/pubsub/pom.xml b/integration/pubsub/pom.xml index 754981bbf8..42409d0aef 100644 --- a/integration/pubsub/pom.xml +++ b/integration/pubsub/pom.xml @@ -9,7 +9,7 @@ 4.0.0 org.thingsboard - 4.4.1-SNAPSHOT + 4.4.2-SNAPSHOT integration org.thingsboard.integration diff --git a/integration/rabbitmq/pom.xml b/integration/rabbitmq/pom.xml index 62c45e51de..d640a35eca 100644 --- a/integration/rabbitmq/pom.xml +++ b/integration/rabbitmq/pom.xml @@ -9,7 +9,7 @@ 4.0.0 org.thingsboard - 4.4.1-SNAPSHOT + 4.4.2-SNAPSHOT integration org.thingsboard.integration diff --git a/integration/tcp-udp/pom.xml b/integration/tcp-udp/pom.xml index 78e65bd6ee..57991fea99 100644 --- a/integration/tcp-udp/pom.xml +++ b/integration/tcp-udp/pom.xml @@ -9,7 +9,7 @@ 4.0.0 org.thingsboard - 4.4.1-SNAPSHOT + 4.4.2-SNAPSHOT integration org.thingsboard.integration diff --git a/integration/tuya/pom.xml b/integration/tuya/pom.xml index 4d6b78b93e..3025160688 100644 --- a/integration/tuya/pom.xml +++ b/integration/tuya/pom.xml @@ -9,7 +9,7 @@ 4.0.0 org.thingsboard - 4.4.1-SNAPSHOT + 4.4.2-SNAPSHOT integration org.thingsboard.integration diff --git a/migrator/pom.xml b/migrator/pom.xml index 41717c4671..469335098b 100644 --- a/migrator/pom.xml +++ b/migrator/pom.xml @@ -12,7 +12,7 @@ thingsboard org.thingsboard - 4.4.1-SNAPSHOT + 4.4.2-SNAPSHOT migrator diff --git a/monitoring/pom.xml b/monitoring/pom.xml index ec2c0bd793..6c264b22b6 100644 --- a/monitoring/pom.xml +++ b/monitoring/pom.xml @@ -11,7 +11,7 @@ 4.0.0 org.thingsboard - 4.4.1-SNAPSHOT + 4.4.2-SNAPSHOT thingsboard diff --git a/msa/black-box-tests/pom.xml b/msa/black-box-tests/pom.xml index 83c14db4e6..d5489e1214 100644 --- a/msa/black-box-tests/pom.xml +++ b/msa/black-box-tests/pom.xml @@ -11,7 +11,7 @@ org.thingsboard - 4.4.1-SNAPSHOT + 4.4.2-SNAPSHOT msa org.thingsboard.msa diff --git a/msa/edqs/pom.xml b/msa/edqs/pom.xml index e1a0365f4f..25f611e29c 100644 --- a/msa/edqs/pom.xml +++ b/msa/edqs/pom.xml @@ -10,7 +10,7 @@ 4.0.0 org.thingsboard - 4.4.1-SNAPSHOT + 4.4.2-SNAPSHOT msa org.thingsboard.msa diff --git a/msa/integration/apache-pulsar/pom.xml b/msa/integration/apache-pulsar/pom.xml index 54ece3fdd1..b307f62da3 100644 --- a/msa/integration/apache-pulsar/pom.xml +++ b/msa/integration/apache-pulsar/pom.xml @@ -10,7 +10,7 @@ org.thingsboard.msa - 4.4.1-SNAPSHOT + 4.4.2-SNAPSHOT integration diff --git a/msa/integration/aws/pom.xml b/msa/integration/aws/pom.xml index d82fdce9bd..b78e4cd1e5 100644 --- a/msa/integration/aws/pom.xml +++ b/msa/integration/aws/pom.xml @@ -10,7 +10,7 @@ org.thingsboard.msa - 4.4.1-SNAPSHOT + 4.4.2-SNAPSHOT integration diff --git a/msa/integration/azure/pom.xml b/msa/integration/azure/pom.xml index 937a526f01..417711a02a 100644 --- a/msa/integration/azure/pom.xml +++ b/msa/integration/azure/pom.xml @@ -10,7 +10,7 @@ org.thingsboard.msa - 4.4.1-SNAPSHOT + 4.4.2-SNAPSHOT integration diff --git a/msa/integration/coap/pom.xml b/msa/integration/coap/pom.xml index 4d62edb089..f655762c9a 100644 --- a/msa/integration/coap/pom.xml +++ b/msa/integration/coap/pom.xml @@ -10,7 +10,7 @@ org.thingsboard.msa - 4.4.1-SNAPSHOT + 4.4.2-SNAPSHOT integration diff --git a/msa/integration/executor/pom.xml b/msa/integration/executor/pom.xml index 63af6ba57a..875a29157c 100644 --- a/msa/integration/executor/pom.xml +++ b/msa/integration/executor/pom.xml @@ -10,7 +10,7 @@ org.thingsboard.msa - 4.4.1-SNAPSHOT + 4.4.2-SNAPSHOT integration diff --git a/msa/integration/http/pom.xml b/msa/integration/http/pom.xml index 6b2c2a9116..4ac57bf9f2 100644 --- a/msa/integration/http/pom.xml +++ b/msa/integration/http/pom.xml @@ -10,7 +10,7 @@ org.thingsboard.msa - 4.4.1-SNAPSHOT + 4.4.2-SNAPSHOT integration diff --git a/msa/integration/kafka/pom.xml b/msa/integration/kafka/pom.xml index 5e706a9f8c..e994e7bdc9 100644 --- a/msa/integration/kafka/pom.xml +++ b/msa/integration/kafka/pom.xml @@ -10,7 +10,7 @@ org.thingsboard.msa - 4.4.1-SNAPSHOT + 4.4.2-SNAPSHOT integration diff --git a/msa/integration/mqtt/pom.xml b/msa/integration/mqtt/pom.xml index 47e1781577..4004336f8c 100644 --- a/msa/integration/mqtt/pom.xml +++ b/msa/integration/mqtt/pom.xml @@ -10,7 +10,7 @@ org.thingsboard.msa - 4.4.1-SNAPSHOT + 4.4.2-SNAPSHOT integration diff --git a/msa/integration/opc-ua/pom.xml b/msa/integration/opc-ua/pom.xml index 39503ca41e..8caf5e9c20 100644 --- a/msa/integration/opc-ua/pom.xml +++ b/msa/integration/opc-ua/pom.xml @@ -10,7 +10,7 @@ org.thingsboard.msa - 4.4.1-SNAPSHOT + 4.4.2-SNAPSHOT integration diff --git a/msa/integration/pom.xml b/msa/integration/pom.xml index 8dc6d15518..cc9e6f925e 100644 --- a/msa/integration/pom.xml +++ b/msa/integration/pom.xml @@ -9,7 +9,7 @@ 4.0.0 org.thingsboard - 4.4.1-SNAPSHOT + 4.4.2-SNAPSHOT msa @@ -117,7 +117,7 @@ - 4.4.1-latest + 4.4.2-latest false ${docker.push-integration-arm-amd-image.phase} diff --git a/msa/integration/pubsub/pom.xml b/msa/integration/pubsub/pom.xml index 3dfc7766a4..7d54cc91a6 100644 --- a/msa/integration/pubsub/pom.xml +++ b/msa/integration/pubsub/pom.xml @@ -10,7 +10,7 @@ org.thingsboard.msa - 4.4.1-SNAPSHOT + 4.4.2-SNAPSHOT integration diff --git a/msa/integration/rabbitmq/pom.xml b/msa/integration/rabbitmq/pom.xml index dff8c91cfd..f4735e59ce 100644 --- a/msa/integration/rabbitmq/pom.xml +++ b/msa/integration/rabbitmq/pom.xml @@ -10,7 +10,7 @@ org.thingsboard.msa - 4.4.1-SNAPSHOT + 4.4.2-SNAPSHOT integration diff --git a/msa/integration/tcp-udp/pom.xml b/msa/integration/tcp-udp/pom.xml index 24cf0ccf53..5123237814 100644 --- a/msa/integration/tcp-udp/pom.xml +++ b/msa/integration/tcp-udp/pom.xml @@ -10,7 +10,7 @@ org.thingsboard.msa - 4.4.1-SNAPSHOT + 4.4.2-SNAPSHOT integration diff --git a/msa/integration/tuya/pom.xml b/msa/integration/tuya/pom.xml index f7d9bc7c6e..a37d7c5358 100644 --- a/msa/integration/tuya/pom.xml +++ b/msa/integration/tuya/pom.xml @@ -10,7 +10,7 @@ org.thingsboard.msa - 4.4.1-SNAPSHOT + 4.4.2-SNAPSHOT integration diff --git a/msa/js-executor/docker/Dockerfile b/msa/js-executor/docker/Dockerfile index 7e5687f01c..37988c7947 100644 --- a/msa/js-executor/docker/Dockerfile +++ b/msa/js-executor/docker/Dockerfile @@ -3,7 +3,7 @@ # SPDX-License-Identifier: Apache-2.0 # -FROM thingsboard/node:22.23.4-bookworm-slim +FROM thingsboard/node:22.23.5-bookworm-slim ENV NODE_ENV production ENV DOCKER_MODE true diff --git a/msa/js-executor/package.json b/msa/js-executor/package.json index c9ddd554a5..e5adac41b9 100644 --- a/msa/js-executor/package.json +++ b/msa/js-executor/package.json @@ -1,7 +1,7 @@ { "name": "thingsboard-js-executor", "private": true, - "version": "4.4.1", + "version": "4.4.2", "description": "ThingsBoard JavaScript Executor Microservice", "main": "server.ts", "bin": "server.js", @@ -49,5 +49,8 @@ "node_modules/config/**/*.*", "node_modules/@antoniomuso/lz4-napi-*/**/*.node" ] + }, + "resolutions": { + "@yao-pkg/pkg/tar": "^8.0.5" } } diff --git a/msa/js-executor/pom.xml b/msa/js-executor/pom.xml index 3bfaee55ae..79ef36ab88 100644 --- a/msa/js-executor/pom.xml +++ b/msa/js-executor/pom.xml @@ -10,7 +10,7 @@ 4.0.0 org.thingsboard - 4.4.1-SNAPSHOT + 4.4.2-SNAPSHOT msa org.thingsboard.msa @@ -92,7 +92,7 @@ install-node-and-yarn - v22.23.4 + v22.23.5 v1.22.22 diff --git a/msa/js-executor/yarn.lock b/msa/js-executor/yarn.lock index 3c195e8c38..36290f0732 100644 --- a/msa/js-executor/yarn.lock +++ b/msa/js-executor/yarn.lock @@ -365,13 +365,6 @@ "@hapi/bourne" "^3.0.0" "@hapi/hoek" "^11.0.2" -"@isaacs/fs-minipass@^4.0.0": - version "4.0.1" - resolved "https://registry.yarnpkg.com/@isaacs/fs-minipass/-/fs-minipass-4.0.1.tgz#2d59ae3ab4b38fb4270bfa23d30f8e2e86c7fe32" - integrity sha512-wgm9Ehl2jpeqP3zw/7mo3kRHFp5MEDhqAdwy1fTGkHAwnkGOVsgpvQhL8B5n1qlb01jV3n/bI0ZfZp5lWA1k4w== - dependencies: - minipass "^7.0.4" - "@jridgewell/gen-mapping@^0.3.12": version "0.3.13" resolved "https://registry.yarnpkg.com/@jridgewell/gen-mapping/-/gen-mapping-0.3.13.tgz#6342a19f44347518c93e43b1ac69deb3c4656a1f" @@ -772,11 +765,6 @@ chownr@^1.1.1: resolved "https://registry.yarnpkg.com/chownr/-/chownr-1.1.4.tgz#6fc9d7b42d32a583596337666e7d08084da2cc6b" integrity sha512-jJ0bqzaylmJtVnNgzTeSOs8DPavpbYgEr/b0YL8/2GO3xJEhInFmhKMUnEJQjZumK7KXGFhUy89PrsJWlakBVg== -chownr@^3.0.0: - version "3.0.0" - resolved "https://registry.yarnpkg.com/chownr/-/chownr-3.0.0.tgz#9855e64ecd240a9cc4267ce8a4aa5d24a1da15e4" - integrity sha512-+IxzY9BZOQd/XuYPRmrvEVjF/nqj5kgT4kEq7VofrDoM1MxoRjEWkrCC3EtLi59TVawxTAn+orJwFQcrqEN1+g== - cliui@^7.0.2: version "7.0.4" resolved "https://registry.yarnpkg.com/cliui/-/cliui-7.0.4.tgz#a0265ee655476fc807aea9df3df8df7783808b4f" @@ -1403,18 +1391,6 @@ minimist@^1.2.0, minimist@^1.2.3: resolved "https://registry.yarnpkg.com/minimist/-/minimist-1.2.8.tgz#c1a464e7693302e082a075cee0c057741ac4772c" integrity sha512-2yyAR8qBkN3YuheJanUpWC5U3bb5osDywNB8RzDVlDwDHbocAJveqqj1u8+SVD7jkWT4yvsHCpWqqWqAxb0zCA== -minipass@^7.0.4, minipass@^7.1.2: - version "7.1.3" - resolved "https://registry.yarnpkg.com/minipass/-/minipass-7.1.3.tgz#79389b4eb1bb2d003a9bba87d492f2bd37bdc65b" - integrity sha512-tEBHqDnIoM/1rXME1zgka9g6Q2lcoCkxHLuc7ODJ5BxbP5d4c2Z5cGgtXAku59200Cx7diuHTOYfSBD8n6mm8A== - -minizlib@^3.1.0: - version "3.1.0" - resolved "https://registry.yarnpkg.com/minizlib/-/minizlib-3.1.0.tgz#6ad76c3a8f10227c9b51d1c9ac8e30b27f5a251c" - integrity sha512-KZxYo1BUkWD2TVFLr0MQoM8vUUigWD3LlD83a/75BqC+4qE0Hb1Vo5v1FgcfaNXvfXzr+5EhQ6ing/CaBijTlw== - dependencies: - minipass "^7.1.2" - mkdirp-classic@^0.5.2, mkdirp-classic@^0.5.3: version "0.5.3" resolved "https://registry.yarnpkg.com/mkdirp-classic/-/mkdirp-classic-0.5.3.tgz#fa10c9115cc6d8865be221ba47ee9bed78601113" @@ -1932,16 +1908,10 @@ tar-stream@^3.1.5: fast-fifo "^1.3.2" streamx "^2.28.1" -tar@^7.5.7: - version "7.5.22" - resolved "https://registry.yarnpkg.com/tar/-/tar-7.5.22.tgz#a696f998136e71487dc3f869a85bba2c67971ba9" - integrity sha512-MFO/QzvtAOmJbkhOaCTvbGcFN9L9b+JunIsDwaKljSOdcLMea3NJ1k9Usz/rjdfSXTq4dfzfeS7W4p4YOAAHeA== - dependencies: - "@isaacs/fs-minipass" "^4.0.0" - chownr "^3.0.0" - minipass "^7.1.2" - minizlib "^3.1.0" - yallist "^5.0.0" +tar@^7.5.7, tar@^8.0.5: + version "8.1.0" + resolved "https://registry.yarnpkg.com/tar/-/tar-8.1.0.tgz#c5cfb646747f360ece8d47c276c46e7bd499861f" + integrity sha512-0QsCa04wk0hddEWM4hSNMtgewhgvFTW+KzMKJzsSIGO2/snEWyaD9s72p9Is8SXHvbd6sxjInzzT39/yxOWTTw== teex@^1.0.1: version "1.0.1" @@ -2139,11 +2109,6 @@ y18n@^5.0.5: resolved "https://registry.yarnpkg.com/y18n/-/y18n-5.0.8.tgz#7f4934d0f7ca8c56f95314939ddcd2dd91ce1d55" integrity sha512-0pfFzegeDWJHJIAmTLRP2DwHjdF5s7jo9tuztdQxAhINCdvS+3nGINqPd00AphqJR/0LhANUS6/+7SCb98YOfA== -yallist@^5.0.0: - version "5.0.0" - resolved "https://registry.yarnpkg.com/yallist/-/yallist-5.0.0.tgz#00e2de443639ed0d78fd87de0d27469fbcffb533" - integrity sha512-YgvUTfwqyc7UXVMrB+SImsVYSmTS8X/tSrtdNZMImM+n7+QTriRXyXim0mBrTXNeqzVF0KWGgHPeiyViFFrNDw== - yargs-parser@^20.2.2: version "20.2.9" resolved "https://registry.yarnpkg.com/yargs-parser/-/yargs-parser-20.2.9.tgz#2eb7dc3b0289718fc295f362753845c41a0c94ee" diff --git a/msa/migrator/pom.xml b/msa/migrator/pom.xml index f7a18b533e..045eb14b3e 100644 --- a/msa/migrator/pom.xml +++ b/msa/migrator/pom.xml @@ -11,7 +11,7 @@ 4.0.0 org.thingsboard - 4.4.1-SNAPSHOT + 4.4.2-SNAPSHOT msa diff --git a/msa/monitoring/pom.xml b/msa/monitoring/pom.xml index 1de7097bf1..195f73e411 100644 --- a/msa/monitoring/pom.xml +++ b/msa/monitoring/pom.xml @@ -12,7 +12,7 @@ 4.0.0 org.thingsboard - 4.4.1-SNAPSHOT + 4.4.2-SNAPSHOT msa diff --git a/msa/pom.xml b/msa/pom.xml index 2d77c14047..7ae6583537 100644 --- a/msa/pom.xml +++ b/msa/pom.xml @@ -10,7 +10,7 @@ 4.0.0 org.thingsboard - 4.4.1-SNAPSHOT + 4.4.2-SNAPSHOT thingsboard msa @@ -221,7 +221,7 @@ - 4.4.1-latest + 4.4.2-latest false ${docker.push-arm-amd-image.phase} diff --git a/msa/report/pom.xml b/msa/report/pom.xml index 07951226f9..9fb3296db3 100644 --- a/msa/report/pom.xml +++ b/msa/report/pom.xml @@ -9,7 +9,7 @@ 4.0.0 org.thingsboard - 4.4.1-SNAPSHOT + 4.4.2-SNAPSHOT msa org.thingsboard.msa diff --git a/msa/tb-node/pom.xml b/msa/tb-node/pom.xml index 334b8faa55..4efbec11e1 100644 --- a/msa/tb-node/pom.xml +++ b/msa/tb-node/pom.xml @@ -10,7 +10,7 @@ 4.0.0 org.thingsboard - 4.4.1-SNAPSHOT + 4.4.2-SNAPSHOT msa org.thingsboard.msa diff --git a/msa/transport/coap/pom.xml b/msa/transport/coap/pom.xml index 64c3b96edb..3d2e8590b4 100644 --- a/msa/transport/coap/pom.xml +++ b/msa/transport/coap/pom.xml @@ -10,7 +10,7 @@ 4.0.0 org.thingsboard.msa - 4.4.1-SNAPSHOT + 4.4.2-SNAPSHOT transport org.thingsboard.msa.transport diff --git a/msa/transport/http/pom.xml b/msa/transport/http/pom.xml index 4382261ab3..784358bb9d 100644 --- a/msa/transport/http/pom.xml +++ b/msa/transport/http/pom.xml @@ -10,7 +10,7 @@ 4.0.0 org.thingsboard.msa - 4.4.1-SNAPSHOT + 4.4.2-SNAPSHOT transport org.thingsboard.msa.transport diff --git a/msa/transport/lwm2m/pom.xml b/msa/transport/lwm2m/pom.xml index 5d0b944e17..b1ae461b1c 100644 --- a/msa/transport/lwm2m/pom.xml +++ b/msa/transport/lwm2m/pom.xml @@ -10,7 +10,7 @@ 4.0.0 org.thingsboard.msa - 4.4.1-SNAPSHOT + 4.4.2-SNAPSHOT transport org.thingsboard.msa.transport diff --git a/msa/transport/mqtt/pom.xml b/msa/transport/mqtt/pom.xml index 89cb717ee7..b6012e3dab 100644 --- a/msa/transport/mqtt/pom.xml +++ b/msa/transport/mqtt/pom.xml @@ -10,7 +10,7 @@ 4.0.0 org.thingsboard.msa - 4.4.1-SNAPSHOT + 4.4.2-SNAPSHOT transport org.thingsboard.msa.transport diff --git a/msa/transport/pom.xml b/msa/transport/pom.xml index 93c2de38bf..05e68ae535 100644 --- a/msa/transport/pom.xml +++ b/msa/transport/pom.xml @@ -10,7 +10,7 @@ 4.0.0 org.thingsboard - 4.4.1-SNAPSHOT + 4.4.2-SNAPSHOT msa org.thingsboard.msa diff --git a/msa/transport/snmp/pom.xml b/msa/transport/snmp/pom.xml index 1aac58a0ea..43e3793e30 100644 --- a/msa/transport/snmp/pom.xml +++ b/msa/transport/snmp/pom.xml @@ -11,7 +11,7 @@ org.thingsboard.msa transport - 4.4.1-SNAPSHOT + 4.4.2-SNAPSHOT org.thingsboard.msa.transport diff --git a/msa/vc-executor-docker/pom.xml b/msa/vc-executor-docker/pom.xml index d326bfec8a..d703927a5b 100644 --- a/msa/vc-executor-docker/pom.xml +++ b/msa/vc-executor-docker/pom.xml @@ -10,7 +10,7 @@ 4.0.0 org.thingsboard - 4.4.1-SNAPSHOT + 4.4.2-SNAPSHOT msa org.thingsboard.msa diff --git a/msa/vc-executor/pom.xml b/msa/vc-executor/pom.xml index 436fe5d06d..6ded68ec01 100644 --- a/msa/vc-executor/pom.xml +++ b/msa/vc-executor/pom.xml @@ -11,7 +11,7 @@ org.thingsboard - 4.4.1-SNAPSHOT + 4.4.2-SNAPSHOT msa org.thingsboard.msa diff --git a/msa/web-report/chromium.js b/msa/web-report/chromium.js index cd9acc9f14..662678c8f6 100644 --- a/msa/web-report/chromium.js +++ b/msa/web-report/chromium.js @@ -22,15 +22,15 @@ module.exports = { // exclude: glob patterns of the files that are not packaged // strip: glob patterns of the executables to strip of their symbols, when GNU strip is installed snapshot: { - version: '156.0.8078.0', + version: '159.0.8154.0', baseUrl: 'https://commondatastorage.googleapis.com/chromium-browser-snapshots', // The .pak.info files, 70 MB, are left from the build of the translations; the browser does not read them - linux: { path: 'Linux_x64/1706520/chrome-linux.zip', sha256: '6b62846a868ea3ee675f77600790877a428dfb2428c940f8eff99db1038f9815', + linux: { path: 'Linux_x64/1739867/chrome-linux.zip', sha256: 'e3dc14d0c796c4cff0a2e67e1d2d384a5228ab7e6adb4d4822d813772e4b8b4b', exclude: ['locales/*.pak.info'], // The Linux builds come with their symbols, 180 MB strip: ['chrome', 'chrome_crashpad_handler', 'chrome_sandbox', '*.so*'] }, // interactive_ui_tests.exe is a test program of 348 MB that the service does not need - windows: { path: 'Win_x64/1706509/chrome-win.zip', sha256: '6bdfecb33dbfa7159e5666798bdc28c76347bef913573e899cb43930b78d26cc', + windows: { path: 'Win_x64/1739762/chrome-win.zip', sha256: '097cc334674de52de3653519d8205bc227c7943f6a6cc0d2a0fc4a8f685284db', exclude: ['interactive_ui_tests.exe'] } } }; diff --git a/msa/web-report/docker/Dockerfile b/msa/web-report/docker/Dockerfile index 17457c153c..f80f704a0e 100644 --- a/msa/web-report/docker/Dockerfile +++ b/msa/web-report/docker/Dockerfile @@ -3,7 +3,7 @@ # SPDX-License-Identifier: BUSL-1.1 # -FROM thingsboard/node:22.23.4-bookworm-slim +FROM thingsboard/node:22.23.5-bookworm-slim ARG TARGETPLATFORM ARG DEBIAN_FRONTEND=noninteractive diff --git a/msa/web-report/package.json b/msa/web-report/package.json index e247cdde62..21143e2bd8 100644 --- a/msa/web-report/package.json +++ b/msa/web-report/package.json @@ -1,7 +1,7 @@ { "name": "thingsboard-web-report", "private": true, - "version": "4.4.1", + "version": "4.4.2", "description": "ThingsBoard Web Reporting Microservice", "main": "server.ts", "bin": "server.js", @@ -18,7 +18,7 @@ "config": "~4.4.2", "express": "~5.3.0", "js-yaml": "^4.3.2", - "playwright-core": "~1.64.1", + "playwright-core": "~1.65.2", "winston": "~3.19.0", "winston-daily-rotate-file": "~5.0.0" }, @@ -44,5 +44,8 @@ "node_modules/playwright-core/lib/server/chromium/appIcon.png", "../../node_modules/playwright-core/lib/webp_codec.wasm" ] + }, + "resolutions": { + "@yao-pkg/pkg/tar": "^8.0.5" } } diff --git a/msa/web-report/playwright-core-1.65.2.tgz b/msa/web-report/playwright-core-1.65.2.tgz new file mode 100644 index 0000000000..f53a0e9a93 Binary files /dev/null and b/msa/web-report/playwright-core-1.65.2.tgz differ diff --git a/msa/web-report/pom.xml b/msa/web-report/pom.xml index 4e5958bfb3..e76e6e7586 100644 --- a/msa/web-report/pom.xml +++ b/msa/web-report/pom.xml @@ -9,7 +9,7 @@ 4.0.0 org.thingsboard - 4.4.1-SNAPSHOT + 4.4.2-SNAPSHOT msa org.thingsboard.msa @@ -88,7 +88,7 @@ install-node-and-yarn - v22.23.4 + v22.23.5 v1.22.22 diff --git a/msa/web-report/yarn.lock b/msa/web-report/yarn.lock index 61a026c6d0..be8dd94dc6 100644 --- a/msa/web-report/yarn.lock +++ b/msa/web-report/yarn.lock @@ -235,13 +235,6 @@ resolved "https://registry.yarnpkg.com/@esbuild/win32-x64/-/win32-x64-0.28.2.tgz#b21affb804cc167c133d95f45b3a1dc1323b9a87" integrity sha512-5ebpxr3nWMzrL/rnUI755Jkuee0bHL/Gq0WTF9lvcpv73wAp5eu8MfBUgWK9bhWvZjj7yX8etf/8tI8Ney695g== -"@isaacs/fs-minipass@^4.0.0": - version "4.0.1" - resolved "https://registry.yarnpkg.com/@isaacs/fs-minipass/-/fs-minipass-4.0.1.tgz#2d59ae3ab4b38fb4270bfa23d30f8e2e86c7fe32" - integrity sha512-wgm9Ehl2jpeqP3zw/7mo3kRHFp5MEDhqAdwy1fTGkHAwnkGOVsgpvQhL8B5n1qlb01jV3n/bI0ZfZp5lWA1k4w== - dependencies: - minipass "^7.0.4" - "@jridgewell/gen-mapping@^0.3.12": version "0.3.13" resolved "https://registry.yarnpkg.com/@jridgewell/gen-mapping/-/gen-mapping-0.3.13.tgz#6342a19f44347518c93e43b1ac69deb3c4656a1f" @@ -591,11 +584,6 @@ chownr@^1.1.1: resolved "https://registry.yarnpkg.com/chownr/-/chownr-1.1.4.tgz#6fc9d7b42d32a583596337666e7d08084da2cc6b" integrity sha512-jJ0bqzaylmJtVnNgzTeSOs8DPavpbYgEr/b0YL8/2GO3xJEhInFmhKMUnEJQjZumK7KXGFhUy89PrsJWlakBVg== -chownr@^3.0.0: - version "3.0.0" - resolved "https://registry.yarnpkg.com/chownr/-/chownr-3.0.0.tgz#9855e64ecd240a9cc4267ce8a4aa5d24a1da15e4" - integrity sha512-+IxzY9BZOQd/XuYPRmrvEVjF/nqj5kgT4kEq7VofrDoM1MxoRjEWkrCC3EtLi59TVawxTAn+orJwFQcrqEN1+g== - cliui@^7.0.2: version "7.0.4" resolved "https://registry.yarnpkg.com/cliui/-/cliui-7.0.4.tgz#a0265ee655476fc807aea9df3df8df7783808b4f" @@ -1178,18 +1166,6 @@ minimist@^1.2.0, minimist@^1.2.3: resolved "https://registry.yarnpkg.com/minimist/-/minimist-1.2.8.tgz#c1a464e7693302e082a075cee0c057741ac4772c" integrity sha512-2yyAR8qBkN3YuheJanUpWC5U3bb5osDywNB8RzDVlDwDHbocAJveqqj1u8+SVD7jkWT4yvsHCpWqqWqAxb0zCA== -minipass@^7.0.4, minipass@^7.1.2: - version "7.1.3" - resolved "https://registry.yarnpkg.com/minipass/-/minipass-7.1.3.tgz#79389b4eb1bb2d003a9bba87d492f2bd37bdc65b" - integrity sha512-tEBHqDnIoM/1rXME1zgka9g6Q2lcoCkxHLuc7ODJ5BxbP5d4c2Z5cGgtXAku59200Cx7diuHTOYfSBD8n6mm8A== - -minizlib@^3.1.0: - version "3.1.0" - resolved "https://registry.yarnpkg.com/minizlib/-/minizlib-3.1.0.tgz#6ad76c3a8f10227c9b51d1c9ac8e30b27f5a251c" - integrity sha512-KZxYo1BUkWD2TVFLr0MQoM8vUUigWD3LlD83a/75BqC+4qE0Hb1Vo5v1FgcfaNXvfXzr+5EhQ6ing/CaBijTlw== - dependencies: - minipass "^7.1.2" - mkdirp-classic@^0.5.2, mkdirp-classic@^0.5.3: version "0.5.3" resolved "https://registry.yarnpkg.com/mkdirp-classic/-/mkdirp-classic-0.5.3.tgz#fa10c9115cc6d8865be221ba47ee9bed78601113" @@ -1307,10 +1283,10 @@ picomatch@^4.0.2, picomatch@^4.0.4: resolved "https://registry.yarnpkg.com/picomatch/-/picomatch-4.0.7.tgz#6313360034ccb36b3dc61ecbdff78121f90fe21f" integrity sha512-qcJu88Q2IWqJsDD529JKMdwGm/dvInW4HvQnRwiH9JtihJvzGOscDtHE3x1pBKeUOTysQ8kVmLnJ2kJu7yhcGA== -playwright-core@~1.64.1: - version "1.64.1" - resolved "https://registry.yarnpkg.com/playwright-core/-/playwright-core-1.64.1.tgz#ca9ec82d7da6ced1b2326ec59ef097aaa9a29f94" - integrity sha512-BC4s8y6SEVA6Q1rSxZTto8hI1KUI3xXlHGZgvGqP4IqPdI/a6FX9H29IDNz7vKo9l21b6LfYosScPL6M3xxyDQ== +playwright-core@~1.65.2: + version "1.65.2" + resolved "https://registry.yarnpkg.com/playwright-core/-/playwright-core-1.65.2.tgz#10b242db00a3cf9d01d2cc38cd91afb66664be6c" + integrity sha512-aHu9F46Mx5ha9iiB+VLZMUUtex3PBw4am9MHptc0IXaJhz++6YXsH96eEyThwCwMkIUiB8TdZcwXqnb3xKDzmA== postinstall-postinstall@^2.1.0: version "2.1.0" @@ -1707,16 +1683,10 @@ tar-stream@^3.1.5: fast-fifo "^1.3.2" streamx "^2.28.1" -tar@^7.5.7: - version "7.5.22" - resolved "https://registry.yarnpkg.com/tar/-/tar-7.5.22.tgz#a696f998136e71487dc3f869a85bba2c67971ba9" - integrity sha512-MFO/QzvtAOmJbkhOaCTvbGcFN9L9b+JunIsDwaKljSOdcLMea3NJ1k9Usz/rjdfSXTq4dfzfeS7W4p4YOAAHeA== - dependencies: - "@isaacs/fs-minipass" "^4.0.0" - chownr "^3.0.0" - minipass "^7.1.2" - minizlib "^3.1.0" - yallist "^5.0.0" +tar@^7.5.7, tar@^8.0.5: + version "8.1.0" + resolved "https://registry.yarnpkg.com/tar/-/tar-8.1.0.tgz#c5cfb646747f360ece8d47c276c46e7bd499861f" + integrity sha512-0QsCa04wk0hddEWM4hSNMtgewhgvFTW+KzMKJzsSIGO2/snEWyaD9s72p9Is8SXHvbd6sxjInzzT39/yxOWTTw== teex@^1.0.1: version "1.0.1" @@ -1909,11 +1879,6 @@ y18n@^5.0.5: resolved "https://registry.yarnpkg.com/y18n/-/y18n-5.0.8.tgz#7f4934d0f7ca8c56f95314939ddcd2dd91ce1d55" integrity sha512-0pfFzegeDWJHJIAmTLRP2DwHjdF5s7jo9tuztdQxAhINCdvS+3nGINqPd00AphqJR/0LhANUS6/+7SCb98YOfA== -yallist@^5.0.0: - version "5.0.0" - resolved "https://registry.yarnpkg.com/yallist/-/yallist-5.0.0.tgz#00e2de443639ed0d78fd87de0d27469fbcffb533" - integrity sha512-YgvUTfwqyc7UXVMrB+SImsVYSmTS8X/tSrtdNZMImM+n7+QTriRXyXim0mBrTXNeqzVF0KWGgHPeiyViFFrNDw== - yargs-parser@^20.2.2: version "20.2.9" resolved "https://registry.yarnpkg.com/yargs-parser/-/yargs-parser-20.2.9.tgz#2eb7dc3b0289718fc295f362753845c41a0c94ee" diff --git a/msa/web-ui/docker/Dockerfile b/msa/web-ui/docker/Dockerfile index 7f316f63ce..6e34dfb6fc 100644 --- a/msa/web-ui/docker/Dockerfile +++ b/msa/web-ui/docker/Dockerfile @@ -3,7 +3,7 @@ # SPDX-License-Identifier: Apache-2.0 # -FROM thingsboard/node:22.23.4-bookworm-slim +FROM thingsboard/node:22.23.5-bookworm-slim ENV NODE_ENV production ENV DOCKER_MODE true diff --git a/msa/web-ui/package.json b/msa/web-ui/package.json index bfcb04bb7d..9a35e6b4b3 100644 --- a/msa/web-ui/package.json +++ b/msa/web-ui/package.json @@ -1,7 +1,7 @@ { "name": "thingsboard-web-ui", "private": true, - "version": "4.4.1", + "version": "4.4.2", "description": "ThingsBoard Web UI Microservice", "main": "server.ts", "bin": "server.js", @@ -42,5 +42,8 @@ "assets": [ "node_modules/config/**/*.*" ] + }, + "resolutions": { + "@yao-pkg/pkg/tar": "^8.0.5" } } diff --git a/msa/web-ui/pom.xml b/msa/web-ui/pom.xml index 37d1815a1b..6488e08843 100644 --- a/msa/web-ui/pom.xml +++ b/msa/web-ui/pom.xml @@ -10,7 +10,7 @@ 4.0.0 org.thingsboard - 4.4.1-SNAPSHOT + 4.4.2-SNAPSHOT msa org.thingsboard.msa @@ -71,7 +71,7 @@ install-node-and-yarn - v22.23.4 + v22.23.5 v1.22.22 diff --git a/msa/web-ui/yarn.lock b/msa/web-ui/yarn.lock index de9d88afe3..290a600123 100644 --- a/msa/web-ui/yarn.lock +++ b/msa/web-ui/yarn.lock @@ -235,13 +235,6 @@ resolved "https://registry.yarnpkg.com/@esbuild/win32-x64/-/win32-x64-0.28.2.tgz#b21affb804cc167c133d95f45b3a1dc1323b9a87" integrity sha512-5ebpxr3nWMzrL/rnUI755Jkuee0bHL/Gq0WTF9lvcpv73wAp5eu8MfBUgWK9bhWvZjj7yX8etf/8tI8Ney695g== -"@isaacs/fs-minipass@^4.0.0": - version "4.0.1" - resolved "https://registry.yarnpkg.com/@isaacs/fs-minipass/-/fs-minipass-4.0.1.tgz#2d59ae3ab4b38fb4270bfa23d30f8e2e86c7fe32" - integrity sha512-wgm9Ehl2jpeqP3zw/7mo3kRHFp5MEDhqAdwy1fTGkHAwnkGOVsgpvQhL8B5n1qlb01jV3n/bI0ZfZp5lWA1k4w== - dependencies: - minipass "^7.0.4" - "@jridgewell/gen-mapping@^0.3.12": version "0.3.13" resolved "https://registry.yarnpkg.com/@jridgewell/gen-mapping/-/gen-mapping-0.3.13.tgz#6342a19f44347518c93e43b1ac69deb3c4656a1f" @@ -606,11 +599,6 @@ chownr@^1.1.1: resolved "https://registry.yarnpkg.com/chownr/-/chownr-1.1.4.tgz#6fc9d7b42d32a583596337666e7d08084da2cc6b" integrity sha512-jJ0bqzaylmJtVnNgzTeSOs8DPavpbYgEr/b0YL8/2GO3xJEhInFmhKMUnEJQjZumK7KXGFhUy89PrsJWlakBVg== -chownr@^3.0.0: - version "3.0.0" - resolved "https://registry.yarnpkg.com/chownr/-/chownr-3.0.0.tgz#9855e64ecd240a9cc4267ce8a4aa5d24a1da15e4" - integrity sha512-+IxzY9BZOQd/XuYPRmrvEVjF/nqj5kgT4kEq7VofrDoM1MxoRjEWkrCC3EtLi59TVawxTAn+orJwFQcrqEN1+g== - cliui@^7.0.2: version "7.0.4" resolved "https://registry.yarnpkg.com/cliui/-/cliui-7.0.4.tgz#a0265ee655476fc807aea9df3df8df7783808b4f" @@ -1217,18 +1205,6 @@ minimist@^1.2.0, minimist@^1.2.3: resolved "https://registry.yarnpkg.com/minimist/-/minimist-1.2.8.tgz#c1a464e7693302e082a075cee0c057741ac4772c" integrity sha512-2yyAR8qBkN3YuheJanUpWC5U3bb5osDywNB8RzDVlDwDHbocAJveqqj1u8+SVD7jkWT4yvsHCpWqqWqAxb0zCA== -minipass@^7.0.4, minipass@^7.1.2: - version "7.1.3" - resolved "https://registry.yarnpkg.com/minipass/-/minipass-7.1.3.tgz#79389b4eb1bb2d003a9bba87d492f2bd37bdc65b" - integrity sha512-tEBHqDnIoM/1rXME1zgka9g6Q2lcoCkxHLuc7ODJ5BxbP5d4c2Z5cGgtXAku59200Cx7diuHTOYfSBD8n6mm8A== - -minizlib@^3.1.0: - version "3.1.0" - resolved "https://registry.yarnpkg.com/minizlib/-/minizlib-3.1.0.tgz#6ad76c3a8f10227c9b51d1c9ac8e30b27f5a251c" - integrity sha512-KZxYo1BUkWD2TVFLr0MQoM8vUUigWD3LlD83a/75BqC+4qE0Hb1Vo5v1FgcfaNXvfXzr+5EhQ6ing/CaBijTlw== - dependencies: - minipass "^7.1.2" - mkdirp-classic@^0.5.2, mkdirp-classic@^0.5.3: version "0.5.3" resolved "https://registry.yarnpkg.com/mkdirp-classic/-/mkdirp-classic-0.5.3.tgz#fa10c9115cc6d8865be221ba47ee9bed78601113" @@ -1741,16 +1717,10 @@ tar-stream@^3.1.5: fast-fifo "^1.3.2" streamx "^2.28.1" -tar@^7.5.7: - version "7.5.22" - resolved "https://registry.yarnpkg.com/tar/-/tar-7.5.22.tgz#a696f998136e71487dc3f869a85bba2c67971ba9" - integrity sha512-MFO/QzvtAOmJbkhOaCTvbGcFN9L9b+JunIsDwaKljSOdcLMea3NJ1k9Usz/rjdfSXTq4dfzfeS7W4p4YOAAHeA== - dependencies: - "@isaacs/fs-minipass" "^4.0.0" - chownr "^3.0.0" - minipass "^7.1.2" - minizlib "^3.1.0" - yallist "^5.0.0" +tar@^7.5.7, tar@^8.0.5: + version "8.0.5" + resolved "https://registry.yarnpkg.com/tar/-/tar-8.0.5.tgz#1f36231a811830520db3a6af984c55505a930ec3" + integrity sha512-iYroSHv/iVs5Bfy7uXCZVTye64oecqEETP3jvxksDcJlf8E3hreHYyhT+Qu7b+JgniditLaQbk4ZujNAnPEX9w== teex@^1.0.1: version "1.0.1" @@ -1943,11 +1913,6 @@ y18n@^5.0.5: resolved "https://registry.yarnpkg.com/y18n/-/y18n-5.0.8.tgz#7f4934d0f7ca8c56f95314939ddcd2dd91ce1d55" integrity sha512-0pfFzegeDWJHJIAmTLRP2DwHjdF5s7jo9tuztdQxAhINCdvS+3nGINqPd00AphqJR/0LhANUS6/+7SCb98YOfA== -yallist@^5.0.0: - version "5.0.0" - resolved "https://registry.yarnpkg.com/yallist/-/yallist-5.0.0.tgz#00e2de443639ed0d78fd87de0d27469fbcffb533" - integrity sha512-YgvUTfwqyc7UXVMrB+SImsVYSmTS8X/tSrtdNZMImM+n7+QTriRXyXim0mBrTXNeqzVF0KWGgHPeiyViFFrNDw== - yargs-parser@^20.2.2: version "20.2.9" resolved "https://registry.yarnpkg.com/yargs-parser/-/yargs-parser-20.2.9.tgz#2eb7dc3b0289718fc295f362753845c41a0c94ee" diff --git a/netty-mqtt/pom.xml b/netty-mqtt/pom.xml index 3316bf1e13..ae51ed9ac1 100644 --- a/netty-mqtt/pom.xml +++ b/netty-mqtt/pom.xml @@ -9,11 +9,11 @@ 4.0.0 org.thingsboard - 4.4.1-SNAPSHOT + 4.4.2-SNAPSHOT thingsboard netty-mqtt - 4.4.1-SNAPSHOT + 4.4.2-SNAPSHOT jar Netty MQTT Client diff --git a/pom.xml b/pom.xml index c86b141c3c..2dadf56746 100755 --- a/pom.xml +++ b/pom.xml @@ -10,7 +10,7 @@ 4.0.0 org.thingsboard thingsboard - 4.4.1-SNAPSHOT + 4.4.2-SNAPSHOT pom ThingsBoard @@ -81,13 +81,16 @@ /var/log/${pkg.name} /usr/share/${pkg.name} control - 2.1.10 + 2.1.11-SNAPSHOT 4.4.0 4.1.3 4.2.20.Final 2.0.85.Final 1.11.4 1.5.7-14 + 2.10.0 + 42.7.15 + 11.0.29 0.13.0 0.10 4.2.25 @@ -1471,6 +1474,37 @@ pom import + + + org.conscrypt + conscrypt-openjdk-uber + ${conscrypt.version} + + + + + org.postgresql + postgresql + ${postgresql.version} + + + + + org.apache.tomcat.embed + tomcat-embed-core + ${tomcat.version} + + + org.apache.tomcat.embed + tomcat-embed-el + ${tomcat.version} + + + org.apache.tomcat.embed + tomcat-embed-websocket + ${tomcat.version} + + org.springframework.boot spring-boot-dependencies diff --git a/report/pom.xml b/report/pom.xml index 197751bd19..ec121acb46 100644 --- a/report/pom.xml +++ b/report/pom.xml @@ -9,7 +9,7 @@ 4.0.0 org.thingsboard - 4.4.1-SNAPSHOT + 4.4.2-SNAPSHOT thingsboard report diff --git a/rest-client/pom.xml b/rest-client/pom.xml index 6ef87dde9b..1e6381f6ab 100644 --- a/rest-client/pom.xml +++ b/rest-client/pom.xml @@ -10,7 +10,7 @@ 4.0.0 org.thingsboard - 4.4.1-SNAPSHOT + 4.4.2-SNAPSHOT thingsboard rest-client diff --git a/rule-engine/pom.xml b/rule-engine/pom.xml index 72c1799c23..e6b22e65a1 100644 --- a/rule-engine/pom.xml +++ b/rule-engine/pom.xml @@ -10,7 +10,7 @@ 4.0.0 org.thingsboard - 4.4.1-SNAPSHOT + 4.4.2-SNAPSHOT thingsboard rule-engine diff --git a/rule-engine/rule-engine-api/pom.xml b/rule-engine/rule-engine-api/pom.xml index bf777a32d9..0dd54d0bbc 100644 --- a/rule-engine/rule-engine-api/pom.xml +++ b/rule-engine/rule-engine-api/pom.xml @@ -12,7 +12,7 @@ 4.0.0 org.thingsboard - 4.4.1-SNAPSHOT + 4.4.2-SNAPSHOT rule-engine org.thingsboard.rule-engine diff --git a/rule-engine/rule-engine-components/pom.xml b/rule-engine/rule-engine-components/pom.xml index 3890642282..56c1f833d6 100644 --- a/rule-engine/rule-engine-components/pom.xml +++ b/rule-engine/rule-engine-components/pom.xml @@ -12,7 +12,7 @@ 4.0.0 org.thingsboard - 4.4.1-SNAPSHOT + 4.4.2-SNAPSHOT rule-engine org.thingsboard.rule-engine diff --git a/tools/pom.xml b/tools/pom.xml index 5d90a97281..8f8b17ae95 100644 --- a/tools/pom.xml +++ b/tools/pom.xml @@ -10,7 +10,7 @@ 4.0.0 org.thingsboard - 4.4.1-SNAPSHOT + 4.4.2-SNAPSHOT thingsboard tools diff --git a/tools/src/main/python/license-headers/curations.json b/tools/src/main/python/license-headers/curations.json index 18e0ec560f..ce7711b735 100644 --- a/tools/src/main/python/license-headers/curations.json +++ b/tools/src/main/python/license-headers/curations.json @@ -421,6 +421,12 @@ "reason": "PE custom menu model interface introduced in 2eb81a2baa9 alongside CustomMenuConfig. The candidate CE DeviceConfiguration.java matches only on Jackson polymorphism annotations, not on the menu model. Reviewed candidate at 317a75614137ab5ddd1aecef1abd4c2fcdcb8710 (blob 6fe689d17c0).", "contentHash": "sha256:da19b1162913a636119fcc953d6366b990d24a6fda8df540497653bb317407b0" }, + { + "path": "common/data/src/main/java/org/thingsboard/server/common/data/notification/info/AiCreditsLimitIncreaseRequestNotificationInfo.java", + "header": "ce-modified", + "reason": "Copied from the CE EntitiesLimitIncreaseRequestNotificationInfo and adapted: entityType replaced by tenantName and limitDescription, same structure and template data map. Reviewed against CE common/data/src/main/java/org/thingsboard/server/common/data/notification/info/EntitiesLimitIncreaseRequestNotificationInfo.java at 0cfdad792af2a7ab1e292742134dce19f5293b7e (blob 9595b4414fd87b3740479c730c8c39928d003e7b).", + "contentHash": "sha256:362d939f065b94a46db4258c87598278b4f4db7b6dcf82a0a57dd762a8f09635" + }, { "path": "common/data/src/main/java/org/thingsboard/server/common/data/notification/info/IntegrationLifecycleEventNotificationInfo.java", "header": "busl", @@ -1157,7 +1163,7 @@ "path": "msa/web-report/pom.xml", "header": "busl", "reason": "Build descriptor of the PE-only web-report module; CE has no web-report module. The only CE version is an empty file (blob e69de29bb2d) added by stray commit 2b1c5d92f3a, pushed to fix/maven-node-lts-4.3 after #16417 merged and carried into lts-4.4 via #16419; it never reached CE lts-4.3 and is not the origin of this file.", - "contentHash": "sha256:1482a75a56fe40ada65e4a1dafedd94c819a03a72ed0bad067ff051d46c12fee" + "contentHash": "sha256:620ece3810c834e5823c845cd98b56c67bf1c6bb39bd8e0c67c075bc0c7b1b53" }, { "path": "report/src/main/conf/logback.xml", @@ -1195,6 +1201,12 @@ "reason": "Configuration holder for the PE customer-attribute rule node. Reviewed property defaults configure this PE node; common rule-node configuration/clone patterns do not establish derivation from the CE entity-data node. Reviewed candidate rule-engine/rule-engine-components/src/main/java/org/thingsboard/rule/engine/metadata/TbGetEntityDataNodeConfiguration.java at 0d3b41e002f958887a317ca8366fdc4efa549058 (blob f68fdf321b69b24e3e15bd2a311e2ccfa86ff890).", "contentHash": "sha256:0b91a00b698884c6654781d43c0debb2e61dcfcb9898811e27dc13baafde2bb0" }, + { + "path": "ui-ngx/src/app/modules/home/components/ai/ai-approval-card.component.scss", + "header": "busl", + "reason": "New AI approval card stylesheet holding only a one-line ':host { display: block; }' rule; it matches CE socialshare-panel.component.scss only because that rule is generic boilerplate, not because anything was copied from it. Reviewed against CE ui-ngx/src/app/shared/components/socialshare-panel.component.scss at 0cfdad792af2a7ab1e292742134dce19f5293b7e (blob 75f4e82b7187d38898ab858dc6a20be6058e9e20).", + "contentHash": "sha256:49fd378740956adca949bca4777b25410d4d9c562716602678360a3aa7f82a91" + }, { "path": "ui-ngx/src/app/modules/home/components/converter/converter-autocomplete.component.scss", "header": "busl", @@ -1393,6 +1405,12 @@ "reason": "New PE file implementing a PE feature. It was written by adapting CE ui-ngx/src/app/modules/home/pages/dashboard/make-dashboard-public-dialog.component.ts, which PE still carries at its own path, so this is not a CE file with PE modifications. Adaptation from CE does not make it CE-derived. Maintainer rule (2026-09-09): a file that exists in CE and carries PE changes is modified CE; a file that does not exist in CE and implements a PE feature is PE-only, however closely it resembles a CE file.", "contentHash": "sha256:07f295f637db24d600798215d33391f4e966954899f644a41b9735f5ed5392db" }, + { + "path": "ui-ngx/src/app/modules/home/pages/home-page/home-page.component.html", + "header": "ce-modified", + "reason": "Renamed from CE home-links.component.html; it keeps the CE embedded tb-dashboard-page for an assigned home dashboard and replaces the links grid with the new Home pages. Reviewed against CE ui-ngx/src/app/modules/home/pages/home-links/home-links.component.html at 0cfdad792af2a7ab1e292742134dce19f5293b7e (blob 3f7184d1828f217480f5e12486f1ff0704d2f7c4).", + "contentHash": "sha256:ab7b00962003c516bce4af3dabc068c37b0d9ee773e960f8607b6a155514f76b" + }, { "path": "ui-ngx/src/app/modules/home/pages/iframe/iframe-view.module.ts", "header": "busl", diff --git a/transport/coap/pom.xml b/transport/coap/pom.xml index 6366afd0a7..16f20f591c 100644 --- a/transport/coap/pom.xml +++ b/transport/coap/pom.xml @@ -10,7 +10,7 @@ 4.0.0 org.thingsboard - 4.4.1-SNAPSHOT + 4.4.2-SNAPSHOT transport org.thingsboard.transport diff --git a/transport/http/pom.xml b/transport/http/pom.xml index 7ba3c6646e..95ffc9e3ae 100644 --- a/transport/http/pom.xml +++ b/transport/http/pom.xml @@ -10,7 +10,7 @@ 4.0.0 org.thingsboard - 4.4.1-SNAPSHOT + 4.4.2-SNAPSHOT transport org.thingsboard.transport diff --git a/transport/lwm2m/pom.xml b/transport/lwm2m/pom.xml index 61269c0a59..04bc000924 100644 --- a/transport/lwm2m/pom.xml +++ b/transport/lwm2m/pom.xml @@ -10,7 +10,7 @@ 4.0.0 org.thingsboard - 4.4.1-SNAPSHOT + 4.4.2-SNAPSHOT transport org.thingsboard.transport diff --git a/transport/mqtt/pom.xml b/transport/mqtt/pom.xml index 8c6c7f97a9..04b3df75c4 100644 --- a/transport/mqtt/pom.xml +++ b/transport/mqtt/pom.xml @@ -10,7 +10,7 @@ 4.0.0 org.thingsboard - 4.4.1-SNAPSHOT + 4.4.2-SNAPSHOT transport org.thingsboard.transport diff --git a/transport/pom.xml b/transport/pom.xml index c308306461..63378e6591 100644 --- a/transport/pom.xml +++ b/transport/pom.xml @@ -10,7 +10,7 @@ 4.0.0 org.thingsboard - 4.4.1-SNAPSHOT + 4.4.2-SNAPSHOT thingsboard transport diff --git a/transport/snmp/pom.xml b/transport/snmp/pom.xml index f742e2c127..bb7a1ded84 100644 --- a/transport/snmp/pom.xml +++ b/transport/snmp/pom.xml @@ -11,7 +11,7 @@ org.thingsboard - 4.4.1-SNAPSHOT + 4.4.2-SNAPSHOT transport diff --git a/ui-ngx/eslint.config.mjs b/ui-ngx/eslint.config.mjs index f003d8cc6d..49c95e6f73 100644 --- a/ui-ngx/eslint.config.mjs +++ b/ui-ngx/eslint.config.mjs @@ -20,16 +20,6 @@ export default tsEslint.config( ], processor: angular.processInlineTemplates, rules: { - "@typescript-eslint/explicit-member-accessibility": [ - "off", - { - accessibility: "explicit" - } - ], - "arrow-parens": [ - "off", - "always" - ], "@angular-eslint/component-selector": [ "error", { @@ -38,7 +28,7 @@ export default tsEslint.config( ] } ], - "id-blacklist": [ + "id-denylist": [ "error", "any", "Number", @@ -49,11 +39,9 @@ export default tsEslint.config( "Undefined", "undefined" ], - "import/order": "off", "@typescript-eslint/member-ordering": "off", "no-underscore-dangle": "off", "@typescript-eslint/naming-convention": "off", - "jsdoc/newline-after-description": 0, "@typescript-eslint/consistent-indexed-object-style": "off", "@typescript-eslint/array-type": "off", "no-extra-boolean-cast": "off", diff --git a/ui-ngx/package.json b/ui-ngx/package.json index c4b5930b13..afd546805d 100644 --- a/ui-ngx/package.json +++ b/ui-ngx/package.json @@ -1,6 +1,6 @@ { "name": "thingsboard", - "version": "4.4.1", + "version": "4.4.2", "scripts": { "ng": "ng", "start": "node --max_old_space_size=8192 ./node_modules/@angular/cli/bin/ng serve --configuration development --host 0.0.0.0 --open", @@ -28,6 +28,8 @@ "@auth0/angular-jwt": "^5.2.0", "@flowjs/flow.js": "^2.14.1", "@flowjs/ngx-flow": "20.0.2", + "@fontsource-variable/roboto": "^5.3.0", + "@fontsource-variable/roboto-mono": "^5.3.0", "@fullcalendar/angular": "^6.1.20", "@fullcalendar/core": "^6.1.20", "@fullcalendar/daygrid": "^6.1.20", @@ -41,6 +43,7 @@ "@mat-datetimepicker/core": "~16.0.1", "@mdi/svg": "^7.4.47", "@messageformat/core": "^3.4.1", + "@messageformat/parser": "^5.2.0", "@ngrx/effects": "^20.1.0", "@ngrx/store": "^20.1.0", "@ngrx/store-devtools": "^20.1.0", @@ -55,8 +58,8 @@ "angular-gridster2": "~20.2.4", "angular2-hotkeys": "^16.0.1", "canvas-gauges": "^2.1.7", - "core-js": "^3.51.0", "dayjs": "1.11.23", + "dompurify": "^3.3.3", "echarts": "https://github.com/thingsboard/echarts/archive/5.5.4-TB.tar.gz", "exceljs-hardened": "~5.1.0", "flag-icons": "7.6.0", @@ -67,8 +70,7 @@ "jquery": "^3.7.1", "jquery-sparkline": "^2.4.0", "jquery.terminal": "^2.48.1", - "js-beautify": "1.15.4", - "json-schema-defaults": "^0.4.0", + "js-beautify": "2.0.3", "jstree": "^3.3.17", "jstree-bootstrap-theme": "^1.0.1", "jszip": "^3.10.2", @@ -79,11 +81,13 @@ "leaflet.gridlayer.googlemutant": "0.15.0", "leaflet.markercluster": "1.5.3", "libphonenumber-js": "^1.13.15", + "lodash": "^4.18.1", "maplibre-gl": "6.15.0", "marked": "~16.4.2", "modern-screenshot": "^4.7.0", "moment": "^2.31.0", "moment-timezone": "^0.6.5", + "mousetrap": "^1.6.5", "ngx-captcha": "^14.0.0", "ngx-clipboard": "^16.0.0", "ngx-daterangepicker-material": "^6.0.4", @@ -94,10 +98,10 @@ "ngx-translate-messageformat-compiler": "^7.3.0", "objectpath": "^2.0.0", "photoswipe": "^5.4.4", + "prismjs": "^1.30.0", "qrcode": "^1.5.4", "raphael": "^2.3.0", "rxjs": "~7.8.2", - "schema-inspector": "^2.1.0", "screenfull": "^6.0.2", "sorted-btree": "^1.8.1", "split.js": "^1.6.5", @@ -105,20 +109,16 @@ "tinycolor2": "^1.6.0", "tooltipster": "^4.2.8", "tslib": "^2.8.1", - "typeface-roboto": "^1.1.13", - "typeface-roboto-mono": "^1.1.13", "yaml": "^2.6.1", "zone.js": "~0.15.1" }, "devDependencies": { "@angular-builders/custom-esbuild": "20.0.0", - "@angular-devkit/core": "20.3.41", - "@angular-devkit/schematics": "20.3.41", "@angular/build": "20.3.41", "@angular/cli": "20.3.41", "@angular/compiler-cli": "20.3.34", - "@angular/language-service": "20.3.34", "@cyclonedx/cyclonedx-library": "10.3.0", + "@eslint/js": "9.39.5", "@types/ace-diff": "^2.1.4", "@types/canvas-gauges": "^2.1.8", "@types/flot": "^0.0.36", @@ -141,24 +141,19 @@ "autoprefixer": "^10.6.1", "directory-tree": "^3.6.0", "eslint": "9.39.5", - "eslint-plugin-import": "^2.32.0", - "eslint-plugin-jsdoc": "^62.9.0", - "eslint-plugin-prefer-arrow": "^1.2.3", "eslint-plugin-tailwindcss": "^3.18.3", "normalize-package-data": "8.0.0", "packageurl-js": "2.0.1", "patch-package": "^8.0.1", "postcss": "^8.5.31", - "postinstall-prepare": "^2.0.0", "spdx-expression-parse": "4.0.0", "tailwindcss": "^3.4.19", - "ts-node": "^10.9.2", "typescript": "~5.9.3", "typescript-eslint": "^8.72.0" }, "resolutions": { "esbuild": "0.28.1", "rollup": "4.59.0", - "js-beautify/**/minimatch": "^9.0.7" + "@angular/cli/**/tar": "^8.0.5" } } diff --git a/ui-ngx/pom.xml b/ui-ngx/pom.xml index aa9013d9b6..7ca54393be 100644 --- a/ui-ngx/pom.xml +++ b/ui-ngx/pom.xml @@ -10,7 +10,7 @@ 4.0.0 org.thingsboard - 4.4.1-SNAPSHOT + 4.4.2-SNAPSHOT thingsboard ui-ngx @@ -57,7 +57,7 @@ install-node-and-yarn - v22.23.4 + v22.23.5 v1.22.22 diff --git a/ui-ngx/src/app/core/auth/auth.actions.ts b/ui-ngx/src/app/core/auth/auth.actions.ts index 328f2e06da..5a1778c63f 100644 --- a/ui-ngx/src/app/core/auth/auth.actions.ts +++ b/ui-ngx/src/app/core/auth/auth.actions.ts @@ -4,7 +4,7 @@ import { Action } from '@ngrx/store'; import { AuthUser, User } from '@shared/models/user.model'; import { AuthPayload } from '@core/auth/auth.models'; -import { UserSettings } from '@shared/models/user-settings.models'; +import { AiTourStep, HomeCardsSettings, UserSettings } from '@shared/models/user-settings.models'; export enum AuthActionTypes { AUTHENTICATED = '[Auth] Authenticated', @@ -16,6 +16,8 @@ export enum AuthActionTypes { UPDATE_HAS_REPOSITORY = '[Auth] Change Has Repository', UPDATE_MOBILE_QR_ENABLED = '[Auth] Update Mobile QR Enabled', UPDATE_OPENED_MENU_SECTION = '[Preferences] Update Opened Menu Section', + UPDATE_AI_TOUR = '[Preferences] Update AI tour', + UPDATE_HOME_CARDS = '[Preferences] Update home cards', PUT_USER_SETTINGS = '[Preferences] Put user settings', DELETE_USER_SETTINGS = '[Preferences] Delete user settings', UPDATE_LICENSE_PARAMS = '[Auth] Update License Parameters', @@ -73,6 +75,18 @@ export class ActionPreferencesUpdateOpenedMenuSection implements Action { constructor(readonly payload: { path: string; opened: boolean }) {} } +export class ActionPreferencesUpdateAiTour implements Action { + readonly type = AuthActionTypes.UPDATE_AI_TOUR; + + constructor(readonly payload: { step: AiTourStep; seen: boolean }) {} +} + +export class ActionPreferencesUpdateHomeCards implements Action { + readonly type = AuthActionTypes.UPDATE_HOME_CARDS; + + constructor(readonly payload: HomeCardsSettings) {} +} + export class ActionPreferencesPutUserSettings implements Action { readonly type = AuthActionTypes.PUT_USER_SETTINGS; @@ -93,5 +107,5 @@ export class ActionUpdateLicenseParams implements Action { export type AuthActions = ActionAuthAuthenticated | ActionAuthUnauthenticated | ActionAuthLoadUser | ActionAuthUpdateUserDetails | ActionAuthUpdateLastPublicDashboardId | ActionAuthUpdateHasRepository | - ActionPreferencesUpdateOpenedMenuSection | ActionPreferencesPutUserSettings | ActionPreferencesDeleteUserSettings | + ActionPreferencesUpdateOpenedMenuSection | ActionPreferencesUpdateAiTour | ActionPreferencesUpdateHomeCards | ActionPreferencesPutUserSettings | ActionPreferencesDeleteUserSettings | ActionAuthUpdateAuthUser | ActionUpdateMobileQrCodeEnabled | ActionUpdateLicenseParams; diff --git a/ui-ngx/src/app/core/auth/auth.effects.ts b/ui-ngx/src/app/core/auth/auth.effects.ts index 1b006fd4f1..49812fc732 100644 --- a/ui-ngx/src/app/core/auth/auth.effects.ts +++ b/ui-ngx/src/app/core/auth/auth.effects.ts @@ -1,11 +1,12 @@ // SPDX-FileCopyrightText: Copyright The ThingsBoard Authors -// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Modifications Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: Apache-2.0 AND BUSL-1.1 import { Injectable } from '@angular/core'; import { Actions, createEffect, ofType } from '@ngrx/effects'; import { select, Store } from '@ngrx/store'; import { AppState } from '@core/core.state'; import { UserSettingsService } from '@core/http/user-settings.service'; -import { mergeMap, withLatestFrom } from 'rxjs/operators'; +import { concatMap, mergeMap, withLatestFrom } from 'rxjs/operators'; import { AuthActions, AuthActionTypes } from '@core/auth/auth.actions'; import { selectAuthState } from '@core/auth/auth.selectors'; @@ -26,6 +27,22 @@ export class AuthEffects { mergeMap(([action, state]) => this.userSettingsService.putUserSettings({ openedMenuSections: state.userSettings.openedMenuSections })) ), {dispatch: false}); + persistAiTour = createEffect(() => this.actions$.pipe( + ofType( + AuthActionTypes.UPDATE_AI_TOUR, + ), + withLatestFrom(this.store.pipe(select(selectAuthState))), + concatMap(([action, state]) => this.userSettingsService.putUserSettings({ aiTour: state.userSettings.aiTour ?? {} })) + ), {dispatch: false}); + + persistHomeCards = createEffect(() => this.actions$.pipe( + ofType( + AuthActionTypes.UPDATE_HOME_CARDS, + ), + withLatestFrom(this.store.pipe(select(selectAuthState))), + concatMap(([action, state]) => this.userSettingsService.putUserSettings({ homeCards: state.userSettings.homeCards ?? {} })) + ), {dispatch: false}); + putUserSettings = createEffect(() => this.actions$.pipe( ofType( AuthActionTypes.PUT_USER_SETTINGS, diff --git a/ui-ngx/src/app/core/auth/auth.reducer.ts b/ui-ngx/src/app/core/auth/auth.reducer.ts index 8fa0d1d2ac..9643135e4b 100644 --- a/ui-ngx/src/app/core/auth/auth.reducer.ts +++ b/ui-ngx/src/app/core/auth/auth.reducer.ts @@ -97,6 +97,20 @@ export const authReducer = ( userSettings = {...state.userSettings, ...{ openedMenuSections: Array.from(openedMenuSections)}}; return { ...state, ...{ userSettings }}; + case AuthActionTypes.UPDATE_AI_TOUR: + const aiTour = {...state.userSettings.aiTour}; + if (action.payload.seen) { + aiTour[action.payload.step] = Date.now(); + } else { + delete aiTour[action.payload.step]; + } + userSettings = {...state.userSettings, aiTour}; + return { ...state, ...{ userSettings }}; + + case AuthActionTypes.UPDATE_HOME_CARDS: + userSettings = {...state.userSettings, homeCards: {...state.userSettings.homeCards, ...action.payload}}; + return { ...state, ...{ userSettings }}; + case AuthActionTypes.PUT_USER_SETTINGS: userSettings = {...state.userSettings, ...action.payload}; return { ...state, ...{ userSettings }}; diff --git a/ui-ngx/src/app/core/auth/auth.selectors.ts b/ui-ngx/src/app/core/auth/auth.selectors.ts index 399fe27183..a0e9f57483 100644 --- a/ui-ngx/src/app/core/auth/auth.selectors.ts +++ b/ui-ngx/src/app/core/auth/auth.selectors.ts @@ -1,12 +1,13 @@ // SPDX-FileCopyrightText: Copyright The ThingsBoard Authors -// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Modifications Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: Apache-2.0 AND BUSL-1.1 import { createFeatureSelector, createSelector, select, Store } from '@ngrx/store'; import { AppState } from '../core.state'; import { AuthState } from './auth.models'; import { take } from 'rxjs/operators'; import { AuthUser } from '@shared/models/user.model'; -import { UserSettings } from '@shared/models/user-settings.models'; +import { AiTourStep, UserSettings } from '@shared/models/user-settings.models'; import { getDescendantProp } from '@core/utils'; export const selectAuthState = createFeatureSelector< AuthState>( @@ -69,12 +70,6 @@ export const selectMobileQrEnabled = createSelector( (state: AuthState) => state.mobileQrEnabled ); -export const selectHomeDashboardParams = createSelector( - selectPersistDeviceStateToTelemetry, - selectMobileQrEnabled, - (persistDeviceStateToTelemetry, mobileQrEnabled) => ({persistDeviceStateToTelemetry, mobileQrEnabled}) -); - export const selectUserSettings = createSelector( selectAuthState, (state: AuthState) => state.userSettings @@ -90,6 +85,20 @@ export const selectOpenedMenuSections = createSelector( (state: AuthState) => state.userSettings.openedMenuSections ); +export const selectAiTour = createSelector( + selectAuthState, + (state: AuthState) => state.userSettings?.aiTour ?? {} +); + +export const selectAiTourStepSeen = (step: AiTourStep) => createSelector( + selectAiTour, + aiTour => !!aiTour[step] +); + +export const selectHomeCards = createSelector( + selectAuthState, + (state: AuthState) => state.userSettings?.homeCards ?? {} +); export const getCurrentAuthState = (store: Store): AuthState => { let state: AuthState; diff --git a/ui-ngx/src/app/core/auth/auth.service.ts b/ui-ngx/src/app/core/auth/auth.service.ts index edd852247c..1c4c57431e 100644 --- a/ui-ngx/src/app/core/auth/auth.service.ts +++ b/ui-ngx/src/app/core/auth/auth.service.ts @@ -10,7 +10,7 @@ import { catchError, map, mergeMap, tap } from 'rxjs/operators'; import { setEdqsEnabled, setNullsOrderStrategy } from '@shared/models/page/page-link'; import { LoginRequest, LoginResponse, PublicLoginRequest } from '@shared/models/login.models'; -import { Router, UrlTree } from '@angular/router'; +import { PRIMARY_OUTLET, Router, UrlTree } from '@angular/router'; import { defaultHttpOptions, defaultHttpOptionsFromConfig, RequestConfig } from '../http/http-utils'; import { UserService } from '../http/user.service'; import { Store } from '@ngrx/store'; @@ -281,24 +281,12 @@ export class AuthService { } else if (authState.authUser.authority === Authority.MFA_CONFIGURATION_TOKEN) { result = this.router.parseUrl('login/force-mfa'); } else if (!path || path === 'login' || this.forceDefaultPlace(authState, path, params)) { - if (this.redirectUrl) { - const redirectUrl = this.redirectUrl; - this.redirectUrl = null; + const redirectUrl = this.redirectUrl; + this.redirectUrl = null; + if (redirectUrl && !authState.authUser.isPublic && this.isDeepLink(redirectUrl)) { result = this.router.parseUrl(redirectUrl); } else { - result = this.router.parseUrl('home'); - } - if (authState.authUser.authority === Authority.TENANT_ADMIN || authState.authUser.authority === Authority.CUSTOMER_USER) { - if (this.userHasDefaultDashboard(authState)) { - const dashboardId = authState.userDetails.additionalInfo.defaultDashboardId; - if (authState.forceFullscreen) { - result = this.router.parseUrl(`dashboard/${dashboardId}`); - } else { - result = this.router.parseUrl(`dashboards/${dashboardId}`); - } - } else if (authState.authUser.isPublic && authState.lastPublicDashboardId) { - result = this.router.parseUrl(`dashboard/${authState.lastPublicDashboardId}`); - } + result = this.defaultPlaceUrl(authState); } } } else { @@ -339,6 +327,23 @@ export class AuthService { })); } + private defaultPlaceUrl(authState: AuthState): UrlTree { + if (authState.authUser.authority === Authority.TENANT_ADMIN || authState.authUser.authority === Authority.CUSTOMER_USER) { + if (this.userHasDefaultDashboard(authState)) { + const dashboardId = authState.userDetails.additionalInfo.defaultDashboardId; + return this.router.parseUrl(authState.forceFullscreen ? `dashboard/${dashboardId}` : `dashboards/${dashboardId}`); + } else if (authState.authUser.isPublic && authState.lastPublicDashboardId) { + return this.router.parseUrl(`dashboard/${authState.lastPublicDashboardId}`); + } + } + return this.router.parseUrl('home'); + } + + private isDeepLink(url: string): boolean { + const segments = this.router.parseUrl(url).root.children[PRIMARY_OUTLET]?.segments.map(segment => segment.path) ?? []; + return segments.length > 0 && segments[0] !== 'login' && !(segments.length === 1 && segments[0] === 'home'); + } + private loadUser(doTokenRefresh): Observable { const authUser = getCurrentAuthUser(this.store); if (!authUser) { diff --git a/ui-ngx/src/app/core/http/admin.service.ts b/ui-ngx/src/app/core/http/admin.service.ts index 8f76ee61c7..77591e5d29 100644 --- a/ui-ngx/src/app/core/http/admin.service.ts +++ b/ui-ngx/src/app/core/http/admin.service.ts @@ -10,7 +10,6 @@ import { AutoCommitSettings, FeaturesInfo, JwtSettings, - LicenseUsageInfo, MailConfigTemplate, MailServerSettings, RepositorySettings, @@ -128,10 +127,6 @@ export class AdminService { return this.http.get('/api/admin/featuresInfo', defaultHttpOptionsFromConfig(config)); } - public getLicenseUsageInfo(config?: RequestConfig): Observable { - return this.http.get('/api/admin/licenseUsageInfo', defaultHttpOptionsFromConfig(config)); - } - public getSubscriptionInfo(config?: RequestConfig): Observable { return this.http.get('/api/admin/subscriptionInfo', defaultHttpOptionsFromConfig(config)); } diff --git a/ui-ngx/src/app/core/http/ai-chat.service.ts b/ui-ngx/src/app/core/http/ai-chat.service.ts index 76b343c072..3a91763c7f 100644 --- a/ui-ngx/src/app/core/http/ai-chat.service.ts +++ b/ui-ngx/src/app/core/http/ai-chat.service.ts @@ -7,6 +7,7 @@ import { HttpClient, HttpEventType } from '@angular/common/http'; import { ApprovalResult, ChatConfiguration, + ChatUpdate, ChatEvent, ChatInfo, SendChatMessageRequest, @@ -29,11 +30,15 @@ export class AiChatService { return this.http.get>(`/api/ai/chats`, defaultHttpOptionsFromConfig(config)) } + public listChatStatuses(config?: RequestConfig): Observable> { + return this.http.get>(`/api/ai/chats/status`, defaultHttpOptionsFromConfig(config)); + } + public createChat(chat: ChatConfiguration, config?: RequestConfig): Observable { return this.http.post(`/api/ai/chats`, chat, defaultHttpOptionsFromConfig(config)); } - public updatedChat(chatId: string, chat: ChatConfiguration, config?: RequestConfig): Observable { + public updatedChat(chatId: string, chat: ChatUpdate, config?: RequestConfig): Observable { return this.http.patch(`/api/ai/chats/${chatId}`, chat, defaultHttpOptionsFromConfig(config)); } @@ -45,10 +50,6 @@ export class AiChatService { return this.http.get>(`/api/ai/chats/${chatId}/messages`, defaultHttpOptionsFromConfig(config)) } - public generateDashboard(deviceId: string, timeseriesKeys?: string[], config?: RequestConfig): Observable { - return this.http.post(`/api/ai/devices/${deviceId}/dashboard`, { timeseriesKeys }, defaultHttpOptionsFromConfig(config)); - } - public resolveToolApproval(result: ApprovalResult, config?: RequestConfig): Observable { return this.http.post('/api/ai/tools/resolve-approval', result, defaultHttpOptionsFromConfig(config)) } @@ -57,6 +58,10 @@ export class AiChatService { return this.streamEvents(`/api/ai/chats/${chatId}/messages`, request, config); } + public stopChat(chatId: string, config?: RequestConfig): Observable { + return this.http.post(`/api/ai/chats/${chatId}/stop`, null, defaultHttpOptionsFromConfig(config)); + } + /** * Follows the reply still running in the chat: a 'turnResumed' event, every event of the reply so far, then the * live ones. Completes with no events when nothing is running. @@ -110,6 +115,9 @@ export class AiChatService { const result: Partial = {}; const lines = input.trim().split('\n'); + if (lines.every(line => !line.trim() || line.trim().startsWith(':'))) { + return null; + } for (const line of lines) { const trimmedLine = line.trim(); diff --git a/ui-ngx/src/app/core/http/custom-menu.service.ts b/ui-ngx/src/app/core/http/custom-menu.service.ts index 7c896934e2..92ad715dd6 100644 --- a/ui-ngx/src/app/core/http/custom-menu.service.ts +++ b/ui-ngx/src/app/core/http/custom-menu.service.ts @@ -7,7 +7,8 @@ import { CustomMenu, CustomMenuConfig, CustomMenuDeleteResult, - CustomMenuInfo + CustomMenuInfo, + withCurrentMenuIds } from '@shared/models/custom-menu.models'; import { mergeMap, Observable, of, Subject } from 'rxjs'; import { map, tap } from 'rxjs/operators'; @@ -38,6 +39,7 @@ export class CustomMenuService { public loadCustomMenu(notify = false): Observable { return this.http.get('/api/customMenu') .pipe( + map(customMenuConfig => withCurrentMenuIds(customMenuConfig)), tap((customMenuConfig) => { this.customMenuConfig = customMenuConfig; if (notify) { diff --git a/ui-ngx/src/app/core/http/dashboard.service.ts b/ui-ngx/src/app/core/http/dashboard.service.ts index 15c2501a76..30608a5b75 100644 --- a/ui-ngx/src/app/core/http/dashboard.service.ts +++ b/ui-ngx/src/app/core/http/dashboard.service.ts @@ -60,7 +60,7 @@ export class DashboardService { } public getUserDashboards(userId: string, operation: Operation, - pageLink: PageLink, config?: RequestConfig): Observable> { + pageLink: PageLink, config?: RequestConfig, mobile = false): Observable> { let url = `/api/user/dashboards${pageLink.toQuery()}`; if (userId) { url += `&userId=${userId}`; @@ -68,6 +68,9 @@ export class DashboardService { if (operation) { url += `&operation=${operation}`; } + if (mobile) { + url += `&mobile=true`; + } return this.http.get>(url, defaultHttpOptionsFromConfig(config)); } diff --git a/ui-ngx/src/app/core/http/notification.service.ts b/ui-ngx/src/app/core/http/notification.service.ts index 42e831e2fd..ecd6ed315e 100644 --- a/ui-ngx/src/app/core/http/notification.service.ts +++ b/ui-ngx/src/app/core/http/notification.service.ts @@ -66,6 +66,10 @@ export class NotificationService { return this.http.post(`/api/notification/sendAddonAccessRequest/${addonType}`, null, defaultHttpOptionsFromConfig(config)); } + public sendAiCreditsLimitIncreaseRequest(limitType: 'TENANT' | 'POOL', config?: RequestConfig): Observable { + return this.http.post(`/api/notification/aiCreditsLimitIncreaseRequest?limitType=${limitType}`, null, defaultHttpOptionsFromConfig(config)); + } + public sendPlanUpgradeRequest(planName: string, config?: RequestConfig): Observable { return this.http.post(`/api/notification/sendPlanUpgradeRequest/${planName}`, null, defaultHttpOptionsFromConfig(config)); } diff --git a/ui-ngx/src/app/core/http/solutions-creator.service.ts b/ui-ngx/src/app/core/http/solutions-creator.service.ts index 2cfc4b2bb2..4cd06c68e3 100644 --- a/ui-ngx/src/app/core/http/solutions-creator.service.ts +++ b/ui-ngx/src/app/core/http/solutions-creator.service.ts @@ -9,8 +9,10 @@ import { SolutionDataKey, SolutionDataValues, SolutionInfo, + SolutionInstallProgress, SolutionInstallResult, - SolutionStep + SolutionStep, + SolutionUpdateRequest } from '@shared/models/solution-creator.models'; @Injectable({ @@ -35,6 +37,10 @@ export class SolutionsCreatorService { return this.http.delete(`/api/ai/solution/${solutionId}/${step}/clear`, defaultHttpOptionsFromConfig(config)); } + public stopSolution(solutionId: string, config?: RequestConfig): Observable { + return this.http.post(`/api/ai/solution/${solutionId}/stop`, null, defaultHttpOptionsFromConfig(config)); + } + public createSolution(solutionId: string, config?: RequestConfig): Observable { return this.http.post(`/api/ai/solution/${solutionId}/create`, '', defaultHttpOptionsFromConfig(config)); } @@ -64,4 +70,12 @@ export class SolutionsCreatorService { public deleteSolution(solutionId: string, config?: RequestConfig): Observable { return this.http.delete(`/api/ai/solution/${solutionId}`, defaultHttpOptionsFromConfig(config)); } + + public updateSolution(solutionId: string, request: SolutionUpdateRequest, config?: RequestConfig): Observable { + return this.http.post(`/api/ai/solution/${solutionId}/update`, request, defaultHttpOptionsFromConfig(config)); + } + + public getInstallProgress(solutionId: string, config?: RequestConfig): Observable { + return this.http.get(`/api/ai/solution/${solutionId}/progress`, defaultHttpOptionsFromConfig(config)); + } } diff --git a/ui-ngx/src/app/core/http/user-permissions.service.ts b/ui-ngx/src/app/core/http/user-permissions.service.ts index 71f952154d..2c93cedd4e 100644 --- a/ui-ngx/src/app/core/http/user-permissions.service.ts +++ b/ui-ngx/src/app/core/http/user-permissions.service.ts @@ -1,9 +1,10 @@ // SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. // SPDX-License-Identifier: BUSL-1.1 -import { Injectable } from '@angular/core'; +import { inject, Injectable } from '@angular/core'; +import { toSignal } from '@angular/core/rxjs-interop'; import { HttpClient } from '@angular/common/http'; import { Observable } from 'rxjs'; -import { tap } from 'rxjs/operators'; +import { distinctUntilChanged, map, tap } from 'rxjs/operators'; import { AllowedPermissionsInfo, groupResourceByGroupType, @@ -19,7 +20,10 @@ import { isArray } from '@core/utils'; import { defaultHttpOptionsFromConfig, RequestConfig } from '@core/http/http-utils'; import { Store } from '@ngrx/store'; import { AppState } from '@core/core.state'; -import { getCurrentAuthState } from '@core/auth/auth.selectors'; +import { getCurrentAuthState, selectAuth } from '@core/auth/auth.selectors'; +import { Authority } from '@shared/models/authority.enum'; + +const AI_RESOURCES: Resource[] = [Resource.AI, Resource.AI_MODEL]; @Injectable({ providedIn: 'root' @@ -34,6 +38,11 @@ export class UserPermissionsService { private userPermissions: MergedUserPermissions; private userOwnerId: EntityId; + readonly aiAvailable = toSignal(inject(Store).select(selectAuth).pipe( + map(() => this.isAiAvailable()), + distinctUntilChanged() + ), {initialValue: false}); + constructor( private http: HttpClient, private store: Store @@ -122,15 +131,42 @@ export class UserPermissionsService { } } + public hasGenericPermissionExceptAi(operation: Operation): boolean { + if (!this.userPermissions) { + return false; + } + if (this.hasGenericAllPermission(Resource.ALL, operation)) { + return true; + } + return Object.keys(this.operationsByResource ?? {}) + .filter(resource => resource !== Resource.ALL && !AI_RESOURCES.includes(resource as Resource)) + .every(resource => this.hasEveryOperation(resource as Resource, operation)); + } + + private hasEveryOperation(resource: Resource, operation: Operation): boolean { + const valid = this.operationsByResource[resource] ?? []; + if (operation !== Operation.ALL) { + return !valid.includes(operation) || this.hasGenericResourcePermission(resource, operation); + } + const required = valid.filter(op => op !== Operation.ALL); + return required.length ? required.every(op => this.hasGenericResourcePermission(resource, op)) + : this.hasGenericResourcePermission(resource, Operation.ALL); + } + public isAiEnabled(): boolean { return getCurrentAuthState(this.store).aiEnabled; } + public isAiAvailable(operation: Operation = Operation.ALL): boolean { + const authState = getCurrentAuthState(this.store); + return !!authState?.aiEnabled && authState.authUser?.authority === Authority.TENANT_ADMIN + && this.hasGenericPermission(Resource.AI, operation); + } + private isResourceAllowed(resource: Resource): boolean { return !this.allowedResources || this.allowedResources.indexOf(resource) > -1; } - public hasGenericPermissionByEntityGroupType(operation: Operation, groupType: EntityType): boolean { if (!groupType) { return false; diff --git a/ui-ngx/src/app/core/interceptors/global-http-interceptor.ts b/ui-ngx/src/app/core/interceptors/global-http-interceptor.ts index 23db865351..0ae54e2121 100644 --- a/ui-ngx/src/app/core/interceptors/global-http-interceptor.ts +++ b/ui-ngx/src/app/core/interceptors/global-http-interceptor.ts @@ -1,18 +1,18 @@ // SPDX-FileCopyrightText: Copyright The ThingsBoard Authors // SPDX-FileCopyrightText: Modifications Copyright ThingsBoard, Inc. // SPDX-License-Identifier: Apache-2.0 AND BUSL-1.1 -import { HttpErrorResponse, HttpEvent, HttpHandler, HttpInterceptor, HttpRequest } from '@angular/common/http'; +import { HttpErrorResponse, HttpEvent, HttpEventType, HttpHandler, HttpInterceptor, HttpRequest } from '@angular/common/http'; import { Observable } from 'rxjs/internal/Observable'; import { DOCUMENT, Inject, Injectable } from '@angular/core'; import { AuthService } from '@core/auth/auth.service'; import { Constants } from '@shared/models/constants'; -import { catchError, delay, finalize, mergeMap, switchMap } from 'rxjs/operators'; +import { catchError, delay, finalize, mergeMap, switchMap, tap } from 'rxjs/operators'; import { of, throwError } from 'rxjs'; import { InterceptorConfig } from './interceptor-config'; import { Store } from '@ngrx/store'; import { AppState } from '@core/core.state'; import { ActionLoadFinish, ActionLoadStart } from './load.actions'; -import { ActionNotificationShow } from '@app/core/notification/notification.actions'; +import { ActionNotificationHide, ActionNotificationShow } from '@app/core/notification/notification.actions'; import { DialogService } from '@core/services/dialog.service'; import { TranslateService } from '@ngx-translate/core'; import { parseHttpErrorMessage } from '@core/utils'; @@ -23,6 +23,8 @@ import { isSetupIncompleteError } from '@shared/models/system-setup.models'; const tmpHeaders = {}; +const CONNECTION_ERROR = 'Unable to connect'; + @Injectable() export class GlobalHttpInterceptor implements HttpInterceptor { @@ -31,6 +33,8 @@ export class GlobalHttpInterceptor implements HttpInterceptor { private activeRequests = 0; + private connectionErrorShown = false; + constructor( private store: Store, private dialogService: DialogService, @@ -39,7 +43,9 @@ export class GlobalHttpInterceptor implements HttpInterceptor { private sanitizer: DomSanitizer, private systemSetupService: SystemSetupService, @Inject(DOCUMENT) private document: Document - ) {} + ) { + this.document.defaultView?.addEventListener('online', () => this.connectionRestored()); + } intercept(req: HttpRequest, next: HttpHandler): Observable> { if (req.url.startsWith('/api/')) { @@ -80,6 +86,11 @@ export class GlobalHttpInterceptor implements HttpInterceptor { private handleRequest(req: HttpRequest, next: HttpHandler): Observable> { return next.handle(req).pipe( + tap(event => { + if (event.type === HttpEventType.ResponseHeader || event.type === HttpEventType.Response) { + this.connectionRestored(); + } + }), catchError((err) => { const errorResponse = err as HttpErrorResponse; return this.handleResponseError(req, next, errorResponse); @@ -92,6 +103,9 @@ export class GlobalHttpInterceptor implements HttpInterceptor { const ignoreErrors = config.ignoreErrors; const resendRequest = config.resendRequest; const errorCode = errorResponse.error ? errorResponse.error.errorCode : null; + if (errorResponse.status > 0) { + this.connectionRestored(); + } if (errorResponse.error && errorResponse.error.refreshTokenPending || errorResponse.status === 401 && req.url !== Constants.entryPoints.tokenRefresh) { if (errorResponse.error && errorResponse.error.refreshTokenPending || @@ -122,7 +136,8 @@ export class GlobalHttpInterceptor implements HttpInterceptor { this.handleLock(errorResponse.error); } else if (errorResponse.status === 0 || errorResponse.status === -1) { if (!ignoreErrors) { - this.showError('Unable to connect'); + this.connectionErrorShown = true; + this.showError(CONNECTION_ERROR); } } else if (!(req.url.startsWith('/api/rpc') || req.url.startsWith('/api/plugins/rpc'))) { if (errorResponse.status === 404) { @@ -218,6 +233,13 @@ export class GlobalHttpInterceptor implements HttpInterceptor { } } + private connectionRestored(): void { + if (this.connectionErrorShown) { + this.connectionErrorShown = false; + this.store.dispatch(new ActionNotificationHide({message: CONNECTION_ERROR})); + } + } + private showError(error: string, timeout: number = 0) { setTimeout(() => { this.store.dispatch(new ActionNotificationShow({message: error, type: 'error'})); diff --git a/ui-ngx/src/app/core/local-storage/stored.ts b/ui-ngx/src/app/core/local-storage/stored.ts new file mode 100644 index 0000000000..8638c04710 --- /dev/null +++ b/ui-ngx/src/app/core/local-storage/stored.ts @@ -0,0 +1,21 @@ +// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: BUSL-1.1 +export function readStored(key: string): string | null { + try { + return localStorage.getItem(key); + } catch { + return null; + } +} + +export function writeStored(key: string, value: string | null): void { + try { + if (value === null) { + localStorage.removeItem(key); + } else { + localStorage.setItem(key, value); + } + } catch { + return; + } +} diff --git a/ui-ngx/src/app/core/notification/notification.models.ts b/ui-ngx/src/app/core/notification/notification.models.ts index cd8428cd75..33d870fa23 100644 --- a/ui-ngx/src/app/core/notification/notification.models.ts +++ b/ui-ngx/src/app/core/notification/notification.models.ts @@ -1,5 +1,6 @@ // SPDX-FileCopyrightText: Copyright The ThingsBoard Authors -// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Modifications Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: Apache-2.0 AND BUSL-1.1 export interface NotificationState { notification: NotificationMessage; hideNotification: HideNotification; @@ -19,8 +20,11 @@ export class NotificationMessage { verticalPosition?: NotificationVerticalPosition; panelClass?: string | string[]; modern?: boolean; + actionLabel?: string; + onAction?: () => void; } export class HideNotification { target?: string; + message?: string; } diff --git a/ui-ngx/src/app/core/services/ai-assistant-config.service.ts b/ui-ngx/src/app/core/services/ai-assistant-config.service.ts new file mode 100644 index 0000000000..6f6f32d6f0 --- /dev/null +++ b/ui-ngx/src/app/core/services/ai-assistant-config.service.ts @@ -0,0 +1,36 @@ +// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: BUSL-1.1 +import { inject, Injectable } from '@angular/core'; +import { TranslateService } from '@ngx-translate/core'; +import { UserPermissionsService } from '@core/http/user-permissions.service'; +import { AiAssistantPanelConfig, AiAssistantViewType } from '@shared/models/ai-chat.models'; +import { EntityId } from '@shared/models/id/entity-id'; +import { HeaderActionDescriptor } from '@home/models/entity/entities-table-config.models'; + +@Injectable({ + providedIn: 'root' +}) +export class AiAssistantConfigService { + + private userPermissionsService = inject(UserPermissionsService); + private translate = inject(TranslateService); + + configureAction(onAction: ($event: MouseEvent) => void): HeaderActionDescriptor[] { + return this.userPermissionsService.isAiAvailable() ? [{ + name: this.translate.instant('ai-assistant.configure-with-ai'), + icon: 'mdi:creation', + isEnabled: () => true, + onAction + }] : []; + } + + tableConfig(listView: AiAssistantViewType, entityView?: AiAssistantViewType, listEntityId?: EntityId): AiAssistantPanelConfig | null { + if (!this.userPermissionsService.isAiAvailable()) { + return null; + } + return { + view: {listView, entityView, listEntityId}, + initialPromptPlaceholder: this.translate.instant('ai-assistant.welcome.placeholder') + }; + } +} diff --git a/ui-ngx/src/app/core/services/ai-assistant-panel.service.ts b/ui-ngx/src/app/core/services/ai-assistant-panel.service.ts index efbd13bed0..4e39d0b71d 100644 --- a/ui-ngx/src/app/core/services/ai-assistant-panel.service.ts +++ b/ui-ngx/src/app/core/services/ai-assistant-panel.service.ts @@ -1,16 +1,11 @@ // SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. // SPDX-License-Identifier: BUSL-1.1 -import { computed, DestroyRef, inject, Injectable, OnDestroy, signal } from '@angular/core'; -import { Subject } from 'rxjs'; -import { distinctUntilChanged, map } from 'rxjs/operators'; +import { computed, DestroyRef, effect, inject, Injectable, OnDestroy, signal } from '@angular/core'; +import { defer, Observable, Subject } from 'rxjs'; +import { buffer, debounceTime, distinctUntilChanged, filter, finalize, map } from 'rxjs/operators'; +import { NavigationEnd, NavigationStart, Router } from '@angular/router'; import { takeUntilDestroyed } from '@angular/core/rxjs-interop'; -import { - AiAssistantPanelConfig, - AiAssistantViewType, - AiChatClientContext, - AiChatView, - ChatInfo -} from '@shared/models/ai-chat.models'; +import { AiAssistantPanelConfig, AiAssistantViewType, AiChatClientContext, aiClientOs, AiChatView, AiPromptMessage } from '@shared/models/ai-chat.models'; import { EntityId } from '@shared/models/id/entity-id'; import { getDefaultTimezone } from '@shared/models/time/time.models'; import { LocalStorageService } from '@core/local-storage/local-storage.service'; @@ -18,12 +13,35 @@ import { Store } from '@ngrx/store'; import { AppState } from '@core/core.state'; import { selectAuthUser } from '@core/auth/auth.selectors'; +export interface AiCustomizationSaved { + kind: 'MAIL_TEMPLATES' | 'TRANSLATION' | 'MENU' | 'MOBILE_QR_CODE' | 'TWO_FACTOR' | 'PROFILE' | 'ACCOUNT_SECURITY' | 'ACCOUNT_NOTIFICATIONS' | 'MAIL_SERVER'; + locale?: string; + menuId?: string; + deleted?: boolean; +} + @Injectable({ providedIn: 'root' }) export class AiAssistantPanelService implements OnDestroy { - private _open = signal(false); + private _editorDraftProvider: (() => unknown | null) | null = null; + + private static readonly WITHOUT_PANEL = ['/home', '/ai-assistant']; + + private static readonly OPEN_KEY = 'tb-ai-panel-open'; + private static readonly RELOAD_DEBOUNCE_MS = 1000; + private static readonly CHATS_KEY = 'tb-ai-panel-chats'; + + private _open = signal(AiAssistantPanelService.readSession(AiAssistantPanelService.OPEN_KEY) === 'true'); readonly open = this._open.asReadonly(); + private openSync = effect(() => AiAssistantPanelService.writeSession(AiAssistantPanelService.OPEN_KEY, this._open() ? 'true' : null)); + + private _restored = signal(this._open()); + readonly restored = this._restored.asReadonly(); + + private _suppressed = signal(false); + readonly suppressed = this._suppressed.asReadonly(); + private _enabled = signal(false); readonly enabled = this._enabled.asReadonly(); @@ -38,110 +56,200 @@ export class AiAssistantPanelService implements OnDestroy { private _sentClientContextByChat = new Map(); - private _chats = signal(null); - readonly chats = this._chats.asReadonly(); - private _lastChatIdByContext = new Map(); + private _lastChatIdByContext = AiAssistantPanelService.readChats(); private static readonly AUTO_APPROVE_STORAGE_KEY = 'aiAssistantAutoApproveChats'; private localStorage = inject(LocalStorageService); private store = inject(Store); private destroyRef = inject(DestroyRef); + private router = inject(Router); + + private routeWatch = (() => { + this._suppressed.set(AiAssistantPanelService.withoutPanel(this.router.url)); + this.router.events.pipe( + filter((event): event is NavigationStart => event instanceof NavigationStart), + takeUntilDestroyed(this.destroyRef) + ).subscribe(event => { + const suppressed = AiAssistantPanelService.withoutPanel(event.url); + this._suppressed.set(suppressed); + if (suppressed) { + this._open.set(false); + } + }); + this.router.events.pipe( + filter((event): event is NavigationEnd => event instanceof NavigationEnd), + takeUntilDestroyed(this.destroyRef) + ).subscribe(event => { + const suppressed = AiAssistantPanelService.withoutPanel(event.urlAfterRedirects); + this._suppressed.set(suppressed); + if (suppressed && !AiAssistantPanelService.onAiPage(event.urlAfterRedirects)) { + this._composed.set(null); + } + const openHere = this._openOnArrival && !suppressed; + if (!suppressed) { + this._openOnArrival = false; + } + if (openHere) { + this._open.set(true); + } + }); + })(); + + private static readSession(key: string): string | null { + try { + return sessionStorage.getItem(key); + } catch { + return null; + } + } + + private static writeSession(key: string, value: string | null): void { + try { + if (value === null) { + sessionStorage.removeItem(key); + } else { + sessionStorage.setItem(key, value); + } + } catch { + return; + } + } + + private static readChats(): Map { + try { + const stored = JSON.parse(AiAssistantPanelService.readSession(AiAssistantPanelService.CHATS_KEY) ?? '{}'); + return new Map(Object.entries(stored).filter((entry): entry is [string, string] => typeof entry[1] === 'string')); + } catch { + return new Map(); + } + } + + private storeChats(): void { + AiAssistantPanelService.writeSession(AiAssistantPanelService.CHATS_KEY, + this._lastChatIdByContext.size ? JSON.stringify(Object.fromEntries(this._lastChatIdByContext)) : null); + } + + private static onAiPage(url: string): boolean { + const path = (url || '/').split(/[?#]/)[0]; + return path === '/ai-assistant' || path.startsWith('/ai-assistant/'); + } + + private static withoutPanel(url: string): boolean { + const path = (url || '/').split(/[?#]/)[0]; + return path === '/' || AiAssistantPanelService.WITHOUT_PANEL.some(page => path === page || path.startsWith(page + '/')); + } private _autoApproveUserId: string | null = null; - private _autoApproveChats = signal>(new Set()); private _autoApproveUserSync = this.store.select(selectAuthUser).pipe( map(user => user?.userId ?? null), distinctUntilChanged(), takeUntilDestroyed(this.destroyRef) ).subscribe(userId => { + if (this._autoApproveUserId !== null && userId !== this._autoApproveUserId) { + this.resetUserState(); + } this._autoApproveUserId = userId; - this._autoApproveChats.set(this.loadAutoApproveChats(userId)); }); + private resetUserState(): void { + this._open.set(false); + this._sentClientContextByChat.clear(); + this._lastChatIdByContext.clear(); + this._carried = null; + this._handOff = null; + this.storeChats(); + } + private _updatedData$ = new Subject>(); readonly updatedData$ = this._updatedData$.asObservable(); + readonly updatedDataBatches$: Observable> = this.updatedData$.pipe( + buffer(this.updatedData$.pipe(debounceTime(AiAssistantPanelService.RELOAD_DEBOUNCE_MS))), + map(batches => batches.flat()) + ); private _teardownTimer: NodeJS.Timeout; - toggle(): void { - if (!this._enabled()) { - return; - } - this._open.update(open => !open); - } + private static readonly CARRY_MS = 15000; + private _carried: {chatId: string; from: string | null; at: number} | null = null; - setChats(chats: ChatInfo[]): void { - this._chats.set(chats); - this.pruneAutoApproveChats(chats); - } + private static readonly FROM_AI_PAGE = 'ai-assistant-page'; + + private _openOnArrival = false; + + private _handOff: AiPromptMessage | null = null; - addChat(chat: ChatInfo): void { - this._chats.update(list => [chat, ...(list ?? [])]); + handOff(prompt: AiPromptMessage): void { + this._handOff = prompt; } - updateChatTitle(chatId: string, title: string): void { - this._chats.update(list => list?.map(c => c.id === chatId ? {...c, title} : c) ?? null); + takeHandOff(): AiPromptMessage | null { + const prompt = this._handOff; + this._handOff = null; + return prompt; } - removeChat(chatId: string): void { - this._chats.update(list => list?.filter(c => c.id !== chatId) ?? null); - this._sentClientContextByChat.delete(chatId); - for (const [key, id] of this._lastChatIdByContext) { - if (id === chatId) { - this._lastChatIdByContext.delete(key); - } - } - this.setAutoApprove(chatId, false); + carryChat(chatId: string): void { + this._carried = {chatId, from: this.contextKey(), at: Date.now()}; } - isAutoApprove(chatId: string | undefined): boolean { - return !!chatId && this._autoApproveChats().has(chatId); + carryChatToPage(chatId: string): void { + this._carried = {chatId, from: AiAssistantPanelService.FROM_AI_PAGE, at: Date.now()}; + this._openOnArrival = true; } - setAutoApprove(chatId: string, enabled: boolean): void { - this._autoApproveChats.update(chats => { - const next = new Set(chats); - if (enabled) { - next.add(chatId); - } else { - next.delete(chatId); - } - return next; - }); - this.persistAutoApproveChats(); + hasCarriedChat(): boolean { + return !!this._carried; } - private pruneAutoApproveChats(chats: ChatInfo[]): void { - const valid = new Set(chats.map(c => c.id)); - const current = this._autoApproveChats(); - const pruned = new Set([...current].filter(id => valid.has(id))); - if (pruned.size !== current.size) { - this._autoApproveChats.set(pruned); - this.persistAutoApproveChats(); + takeCarriedChat(): string | undefined { + const carried = this._carried; + const key = this.contextKey(); + const fromPage = carried?.from === AiAssistantPanelService.FROM_AI_PAGE; + if (!carried || (key === null && !fromPage) || key === carried.from) { + return undefined; + } + this._carried = null; + if (Date.now() - carried.at > AiAssistantPanelService.CARRY_MS) { + return undefined; + } + if (key !== null) { + this._lastChatIdByContext.set(key, carried.chatId); + this.storeChats(); } + return carried.chatId; } - private autoApproveStorageKey(userId: string | null): string { - return `${AiAssistantPanelService.AUTO_APPROVE_STORAGE_KEY}_${userId ?? 'anonymous'}`; + toggle(): void { + if (this._suppressed() && !this._open()) { + return; + } + this._restored.set(false); + this._open.update(open => !open); } - private loadAutoApproveChats(userId: string | null): Set { - try { - const ids = this.localStorage.getItem(this.autoApproveStorageKey(userId)); - return new Set(Array.isArray(ids) ? ids as string[] : []); - } catch { - return new Set(); + forgetChat(chatId: string): void { + this._sentClientContextByChat.delete(chatId); + for (const [key, id] of this._lastChatIdByContext) { + if (id === chatId) { + this._lastChatIdByContext.delete(key); + } } + this.storeChats(); } - private persistAutoApproveChats(): void { + takeStoredAutoApproveChats(): string[] { + const key = `${AiAssistantPanelService.AUTO_APPROVE_STORAGE_KEY}_${this._autoApproveUserId ?? 'anonymous'}`; try { - this.localStorage.setItem(this.autoApproveStorageKey(this._autoApproveUserId), [...this._autoApproveChats()]); + const ids = this.localStorage.getItem(key); + if (ids !== null) { + this.localStorage.removeItem(key); + } + return Array.isArray(ids) ? ids as string[] : []; } catch { - // ignore storage write errors (e.g. private mode quota) + return []; } } @@ -159,6 +267,7 @@ export class AiAssistantPanelService implements OnDestroy { case AiAssistantViewType.ALARM_RULE: case AiAssistantViewType.ALARM_RULE_LIST: case AiAssistantViewType.ALARM_LIST: + case AiAssistantViewType.ALARM: return 'ALARM_RULE'; case AiAssistantViewType.CALCULATED_FIELD: case AiAssistantViewType.CALCULATED_FIELD_LIST: @@ -169,17 +278,87 @@ export class AiAssistantPanelService implements OnDestroy { case AiAssistantViewType.DEVICE_GROUP: case AiAssistantViewType.DEVICE_GROUP_LIST: return 'DEVICE_GROUP'; + case AiAssistantViewType.ASSET: + case AiAssistantViewType.ASSET_LIST: + return 'ASSET'; + case AiAssistantViewType.ASSET_GROUP: + case AiAssistantViewType.ASSET_GROUP_LIST: + return 'ASSET_GROUP'; + case AiAssistantViewType.ENTITY_VIEW: + case AiAssistantViewType.ENTITY_VIEW_LIST: + return 'ENTITY_VIEW'; + case AiAssistantViewType.ENTITY_VIEW_GROUP: + case AiAssistantViewType.ENTITY_VIEW_GROUP_LIST: + return 'ENTITY_VIEW_GROUP'; + case AiAssistantViewType.DASHBOARD_GROUP: + case AiAssistantViewType.DASHBOARD_GROUP_LIST: + return 'DASHBOARD_GROUP'; + case AiAssistantViewType.DEVICE_PROFILE: + case AiAssistantViewType.DEVICE_PROFILE_LIST: + return 'DEVICE_PROFILE'; + case AiAssistantViewType.ASSET_PROFILE: + case AiAssistantViewType.ASSET_PROFILE_LIST: + return 'ASSET_PROFILE'; + case AiAssistantViewType.CUSTOMER: + case AiAssistantViewType.CUSTOMER_LIST: + return 'CUSTOMER'; + case AiAssistantViewType.USER: + case AiAssistantViewType.USER_LIST: + return 'USER'; + case AiAssistantViewType.RULE_CHAIN: + case AiAssistantViewType.RULE_CHAIN_LIST: + return 'RULE_CHAIN'; + case AiAssistantViewType.INTEGRATION: + case AiAssistantViewType.INTEGRATION_LIST: + return 'INTEGRATION'; + case AiAssistantViewType.CONVERTER: + case AiAssistantViewType.CONVERTER_LIST: + return 'CONVERTER'; case AiAssistantViewType.NOTIFICATION_INBOX: case AiAssistantViewType.SENT_NOTIFICATION_LIST: case AiAssistantViewType.NOTIFICATION_TEMPLATE_LIST: case AiAssistantViewType.NOTIFICATION_RECIPIENT_LIST: case AiAssistantViewType.NOTIFICATION_RULE_LIST: + case AiAssistantViewType.NOTIFICATION_TEMPLATE: + case AiAssistantViewType.NOTIFICATION_RULE: + case AiAssistantViewType.NOTIFICATION_RECIPIENT: return 'NOTIFICATION'; default: return view.type; } }); + private static readonly STARTED_KEY = 'tb-ai-panel-started'; + private static readonly STARTED_MAX = 20; + + private _startedByContext = signal>(AiAssistantPanelService.readStarted()); + + private static readStarted(): Record { + try { + const stored = JSON.parse(AiAssistantPanelService.readSession(AiAssistantPanelService.STARTED_KEY) ?? '{}'); + return stored && typeof stored === 'object' ? stored : {}; + } catch { + return {}; + } + } + + noteStartedHere(chatId: string): void { + const key = this.contextKey(); + if (!key) { + return; + } + this._startedByContext.update(started => { + const next = {...started, [key]: [chatId, ...(started[key] ?? []).filter(id => id !== chatId)].slice(0, AiAssistantPanelService.STARTED_MAX)}; + AiAssistantPanelService.writeSession(AiAssistantPanelService.STARTED_KEY, JSON.stringify(next)); + return next; + }); + } + + chatsStartedHere(): string[] { + const key = this.contextKey(); + return key ? this._startedByContext()[key] ?? [] : []; + } + setLastChatId(id: string | undefined): void { const key = this.contextKey(); if (!key) { @@ -190,6 +369,7 @@ export class AiAssistantPanelService implements OnDestroy { } else { this._lastChatIdByContext.delete(key); } + this.storeChats(); } lastChatIdForContext(): string | undefined { @@ -198,13 +378,36 @@ export class AiAssistantPanelService implements OnDestroy { } close(): void { + this._restored.set(false); this._open.set(false); } openPanel(): void { + if (this._suppressed()) { + return; + } + this._restored.set(false); this._open.set(true); } + private _composed = signal(null); + readonly composed = this._composed.asReadonly(); + + compose(text: string): void { + this._composed.set(text); + if (!this._suppressed()) { + this.openPanel(); + } else if (!AiAssistantPanelService.onAiPage(this.router.url)) { + this.router.navigateByUrl('/ai-assistant'); + } + } + + takeComposed(): string | null { + const composed = this._composed(); + this._composed.set(null); + return composed; + } + setEnabled(enabled: boolean): void { this._enabled.set(enabled); if (enabled) { @@ -212,6 +415,17 @@ export class AiAssistantPanelService implements OnDestroy { } } + private _viewName = signal(null); + readonly viewName = this._viewName.asReadonly(); + + setViewName(name: string | null): void { + if (this._focus) { + this._focus.previousName = name?.trim() || null; + return; + } + this._viewName.set(name?.trim() || null); + } + setConfig(config: AiAssistantPanelConfig | null): void { this._config.set(config); } @@ -220,12 +434,39 @@ export class AiAssistantPanelService implements OnDestroy { this._detailsOpen.set(open); } + private _focus: {context: AiChatClientContext; previous: AiChatClientContext; previousName: string | null} | null = null; + setClientContext(ctx: AiChatClientContext | null): void { + if (this._focus && ctx) { + this._focus.previous = ctx; + return; + } + this._focus = null; this._clientContext.set(ctx); } setClientContextForView(view: AiChatView): void { - this.setClientContext({view, timeZone: getDefaultTimezone()}); + this.setClientContext({view, timeZone: getDefaultTimezone(), os: aiClientOs()}); + } + + focusWhile(view: AiChatView, name: string | null | undefined, until: Observable): Observable { + return defer(() => { + const previous = this._clientContext(); + if (!previous || !view.entityId?.id) { + return until; + } + const focus = {context: {view, timeZone: getDefaultTimezone(), os: aiClientOs()}, previous, previousName: this._viewName()}; + this._focus = focus; + this._clientContext.set(focus.context); + this._viewName.set(name?.trim() || null); + return until.pipe(finalize(() => { + if (this._focus === focus) { + this._focus = null; + this._clientContext.set(focus.previous); + this._viewName.set(focus.previousName); + } + })); + }); } getSentClientContext(chatId: string): AiChatClientContext | undefined { @@ -240,19 +481,70 @@ export class AiAssistantPanelService implements OnDestroy { this._updatedData$.complete(); } + private _whiteLabelingSaved$ = new Subject<'GENERAL' | 'LOGIN'>(); + readonly whiteLabelingSaved$ = this._whiteLabelingSaved$.asObservable(); + + emitWhiteLabelingSaved(target: 'GENERAL' | 'LOGIN'): void { + this._whiteLabelingSaved$.next(target); + } + + private _customizationSaved$ = new Subject(); + readonly customizationSaved$ = this._customizationSaved$.asObservable(); + + customizationReload$(kind: AiCustomizationSaved['kind'], clean: () => boolean = () => true): Observable { + return this.customizationSaved$.pipe(filter(event => event.kind === kind && clean())); + } + + emitCustomizationSaved(event: AiCustomizationSaved): void { + this._customizationSaved$.next(event); + } + + setEditorDraftProvider(provider: (() => unknown | null) | null): void { + this._editorDraftProvider = provider; + } + + editorDraft(): unknown | null { + try { + return this._editorDraftProvider ? this._editorDraftProvider() : null; + } catch (e) { + return null; + } + } + + private readonly _keptEdits = signal<{kind: 'dashboard' | 'entity'; reload: () => void} | null>(null); + readonly keptEdits = this._keptEdits.asReadonly(); + + keepEdits(kind: 'dashboard' | 'entity', reload: () => void): void { + this._keptEdits.set({kind, reload}); + } + + clearKeptEdits(kind?: 'dashboard' | 'entity'): void { + if (!kind || this._keptEdits()?.kind === kind) { + this._keptEdits.set(null); + } + } + + reloadKeptEdits(): void { + const kept = this._keptEdits(); + this._keptEdits.set(null); + kept?.reload(); + } + emitUpdatedData(affectedEntities: Array): void { this._updatedData$.next(affectedEntities); } teardown(): void { + this._keptEdits.set(null); + this._editorDraftProvider = null; this._enabled.set(false); this._detailsOpen.set(false); + this._focus = null; this._clientContext.set(null); + this._viewName.set(null); this._sentClientContextByChat.clear(); - this._chats.set(null); this._teardownTimer = setTimeout(() => { this._config.set(null); - this._open.set(false); }); } } diff --git a/ui-ngx/src/app/core/services/ai-chats.service.ts b/ui-ngx/src/app/core/services/ai-chats.service.ts new file mode 100644 index 0000000000..e57a2ea93a --- /dev/null +++ b/ui-ngx/src/app/core/services/ai-chats.service.ts @@ -0,0 +1,353 @@ +// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: BUSL-1.1 +import { computed, DestroyRef, effect, inject, Injectable, Injector, signal, untracked, WritableSignal } from '@angular/core'; +import { interval, Observable, of } from 'rxjs'; +import { distinctUntilChanged, filter, map, skip, switchMap, tap } from 'rxjs/operators'; +import { takeUntilDestroyed } from '@angular/core/rxjs-interop'; +import { Store } from '@ngrx/store'; +import { AppState } from '@core/core.state'; +import { selectAuthUser } from '@core/auth/auth.selectors'; +import { UserPermissionsService } from '@core/http/user-permissions.service'; +import { TranslateService } from '@ngx-translate/core'; +import { AiChatService } from '@core/http/ai-chat.service'; +import { AiAssistantPanelService } from '@core/services/ai-assistant-panel.service'; +import { DialogService } from '@core/services/dialog.service'; +import { AnswerFeedback, ChatConfiguration, ChatInfo, ChatLevel } from '@shared/models/ai-chat.models'; + +@Injectable({ providedIn: 'root' }) +export class AiChatsService { + + private aiChat = inject(AiChatService); + private panelService = inject(AiAssistantPanelService); + private dialog = inject(DialogService); + private translate = inject(TranslateService); + private destroyRef = inject(DestroyRef); + private injector = inject(Injector); + + private _chats = signal([]); + readonly chats = this._chats.asReadonly(); + + private _loaded = signal(false); + readonly loaded = this._loaded.asReadonly(); + + private _replying = signal>(new Set()); + readonly replying = this._replying.asReadonly(); + + private _waiting = signal>(new Set()); + + private _open = signal>(new Set()); + + private _failed = signal>(new Map()); + + private static readonly STATUS_POLL_MS = 15000; + + private _statuses = signal([]); + + private _statusResolved = signal(false); + + readonly statusChats = computed(() => this._loaded() ? this._chats() : this._statuses()); + + readonly statusResolved = computed(() => this._loaded() || this._statusResolved()); + + private watching = false; + + private polling = false; + + private generation = 0; + + private store = inject(Store); + + private userPermissions = inject(UserPermissionsService); + + private userWatch = this.store.select(selectAuthUser).pipe( + map(user => user?.userId ?? null), + distinctUntilChanged(), + skip(1), + takeUntilDestroyed(this.destroyRef) + ).subscribe(userId => this.reset(userId)); + + private reset(userId: string | null): void { + this.generation++; + this.polling = false; + this.ensuring = false; + this._chats.set([]); + this._loaded.set(false); + this._replying.set(new Set()); + this._waiting.set(new Set()); + this._open.set(new Set()); + this._failed.set(new Map()); + this._statuses.set([]); + this._statusResolved.set(false); + if (userId && this.watching) { + this.pollStatus(); + } + } + + private aiAvailable(): boolean { + return this.userPermissions.isAiAvailable(); + } + + watchStatus(): void { + if (this.watching) { + return; + } + this.watching = true; + this.pollStatus(); + let wasOpen = untracked(this.panelService.open); + const panelWatch = effect(() => { + const open = this.panelService.open(); + if (wasOpen && !open) { + this.pollStatus(); + } + wasOpen = open; + }, {injector: this.injector}); + const poll = interval(AiChatsService.STATUS_POLL_MS).subscribe(() => { + if (!untracked(this.panelService.open) && document.visibilityState === 'visible' + && untracked(this.statusChats).some(chat => this.levelOf(chat) === 'running')) { + this.pollStatus(); + } + }); + this.destroyRef.onDestroy(() => { + panelWatch.destroy(); + poll.unsubscribe(); + }); + } + + private pollStatus(): void { + if (this.polling || !this.aiAvailable()) { + return; + } + this.polling = true; + const generation = this.generation; + this.aiChat.listChatStatuses({ignoreLoading: true, ignoreErrors: true}).pipe( + filter(() => generation === this.generation) + ).subscribe({ + next: statuses => { + this.polling = false; + this._statuses.set(statuses); + this._statusResolved.set(true); + if (untracked(this._loaded)) { + const byId = new Map(statuses.map(chat => [chat.id, chat])); + this._chats.update(list => list.map(chat => { + const live = byId.get(chat.id); + return live?.status === chat.status && live?.statusReason === chat.statusReason && (!live || live.updatedTime === chat.updatedTime) + ? chat : {...chat, status: live?.status, statusReason: live?.statusReason, updatedTime: live?.updatedTime ?? chat.updatedTime}; + })); + } + }, + error: () => { + if (generation === this.generation) { + this.polling = false; + this._statusResolved.set(true); + } + } + }); + } + + levelOf(chat: ChatInfo, ignoreOpen = false): ChatLevel | null { + if (this._waiting().has(chat.id)) { + return 'needs'; + } + if (this._replying().has(chat.id)) { + return 'running'; + } + if (this._failed().has(chat.id)) { + return 'error'; + } + if (!ignoreOpen && this._open().has(chat.id)) { + return chat.status === 'FAILED' ? 'error' : null; + } + return chat.status === 'NEEDS_YOU' ? 'needs' : chat.status === 'NO_DATA' ? 'nodata' : chat.status === 'RUNNING' ? 'running' : chat.status === 'FAILED' ? 'error' : null; + } + + needsAttention(chat: ChatInfo): boolean { + const level = this.levelOf(chat); + return level === 'needs' || level === 'error'; + } + + tipOf(chat: ChatInfo): string { + const level = this.levelOf(chat); + if (!level) { + return ''; + } + const reason = level === 'error' ? this._failed().get(chat.id) ?? chat.statusReason : undefined; + return reason || this.translate.instant('ai-assistant.status-tip-' + level); + } + + setFailed(chatId: string | undefined, reason: string): void { + if (chatId) { + this._failed.update(map => new Map(map).set(chatId, reason)); + } + } + + clearFailure(chatId: string | undefined): void { + if (!chatId) { + return; + } + if (untracked(this._failed).has(chatId)) { + this._failed.update(map => { + const next = new Map(map); + next.delete(chatId); + return next; + }); + } + if (untracked(this._chats).some(chat => chat.id === chatId && chat.status === 'FAILED')) { + this._chats.update(list => list.map(chat => chat.id === chatId && chat.status === 'FAILED' + ? {...chat, status: undefined, statusReason: undefined} : chat)); + } + } + + setWaiting(chatId: string | undefined, waiting: boolean): void { + this.toggle(this._waiting, chatId, waiting); + } + + setOpen(chatId: string | undefined, open: boolean): void { + this.toggle(this._open, chatId, open); + } + + refresh(): Observable { + const generation = this.generation; + return this.aiChat.listChats({ignoreLoading: true, ignoreErrors: true}).pipe( + tap(chats => { + if (generation === this.generation) { + this._chats.set(chats); + } + }) + ); + } + + private ensuring = false; + + ensureLoaded(): void { + if (this._loaded() || this.ensuring) { + return; + } + this.ensuring = true; + const generation = this.generation; + const done = () => { + if (generation === this.generation) { + this.ensuring = false; + } + }; + this.load().subscribe({error: done, complete: done}); + } + + load(): Observable { + const generation = this.generation; + return this.aiChat.listChats({ignoreLoading: true, ignoreErrors: true}).pipe( + filter(() => generation === this.generation), + tap({ + next: chats => { + this._chats.set(chats); + this._loaded.set(true); + this.moveStoredAutoApprove(chats); + }, + error: () => this._loaded.set(true) + }) + ); + } + + find(chatId: string | undefined): ChatInfo | undefined { + return chatId ? this._chats().find(chat => chat.id === chatId) : undefined; + } + + create(title: string, autoApprove = false): Observable { + const request: ChatConfiguration = autoApprove ? {title, autoApprove} : {title}; + return this.aiChat.createChat(request, {ignoreLoading: true, ignoreErrors: true}).pipe( + map(id => ({id, title, createdTime: Date.now(), autoApprove} as ChatInfo)), + tap(chat => { + this._chats.update(list => [chat, ...list]); + }) + ); + } + + rename(chatId: string, title: string): Observable { + return this.aiChat.updatedChat(chatId, {title}, {ignoreLoading: true, ignoreErrors: true}).pipe( + tap(() => this.setTitle(chatId, title)) + ); + } + + sendFeedback(chatId: string, feedback: AnswerFeedback): Observable { + return this.aiChat.updatedChat(chatId, {feedback}, {ignoreLoading: true}); + } + + isAutoApprove(chatId: string | undefined): boolean { + return !!this.find(chatId)?.autoApprove; + } + + setAutoApprove(chatId: string, autoApprove: boolean): Observable { + const before = this.isAutoApprove(chatId); + this.applyAutoApprove(chatId, autoApprove); + return this.aiChat.updatedChat(chatId, {autoApprove}, {ignoreLoading: true, ignoreErrors: true}).pipe( + tap({error: () => this.applyAutoApprove(chatId, before)}) + ); + } + + private applyAutoApprove(chatId: string, autoApprove: boolean): void { + this._chats.update(list => list.map(chat => chat.id === chatId ? {...chat, autoApprove} : chat)); + } + + private moveStoredAutoApprove(chats: ChatInfo[]): void { + const stored = new Set(this.panelService.takeStoredAutoApproveChats()); + chats.filter(chat => stored.has(chat.id) && !chat.autoApprove) + .forEach(chat => this.setAutoApprove(chat.id, true).subscribe({error: () => {}})); + } + + setPinned(chatId: string, pinned: boolean): Observable { + return this.aiChat.updatedChat(chatId, {pinned}, {ignoreLoading: true, ignoreErrors: true}).pipe( + tap(() => this._chats.update(list => list.map(chat => chat.id === chatId ? {...chat, pinned, pinnedTime: pinned ? Date.now() : undefined} : chat))) + ); + } + + setTitle(chatId: string, title: string): void { + this._chats.update(list => list.map(chat => chat.id === chatId ? {...chat, title} : chat)); + } + + discard(chatId: string): Observable { + return this.aiChat.deleteChat(chatId, {ignoreLoading: true, ignoreErrors: true}).pipe( + tap(() => { + this._chats.update(list => list.filter(c => c.id !== chatId)); + this.panelService.forgetChat(chatId); + }) + ); + } + + confirmAndDelete(chat: ChatInfo): Observable { + const title = chat.title || this.translate.instant('ai-assistant.new-chat'); + return this.dialog.confirm( + this.translate.instant('ai-assistant.delete-chat-title', {name: title}), + this.translate.instant('ai-assistant.delete-chat-text'), + this.translate.instant('action.no'), + this.translate.instant('ai-assistant.delete-chat-confirm') + ).pipe( + switchMap(confirmed => confirmed + ? this.aiChat.deleteChat(chat.id, {ignoreLoading: true, ignoreErrors: true}).pipe( + tap(() => { + this._chats.update(list => list.filter(c => c.id !== chat.id)); + this.panelService.forgetChat(chat.id); + }), + map(() => true) + ) + : of(false)) + ); + } + + setReplying(chatId: string | undefined, replying: boolean): void { + this.toggle(this._replying, chatId, replying); + } + + private toggle(target: WritableSignal>, chatId: string | undefined, on: boolean): void { + if (!chatId || untracked(target).has(chatId) === on) { + return; + } + target.update(set => { + const next = new Set(set); + if (on) { + next.add(chatId); + } else { + next.delete(chatId); + } + return next; + }); + } +} diff --git a/ui-ngx/src/app/core/services/ai-slash.service.ts b/ui-ngx/src/app/core/services/ai-slash.service.ts new file mode 100644 index 0000000000..4d74aa93a1 --- /dev/null +++ b/ui-ngx/src/app/core/services/ai-slash.service.ts @@ -0,0 +1,74 @@ +// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: BUSL-1.1 +import { inject, Injectable, NgZone } from '@angular/core'; +import { MatDialog } from '@angular/material/dialog'; + +export interface AiSlashComposer { + field(): HTMLTextAreaElement | undefined; + focusEnd(): void; +} + +export interface AiSlashOpener { + canOpen(): boolean; + open(): void; +} + +@Injectable({ + providedIn: 'root' +}) +export class AiSlashService { + + private zone = inject(NgZone); + private dialog = inject(MatDialog); + private composers = new Set(); + private opener: AiSlashOpener | null = null; + private listening = false; + + addComposer(composer: AiSlashComposer): () => void { + this.listen(); + this.composers.add(composer); + return () => this.composers.delete(composer); + } + + setOpener(opener: AiSlashOpener): () => void { + this.listen(); + this.opener = opener; + return () => { + if (this.opener === opener) { + this.opener = null; + } + }; + } + + private listen(): void { + if (this.listening) { + return; + } + this.listening = true; + this.zone.runOutsideAngular(() => document.addEventListener('keydown', event => this.onKeydown(event))); + } + + private onKeydown(event: KeyboardEvent): void { + if (event.key !== '/' || event.metaKey || event.ctrlKey || event.altKey || event.defaultPrevented || this.dialog.openDialogs.length + || (event.target as HTMLElement)?.closest?.('input, textarea, select, [contenteditable], [role="combobox"], [role="listbox"], [role="menu"], [role="menuitem"]') + || document.querySelector('.cdk-overlay-container .mat-mdc-select-panel, .cdk-overlay-container .mat-mdc-menu-panel, .cdk-overlay-container .mat-mdc-autocomplete-panel')) { + return; + } + const visible = Array.from(this.composers) + .filter(composer => { + const field = composer.field(); + return !!field?.offsetParent && !field.closest('tb-ai-assistant-panel:not(.open)'); + }) + .sort((a, b) => a.field().compareDocumentPosition(b.field()) & Node.DOCUMENT_POSITION_FOLLOWING ? -1 : 1); + const last = visible[visible.length - 1]; + if (last) { + event.preventDefault(); + this.zone.run(() => last.focusEnd()); + return; + } + if (this.opener?.canOpen()) { + event.preventDefault(); + this.zone.run(() => this.opener.open()); + } + } +} diff --git a/ui-ngx/src/app/core/services/ai-solutions.service.ts b/ui-ngx/src/app/core/services/ai-solutions.service.ts new file mode 100644 index 0000000000..a426eed1c4 --- /dev/null +++ b/ui-ngx/src/app/core/services/ai-solutions.service.ts @@ -0,0 +1,286 @@ +// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: BUSL-1.1 +import { computed, DestroyRef, inject, Injectable, signal } from '@angular/core'; +import { takeUntilDestroyed } from '@angular/core/rxjs-interop'; +import { Store } from '@ngrx/store'; +import { AppState } from '@core/core.state'; +import { selectAuthUser } from '@core/auth/auth.selectors'; +import { EMPTY, Observable, of, Subscription, timer } from 'rxjs'; +import { catchError, distinctUntilChanged, filter, finalize, map, skip, switchMap, takeWhile, tap } from 'rxjs/operators'; +import { TranslateService } from '@ngx-translate/core'; +import { ChatLevel } from '@shared/models/ai-chat.models'; +import { SolutionsCreatorService } from '@core/http/solutions-creator.service'; +import { DialogService } from '@core/services/dialog.service'; +import { + SolutionCreatorInfo, + SolutionInfo, + SolutionInstallProgress, + SolutionStep, + SolutionUpdateRequest +} from '@shared/models/solution-creator.models'; + +const SOLUTIONS_POLL_MS = 5000; + +@Injectable({providedIn: 'root'}) +export class AiSolutionsService { + + private following: Subscription | null = null; + + private _solutions = signal([]); + readonly solutions = this._solutions.asReadonly(); + + private _loaded = signal(false); + readonly loaded = this._loaded.asReadonly(); + + private _running = signal>(new Set()); + readonly running = this._running.asReadonly(); + private _failed = signal>(new Map()); + private _needs = signal>(new Set()); + + private api = inject(SolutionsCreatorService); + private dialog = inject(DialogService); + private translate = inject(TranslateService); + + private generation = 0; + + private userWatch = inject(Store).select(selectAuthUser).pipe( + map(user => user?.userId ?? null), + distinctUntilChanged(), + skip(1), + takeUntilDestroyed(inject(DestroyRef)) + ).subscribe(() => this.reset()); + + private reset(): void { + this.generation++; + this.ensuring = false; + this.following?.unsubscribe(); + this.following = null; + this._solutions.set([]); + this._loaded.set(false); + this._running.set(new Set()); + this._failed.set(new Map()); + } + + private ensuring = false; + + ensureLoaded(): void { + if (this._loaded() || this.ensuring) { + return; + } + this.ensuring = true; + const generation = this.generation; + const done = () => { + if (generation === this.generation) { + this.ensuring = false; + } + }; + this.load().subscribe({error: done, complete: done}); + } + + load(): Observable { + const generation = this.generation; + return this.api.getSolutions({ignoreLoading: true, ignoreErrors: true}).pipe( + filter(() => generation === this.generation), + tap({ + next: solutions => { + this._solutions.set(solutions); + this._loaded.set(true); + this.followRunning(); + }, + error: () => this._loaded.set(true) + }) + ); + } + + keepRunning(solutionId: string | undefined): void { + if (!solutionId) { + return; + } + this.update(solutionId, {status: 'RUNNING', statusReason: undefined}); + this.followRunning(); + } + + followRunning(): void { + if (this.following) { + return; + } + this.following = timer(SOLUTIONS_POLL_MS, SOLUTIONS_POLL_MS).pipe( + takeWhile(() => this._solutions().some(solution => solution.status === 'RUNNING' && !this._running().has(solution.id))), + switchMap(() => this.load().pipe(catchError(() => EMPTY))), + finalize(() => this.following = null) + ).subscribe(); + } + + setNeeds(solutionId: string | undefined, needs: boolean): void { + if (!solutionId || this._needs().has(solutionId) === needs) { + return; + } + if (needs && !['FAILED', 'RUNNING'].includes(this.find(solutionId)?.status)) { + this.update(solutionId, {status: 'NEEDS_YOU', statusReason: undefined}); + } + this._needs.update(set => { + const next = new Set(set); + if (needs) { + next.add(solutionId); + } else { + next.delete(solutionId); + } + return next; + }); + } + + setRunning(solutionId: string | undefined, running: boolean): void { + if (!solutionId || this._running().has(solutionId) === running) { + return; + } + if (running && this.find(solutionId)?.status !== 'RUNNING') { + this.update(solutionId, {status: undefined, statusReason: undefined}); + } + this._running.update(set => { + const next = new Set(set); + if (running) { + next.add(solutionId); + } else { + next.delete(solutionId); + } + return next; + }); + if (!running && this.find(solutionId)?.status === 'RUNNING') { + this.followRunning(); + } + } + + isRunning(solutionId: string): boolean { + return this._running().has(solutionId); + } + + setFailed(solutionId: string | undefined, reason: string | null): void { + if (!solutionId || this._failed().get(solutionId) === (reason ?? undefined)) { + return; + } + this._failed.update(map => { + const next = new Map(map); + if (reason) { + next.set(solutionId, reason); + } else { + next.delete(solutionId); + } + return next; + }); + } + + levelOf(solution: SolutionInfo, open = false): ChatLevel | null { + if (this._running().has(solution.id)) { + return 'running'; + } + if (this._failed().has(solution.id)) { + return 'error'; + } + if (open) { + return solution.status === 'FAILED' ? 'error' : this._needs().has(solution.id) ? 'needs' : null; + } + return solution.status === 'NEEDS_YOU' ? 'needs' : solution.status === 'RUNNING' ? 'running' : solution.status === 'FAILED' ? 'error' : null; + } + + needsAttention(solution: SolutionInfo): boolean { + const level = this.levelOf(solution); + if (this._needs().has(solution.id)) { + return level === 'error'; + } + return level === 'needs' || level === 'error'; + } + + readonly attention = computed(() => this._solutions().filter(solution => this.needsAttention(solution))); + + tipOf(solution: SolutionInfo, open = false): string { + const level = this.levelOf(solution, open); + if (!level) { + return ''; + } + const reason = level === 'error' ? this._failed().get(solution.id) ?? solution.statusReason : undefined; + return reason || this.translate.instant('ai-assistant.status-tip-' + level); + } + + find(solutionId: string | undefined): SolutionInfo | undefined { + return solutionId ? this._solutions().find(solution => solution.id === solutionId) : undefined; + } + + titleOf(solution: SolutionInfo): string { + return solution.solutionTitle || this.translate.instant('solution-creator.new-solution'); + } + + upsert(info: SolutionCreatorInfo): void { + const solution: SolutionInfo = { + id: info.id, + createdTime: info.createdTime, + updatedTime: this.find(info.id)?.updatedTime ?? info.createdTime, + solutionTitle: info.data?.solutionTitle || info.data?.aiSolutionTitle || this.find(info.id)?.solutionTitle || '', + built: !!info.metadata?.built, + installed: !!info.metadata?.installed + }; + this._solutions.update(list => list.some(item => item.id === solution.id) + ? list.map(item => item.id === solution.id ? {...item, ...solution, createdTime: item.createdTime ?? solution.createdTime} : item) + : [solution, ...list]); + } + + update(solutionId: string, fields: Partial): void { + this._solutions.update(list => list.map(item => item.id === solutionId ? {...item, ...fields} : item)); + } + + rename(solution: SolutionInfo, title: string): Observable { + return this.api.updateSolutionData(solution.id, 'solutionTitle', JSON.stringify(title), {ignoreLoading: true, ignoreErrors: true}).pipe( + tap(() => this.update(solution.id, {solutionTitle: title})) + ); + } + + setPinned(solution: SolutionInfo, pinned: boolean): Observable { + return this.api.updateSolution(solution.id, {pinned}, {ignoreLoading: true, ignoreErrors: true}).pipe( + tap(() => this.update(solution.id, {pinned})) + ); + } + + sendFeedback(solutionId: string, step: SolutionStep, feedback: SolutionUpdateRequest['feedback']): Observable { + return this.api.updateSolution(solutionId, {step, feedback}, {ignoreLoading: true}); + } + + installProgress(solutionId: string): Observable { + return this.api.getInstallProgress(solutionId, {ignoreLoading: true, ignoreErrors: true}); + } + + confirmAndUninstall(solution: SolutionInfo): Observable { + return this.dialog.confirm( + this.translate.instant('solution-creator.uninstall-solution-dialog-title', {name: this.titleOf(solution)}), + this.translate.instant('solution-creator.uninstall-solution-dialog-text'), + this.translate.instant('action.no'), + this.translate.instant('solution-creator.uninstall-solution-dialog-confirm') + ).pipe( + switchMap(confirmed => confirmed + ? this.api.uninstallSolution(solution.id, {ignoreErrors: true}).pipe( + tap(() => this.update(solution.id, {installed: false})) + ) + : of(null)) + ); + } + + discard(solutionId: string): Observable { + return this.api.deleteSolution(solutionId, {ignoreLoading: true, ignoreErrors: true}).pipe( + tap(() => this._solutions.update(list => list.filter(item => item.id !== solutionId))) + ); + } + + confirmAndDelete(solution: SolutionInfo): Observable { + return this.dialog.confirm( + this.translate.instant('solution-creator.delete-solution-title', {name: this.titleOf(solution)}), + this.translate.instant('solution-creator.delete-solution-text'), + this.translate.instant('action.no'), + this.translate.instant('solution-creator.delete-solution-confirm') + ).pipe( + switchMap(confirmed => confirmed + ? this.api.deleteSolution(solution.id, {ignoreErrors: true}).pipe( + tap(() => this._solutions.update(list => list.filter(item => item.id !== solution.id))), + map(() => true) + ) + : of(false)) + ); + } +} diff --git a/ui-ngx/src/app/core/services/menu.models.ts b/ui-ngx/src/app/core/services/menu.models.ts index 85316cf568..e035b89a13 100644 --- a/ui-ngx/src/app/core/services/menu.models.ts +++ b/ui-ngx/src/app/core/services/menu.models.ts @@ -145,7 +145,6 @@ export enum MenuId { dashboard_all = 'dashboard_all', dashboard_groups = 'dashboard_groups', dashboard_shared = 'dashboard_shared', - ai_solution_creator = 'ai_solution_creator', device_all = 'device_all', device_groups = 'device_groups', device_shared = 'device_shared', @@ -178,6 +177,7 @@ export enum MenuId { secrets = 'secrets', ai_models = 'ai_models', iot_hub = 'iot_hub', + ai_assistant = 'ai_assistant', reporting = 'reporting', report_templates = 'report_templates', report_scheduling = 'report_scheduling', @@ -1117,18 +1117,6 @@ export const menuSectionMap = new Map([ rootOnly: true } ], - [ - MenuId.ai_solution_creator, - { - id: MenuId.ai_solution_creator, - name: 'solution-creator.ai-solution-creator', - type: 'link', - path: '/ai-solution-creator', - icon: 'mdi:creation', - outlinedIcon: 'mdi:creation-outline', - isNew: true, - } - ], [ MenuId.device_all, { @@ -1551,6 +1539,18 @@ export const menuSectionMap = new Map([ outlinedIcon: 'mdi:hub-outline', isNew: true } + ], + [ + MenuId.ai_assistant, + { + id: MenuId.ai_assistant, + name: 'ai-assistant.ai-assistant', + type: 'link', + path: '/ai-assistant', + icon: 'auto_awesome', + outlinedIcon: 'mdi:creation-outline', + isNew: true + } ] ]); @@ -1576,16 +1576,13 @@ const menuFilters = new Map([ MenuId.dashboard_shared, (_authState, userPermissionsService) => userPermissionsService.hasSharedReadGroupsPermission(EntityType.DASHBOARD) ], - [ - MenuId.ai_solution_creator, (authState, userPermissionsService) => - authState.aiEnabled && - authState.authUser.authority === Authority.TENANT_ADMIN && - userPermissionsService.hasGenericPermission(Resource.AI, Operation.ALL) - ], [ MenuId.iot_hub, (authState, userPermissionsService) => authState.authUser.authority === Authority.TENANT_ADMIN && - userPermissionsService.hasGenericPermission(Resource.ALL, Operation.ALL) + userPermissionsService.hasGenericPermissionExceptAi(Operation.ALL) + ], + [ + MenuId.ai_assistant, (_authState, userPermissionsService) => userPermissionsService.isAiAvailable() ], [ MenuId.device_all, (_authState, userPermissionsService) => @@ -2007,8 +2004,8 @@ export const defaultUserMenuMap = new Map([ Authority.TENANT_ADMIN, [ {id: MenuId.home}, + {id: MenuId.ai_assistant}, {id: MenuId.iot_hub}, - {id: MenuId.ai_solution_creator}, { id: MenuId.monitor, pages: [ diff --git a/ui-ngx/src/app/core/services/tour.service.ts b/ui-ngx/src/app/core/services/tour.service.ts new file mode 100644 index 0000000000..5d59332a92 --- /dev/null +++ b/ui-ngx/src/app/core/services/tour.service.ts @@ -0,0 +1,71 @@ +// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: BUSL-1.1 +import { createNgModule, inject, Injectable, Injector, signal, untracked } from '@angular/core'; +import { Store } from '@ngrx/store'; +import { MatDialog } from '@angular/material/dialog'; +import { AppState } from '@core/core.state'; +import { getCurrentUserSettings } from '@core/auth/auth.selectors'; +import { UserPermissionsService } from '@core/http/user-permissions.service'; +import { AiTourStep } from '@shared/models/user-settings.models'; +import { AiChatsService } from '@core/services/ai-chats.service'; + +export interface TourLauncherApi { + welcome(): void; + assistantTour(): Promise; +} + +const OFFER_DELAY_MS = 1200; + +@Injectable({providedIn: 'root'}) +export class TourService { + + readonly active = signal(false); + + private store = inject(Store); + private injector = inject(Injector); + private userPermissions = inject(UserPermissionsService); + private chats = inject(AiChatsService); + private dialog = inject(MatDialog); + + private launcher: Promise | null = null; + + private offered = false; + + aiAvailable(): boolean { + return this.userPermissions.aiAvailable(); + } + + offerWelcome(): void { + if (this.offered || !this.aiAvailable() || this.seen(AiTourStep.WELCOME)) { + return; + } + this.offered = true; + this.chats.watchStatus(); + setTimeout(() => { + if (this.active() || this.seen(AiTourStep.WELCOME) || this.dialog.openDialogs.length + || untracked(this.chats.statusChats).some(chat => this.chats.levelOf(chat) === 'running')) { + this.offered = false; + return; + } + this.load().then(launcher => launcher.welcome()); + }, OFFER_DELAY_MS); + } + + playAssistantTour(): void { + if (this.aiAvailable() && !this.active()) { + this.load().then(launcher => launcher.assistantTour()); + } + } + + private seen(step: AiTourStep): boolean { + return !!getCurrentUserSettings(this.store)?.aiTour?.[step]; + } + + private load(): Promise { + if (!this.launcher) { + this.launcher = import('@modules/tour/tour.module').then(m => createNgModule(m.TourModule, this.injector).injector.get(m.TourLauncher)); + this.launcher.catch(() => this.launcher = null); + } + return this.launcher; + } +} diff --git a/ui-ngx/src/app/core/utils.ts b/ui-ngx/src/app/core/utils.ts index 5b134a2b56..8840b63513 100644 --- a/ui-ngx/src/app/core/utils.ts +++ b/ui-ngx/src/app/core/utils.ts @@ -1283,3 +1283,19 @@ export const objectRequired = (): ValidatorFn => { return null; }; } + +export function escapeHtml(value: string): string { + return value.replace(/[&<>]/g, ch => ch === '&' ? '&' : ch === '<' ? '<' : '>'); +} + +export function escapeHtmlAttr(value: string): string { + return value.replace(/[&<>"']/g, ch => { + switch (ch) { + case '&': return '&'; + case '<': return '<'; + case '>': return '>'; + case '"': return '"'; + default: return '''; + } + }); +} diff --git a/ui-ngx/src/app/modules/home/components/agent/_agent-shared.scss b/ui-ngx/src/app/modules/home/components/agent/_agent-shared.scss index c44b7923e8..3daf483b7f 100644 --- a/ui-ngx/src/app/modules/home/components/agent/_agent-shared.scss +++ b/ui-ngx/src/app/modules/home/components/agent/_agent-shared.scss @@ -93,10 +93,11 @@ $agent-type-generic-fg: #6a1b9a; display: flex; align-items: center; justify-content: space-between; + gap: 16px; padding: 4px 0; font-size: 13px; - .label { color: $agent-text-secondary; } - .value { color: $agent-text-primary; font-weight: 500; } + .label { flex: none; color: $agent-text-secondary; } + .value { min-width: 0; color: $agent-text-primary; font-weight: 500; text-align: right; overflow-wrap: anywhere; } } } diff --git a/ui-ngx/src/app/modules/home/components/agent/agent-deploy-status.component.scss b/ui-ngx/src/app/modules/home/components/agent/agent-deploy-status.component.scss index 231d0ac663..d4c26d1fe8 100644 --- a/ui-ngx/src/app/modules/home/components/agent/agent-deploy-status.component.scss +++ b/ui-ngx/src/app/modules/home/components/agent/agent-deploy-status.component.scss @@ -21,6 +21,12 @@ border: 1px solid $agent-divider-light; border-radius: 10px; box-shadow: 0 1px 2px rgba(0, 0, 0, 0.03); + + @media #{$mat-lt-sm} { + flex-wrap: wrap; + gap: 12px 16px; + padding: 16px; + } } .tb-deploy-card-icon { @@ -33,11 +39,22 @@ justify-content: center; background: color-mix(in srgb, var(--tb-primary-500) 14%, transparent); + @media #{$mat-lt-sm} { + width: 44px; + height: 44px; + } + mat-icon { color: var(--tb-primary-600, var(--tb-primary-500)); font-size: 32px; width: 32px; height: 32px; + + @media #{$mat-lt-sm} { + font-size: 24px; + width: 24px; + height: 24px; + } } } @@ -58,6 +75,10 @@ font-size: 20px; font-weight: 600; color: $agent-text-primary; + + @media #{$mat-lt-sm} { + font-size: 17px; + } } .tb-deploy-card-desc { @@ -85,6 +106,13 @@ align-items: flex-end; gap: 6px; flex-shrink: 0; + + @media #{$mat-lt-sm} { + flex-direction: row; + flex-wrap: wrap; + align-items: center; + width: 100%; + } } .tb-deploy-pill { @@ -181,6 +209,10 @@ transition: border-color 0.15s, box-shadow 0.15s, transform 0.15s; text-align: left; + @media #{$mat-lt-sm} { + padding: 16px; + } + &:hover { border-color: color-mix(in srgb, var(--tb-primary-500) 40%, transparent); box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05); diff --git a/ui-ngx/src/app/modules/home/components/agent/component/agent-compose-diff.component.scss b/ui-ngx/src/app/modules/home/components/agent/component/agent-compose-diff.component.scss index 891f4f85a5..426cfa045e 100644 --- a/ui-ngx/src/app/modules/home/components/agent/component/agent-compose-diff.component.scss +++ b/ui-ngx/src/app/modules/home/components/agent/component/agent-compose-diff.component.scss @@ -8,7 +8,7 @@ tb-agent-compose-diff { .diff-viewer { position: relative; overflow: hidden; - height: clamp(220px, calc(85vh - 280px), 520px); + height: clamp(220px, calc(75vh - 240px), 520px); width: 100%; .acediff__wrap { @@ -32,7 +32,7 @@ tb-agent-compose-diff { .ace_editor { font-family: $agent-mono-font !important; } - .ace_gutter { width: 44px !important; background: #f5f5f5; color: rgba(0, 0, 0, 0.42); } + .ace_gutter { width: 44px !important; background: $agent-surface-soft; color: $agent-ink-42; } .ace_gutter-layer { width: 44px !important; } .acediff__right .ace_gutter { diff --git a/ui-ngx/src/app/modules/home/components/agent/component/agent-compose-diff.component.ts b/ui-ngx/src/app/modules/home/components/agent/component/agent-compose-diff.component.ts index 216ceb2e4e..c5495ca4a2 100644 --- a/ui-ngx/src/app/modules/home/components/agent/component/agent-compose-diff.component.ts +++ b/ui-ngx/src/app/modules/home/components/agent/component/agent-compose-diff.component.ts @@ -221,15 +221,20 @@ export class AgentComposeDiffComponent implements AfterViewInit, OnChanges, OnDe requestAnimationFrame(() => this.whenReady(cb, frames - 1)); } - private scheduleRebuild(): void { + private scheduleRebuild(frames = 60): void { if (this.rebuildHandle != null || this.destroyed) { return; } this.rebuildHandle = requestAnimationFrame(() => { this.rebuildHandle = null; - if (!this.destroyed) { - this.build(); + if (this.destroyed) { + return; } + if (this.differ && !this.ready && frames > 0) { + this.scheduleRebuild(frames - 1); + return; + } + this.build(); }); } diff --git a/ui-ngx/src/app/modules/home/components/agent/component/agent-compose-editor.component.scss b/ui-ngx/src/app/modules/home/components/agent/component/agent-compose-editor.component.scss index a4c87845ac..38a3946a9a 100644 --- a/ui-ngx/src/app/modules/home/components/agent/component/agent-compose-editor.component.scss +++ b/ui-ngx/src/app/modules/home/components/agent/component/agent-compose-editor.component.scss @@ -8,7 +8,7 @@ tb-agent-compose-editor { .yaml-editor { width: 100%; box-sizing: border-box; padding: 12px 14px; border: 1px solid $agent-divider; border-radius: 4px; - background: $agent-surface-muted; color: #1f2328; + background: $agent-surface-muted; color: $agent-editor-fg; font-family: $agent-mono-font; font-size: 12px; line-height: 1.55; letter-spacing: 0; tab-size: 2; -moz-tab-size: 2; @@ -16,7 +16,7 @@ tb-agent-compose-editor { .yaml-editor-ace { padding: 0; - height: clamp(220px, calc(85vh - 280px), 520px); + height: clamp(220px, calc(75vh - 240px), 520px); overflow: hidden; overscroll-behavior: contain; .ace_editor { @@ -28,6 +28,6 @@ tb-agent-compose-editor { .ace_content { overscroll-behavior: contain; } - .ace_gutter { background: #f5f5f5; color: rgba(0, 0, 0, 0.42); } + .ace_gutter { background: $agent-surface-soft; color: $agent-ink-42; } } } diff --git a/ui-ngx/src/app/modules/home/components/agent/dialog/agent-auto-provision-dialog.component.html b/ui-ngx/src/app/modules/home/components/agent/dialog/agent-auto-provision-dialog.component.html index 88855e5893..99b0e1a1c5 100644 --- a/ui-ngx/src/app/modules/home/components/agent/dialog/agent-auto-provision-dialog.component.html +++ b/ui-ngx/src/app/modules/home/components/agent/dialog/agent-auto-provision-dialog.component.html @@ -4,18 +4,17 @@ SPDX-License-Identifier: BUSL-1.1 --> - -
-

{{ titleKey | translate }}

-
+ +

{{ titleKey | translate }}

+
-
- -
- +
+ @@ -98,16 +97,6 @@ }
- - @@ -146,16 +135,30 @@ edge.auto-provision-no-script
} - - - +
+ @if (selectedIndex === 0) { +
+ +
+ + } +
+ + @if (selectedIndex > 0) { + + } +
+
diff --git a/ui-ngx/src/app/modules/home/components/agent/dialog/agent-auto-provision-dialog.component.scss b/ui-ngx/src/app/modules/home/components/agent/dialog/agent-auto-provision-dialog.component.scss index c3f58c4989..ffe68e19c0 100644 --- a/ui-ngx/src/app/modules/home/components/agent/dialog/agent-auto-provision-dialog.component.scss +++ b/ui-ngx/src/app/modules/home/components/agent/dialog/agent-auto-provision-dialog.component.scss @@ -2,14 +2,7 @@ // SPDX-License-Identifier: BUSL-1.1 @use '../wizard/agent-wizard' as *; -@include wizard-chrome; - -:host { - display: block; - width: min(800px, 95vw); - min-width: 0; - max-width: 95vw; -} +@include wizard-stepper-dialog(800px); .select-form { display: block; diff --git a/ui-ngx/src/app/modules/home/components/agent/dialog/agent-auto-provision-dialog.component.ts b/ui-ngx/src/app/modules/home/components/agent/dialog/agent-auto-provision-dialog.component.ts index a833397836..395f72bb99 100644 --- a/ui-ngx/src/app/modules/home/components/agent/dialog/agent-auto-provision-dialog.component.ts +++ b/ui-ngx/src/app/modules/home/components/agent/dialog/agent-auto-provision-dialog.component.ts @@ -58,6 +58,7 @@ export class AgentAutoProvisionDialogComponent searchText = ''; loading = false; + selectedIndex = 0; @ViewChild('stepper', { static: false }) stepper: MatStepper; @ViewChild(MatAutocompleteTrigger) private autocompleteTrigger: MatAutocompleteTrigger; @@ -221,7 +222,7 @@ export class AgentAutoProvisionDialogComponent return this.dialog.open( AgentProfileAssignProfileDialogComponent, { disableClose: true, - panelClass: ['tb-dialog'], + panelClass: ['tb-dialog', 'tb-fullscreen-dialog', 'tb-wide-dialog'], data: { selectedIds, lockedAppType: this.appType } } ).afterClosed(); diff --git a/ui-ngx/src/app/modules/home/components/agent/dialog/agent-auto-provision-dialog.service.ts b/ui-ngx/src/app/modules/home/components/agent/dialog/agent-auto-provision-dialog.service.ts index 4283ec6f50..30ab9e23c9 100644 --- a/ui-ngx/src/app/modules/home/components/agent/dialog/agent-auto-provision-dialog.service.ts +++ b/ui-ngx/src/app/modules/home/components/agent/dialog/agent-auto-provision-dialog.service.ts @@ -20,7 +20,7 @@ export class AgentAutoProvisionDialogService { return this.dialog.open( AgentAutoProvisionDialogComponent, { disableClose: true, - panelClass: ['tb-dialog', 'tb-fullscreen-dialog', 'tb-agent-wizard-dialog'], + panelClass: ['tb-dialog', 'tb-fullscreen-dialog', 'tb-wide-dialog'], data: { appType } } ).afterClosed(); diff --git a/ui-ngx/src/app/modules/home/components/agent/wizard/_agent-wizard.scss b/ui-ngx/src/app/modules/home/components/agent/wizard/_agent-wizard.scss index b1a57cfd06..85e0b73a8a 100644 --- a/ui-ngx/src/app/modules/home/components/agent/wizard/_agent-wizard.scss +++ b/ui-ngx/src/app/modules/home/components/agent/wizard/_agent-wizard.scss @@ -4,96 +4,76 @@ @forward '../agent-shared'; @use '../agent-shared' as *; -@mixin wizard-chrome { +@mixin wizard-dialog($width) { :host { - display: block; - width: min(1280px, 95vw); - min-width: 0; - max-width: 95vw; + height: 100%; + width: $width; + max-width: 100%; + display: grid; + grid-template-rows: min-content minmax(0, 1fr) min-content; + grid-template-columns: minmax(0, 1fr); } - .tb-install-wizard-toolbar { - display: flex; align-items: center; gap: 8px; - padding: 0 16px; - min-height: 56px; - .tb-install-wizard-toolbar-content { - flex: 1; min-width: 0; - display: flex; flex-direction: row; align-items: center; gap: 8px; - h2 { font-size: 20px; font-weight: 400; margin: 0; color: inherit; } - span { font-size: 20px; font-weight: 400; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; } + :host-context(.mat-mdc-dialog-container) { + @media #{$mat-gt-xs} { + max-height: calc(100vh - 32px); } - } - .tb-install-wizard-body.tb-install-wizard-embedded { - max-height: none !important; - overflow-y: visible !important; - padding: 8px 0 !important; - } + .mat-mdc-dialog-content { + overscroll-behavior: contain; - .tb-install-wizard-body { - // No vertical padding: the sticky stepper header sits flush at the top and the - // sticky footer flush at the bottom, with the content carrying its own spacing. - padding: 0 24px !important; - // Cap the dialog body to the viewport. Allow vertical scroll so tall step - // content (e.g. update/upgrade step 2 with config sections + summary card + - // info box + footer) can reach its buttons. The ace editors inside are - // clamped so they don't contribute unbounded height, and .acediff__wrap has - // its own overflow killed — so the only outer scrollbar that appears here - // is a legitimate chrome scroll when the step content genuinely overflows. - max-height: 85vh; - overflow-y: auto; - // Contain horizontal overscroll so two-finger trackpad swipes inside the - // ace editors / diff panes don't bubble up to the browser's back/forward - // page navigation. Also block vertical bounce from escaping the dialog. - overscroll-behavior: contain; + @media #{$mat-gt-xs} { + max-height: 75vh; + } + } } +} - :host ::ng-deep .mat-horizontal-stepper-wrapper { - margin-top: 0; - } +@mixin wizard-stepper-dialog($width) { + @include wizard-dialog($width); - :host ::ng-deep .mat-horizontal-stepper-header-container { - margin-top: 0; - // Keep the step indicators (1)…(N) pinned at the top while content scrolls. - position: sticky; - top: 0; - z-index: 5; - background: #fff; + :host { + .dialog-actions-row { + padding: 8px; + } } - :host ::ng-deep .mat-horizontal-stepper-header { - padding: 0 12px; - } + :host-context(.mat-mdc-dialog-container) { + .mat-mdc-dialog-content { + padding: 0; + scrollbar-gutter: stable; + } - :host ::ng-deep .mat-horizontal-content-container { - padding: 12px 0; - // Material defaults this to `overflow: hidden`, which makes it a scroll - // container and anchors the sticky `.step-footer` here (content height, so it - // never sticks). `clip` still clips the sliding steps but is NOT a scroll - // container, so the footer anchors to the scrolling `.tb-install-wizard-body`. - overflow: clip; - max-width: 100%; + .mat-mdc-dialog-actions { + padding: 0; + } } - :host-context(.tb-fullscreen-dialog .mat-mdc-dialog-container) { - max-width: 100%; + :host ::ng-deep { + .mat-horizontal-stepper-header-container { + position: sticky; + top: 0; + z-index: 5; + background: #fff; + } - .tb-install-wizard-body { - max-width: 100%; - overflow-x: hidden; + .mat-horizontal-content-container, + .mat-vertical-content { + padding-top: 4px; } - } - :host ::ng-deep .mat-step-header { - // Kill the hover/focus background — navigation works, but no visual fill. - &:hover, - &.cdk-program-focused, - &.cdk-mouse-focused, - &.cdk-focused { - background-color: transparent !important; + .mat-step-header { + &:hover, + &.cdk-program-focused, + &.cdk-mouse-focused, + &.cdk-focused { + background-color: transparent !important; + } } } +} +@mixin wizard-steps-locked { :host ::ng-deep .tb-steps-locked .mat-step-header[aria-selected="false"] { pointer-events: none; cursor: default; @@ -107,22 +87,6 @@ color: $agent-text-hint !important; } } - - .step-footer { - display: flex; align-items: center; justify-content: flex-end; gap: 8px; - padding: 12px 0; border-top: 1px solid $agent-divider-light; margin-top: 16px; - button mat-icon { font-size: 18px; width: 18px; height: 18px; } - } - - // Pin the footer to the bottom of the scrolling body so its action buttons stay - // visible while tall step content scrolls. Skipped in embedded mode, where the - // body doesn't scroll (the host dialog does) and a sticky footer would misbehave. - .tb-install-wizard-body:not(.tb-install-wizard-embedded) .step-footer { - position: sticky; - bottom: 0; - z-index: 15; - background: #fff; - } } @mixin wizard-step-basics { @@ -172,23 +136,20 @@ mat-icon { font-size: 36px; width: 36px; height: 36px; color: var(--tb-primary-500); margin-bottom: 8px; } h4 { font-size: 16px; font-weight: 500; margin: 0 0 4px; } p { font-size: 13px; color: $agent-text-secondary; margin: 0; } - } -} -@mixin wizard-yaml-editor { - // Defensive: also contain overscroll on the editor hosts themselves, so even - // if a swipe lands directly on an ace editor (not on the body), it won't be - // interpreted as page navigation. - .diff-viewer, - .yaml-editor-ace { - overscroll-behavior: contain; - ::ng-deep .ace_editor, - ::ng-deep .ace_scroller, - ::ng-deep .ace_content { - overscroll-behavior: contain; + @media #{$mat-lt-sm} { + display: grid; + grid-template-columns: 32px minmax(0, 1fr); + column-gap: 12px; + align-items: center; + padding: 12px 16px; + text-align: left; + mat-icon { grid-row: span 2; font-size: 32px; width: 32px; height: 32px; margin: 0; } } } +} +@mixin wizard-yaml-editor { .tb-compose-panel { box-shadow: none !important; border: 1px solid $agent-divider; @@ -198,33 +159,6 @@ } } - .yaml-editor { - width: 100%; box-sizing: border-box; padding: 12px 14px; - border: 1px solid $agent-divider; border-radius: 4px; - background: $agent-surface-muted; color: $agent-editor-fg; - font-family: $agent-mono-font; - font-size: 12px; line-height: 1.55; letter-spacing: 0; - tab-size: 2; -moz-tab-size: 2; - resize: vertical; - &:focus { - outline: none; border-color: var(--tb-primary-400); - box-shadow: 0 0 0 3px color-mix(in srgb, var(--tb-primary-400) 15%, transparent); - } - } - - // Ace-backed single editor (install mode and detail view) sits in the same - // .yaml-editor box but needs padding removed and a fixed height for ace layout. - .yaml-editor-ace { - padding: 0; - height: clamp(220px, calc(85vh - 280px), 520px); - overflow: hidden; - ::ng-deep .ace_editor { - font-family: $agent-mono-font !important; - background: transparent; - } - ::ng-deep .ace_gutter { background: $agent-surface-soft; color: $agent-ink-42; } - } - .pull-images { display: block; margin-top: 12px; } // Compact, content-width toggle (Material defaults the group to full width). @@ -283,6 +217,8 @@ .diff-header { flex: 1 1 50%; box-sizing: border-box; padding: 8px 12px; font-size: 12px; font-weight: 500; letter-spacing: 0.3px; + min-width: 0; overflow-wrap: anywhere; + @media #{$mat-lt-sm} { padding: 6px 8px; font-size: 11px; } & + .diff-header { border-left: 1px solid $agent-divider; padding-right: 36px; } &.added { background: $agent-success-surface; color: $agent-color-success-dark; } &.removed { background: #fce4ec; color: $agent-color-error-dark; } @@ -350,102 +286,6 @@ } } - .diff-viewer { - position: relative; - overflow: hidden; - // Fit within the wizard body (which no longer scrolls). Chrome above/below - // the editor (toolbar + stepper header + name field + footer + padding) is - // roughly 280px; the clamp floors at 220px so very short viewports still - // show a usable editor and cap at 520px on large displays. - height: clamp(220px, calc(85vh - 280px), 520px); - width: 100%; - - // ace-diff ships with `.acediff__wrap { overflow: auto }`. That creates an - // extra scrollbar wrapping the two editors + center gutter — the outer - // scrollbar the user sees. Force it hidden; each ace editor has its own - // internal scrollbar for the YAML content and that's the only one we want. - ::ng-deep .acediff__wrap { - overflow: hidden !important; - } - border: 1px solid $agent-divider; - border-bottom-left-radius: 4px; border-bottom-right-radius: 4px; - background: $agent-surface-muted; - - // ace-diff overrides: narrow center gutter, unified monospace styling, tight gutters. - // flex: 0 0 60px is ace-diff's default — must override flex-basis, not just width, - // otherwise the element stays 60px and its grey background leaks around the arrows. - ::ng-deep .acediff__gutter { - flex: 0 0 40px !important; - width: 40px !important; - background: #ffffff !important; - border-left: 1px solid $agent-divider-light !important; - border-right: 1px solid $agent-divider-light !important; - overflow: visible !important; - contain: layout paint style; - will-change: transform; - svg { width: 40px !important; background: transparent !important; } - } - ::ng-deep .ace_editor { - font-family: $agent-mono-font !important; - } - ::ng-deep .ace_gutter { width: 44px !important; background: $agent-surface-soft; color: $agent-ink-42; } - ::ng-deep .ace_gutter-layer { width: 44px !important; } - - // Flip the right pane's gutter to the right edge. Ace lays out .ace_gutter - // and .ace_scroller with absolute positioning (gutter: left 0; scroller: left - // ). Overriding both moves the line numbers against the outer - // edge of the right pane, mirroring the left pane — numbers end up hugging - // both outside edges, with code meeting in the middle at the copy arrows. - ::ng-deep .acediff__right .ace_gutter { - left: auto !important; - right: 0 !important; - border-left: 1px solid $agent-divider-light; - } - ::ng-deep .acediff__right .ace_scroller { - left: 0 !important; - right: 44px !important; - } - ::ng-deep .acediff__right .ace_scrollbar-v { - right: 44px !important; - } - - // Hide the LEFT pane's vertical scrollbar — it overlaps the center gutter and - // covers ace-diff's copy-arrow circles. ace-diff keeps both editors scroll- - // synced internally, and the right pane still shows its own scrollbar, so - // vertical scrolling remains available via mouse wheel / right-side thumb. - ::ng-deep .acediff__left .ace_scrollbar, - ::ng-deep .acediff__left .ace_scrollbar-v { - display: none !important; - width: 0 !important; - } - // Pull the left pane's scroller flush to its right edge so no blank strip - // remains where the scrollbar used to sit. - ::ng-deep .acediff__left .ace_scroller { - right: 0 !important; - } - // Raise the entire center gutter above the panes so nothing from either - // editor can occlude the copy-arrow SVGs. - ::ng-deep .acediff__gutter { - z-index: 10; - } - ::ng-deep .acediff__gutter svg, - ::ng-deep .acediff__copy { - z-index: 11; - position: relative; - } - // The connector SVG paints over the copy arrows and swallows clicks. - // Make the whole gutter SVG click-through so the copy arrow
s stay hit-testable. - ::ng-deep .acediff__gutter svg { pointer-events: none !important; } - ::ng-deep .acediff__copy, - ::ng-deep .acediff__copy--left, - ::ng-deep .acediff__copy--right, - ::ng-deep .acediff__copy--left div, - ::ng-deep .acediff__copy--right div { - pointer-events: auto !important; - z-index: 12 !important; - } - } - .diff-hint { font-size: 12px; color: $agent-text-secondary; margin: 6px 0 0; } diff --git a/ui-ngx/src/app/modules/home/components/agent/wizard/agent-app-install-flow.component.html b/ui-ngx/src/app/modules/home/components/agent/wizard/agent-app-install-flow.component.html index a99468da7f..de4faf9639 100644 --- a/ui-ngx/src/app/modules/home/components/agent/wizard/agent-app-install-flow.component.html +++ b/ui-ngx/src/app/modules/home/components/agent/wizard/agent-app-install-flow.component.html @@ -5,28 +5,33 @@ --> @if (!embedded) { - + @if (showBack) { - } -
-

{{ 'agent.app-install-title' | translate }}@if (agent) {:}

- @if (agent) { - - {{ 'agent.app-install-on-agent' | translate: { name: agent?.name } }} - - } -
+

{{ 'agent.app-install-title' | translate }}@if (agent) {: {{ 'agent.app-install-on-agent' | translate: { name: agent?.name } }}}

+
-
} +@if (embedded) { + + +} @else { +
+ +
+
+ +
+} -
+ @if (checkingManaged) {
@@ -35,7 +40,7 @@ } @if (!checkingManaged && managedApp) { -
+
-
} @if (selectAgent && !embedded && !checkingManaged && !managedApp) { -
+
info_outline agent.deploy-via-agent-desc
@@ -62,302 +61,292 @@ @if (!checkingManaged && !managedApp) { - @if (selectAgent) { - -

agent.deploy-intro

- - - -
- } - @if (!lockedType) { - -

agent.app-install-pick-type

-
- @for (card of typeCards; track card.type) { - - } -
- @if (loadingTemplate) { -
- - agent.app-install-loading-template -
+ @for (step of steps; track step) { + @switch (step) { + @case ('agent') { + +

agent.deploy-intro

+ + +
} - @if (loadError) { -
- error_outline - {{ loadError }} -
+ @case ('type') { + +

agent.app-install-pick-type

+
+ @for (card of typeCards; track card.type) { + + } +
+ @if (loadingTemplate) { +
+ + agent.app-install-loading-template +
+ } + @if (loadError) { +
+ error_outline + {{ loadError }} +
+ } +
} - -
- } - -
- - {{ 'agent.app-install-from-profile' | translate }} - {{ 'agent.app-install-custom-config' | translate }} - -
- - agent.app-install-name - - - @if (canHaveRelatedEntity) { - - - } - @if (useProfile && typesWithoutTemplates.has(selectedType)) { -
- warning_amber - agent.app-no-templates -
- } - @if (useProfile) { - - agent.app-install-select-profile - - @if (profileSelectFormGroup.get('profile').value) { - - } - @if (!profileSelectFormGroup.get('profile').value && canCreateProfileForType) { - - } - - @if (filteredProfiles | async; as profiles) { - @for (p of profiles; track trackKey(p)) { - - {{ p.name }} - @if (isVirtualProfile(p)) { - {{ 'agent.app-install-virtual-profile-badge' | translate }} - } - @if (!isVirtualProfile(p) && p.templateVersion) { - {{ profileTemplateLabel(p) }} + @case ('config') { + +
+ + {{ 'agent.app-install-from-profile' | translate }} + {{ 'agent.app-install-custom-config' | translate }} + +
+ + agent.app-install-name + + + @if (canHaveRelatedEntity) { + + + } + @if (useProfile && typesWithoutTemplates.has(selectedType)) { +
+ warning_amber + agent.app-no-templates +
+ } + @if (useProfile) { + + agent.app-install-select-profile + + @if (profileSelectFormGroup.get('profile').value) { + + } + @if (!profileSelectFormGroup.get('profile').value && canCreateProfileForType) { + + } + + @if (filteredProfiles | async; as profiles) { + @for (p of profiles; track trackKey(p)) { + + {{ p.name }} + @if (isVirtualProfile(p)) { + {{ 'agent.app-install-virtual-profile-badge' | translate }} + } + @if (!isVirtualProfile(p) && p.templateVersion) { + {{ profileTemplateLabel(p) }} + } + + } + @if (!profiles.length) { + +
+ agent.app-install-no-profiles +
+
+ } } -
+
+
+ } + @if (loadingProfiles) { +
+ + agent.app-install-loading-template +
+ } + + @if (useProfile && selectedProfile && !isVirtualProfile(selectedProfile)) { +
+ +
+ } + @if (useProfile && selectedProfile) { + + + agent.app-install-yaml + + + + + + } + @if (mergeError) { +
+ error_outline + {{ mergeError }} +
+ } + @if (!useProfile && !template && loadError) { +
+ error_outline + {{ loadError }} +
+ } @else if (!useProfile) { + @if (composeTypeKeys.length > 1) { + + agent.app-compose-template-select + + @for (key of composeTypeKeys; track key) { + + {{ composeTypeLabel(key) }} + + } + + } - @if (!profiles.length) { - -
- agent.app-install-no-profiles -
-
+ @if (relatedEntityId) { +
+ info_outline + agent.app-compose-creds-overridden-hint +
} +
+
agent.app-install-diff-template
+
agent.app-install-diff-editable
+ +
+ +

agent.app-install-diff-hint

} - - - } - @if (loadingProfiles) { -
- - agent.app-install-loading-template -
- } - - @if (useProfile && selectedProfile && !isVirtualProfile(selectedProfile)) { -
- -
- } - @if (useProfile && selectedProfile) { - - - agent.app-install-yaml - - - - - - } - @if (mergeError) { -
- error_outline - {{ mergeError }} -
- } - @if (!useProfile && !template && loadError) { -
- error_outline - {{ loadError }} -
- } @else if (!useProfile) { - @if (composeTypeKeys.length > 1) { - - agent.app-compose-template-select - - @for (key of composeTypeKeys; track key) { - - {{ composeTypeLabel(key) }} - +
+ } + @case ('summary') { + +
+
+ agent.app-name + {{ appName }} +
+
+ agent.app-type + {{ selectedType }} +
+ @if (template) { +
+ agent.app-template + {{ template.appType }} {{ template.currentVersion }} +
} - - + @if (useProfile && selectedProfile) { +
+ agent.app-install-select-profile + {{ selectedProfile.name }} +
+ } + @if (agent) { +
+ agent.agents + {{ agent.name }} +
+ } +
+
+ info_outline + agent.app-install-confirm-info +
+
} - @if (relatedEntityId) { -
- info_outline - agent.app-compose-creds-overridden-hint -
+ @case ('deploy') { + + + + } -
-
agent.app-install-diff-template
-
agent.app-install-diff-editable
- -
- -

agent.app-install-diff-hint

} - - - -
-
- agent.app-name - {{ appName }} -
-
- agent.app-type - {{ selectedType }} -
- @if (template) { -
- agent.app-template - {{ template.appType }} {{ template.currentVersion }} -
- } - @if (useProfile && selectedProfile) { -
- agent.app-install-select-profile - {{ selectedProfile.name }} -
- } - @if (agent) { -
- agent.agents - {{ agent.name }} -
- } -
-
- info_outline - agent.app-install-confirm-info -
- -
- @if (selectAgent) { - - - - - }
} -
+ + + + @if (!checkingManaged && !managedApp && (canGoBack() || showNext())) { +
+ @if (canGoBack()) { + + } + + @if (showNext()) { + + } +
+ @if (!embedded || canInstall()) { + + } + } + @if (!embedded || canInstall()) { +
+ @if (!embedded) { + + } + @if (canInstall()) { + + } +
+ } +
diff --git a/ui-ngx/src/app/modules/home/components/agent/wizard/agent-app-install-flow.component.scss b/ui-ngx/src/app/modules/home/components/agent/wizard/agent-app-install-flow.component.scss index 1af432721a..95d4951c34 100644 --- a/ui-ngx/src/app/modules/home/components/agent/wizard/agent-app-install-flow.component.scss +++ b/ui-ngx/src/app/modules/home/components/agent/wizard/agent-app-install-flow.component.scss @@ -2,10 +2,18 @@ // SPDX-License-Identifier: BUSL-1.1 @use 'agent-wizard' as *; -@include wizard-chrome; +@include wizard-stepper-dialog(1280px); @include wizard-step-basics; @include wizard-type-cards; @include wizard-yaml-editor; @include wizard-diff; @include wizard-summary; @include agent-virtual-profile-badge; +@include wizard-steps-locked; + +:host(.tb-embedded) { + display: block; + width: auto; + height: auto; + max-height: none; +} diff --git a/ui-ngx/src/app/modules/home/components/agent/wizard/agent-app-install-flow.component.ts b/ui-ngx/src/app/modules/home/components/agent/wizard/agent-app-install-flow.component.ts index 4e42694692..ece77cd194 100644 --- a/ui-ngx/src/app/modules/home/components/agent/wizard/agent-app-install-flow.component.ts +++ b/ui-ngx/src/app/modules/home/components/agent/wizard/agent-app-install-flow.component.ts @@ -38,22 +38,28 @@ import { buildVirtualAppProfiles, VIRTUAL_APP_TYPES } from '@home/pages/agent/util/virtual-app-profiles'; -import { - AgentAppProfileWizardComponent, - AgentAppProfileWizardData -} from '@home/pages/agent/wizard/agent-app-profile-wizard.component'; +import { openAgentAppProfileWizard } from '@home/pages/agent/wizard/agent-app-profile-wizard-dialog'; import { UserPermissionsService } from '@core/http/user-permissions.service'; import { Operation, Resource } from '@shared/models/security.models'; import { AgentAppWizardLoaderService } from '@home/pages/agent/wizard/agent-app-wizard-loader.service'; import { AgentAppWizardSubmitService } from '@home/pages/agent/wizard/agent-app-wizard-submit.service'; -import { AgentAppUpgradeResult, AgentAppWizardFinish, AgentTypeCard } from '@home/pages/agent/wizard/agent-app-wizard.models'; +import { + AGENT_APP_INSTALL_STEP_LABELS, + AgentAppInstallStepKey, + AgentAppUpgradeResult, + AgentAppWizardFinish, + AgentTypeCard +} from '@home/pages/agent/wizard/agent-app-wizard.models'; import { EdgeTemplateCompatibilityService } from '@home/pages/agent/util/edge-template-compatibility.service'; @Component({ selector: 'tb-agent-app-install-flow', templateUrl: './agent-app-install-flow.component.html', styleUrls: ['./agent-app-install-flow.component.scss'], - standalone: false + standalone: false, + host: { + '[class.tb-embedded]': 'embedded' + } }) export class AgentAppInstallFlowComponent extends PageComponent implements OnInit { @@ -82,6 +88,9 @@ export class AgentAppInstallFlowComponent extends PageComponent implements OnIni @ViewChild('stepper', { static: false }) stepper: MatStepper; + readonly stepLabels = AGENT_APP_INSTALL_STEP_LABELS; + steps: AgentAppInstallStepKey[] = []; + selectedIndex = 0; bindings: StepBinding[] = []; @@ -207,6 +216,7 @@ export class AgentAppInstallFlowComponent extends PageComponent implements OnIni } ngOnInit() { + this.steps = this.buildSteps(); this.relatedEntityId = this.lockedRelatedEntity || null; if (this.selectAgent && this.lockedRelatedEntity?.id && this.lockedRelatedEntity?.entityType) { this.checkingManaged = true; @@ -402,12 +412,7 @@ export class AgentAppInstallFlowComponent extends PageComponent implements OnIni const appType = this.selectedType || this.lockedType; if (!appType) { return; } const presetName = this.relatedEntityName ? `${this.relatedEntityName} profile` : undefined; - this.dialog.open( - AgentAppProfileWizardComponent, { - disableClose: true, - panelClass: ['tb-dialog', 'tb-fullscreen-dialog', 'tb-agent-wizard-dialog'], - data: { lockedAppType: appType, presetName } - }).afterClosed().subscribe(saved => { + openAgentAppProfileWizard(this.dialog, { lockedAppType: appType, presetName }).subscribe(saved => { if (saved) { this.availableProfiles = [ ...this.availableProfiles.filter(p => !(isVirtualAppProfile(p) && p.templateVersion === saved.templateVersion)), @@ -421,12 +426,7 @@ export class AgentAppInstallFlowComponent extends PageComponent implements OnIni openEditProfile() { if (!this.selectedProfile || isVirtualAppProfile(this.selectedProfile)) { return; } - this.dialog.open( - AgentAppProfileWizardComponent, { - disableClose: true, - panelClass: ['tb-dialog', 'tb-fullscreen-dialog', 'tb-agent-wizard-dialog'], - data: { profile: this.selectedProfile } - }).afterClosed().subscribe(saved => { + openAgentAppProfileWizard(this.dialog, { profile: this.selectedProfile }).subscribe(saved => { if (saved) { this.availableProfiles = this.availableProfiles.map(p => p.id?.id === saved.id?.id ? saved : p); this.cacheRealProfiles(saved.appType); @@ -731,4 +731,55 @@ export class AgentAppInstallFlowComponent extends PageComponent implements OnIni cancel() { this.cancelled.emit(null); } + + currentStep(): AgentAppInstallStepKey | undefined { + return this.steps[this.selectedIndex]; + } + + canGoBack(): boolean { + return this.selectedIndex > 0 && !this.installedApplication; + } + + canInstall(): boolean { + return !this.checkingManaged && !this.managedApp && !this.installedApplication; + } + + showNext(): boolean { + const hasNext = this.selectedIndex < this.steps.length - 1; + return hasNext && (this.currentStep() !== 'summary' || !!this.installedApplication); + } + + canGoNext(): boolean { + switch (this.currentStep()) { + case 'agent': + return this.canProceedFromAgent(); + case 'type': + return this.canProceedFromType(); + case 'config': + return this.canSubmit(); + case 'summary': + return !!this.installedApplication; + default: + return false; + } + } + + nextStepLabel(): string { + return this.stepLabels[this.steps[this.selectedIndex + 1]] ?? ''; + } + + private buildSteps(): AgentAppInstallStepKey[] { + const keys: AgentAppInstallStepKey[] = []; + if (this.selectAgent) { + keys.push('agent'); + } + if (!this.lockedType) { + keys.push('type'); + } + keys.push('config', 'summary'); + if (this.selectAgent) { + keys.push('deploy'); + } + return keys; + } } diff --git a/ui-ngx/src/app/modules/home/components/agent/wizard/agent-app-install-wizard-dialog.ts b/ui-ngx/src/app/modules/home/components/agent/wizard/agent-app-install-wizard-dialog.ts new file mode 100644 index 0000000000..c4d6a400fd --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/agent/wizard/agent-app-install-wizard-dialog.ts @@ -0,0 +1,22 @@ +// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: BUSL-1.1 +import { MatDialog } from '@angular/material/dialog'; +import { Observable } from 'rxjs'; +import { + AgentAppInstallWizardComponent, + AgentAppInstallWizardData, + AgentAppInstallWizardResult +} from '@home/components/agent/wizard/agent-app-install-wizard.component'; + +export function openAgentAppInstallWizard( + dialog: MatDialog, + data: AgentAppInstallWizardData +): Observable { + return dialog.open( + AgentAppInstallWizardComponent, { + disableClose: false, + panelClass: ['tb-dialog', 'tb-fullscreen-dialog', 'tb-wide-dialog'], + data + } + ).afterClosed(); +} diff --git a/ui-ngx/src/app/modules/home/components/agent/wizard/agent-app-install-wizard.component.scss b/ui-ngx/src/app/modules/home/components/agent/wizard/agent-app-install-wizard.component.scss deleted file mode 100644 index d662554d66..0000000000 --- a/ui-ngx/src/app/modules/home/components/agent/wizard/agent-app-install-wizard.component.scss +++ /dev/null @@ -1,5 +0,0 @@ -// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. -// SPDX-License-Identifier: BUSL-1.1 -@use 'agent-wizard' as *; - -@include wizard-chrome; diff --git a/ui-ngx/src/app/modules/home/components/agent/wizard/agent-app-install-wizard.component.ts b/ui-ngx/src/app/modules/home/components/agent/wizard/agent-app-install-wizard.component.ts index 6b74694329..2a95ed1705 100644 --- a/ui-ngx/src/app/modules/home/components/agent/wizard/agent-app-install-wizard.component.ts +++ b/ui-ngx/src/app/modules/home/components/agent/wizard/agent-app-install-wizard.component.ts @@ -47,7 +47,6 @@ export { isAgentAppUpgradeResult } from '@home/pages/agent/wizard/agent-app-wiza @Component({ selector: 'tb-agent-app-install-wizard', templateUrl: './agent-app-install-wizard.component.html', - styleUrls: ['./agent-app-install-wizard.component.scss'], standalone: false, providers: [AgentAppWizardLoaderService, AgentAppWizardSubmitService] }) diff --git a/ui-ngx/src/app/modules/home/components/agent/wizard/agent-app-update-flow.component.html b/ui-ngx/src/app/modules/home/components/agent/wizard/agent-app-update-flow.component.html index 46c50b18b7..6f42c808d0 100644 --- a/ui-ngx/src/app/modules/home/components/agent/wizard/agent-app-update-flow.component.html +++ b/ui-ngx/src/app/modules/home/components/agent/wizard/agent-app-update-flow.component.html @@ -5,36 +5,28 @@ --> @if (!embedded) { - + @if (showBack) { - } -
-

{{ 'agent.app-update-wizard-title' | translate }}@if (existingApplication) { - : - }

- @if (existingApplication) { - - {{ 'agent.app-update-on-app' | translate: { name: existingApplication?.name } }} - - } -
+

{{ 'agent.app-update-wizard-title' | translate }}@if (existingApplication) {: {{ 'agent.app-update-on-app' | translate: { name: existingApplication?.name } }}}

+
-
} - -
+
- + agent.app-install-name @@ -124,13 +116,6 @@

agent.app-update-compare-hint

} - -
@@ -171,18 +156,33 @@ info_outline agent.app-install-confirm-info
- -
+
+
+ @if (selectedIndex > 0) { + + } + + @if (selectedIndex === 0) { + + } +
+ +
+ + +
+
diff --git a/ui-ngx/src/app/modules/home/components/agent/wizard/agent-app-update-flow.component.scss b/ui-ngx/src/app/modules/home/components/agent/wizard/agent-app-update-flow.component.scss index 29da806e40..a5d3ab398a 100644 --- a/ui-ngx/src/app/modules/home/components/agent/wizard/agent-app-update-flow.component.scss +++ b/ui-ngx/src/app/modules/home/components/agent/wizard/agent-app-update-flow.component.scss @@ -2,7 +2,7 @@ // SPDX-License-Identifier: BUSL-1.1 @use 'agent-wizard' as *; -@include wizard-chrome; +@include wizard-stepper-dialog(1280px); @include wizard-step-basics; @include wizard-config-section; @include wizard-diff; diff --git a/ui-ngx/src/app/modules/home/components/agent/wizard/agent-app-update-flow.component.ts b/ui-ngx/src/app/modules/home/components/agent/wizard/agent-app-update-flow.component.ts index 83dc7275e8..481316fb06 100644 --- a/ui-ngx/src/app/modules/home/components/agent/wizard/agent-app-update-flow.component.ts +++ b/ui-ngx/src/app/modules/home/components/agent/wizard/agent-app-update-flow.component.ts @@ -23,10 +23,7 @@ import { buildStepInputs, createStepBinding, StepBinding } from '@home/pages/age import { buildUpdateApplication } from '@home/pages/agent/util/agent-app-payloads'; import { buildUpdateMergeDraft } from '@home/pages/agent/util/agent-app-compose-preview'; import { composeTemplateKeys, composeTypeLabelKey, dumpCompose, pickComposeType } from '@home/pages/agent/util/agent-compose-yaml'; -import { - AgentAppProfileWizardComponent, - AgentAppProfileWizardData -} from '@home/pages/agent/wizard/agent-app-profile-wizard.component'; +import { openAgentAppProfileWizard } from '@home/pages/agent/wizard/agent-app-profile-wizard-dialog'; import { AgentAppWizardLoaderService } from '@home/pages/agent/wizard/agent-app-wizard-loader.service'; import { AgentAppWizardSubmitService } from '@home/pages/agent/wizard/agent-app-wizard-submit.service'; import { AgentAppUpgradeResult, AgentAppWizardFinish } from '@home/pages/agent/wizard/agent-app-wizard.models'; @@ -52,6 +49,8 @@ export class AgentAppUpdateFlowComponent extends PageComponent implements OnInit @Output() cancelled = new EventEmitter(); @Output() back = new EventEmitter(); + selectedIndex = 0; + bindings: StepBinding[] = []; proposedYaml = ''; @@ -237,12 +236,7 @@ export class AgentAppUpdateFlowComponent extends PageComponent implements OnInit openEditProfile() { if (!this.profileForCompare) { return; } - this.dialog.open( - AgentAppProfileWizardComponent, { - disableClose: true, - panelClass: ['tb-dialog', 'tb-fullscreen-dialog', 'tb-agent-wizard-dialog'], - data: { profile: this.profileForCompare } - }).afterClosed().subscribe(saved => { + openAgentAppProfileWizard(this.dialog, { profile: this.profileForCompare }).subscribe(saved => { if (saved) { this.profileForCompare = saved; this.refreshFutureCompare(); diff --git a/ui-ngx/src/app/modules/home/components/agent/wizard/agent-app-upgrade-flow.component.html b/ui-ngx/src/app/modules/home/components/agent/wizard/agent-app-upgrade-flow.component.html index aba02480fa..bf7cfeb2e2 100644 --- a/ui-ngx/src/app/modules/home/components/agent/wizard/agent-app-upgrade-flow.component.html +++ b/ui-ngx/src/app/modules/home/components/agent/wizard/agent-app-upgrade-flow.component.html @@ -5,30 +5,21 @@ --> @if (!embedded) { - + @if (showBack) { - } -
-

{{ 'agent.app-upgrade-title' | translate }}@if (existingApplication) { - : - }

- @if (existingApplication) { - - {{ 'agent.app-upgrade-heading' | translate: { name: existingApplication?.name, from: fromVersion || '—', to: toVersion || '—' } }} - - } -
+

{{ 'agent.app-upgrade-title' | translate }}@if (existingApplication) {: {{ 'agent.app-upgrade-heading' | translate: { name: existingApplication?.name, from: fromVersion || '—', to: toVersion || '—' } }}}

+
-
} - -
+
@if (loadingTemplate || loadingProfile) {
@@ -45,143 +36,154 @@ @if (!(loadingTemplate || loadingProfile || loadError)) { - @if (showProfileUpgradeStep) { - - @if (loadingProfile) { -
- - agent.app-upgrade-profile-loading -
+ @for (step of steps; track step) { + @switch (step) { + @case ('profile') { + + @if (loadingProfile) { +
+ + agent.app-upgrade-profile-loading +
+ } + @if (!loadingProfile && profileLoadError) { +
+ error_outline + {{ profileLoadError }} +
+ } + @if (!loadingProfile && !profileLoadError && profile && template) { +
+
+ agent.app-upgrade-profile-name + {{ profile.name }} +
+
+ agent.app-upgrade-summary-versions + {{ fromVersion || '—' }} → {{ toVersion || '—' }} +
+
+

agent.app-upgrade-profile-hint

+
+
+ {{ 'agent.app-upgrade-template-new' | translate: { version: toVersion || '—' } }} +
+
agent.app-upgrade-profile-current
+ @if (profileUpgraded) { +
+ lock + agent.app-diff-read-only +
+ } + +
+ +

agent.app-upgrade-diff-hint

+ } +
} - @if (!loadingProfile && profileLoadError) { -
- error_outline - {{ profileLoadError }} -
+ @case ('config') { + + @if (canHaveRelatedEntity && isProfileBoundUpgrade) { + + + } + + @if (!isProfileBoundUpgrade) { +
+
+ {{ 'agent.app-upgrade-template-new' | translate: { version: toVersion || '—' } }} +
+
agent.app-upgrade-current
+ +
+ +

agent.app-upgrade-diff-hint

+ } +
} - @if (!loadingProfile && !profileLoadError && profile && template) { -
-
- agent.app-upgrade-profile-name - {{ profile.name }} -
-
- agent.app-upgrade-summary-versions - {{ fromVersion || '—' }} → {{ toVersion || '—' }} + @case ('summary') { + +
+
+ agent.app-name + {{ appName }} +
+
+ agent.app-upgrade-summary-versions + {{ fromVersion || '—' }} → {{ toVersion || '—' }} +
+ @if (hasBackupVolumeInput) { +
+ agent.app-upgrade-summary-volumes-label + + {{ 'agent.app-upgrade-summary-volumes' | translate: { count: selectedBackupVolumeCount } }} + +
+ }
-
-

agent.app-upgrade-profile-hint

-
-
- {{ 'agent.app-upgrade-template-new' | translate: { version: toVersion || '—' } }} +
+ info_outline + agent.app-upgrade-rollback-info
-
agent.app-upgrade-profile-current
- @if (profileUpgraded) { -
- lock - agent.app-diff-read-only -
- } - -
- -

agent.app-upgrade-diff-hint

+ } - - - } - - @if (canHaveRelatedEntity && isProfileBoundUpgrade) { - - - } - - @if (!isProfileBoundUpgrade) { -
-
- {{ 'agent.app-upgrade-template-new' | translate: { version: toVersion || '—' } }} -
-
agent.app-upgrade-current
- -
- -

agent.app-upgrade-diff-hint

} - -
- -
-
- agent.app-name - {{ appName }} -
-
- agent.app-upgrade-summary-versions - {{ fromVersion || '—' }} → {{ toVersion || '—' }} -
- @if (hasBackupVolumeInput) { -
- agent.app-upgrade-summary-volumes-label - - {{ 'agent.app-upgrade-summary-volumes' | translate: { count: selectedBackupVolumeCount } }} - -
- } -
-
- info_outline - agent.app-upgrade-rollback-info -
- -
+ } }
+
+ @if (canGoBack() || showNext()) { +
+ @if (canGoBack()) { + + } + + @if (showNext()) { + + } +
+ + } +
+ + @if (currentStep() === 'profile' && !profileUpgraded) { + + } @else { + + } +
+
diff --git a/ui-ngx/src/app/modules/home/components/agent/wizard/agent-app-upgrade-flow.component.scss b/ui-ngx/src/app/modules/home/components/agent/wizard/agent-app-upgrade-flow.component.scss index fcbe6cb001..d3ab782e2b 100644 --- a/ui-ngx/src/app/modules/home/components/agent/wizard/agent-app-upgrade-flow.component.scss +++ b/ui-ngx/src/app/modules/home/components/agent/wizard/agent-app-upgrade-flow.component.scss @@ -2,7 +2,7 @@ // SPDX-License-Identifier: BUSL-1.1 @use 'agent-wizard' as *; -@include wizard-chrome; +@include wizard-stepper-dialog(1280px); @include wizard-step-basics; @include wizard-diff; @include wizard-summary; diff --git a/ui-ngx/src/app/modules/home/components/agent/wizard/agent-app-upgrade-flow.component.ts b/ui-ngx/src/app/modules/home/components/agent/wizard/agent-app-upgrade-flow.component.ts index 12a0e21ae7..133567985a 100644 --- a/ui-ngx/src/app/modules/home/components/agent/wizard/agent-app-upgrade-flow.component.ts +++ b/ui-ngx/src/app/modules/home/components/agent/wizard/agent-app-upgrade-flow.component.ts @@ -29,7 +29,12 @@ import { ActionNotificationShow } from '@core/notification/notification.actions' import * as YAML from 'yaml'; import { AgentAppWizardLoaderService } from '@home/pages/agent/wizard/agent-app-wizard-loader.service'; import { AgentAppWizardSubmitService } from '@home/pages/agent/wizard/agent-app-wizard-submit.service'; -import { AgentAppUpgradeResult, AgentAppWizardFinish } from '@home/pages/agent/wizard/agent-app-wizard.models'; +import { + AGENT_APP_UPGRADE_STEP_LABELS, + AgentAppUpgradeResult, + AgentAppUpgradeStepKey, + AgentAppWizardFinish +} from '@home/pages/agent/wizard/agent-app-wizard.models'; @Component({ selector: 'tb-agent-app-upgrade-flow', @@ -65,10 +70,11 @@ export class AgentAppUpgradeFlowComponent extends PageComponent implements OnIni profileLoadError = ''; profileUpgrading = false; profileUpgraded = false; - showProfileUpgradeStep = false; - @ViewChild('stepper', { static: false }) stepper: MatStepper; + readonly stepLabels = AGENT_APP_UPGRADE_STEP_LABELS; + steps: AgentAppUpgradeStepKey[] = ['config', 'summary']; + selectedIndex = 0; bindings: StepBinding[] = []; @@ -210,7 +216,7 @@ export class AgentAppUpgradeFlowComponent extends PageComponent implements OnIni private maybeInitProfileDiff() { if (!this.needsProfileUpgrade || !this.template || !this.profile || this.profileMergeRequested) { return; } this.profileMergeRequested = true; - this.showProfileUpgradeStep = true; + this.steps = ['profile', 'config', 'summary']; const profileComposeType = dockerComposeConfig(this.profile)?.composeType || undefined; this.profileProposedYaml = dumpRawTemplateCompose(this.template, profileComposeType); const draft = { ...this.profile, templateVersion: this.template.currentVersion } as AgentAppProfile; @@ -354,4 +360,25 @@ export class AgentAppUpgradeFlowComponent extends PageComponent implements OnIni // the caller refresh even when the user backs out before the app upgrade. this.cancelled.emit(this.profileUpgraded ? { profileOnly: true } : null); } + + currentStep(): AgentAppUpgradeStepKey | undefined { + return this.loadingTemplate || this.loadingProfile || this.loadError ? undefined : this.steps[this.selectedIndex]; + } + + canGoBack(): boolean { + return this.selectedIndex > 0 && this.steps[this.selectedIndex - 1] !== 'profile'; + } + + showNext(): boolean { + const step = this.currentStep(); + return step === 'config' || (step === 'profile' && this.profileUpgraded); + } + + canGoNext(): boolean { + return this.currentStep() === 'profile' ? this.profileUpgraded : this.canSubmit(); + } + + nextStepLabel(): string { + return this.stepLabels[this.steps[this.selectedIndex + 1]] ?? ''; + } } diff --git a/ui-ngx/src/app/modules/home/components/ai/_ai-breakpoints.scss b/ui-ngx/src/app/modules/home/components/ai/_ai-breakpoints.scss new file mode 100644 index 0000000000..fae4946635 --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/ai/_ai-breakpoints.scss @@ -0,0 +1,7 @@ +// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: BUSL-1.1 + +// Widths at which the AI chat drops secondary text. The chat head's narrow width used by the +// component code is AI_NARROW_HEAD_WIDTH in ai-breakpoints.ts. +$ai-head-status-hidden-below: 400px; +$ai-composer-auto-label-max: 400px; diff --git a/ui-ngx/src/app/modules/home/components/ai/_ai-code-blocks.scss b/ui-ngx/src/app/modules/home/components/ai/_ai-code-blocks.scss new file mode 100644 index 0000000000..5596a7f727 --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/ai/_ai-code-blocks.scss @@ -0,0 +1,506 @@ +// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: BUSL-1.1 +@mixin ai-code-blocks { + div.code-wrapper { + margin-top: 14px; + } + + .tb-codeblock { + position: relative; + min-width: 0; + font-size: 14px; + line-height: 20px; + border-radius: 10px; + background: var(--tb-code-bg); + box-shadow: inset 0 0 0 1px rgba(255, 255, 255, 0.05); + + &.folded { + .tb-code { + display: none; + } + + .tb-codeblock-head { + border-bottom-color: transparent; + } + } + + &:not(.labeled) .tb-code { + padding-right: 44px; + } + + &.labeled .tb-code { + border-radius: 0 0 10px 10px; + } + + &:is([data-lang="python"], [data-lang="js"], [data-lang="c"], [data-lang="json"], [data-lang="yaml"]) .tb-code { + overflow-x: auto; + scrollbar-width: thin; + scrollbar-color: rgba(255, 255, 255, 0.2) transparent; + + &, code { + white-space: pre; + overflow-wrap: normal; + } + } + + &.wrap .tb-code { + &, code { + white-space: pre-wrap; + overflow-wrap: anywhere; + } + } + } + + .tb-codeblock-head { + display: flex; + align-items: center; + gap: 8px; + height: 36px; + box-sizing: border-box; + padding: 0 4px 0 12px; + border-bottom: 1px solid var(--tb-code-line); + font-family: var(--tb-font); + font-size: 12px; + line-height: 16px; + letter-spacing: .2px; + font-weight: 500; + color: var(--tb-code-head-fg); + + .mat-icon { + flex: none; + color: rgba(255, 255, 255, 0.42); + } + + > .tb-codeblock-label { + flex: 1; + min-width: 0; + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; + font-size: 12px; + line-height: 16px; + letter-spacing: .2px; + color: var(--tb-code-head-fg); + } + } + + .tb-codetabs { + flex: 1; + display: flex; + align-self: stretch; + gap: 2px; + min-width: 0; + margin-left: -4px; + overflow-x: auto; + scrollbar-width: none; + } + + .tb-codetab { + position: relative; + height: 100%; + padding: 0 8px; + border: 0; + border-radius: 6px 6px 0 0; + background: none; + font: 500 12px/16px var(--tb-font); + letter-spacing: .2px; + white-space: nowrap; + color: rgba(255, 255, 255, 0.62); + cursor: pointer; + + &:hover { + color: rgba(255, 255, 255, 0.85); + } + + &[aria-selected="true"] { + color: #fff; + + &::after { + content: ''; + position: absolute; + left: 8px; + right: 8px; + bottom: -1px; + height: 2px; + border-radius: 2px 2px 0 0; + background: var(--hl-cmd); + } + } + + &:focus-visible { + outline: 2px solid var(--tb-primary-300, #7fb5ff); + outline-offset: -4px; + } + } + + .tb-codefold { + flex: 1; + min-width: 0; + display: flex; + align-items: center; + gap: 8px; + height: 100%; + margin-left: -6px; + padding: 0 6px; + border: 0; + border-radius: 6px; + background: none; + color: inherit; + font: inherit; + letter-spacing: inherit; + text-align: left; + cursor: pointer; + + &:hover { + background: rgba(255, 255, 255, 0.05); + } + + &:focus-visible { + outline: 2px solid var(--tb-primary-300); + outline-offset: -2px; + } + + .tb-codeblock-label { + flex: none; + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; + } + + .tb-codeblock-size { + flex: none; + color: rgba(255, 255, 255, 0.55); + font-weight: 400; + white-space: nowrap; + } + + .tb-codefold-tg { + margin-left: auto; + transition: transform .2s ease; + } + } + + .tb-codeblock:not(.folded) .tb-codefold-tg { + transform: rotate(180deg); + } + + .tb-codecopy { + position: relative; + flex: none; + display: inline-flex; + align-items: center; + justify-content: center; + width: 28px; + height: 28px; + margin: 0; + padding: 0; + border: 0; + border-radius: 6px; + background: none; + color: rgba(255, 255, 255, 0.72); + font: inherit; + letter-spacing: normal; + cursor: pointer; + outline: none; + + &:hover { + background: rgba(255, 255, 255, 0.1); + color: #fff; + } + + &[aria-pressed="true"] { + background: rgba(255, 255, 255, 0.12); + color: #fff; + } + + &:focus-visible { + outline: 2px solid var(--tb-primary-300); + outline-offset: 1px; + } + + &.floating { + position: absolute; + top: 8px; + right: 8px; + } + + &::after { + content: attr(data-tip); + position: absolute; + right: 0; + bottom: calc(100% + 6px); + padding: 3px 8px; + border-radius: 5px; + background: #10181d; + color: #fff; + font: 500 11px/16px var(--tb-font); + letter-spacing: .2px; + white-space: nowrap; + box-shadow: 0 2px 8px rgba(16, 24, 40, 0.3); + opacity: 0; + pointer-events: none; + transition: opacity .12s ease; + } + + &.copied::after { + content: attr(data-copied); + } + + &:hover::after, &:focus-visible::after, &.copied::after { + opacity: 1; + } + } + + .tb-codecopy > .mat-icon { + transition: opacity .15s ease, transform .15s cubic-bezier(.2, 0, 0, 1); + } + + .tb-codecopy > .mat-icon.tb-copy-ok { + position: absolute; + inset: 0; + margin: auto; + opacity: 0; + transform: scale(.5); + color: var(--ai-dark-accent); + } + + .tb-codecopy.copied > .mat-icon:not(.tb-copy-ok) { + opacity: 0; + transform: scale(.5); + } + + .tb-codecopy.copied > .mat-icon.tb-copy-ok { + opacity: 1; + transform: scale(1); + } + + .tb-codecopy.labelled { + width: auto; + gap: 5px; + padding: 0 8px 0 6px; + + &::after { + display: none; + } + } + + .tb-codeblock.value { + display: flex; + align-items: center; + gap: 8px; + min-height: 36px; + box-sizing: border-box; + padding: 0 4px 0 12px; + color: var(--tb-code-fg); + font: 500 12px/16px var(--tb-font); + letter-spacing: .2px; + + .tb-codeblock-label { + flex: none; + min-width: 84px; + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; + color: rgba(255, 255, 255, 0.62); + } + + > code.tb-value { + flex: 1; + min-width: 0; + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; + padding: 0; + border: 0; + border-radius: 0; + background: none; + font: 13px/20px var(--tb-mono); + letter-spacing: 0; + color: var(--tb-code-fg); + } + } + + .tb-cmdrow { + display: flex; + align-items: center; + gap: 10px; + min-height: 40px; + box-sizing: border-box; + padding: 6px 6px 6px 12px; + border-radius: 8px; + background: var(--tb-code-bg); + box-shadow: inset 0 0 0 1px rgba(255, 255, 255, 0.05); + + .tb-cmd-p { + flex: none; + font: 500 13px/20px var(--tb-mono); + color: #7d8c96; + } + + > code.tb-cmd-t { + flex: 1; + min-width: 0; + overflow-x: auto; + scrollbar-width: none; + white-space: nowrap; + padding: 0; + border: 0; + border-radius: 0; + background: none; + font: 400 13px/20px var(--tb-mono); + color: #e8eef2; + -webkit-font-smoothing: antialiased; + } + + .tb-codecopy.tb-cmd-copy { + color: #b4bec6; + } + } + + pre.tb-code, pre.tb-code[class*=language-] { + margin: 0; + padding: 12px 16px 14px; + border: 0; + border-radius: 10px; + background: none; + box-shadow: none; + font-family: var(--tb-mono); + font-size: var(--chat-code); + line-height: var(--chat-code-lh); + color: var(--tb-code-fg); + white-space: pre-wrap; + overflow-wrap: anywhere; + -webkit-font-smoothing: antialiased; + + code, code[class*=language-] { + display: block; + white-space: inherit; + overflow-wrap: inherit; + padding: 0; + border: 0; + border-radius: 0; + background: none; + font: inherit; + color: inherit; + text-shadow: none; + } + } + + .tb-line { + display: block; + min-height: 20px; + + &.add, &.del { + margin: 0 -16px; + padding: 0 16px; + } + + &.add { + background: rgba(143, 227, 211, 0.12); + color: var(--hl-cmd); + } + + &.del { + background: rgba(255, 157, 146, 0.12); + color: var(--hl-err); + } + } + + .tb-codeblock.shell .tb-line { + padding-left: 24px; + text-indent: -24px; + + &.cont { + padding-left: 40px; + } + } + + pre.tb-code div.tb-cmd { + font: inherit; + letter-spacing: inherit; + color: inherit; + } + + .tb-cmd { + position: relative; + margin: 0 -8px; + padding: 2px 36px 2px 8px; + border-radius: 6px; + + & + .tb-cmd { + margin-top: 4px; + } + + &:hover, &:focus-within { + background: rgba(255, 255, 255, 0.05); + + .tb-cmdcopy { + opacity: 1; + } + } + } + + .tb-codecopy.tb-cmdcopy { + position: absolute; + top: 0; + right: 4px; + width: 24px; + height: 24px; + opacity: 0; + text-indent: 0; + + &.copied { + opacity: 1; + } + } + + @media (hover: none) { + .tb-codecopy.tb-cmdcopy { + opacity: .6; + } + } + + .hl-cmd, .hl-ok { + color: var(--hl-cmd); + } + + .hl-flag { + color: var(--hl-flag); + } + + .hl-str, .hl-warn { + color: var(--hl-str); + } + + .hl-num, .hl-kw { + color: var(--hl-num); + } + + .hl-key, .hl-var { + color: var(--hl-key); + } + + .hl-com, .hl-op { + color: var(--hl-com); + } + + .hl-err { + color: var(--hl-err); + } + + .hl-val { + color: var(--tb-code-fg); + } + + .hl-fn { + color: var(--hl-fn); + } + + .hl-bool { + color: var(--hl-bool); + } + + .hl-lvl { + color: var(--hl-lvl); + } +} diff --git a/ui-ngx/src/app/modules/home/components/ai/_ai-icon-button.scss b/ui-ngx/src/app/modules/home/components/ai/_ai-icon-button.scss new file mode 100644 index 0000000000..894eeaad97 --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/ai/_ai-icon-button.scss @@ -0,0 +1,40 @@ +// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: BUSL-1.1 +@mixin ai-icon-button($color: var(--tb-ink-54), $icon: 19px, $tap: true, $relative: true) { + @if $relative { + position: relative; + } + flex: none; + width: 32px; + height: 32px; + @if $tap { + min-width: var(--chat-tap); + min-height: var(--chat-tap); + } + padding: 0; + border: 0; + border-radius: 8px; + background: none; + color: $color; + display: inline-flex; + align-items: center; + justify-content: center; + cursor: pointer; + transition: background-color .15s ease, color .15s ease; + + &:hover { + background: rgba(0, 0, 0, 0.06); + color: var(--tb-ink); + } + + &:focus-visible { + outline: 2px solid var(--ai-focus); + outline-offset: 1px; + } + + .mat-icon { + font-size: $icon; + width: $icon; + height: $icon; + } +} diff --git a/ui-ngx/src/app/modules/home/components/ai/ai-action-detail.component.html b/ui-ngx/src/app/modules/home/components/ai/ai-action-detail.component.html new file mode 100644 index 0000000000..fd61708266 --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/ai/ai-action-detail.component.html @@ -0,0 +1,258 @@ + +@if (hood()) { +

{{ 'ai-assistant.detail.asked-for' | translate }}{{ hood() }}

+} +@for (block of view().blocks; track $index) { + @switch (block.type) { + @case ('hub') { +
+ @for (rec of shown(hub(), 'hub'); track rec.key) { + + } + @if (hub().length > LIST_SHOWN) { + + } +
+ } + @case ('records') { + @if (block.label) { +
{{ say(block.label) }}
+ } +
+ @for (row of shown(block.rows, 'records' + $index); track $index) { +
+ + @if (recordUrl(row); as url) { + {{ row.name }} + } @else { + {{ row.name }} + } + @if (row.status) { + {{ 'ai-assistant.detail.alarm-meta' | translate:{ + severity: ('alarm.severity-' + (row.severity || 'indeterminate').toLowerCase()) | translate, + status: ('ai-assistant.detail.alarm-status.' + row.status) | translate, + since: row.since || '—'} }} + } @else if (row.meta) { + {{ row.meta }} + } +
+ } + @if (block.rows.length > LIST_SHOWN) { + + } +
+ @if (more(block); as rest) { +
{{ 'ai-assistant.detail.more' | translate:{count: rest} }}
+ } + } + @case ('values') { + @if (block.entity) { +

{{ entityName(block.entity) }}

+ } @else if (block.label) { +
{{ say(block.label) }}
+ } +
+ @for (row of block.rows; track $index) { +
{{ row.key }}
+
{{ row.value }}
+ } +
+ } + @case ('series') { + @if (block.entity) { +

{{ entityName(block.entity) }}

+ } + + + + + + + + + + + @for (row of block.rows; track row.key) { + + + + + + + } + +
{{ 'ai-assistant.detail.history-key' | translate }}{{ 'ai-assistant.detail.history-curve' | translate }}{{ 'ai-assistant.detail.history-last' | translate }}{{ 'ai-assistant.detail.history-range' | translate }}
{{ row.key }} + + {{ row.lastText ?? number(row.last) }}{{ row.changes !== undefined + ? ('ai-assistant.detail.history-changes' | translate: {count: row.changes}) + : ('ai-assistant.detail.history-span' | translate: {min: number(row.min), max: number(row.max)}) }}
+ } + @case ('keys') { + @if (block.label) { +
{{ say(block.label) }}
+ } +
+ @for (key of block.keys; track $index) { + {{ key }} + } +
+ } + @case ('facts') { + @if (changeRows(block.rows); as changes) { + @if (changes.length) { +
+ @for (change of changes; track $index) { +
+
{{ label(change) }}
+ @if (change.images; as pair) { +
+ @if (pair.current) { + + } @else { + + } + + {{ 'ai-assistant.review.changes-to' | translate }} + @if (pair.value) { + + } @else { + + } +
+ } @else { +
+ {{ change.was }} + + {{ 'ai-assistant.review.changes-to' | translate }} + {{ factValue(change) }} +
+ } +
+ } +
+ } + } + @if (plainRows(block.rows).length) { +
+ @for (fact of plainRows(block.rows); track $index) { +
{{ label(fact) }}
+
+ @if (fact.images; as pair) { + + @if (pair.current) { + + + } + @if (pair.value) { + + } @else { + {{ 'ai-assistant.review.not-set' | translate }} + } + + } @else if (fact.chip; as chip) { + + @if (chip.image) { + + } @else if (chip.icon) { + + } + {{ factValue(fact) }} + + } @else if (factLink(fact); as url) { + {{ factValue(fact) }} + } @else if (fact.secret && !revealed().has(view().hood?.key + $index)) { + {{ masked(factValue(fact)) }} + + } @else { + {{ factValue(fact) }} + } +
+ } +
+ } + } + @case ('list') { + @if (block.label) { +
{{ say(block.label) }}
+ } +
    + @for (row of block.rows; track $index) { +
  • {{ rowText(row) }}
  • + } +
+ } + @case ('commands') { +
+ } + @case ('code') { + @if (block.title) { +
{{ ('ai-assistant.action.' + block.title) | translate }}
+ } +
{{ block.text }}
+ } + @case ('links') { + + } + @case ('markdown') { +
+ +
+ } + @case ('images') { +
+ @for (image of block.rows; track image.url) { +
+ + @if (image.label) { +
{{ say(image.label) }}
+ } +
+ } +
+ } + @case ('warning') { +
{{ 'ai-assistant.detail.heads-up' | translate }}@if (block.label) {{{ say(block.label) }} }@for (row of block.rows; track $index) {{{ rowText(row) }}@if (!$last) {; }}
+ } + @case ('found') { +

{{ say(block.text) }}

+ } + @case ('note') { +

{{ say(block.text) }}

+ } + @case ('text') { +

{{ block.text }}

+ } + @case ('json') { +
{{ ('ai-assistant.action.' + block.label) | translate }}
+
{{ block.text }}
+ } + } +} + + + + diff --git a/ui-ngx/src/app/modules/home/components/ai/ai-action-detail.component.ts b/ui-ngx/src/app/modules/home/components/ai/ai-action-detail.component.ts new file mode 100644 index 0000000000..a810676ce5 --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/ai/ai-action-detail.component.ts @@ -0,0 +1,293 @@ +// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: BUSL-1.1 +import { aiTrueMinus } from '@home/components/ai/ai-text'; +import { afterRenderEffect, ChangeDetectionStrategy, Component, computed, DestroyRef, effect, ElementRef, inject, input, signal, untracked } from '@angular/core'; +import { ClipboardService } from 'ngx-clipboard'; +import { takeUntilDestroyed } from '@angular/core/rxjs-interop'; +import { TranslateService } from '@ngx-translate/core'; +import { forkJoin, of } from 'rxjs'; +import { catchError, map } from 'rxjs/operators'; +import { EntityType, baseDetailsPageByEntityType } from '@shared/models/entity-type.models'; +import { EntityService } from '@core/http/entity.service'; +import { IotHubApiService } from '@core/http/iot-hub-api.service'; +import { MpItemVersionView } from '@shared/models/iot-hub/iot-hub-version.models'; +import { AiRecordLoaderService } from '@home/components/ai/ai-record-loader.service'; +import { AiRecordView } from '@home/components/ai/ai-record.models'; +import { getEntityDetailsPageURL } from '@core/utils'; +import { aiEntityKind, aiJoinWords, aiThingWord, isAiWordList } from '@home/components/ai/ai-action.models'; +import { codeTabsBlock, decorateCodeBlocks } from '@home/components/ai/ai-code-block'; +import { readStored, writeStored } from '@core/local-storage/stored'; +import { + AiDetailBlock, + AiDetailEntity, + AiDetailFact, + AiDetailNames, + AiDetailRecord, + AiDetailText, + AiDetailView +} from '@home/components/ai/ai-action-detail.models'; + +const FETCHED = new Set([ + EntityType.DEVICE, EntityType.ASSET, EntityType.DASHBOARD, EntityType.CUSTOMER, EntityType.USER, EntityType.DEVICE_PROFILE, + EntityType.ASSET_PROFILE, EntityType.ENTITY_VIEW, EntityType.EDGE, EntityType.RULE_CHAIN +]); + +const MAX_HUB = 50; + +const PROTOCOL_KEY = 'tb-ai-code-protocol'; + +@Component({ + selector: 'tb-ai-action-detail', + templateUrl: './ai-action-detail.component.html', + standalone: false, + changeDetection: ChangeDetectionStrategy.OnPush, + host: { + 'class': 'k-detail' + } +}) +export class AiActionDetailComponent { + + view = input.required(); + + names = input(new Map()); + + private translate = inject(TranslateService); + private entityService = inject(EntityService); + private iotHubApi = inject(IotHubApiService); + private recordLoader = inject(AiRecordLoaderService); + private destroyRef = inject(DestroyRef); + private host = inject(ElementRef); + private clipboard = inject(ClipboardService); + + private fetched = signal>(new Map()); + + private hubItems = signal>(new Map()); + + revealed = signal>(new Set()); + + readonly LIST_SHOWN = 8; + + private opened = signal>(new Set()); + + isOpen(key: string): boolean { + return this.opened().has(key); + } + + toggleMore(key: string): void { + const next = new Set(this.opened()); + if (!next.delete(key)) { + next.add(key); + } + this.opened.set(next); + } + + shown(rows: T[], key: string): T[] { + return this.isOpen(key) ? rows : rows.slice(0, this.LIST_SHOWN); + } + + hood = computed(() => { + const hood = this.view().hood; + this.fetched(); + return hood ? this.say(hood) : ''; + }); + + hub = computed(() => { + const block = this.view().blocks.find(item => item.type === 'hub'); + const items = this.hubItems(); + if (block?.type !== 'hub') { + return []; + } + return block.rows.map(row => { + const item = items.get(row.id); + if (item) { + const view = this.recordLoader.hubView(item); + return {...view, description: row.description ?? view.description}; + } + return { + key: `HUB:${row.id}`, entityType: 'SOLUTION_TEMPLATE', alarmRule: false, name: row.name, meta: '', + url: `/iot-hub/version/${row.id}`, description: row.description, + hub: {type: '', creator: row.vendor} + }; + }); + }); + + constructor() { + effect(() => { + const view = this.view(); + untracked(() => { + this.resolveNames(view); + this.loadHub(view); + }); + }); + afterRenderEffect(() => { + const view = this.view(); + const copy = (text: string) => this.clipboard.copyFromContent(text); + decorateCodeBlocks(this.host.nativeElement, this.translate, copy); + this.host.nativeElement.querySelectorAll('.k-codetabs-slot:empty').forEach((slot: HTMLElement) => { + const block = view.blocks[Number(slot.dataset.block)]; + if (block?.type === 'commands' && block.rows.length) { + const remembered = this.rememberedTab(); + const initial = Math.max(block.rows.findIndex(row => row.label === remembered), 0); + slot.append(codeTabsBlock(block.rows, 'bash', this.translate, copy, initial, tab => this.rememberTab(tab.label))); + } + }); + }); + } + + say(text: AiDetailText): string { + const params: Record = {}; + for (const [key, value] of Object.entries(text.params ?? {})) { + params[key] = isAiWordList(value) ? aiJoinWords(this.translate, value) + : typeof value === 'object' ? this.entityText(value) : typeof value === 'string' && value.startsWith('ai-assistant.') ? this.translate.instant(value) : value; + } + return this.translate.instant(text.key, params); + } + + codeLabel(label: string): string { + return label.startsWith('ai-assistant.') ? this.translate.instant(label) : label; + } + + label(fact: AiDetailFact): string { + return fact.raw ? fact.label : this.translate.instant(fact.label); + } + + rowText(row: string | AiDetailText): string { + return typeof row === 'string' ? row : this.say(row); + } + + factValue(fact: AiDetailFact): string { + if (fact.say) { + return this.say(fact.say); + } + if (fact.entity) { + return this.nameOf(fact.entity) ?? fact.entity.id ?? '—'; + } + return fact.value && (fact.chip || fact.value.startsWith('ai-assistant.')) ? this.translate.instant(fact.value) : fact.value ?? ''; + } + + factLink(fact: AiDetailFact): string | null { + return fact.entity ? this.urlOf(fact.entity.id, fact.entity.entityType) : null; + } + + masked(value: string): string { + return value.length <= 6 ? '••••••' : '••••••••' + value.slice(-4); + } + + reveal(key: string): void { + this.revealed.update(set => new Set(set).add(key)); + } + + recordUrl(record: AiDetailRecord): string | null { + if (record.entityType === EntityType.ENTITY_GROUP) { + const base = record.id && record.groupType ? baseDetailsPageByEntityType.get(record.groupType as EntityType) : undefined; + return base ? `${base.replace(/\/all$/, '/groups')}/${record.id}` : null; + } + return this.urlOf(record.id, record.entityType); + } + + kind(entityType: string, groupType?: string) { + return entityType === 'IMAGE' ? {icon: 'image', palette: 'view'} : aiEntityKind(entityType, entityType === 'ALARM_RULE', groupType); + } + + more(block: AiDetailBlock): number { + return block.type === 'records' && block.total ? Math.max(block.total - block.rows.length, 0) : 0; + } + + time(ts: number): string { + return new Date(ts).toLocaleString([], {dateStyle: 'short', timeStyle: 'short'}); + } + + number(value?: number): string { + if (value === undefined) { + return ''; + } + return aiTrueMinus(Number.isInteger(value) ? String(value) : String(Math.round(value * 100) / 100)); + } + + private rememberedTab(): string | null { + return readStored(PROTOCOL_KEY); + } + + private rememberTab(label: string): void { + writeStored(PROTOCOL_KEY, label); + } + + changeRows(rows: AiDetailFact[]): AiDetailFact[] { + return rows.filter(row => row.change); + } + + plainRows(rows: AiDetailFact[]): AiDetailFact[] { + return rows.filter(row => !row.change); + } + + entityName(entity: AiDetailEntity): string { + return this.nameOf(entity) ?? this.translate.instant('ai-assistant.detail.this', {what: this.typeWord(entity.entityType)}); + } + + private entityText(entity: AiDetailEntity): string { + const name = this.nameOf(entity); + if (name) { + return name; + } + return this.translate.instant('ai-assistant.detail.this', {what: this.typeWord(entity.entityType)}); + } + + private typeWord(entityType?: string): string { + return aiThingWord(this.translate, entityType, 'ai-assistant.detail.thing.entity'); + } + + private nameOf(entity: AiDetailEntity): string | undefined { + return entity.name ?? (entity.id ? this.names().get(entity.id)?.name ?? this.fetched().get(entity.id) : undefined); + } + + private urlOf(id?: string, entityType?: string): string | null { + return id && entityType && FETCHED.has(entityType) ? getEntityDetailsPageURL(id, entityType as EntityType) || null : null; + } + + private resolveNames(view: AiDetailView): void { + const wanted = new Map(); + const want = (entity?: AiDetailEntity) => { + if (entity?.id && !entity.name && entity.entityType && FETCHED.has(entity.entityType) && !this.names().has(entity.id) && !this.fetched().has(entity.id)) { + wanted.set(entity.id, entity.entityType); + } + }; + Object.values(view.hood?.params ?? {}).forEach(value => typeof value === 'object' && !isAiWordList(value) && want(value)); + view.blocks.forEach(block => { + if (block.type === 'facts') { + block.rows.forEach(fact => want(fact.entity)); + } else if (block.type === 'values' || block.type === 'series') { + want(block.entity); + } + }); + if (!wanted.size) { + return; + } + const config = {ignoreLoading: true, ignoreErrors: true}; + forkJoin([...wanted].map(([id, type]) => this.entityService.getEntity(type as EntityType, id, config).pipe( + map(found => [id, (found as {name?: string; title?: string})?.name ?? (found as {title?: string})?.title] as [string, string]), + catchError(() => of([id, undefined] as [string, string])) + ))).pipe(takeUntilDestroyed(this.destroyRef)).subscribe(found => { + const next = new Map(this.fetched()); + found.filter(([, name]) => !!name).forEach(([id, name]) => next.set(id, name)); + this.fetched.set(next); + }); + } + + private loadHub(view: AiDetailView): void { + const block = view.blocks.find(item => item.type === 'hub'); + if (block?.type !== 'hub' || !this.iotHubApi.baseUrl) { + return; + } + const ids = block.rows.slice(0, MAX_HUB).map(row => row.id).filter(id => !this.hubItems().has(id)); + if (!ids.length) { + return; + } + const config = {ignoreLoading: true, ignoreErrors: true}; + forkJoin(ids.map(id => this.iotHubApi.getVersionInfo(id, config).pipe(catchError(() => of(null))))).pipe(takeUntilDestroyed(this.destroyRef)) + .subscribe(items => { + const next = new Map(this.hubItems()); + items.filter(Boolean).forEach(item => next.set(item.id, item)); + this.hubItems.set(next); + }); + } +} diff --git a/ui-ngx/src/app/modules/home/components/ai/ai-action-detail.models.ts b/ui-ngx/src/app/modules/home/components/ai/ai-action-detail.models.ts new file mode 100644 index 0000000000..0180665132 --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/ai/ai-action-detail.models.ts @@ -0,0 +1,2393 @@ +// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: BUSL-1.1 +import { aiTrueMinus } from '@home/components/ai/ai-text'; +import { AiAction } from '@shared/models/ai-chat.models'; +import { aiPartTitle, aiPartWord, AiWordList, aiWordList, alarmUpdateAction, widgetParts } from '@home/components/ai/ai-action.models'; +import { IntegrationType, integrationTypeInfoMap } from '@shared/models/integration.models'; +import { ConverterType, converterTypeTranslationMap } from '@shared/models/converter.models'; + +const WIDGET_PART_LANGS: Record = {html: 'html', css: 'css', js: 'javascript'}; + +const SCADA_SYMBOL_PART_LANGS: Record = {svg: 'html', functions: 'javascript'}; + +export interface AiDetailEntity { + id?: string; + entityType?: string; + name?: string; +} + +export type AiDetailParam = string | number | AiDetailEntity | AiWordList; + +export interface AiDetailText { + key: string; + params?: Record; +} + +export interface AiDetailRecord { + entityType: string; + groupType?: string; + id?: string; + name: string; + meta?: string; + severity?: string; + status?: string; + since?: string; +} + +export interface AiDetailHubItem { + id: string; + name: string; + vendor?: string; + description?: string; +} + +export interface AiDetailValue { + key: string; + value: string; + time?: number; +} + +export interface AiDetailSeries { + key: string; + points: number; + min?: number; + max?: number; + last?: number; + lastText?: string; + changes?: number; + from: number; + to: number; + path: string; + dot: number; +} + +export interface AiDetailFact { + label: string; + raw?: boolean; + value?: string; + say?: AiDetailText; + entity?: AiDetailEntity; + mono?: boolean; + secret?: boolean; + images?: {current?: string; value?: string}; + chip?: {icon?: string; image?: string}; + change?: boolean; + was?: string; + long?: boolean; +} + +export interface AiDetailCommand { + label: string; + text: string; +} + +export interface AiDetailLink { + title: string; + url: string; + from: string; + snippet?: string; +} + +export type AiDetailBlock = + | {type: 'records'; label?: AiDetailText; rows: AiDetailRecord[]; total?: number} + | {type: 'hub'; rows: AiDetailHubItem[]} + | {type: 'values'; label?: AiDetailText; entity?: AiDetailEntity; rows: AiDetailValue[]} + | {type: 'series'; entity?: AiDetailEntity; rows: AiDetailSeries[]} + | {type: 'keys'; label?: AiDetailText; keys: string[]} + | {type: 'facts'; rows: AiDetailFact[]} + | {type: 'list'; label?: AiDetailText; rows: Array} + | {type: 'commands'; rows: AiDetailCommand[]} + | {type: 'links'; rows: AiDetailLink[]} + | {type: 'markdown'; text: string} + | {type: 'code'; label: string; text: string; lang?: string; title?: string} + | {type: 'note'; text: AiDetailText} + | {type: 'found'; text: AiDetailText} + | {type: 'text'; text: string} + | {type: 'json'; label: string; text: string} + | {type: 'images'; rows: AiDetailImage[]} + | {type: 'warning'; label?: AiDetailText; rows: Array}; + +export interface AiDetailImage { + label?: AiDetailText; + url: string; +} + +export interface AiDetailView { + hood?: AiDetailText; + blocks: AiDetailBlock[]; +} + +export type AiDetailNames = ReadonlyMap; + +export interface AiStepView { + askedFor?: AiDetailText; + blocks: AiDetailBlock[]; + under: AiDetailBlock[]; +} + +const ASKED_FOR: Record = { + 'search-named': 'named', 'search-typed': 'typed', 'search-text': 'text', 'search-related-from': 'related-from', + 'search-related-to': 'related-to', 'read-attributes-scope': 'attributes-scope', + 'search-alarms': 'alarms', 'search-alarms-on': 'alarms-on', 'search-alarms-filter-on': 'alarms-filter-on', 'search-alarms-window': 'alarms-window', + 'search-alarms-filter-window': 'alarms-filter-window', 'search-alarms-on-window': 'alarms-on-window', 'search-alarms-filter-on-window': 'alarms-filter-on-window', + 'read-history': 'history', 'read-history-keys': 'history-keys', 'read-latest-keys': 'latest-keys', 'iot-hub-query': 'query', + 'search-web': 'query', 'read-widget-parts': 'widget' +}; + +export function aiStepView(action: AiAction, names: AiDetailNames): AiStepView { + const view = aiActionDetailView(action, names); + const hood = view.hood?.key.slice(K.length); + const asked = hood ? ASKED_FOR[hood] : undefined; + const askedFor = asked ? {key: K + 'asked.' + asked, params: view.hood.params} : undefined; + const under: AiDetailBlock[] = []; + const blocks: AiDetailBlock[] = []; + for (const block of view.blocks) { + if (block.type === 'list' && block.label?.key === K + 'widget-warnings') { + under.push({type: 'warning', label: block.label, rows: block.rows}); + } else { + blocks.push(block); + } + } + return {askedFor, blocks, under}; +} + +const K = 'ai-assistant.detail.'; + +const ALARM_FILTER_WORDS = new Set(['ACTIVE', 'CLEARED', 'ACK', 'UNACK', 'CRITICAL', 'MAJOR', 'MINOR', 'WARNING', 'INDETERMINATE']); + +const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i; + +const OK_ID = /^OK:\s*([0-9a-z_-]+)/i; + +const MAX_ROWS = 20; + +const SCOPES: Record = { + SERVER_SCOPE: 'server', + SHARED_SCOPE: 'shared', + CLIENT_SCOPE: 'client' +}; + +const SEARCHED: Record = { + DEVICE: 'devices', + ASSET: 'assets', + ENTITY_VIEW: 'entity-views', + EDGE: 'edges', + CUSTOMER: 'customers', + USER: 'users', + DASHBOARD: 'dashboards', + TENANT: 'tenants', + DEVICE_PROFILE: 'device-profiles', + ASSET_PROFILE: 'asset-profiles', + ENTITY_GROUP: 'groups' +}; + +const FILTER_TYPES: Record = { + deviceType: 'DEVICE', + assetType: 'ASSET', + entityViewType: 'ENTITY_VIEW', + edgeType: 'EDGE', + gateway: 'DEVICE', + alarm: 'ALARM', + alarmRule: 'ALARM_RULE', + calculatedField: 'CALCULATED_FIELD', + notificationTarget: 'NOTIFICATION_TARGET', + notificationTemplate: 'NOTIFICATION_TEMPLATE', + notificationRule: 'NOTIFICATION_RULE', + image: 'IMAGE', + entityGroupName: 'ENTITY_GROUP' +}; + +const FILTER_WORDS: Record = { + gateway: 'gateways', + alarm: 'alarms', + alarmRule: 'alarm-rules', + calculatedField: 'calculated-fields', + notificationTarget: 'notification-targets', + notificationTemplate: 'notification-templates', + notificationRule: 'notification-rules', + image: 'images' +}; + +const DELETE_TYPES: Record = { + DASHBOARD_WIDGET: 'DASHBOARD_WIDGET', + DASHBOARD_STATE: 'DASHBOARD_STATE', + DASHBOARD_ENTITY_ALIAS: 'DASHBOARD_ENTITY_ALIAS', + DASHBOARD_FILTER: 'DASHBOARD_FILTER' +}; + +type Values = Record; + +export function aiParse(value: unknown): unknown { + if (typeof value !== 'string') { + return value ?? undefined; + } + const text = value.trim(); + if (!text.startsWith('{') && !text.startsWith('[')) { + return value; + } + try { + return JSON.parse(text); + } catch { + return value; + } +} + +const isObject = (value: unknown): value is Values => !!value && typeof value === 'object' && !Array.isArray(value); + +const str = (value: unknown): string | undefined => typeof value === 'string' && value.trim() ? value.trim() : undefined; + +const idOf = (value: unknown): string | undefined => typeof value === 'string' ? value : isObject(value) ? str(value.id) : undefined; + +const okId = (result: unknown): string | undefined => typeof result === 'string' ? OK_ID.exec(result.trim())?.[1] : undefined; + + +export function aiValueText(value: unknown): string { + if (value === null || value === undefined) { + return '—'; + } + if (typeof value === 'number') { + return aiTrueMinus(Number.isInteger(value) ? String(value) : String(Math.round(value * 1000) / 1000)); + } + if (typeof value === 'string') { + const parsed = aiParse(value); + return parsed !== value ? aiValueText(parsed) : aiTrueMinus(value.length > 120 ? value.slice(0, 120) + '…' : value); + } + if (typeof value === 'boolean') { + return String(value); + } + const json = JSON.stringify(value); + return json.length > 120 ? json.slice(0, 120) + '…' : json; +} + +const ACRONYMS: ReadonlySet = new Set(['fqn', 'id', 'url', 'uri', 'ip', 'api', 'mqtt', 'mqtts', 'http', 'https', 'coap', 'coaps', + 'lwm2m', 'snmp', 'ota', 'json', 'tls', 'ssl', 'rpc', 'tbel', 'js', 'ttn', 'tti', 'sms', 'eui', 'oid', 'qos', 'cf']); + +export const aiHumanize = (key: string): string => { + const words = key.replace(/([a-z0-9])([A-Z])/g, '$1 $2').replace(/[_-]+/g, ' ').trim().toLowerCase(); + if (!words) { + return key; + } + const cased = words.split(' ').map(word => ACRONYMS.has(word) ? word.toUpperCase() : word).join(' '); + return cased.charAt(0).toUpperCase() + cased.slice(1); +}; + +function entity(id: unknown, entityType: unknown, names: AiDetailNames): AiDetailEntity { + const key = idOf(id); + const type = str(entityType) ?? (isObject(id) ? str(id.entityType) : undefined); + const known = key ? names.get(key) : undefined; + return {id: key, entityType: type ?? known?.entityType, name: known?.name}; +} + +function galleryImage(value: unknown): string | undefined { + const url = str(value); + return url && /^(tb-image;)?\/api\/images\//.test(url) ? url : undefined; +} + +function images(rows: {label?: AiDetailText; value: unknown}[]): AiDetailBlock[] { + const found: AiDetailImage[] = rows.map(row => ({label: row.label, url: galleryImage(row.value)})).filter(row => !!row.url); + return found.length ? [{type: 'images', rows: found}] : []; +} + +function text(key: string, params?: Record): AiDetailText { + return {key: K + key, params}; +} + +function scadaSymbolPicture(values: Values): AiDetailBlock[] { + const link = str(values.link); + return link && link.startsWith('tb-image;') ? [{type: 'images', rows: [{url: link}]}] : []; +} + +function scadaSymbolOverviewBlocks(overview: Values): AiDetailBlock[] { + const rows = facts(overview, ['link', 'note', 'tags', 'behavior', 'properties', 'problems', 'searchTags', 'description']); + const behaviors = Array.isArray(overview.behavior) + ? overview.behavior.filter(isObject).map(item => [item.name || item.id, item.default].filter(Boolean).join(' — ')) : []; + const problems = Array.isArray(overview.problems) ? overview.problems.map(item => String(item)) : []; + return [...scadaSymbolPicture(overview), ...(rows.length ? [{type: 'facts' as const, rows}] : []), + ...(behaviors.length ? [{type: 'list' as const, label: text('scada-symbol-behaviors'), rows: behaviors.slice(0, MAX_ROWS)}] : []), + ...(problems.length ? [{type: 'list' as const, label: text('scada-symbol-problems'), rows: problems.slice(0, MAX_ROWS)}] : [])]; +} + +const CODE_KEYS = new Set(['script', 'decoder', 'encoder', 'tbelDecoder', 'tbelEncoder', 'jsDecoder', 'jsEncoder']); + +const CONVERTER_ICONS: Record = {UPLINK: 'call_received', DOWNLINK: 'call_made'}; + +function converterTypeFact(type: unknown, label = K + 'fact.type'): AiDetailFact[] { + const key = converterTypeTranslationMap.get(type as ConverterType); + return key ? [{label, value: key, chip: {icon: CONVERTER_ICONS[type as string]}}] : []; +} + +function integrationTypeFact(type: unknown): AiDetailFact[] { + const info = integrationTypeInfoMap.get(type as IntegrationType); + return info ? [{label: K + 'fact.integration-type', value: info.name, chip: {image: info.icon}}] : []; +} + +function typedFact(key: string, value: unknown): AiDetailFact[] { + if (key === 'integrationType') { + return integrationTypeFact(value); + } + if (key === 'type' || key === 'converterType') { + return converterTypeFact(value); + } + return []; +} + +function codeBlocks(values: Values): AiDetailBlock[] { + return Object.entries(values).filter(([key, value]) => CODE_KEYS.has(key) && str(value)) + .map(([, value]) => ({type: 'code', title: 'script', label: 'TBEL', lang: 'tbel', text: (value as string).replace(/\n+$/, '')})); +} + +function messageBlock(label: string, value: unknown): AiDetailBlock[] { + if (isObject(value) || Array.isArray(value)) { + return [{type: 'json', label, text: JSON.stringify(value, null, 2)}]; + } + const text = str(value); + if (!text) { + return []; + } + const parsed = /^[[{]/.test(text) ? aiParse(text) : undefined; + return isObject(parsed) || Array.isArray(parsed) ? [{type: 'json', label, text: JSON.stringify(parsed, null, 2)}] : [{type: 'json', label, text}]; +} + +function converterBlocks(values: Values, result: unknown): AiDetailBlock[] { + const rows = [...converterTypeFact(values.type), ...integrationTypeFact(values.integrationType), + ...facts(values, ['type', 'integrationType', 'payload', 'metadata', 'integrationMetadata', ...CODE_KEYS])]; + const outcome = isObject(result) ? result : {}; + return [ + ...(rows.length ? [{type: 'facts' as const, rows}] : []), + ...codeBlocks(values), + ...messageBlock('payload', values.payload), + ...messageBlock('metadata', values.metadata), + ...messageBlock('error', outcome.error), + ...messageBlock('output', outcome.output), + ...messageBlock('result', outcome.result) + ]; +} + +function facts(values: Values, skip: string[] = [], names?: AiDetailNames): AiDetailFact[] { + const rows: AiDetailFact[] = []; + for (const [key, value] of Object.entries(values)) { + if (skip.includes(key) || value === null || value === undefined || value === '') { + continue; + } + const typed = typedFact(key, value); + if (typed.length) { + rows.push(...typed); + continue; + } + if (names && /Id$/.test(key) && (typeof value === 'string' || isObject(value)) && idOf(value)) { + const ref = entity(value, isObject(value) ? value.entityType : undefined, names); + rows.push(ref.name ? {label: aiHumanize(key.replace(/Id$/, '')), raw: true, entity: ref} : {label: aiHumanize(key), raw: true, value: idOf(value), mono: true}); + continue; + } + if (Array.isArray(value) && value.every(item => typeof item !== 'object')) { + rows.push({label: aiHumanize(key), raw: true, value: value.map(aiValueText).join(', ')}); + } else if (typeof value === 'object') { + rows.push({label: aiHumanize(key), raw: true, value: aiValueText(value), mono: true}); + } else { + rows.push({label: aiHumanize(key), raw: true, value: aiValueText(value)}); + } + } + return rows; +} + +function flat(value: unknown, depth = 0): boolean { + if (!isObject(value)) { + return false; + } + return Object.values(value).every(item => item === null || typeof item !== 'object' + || (depth < 1 && (isObject(item) ? flat(item, depth + 1) : (item as unknown[]).every(entry => typeof entry !== 'object')))); +} + +function json(label: string, value: unknown): AiDetailBlock[] { + if (value === undefined || value === null || value === '') { + return []; + } + if (typeof value === 'string') { + return [{type: 'text', text: value}]; + } + return [{type: 'json', label, text: JSON.stringify(value, null, 2)}]; +} + +function generic(value: unknown, label: string, skip: string[] = [], names?: AiDetailNames): AiDetailBlock[] { + if (typeof value === 'string') { + const trimmed = value.trim().replace(/^OK:\s*/i, ''); + return !trimmed || /^OK\.?$/i.test(trimmed) || UUID.test(trimmed) ? [] : [{type: 'text', text: trimmed}]; + } + if (isObject(value) && Object.keys(value).length <= 16 && flat(value)) { + const rows = facts(value, skip, names); + return rows.length ? [{type: 'facts', rows}] : []; + } + return json(label, value); +} + +function timeOf(ts: unknown): number | undefined { + const value = typeof ts === 'string' ? Number(ts) : ts; + return typeof value === 'number' && Number.isFinite(value) && value > 1e11 ? value : undefined; +} + +function sparkPath(values: number[], times: number[]): {path: string; dot: number} { + const width = 300; + const height = 60; + const pad = 6; + const from = times[0]; + const span = times[times.length - 1] - from || 1; + const min = Math.min(...values); + const range = Math.max(...values) - min || 1; + const y = (value: number) => height - pad - (value - min) / range * (height - 2 * pad); + const path = values.map((value, index) => + `${index ? 'L' : 'M'}${((times[index] - from) / span * width).toFixed(1)} ${y(value).toFixed(1)}`).join(''); + return {path, dot: Math.round(y(values[values.length - 1]) / height * 100)}; +} + +function series(key: string, points: Array<[number, number]>): AiDetailSeries { + const sorted = [...points].sort((a, b) => a[0] - b[0]); + const values = sorted.map(point => point[1]); + const times = sorted.map(point => point[0]); + return {key, points: sorted.length, min: Math.min(...values), max: Math.max(...values), last: values[values.length - 1], + from: times[0], to: times[times.length - 1], ...sparkPath(values, times)}; +} + +function changesSeries(key: string, points: Array<[number, unknown]>): AiDetailSeries { + const sorted = [...points].sort((a, b) => a[0] - b[0]); + const words = sorted.map(point => aiValueText(point[1])); + const levels = [...new Set(words)]; + const changes = words.filter((word, index) => index && word !== words[index - 1]).length; + const times = sorted.map(point => point[0]); + return {key, points: sorted.length, lastText: words[words.length - 1], changes, from: times[0], to: times[times.length - 1], + ...sparkPath(words.map(word => levels.indexOf(word)), times)}; +} + +function telemetry(result: Values, entityOf?: (id: string) => AiDetailEntity): AiDetailBlock[] { + const ids = Object.keys(result); + if (entityOf && ids.length && ids.every(id => UUID.test(id) && isObject(result[id]))) { + return ids.flatMap(id => telemetry(result[id] as Values).map(block => + block.type === 'values' || block.type === 'series' ? {...block, entity: entityOf(id)} : block)); + } + const latest: AiDetailValue[] = []; + const history: AiDetailSeries[] = []; + const other: AiDetailValue[] = []; + const add = (key: string, points: Array<[number, unknown]>) => { + const numbers = points.map(([ts, value]) => [ts, typeof value === 'boolean' ? NaN : Number(value)] as [number, number]); + if (points.length > 1 && numbers.every(([, value]) => Number.isFinite(value))) { + history.push(series(key, numbers)); + } else if (points.length > 1) { + history.push(changesSeries(key, points)); + } else if (points.length) { + latest.push({key, value: aiValueText(points[0][1]), time: points[0][0]}); + } + }; + for (const [key, data] of Object.entries(result)) { + if (isObject(data) && 'value' in data) { + latest.push({key, value: aiValueText(data.value), time: timeOf(data.ts)}); + continue; + } + if (Array.isArray(data) && data.every(point => isObject(point) && 'ts' in point)) { + add(key, data.map(point => [timeOf(point.ts), point.value] as [number, unknown]).filter(([ts]) => !!ts)); + continue; + } + if (!isObject(data)) { + other.push({key, value: aiValueText(data)}); + continue; + } + const entries = Object.entries(data).filter(([ts]) => timeOf(ts)); + if (entries.length) { + add(key, entries.map(([ts, value]) => [timeOf(ts), value] as [number, unknown])); + } else { + other.push({key, value: aiValueText(data)}); + } + } + const blocks: AiDetailBlock[] = []; + if (history.length) { + blocks.push({type: 'series', rows: history}); + } + if (latest.length || other.length) { + blocks.push({type: 'values', rows: [...latest, ...other]}); + } + return blocks; +} + +function searchSections(result: unknown): Array<{entityType?: string; page: Values}> { + if (isObject(result)) { + return [{page: result}]; + } + if (typeof result !== 'string') { + return []; + } + const sections: Array<{entityType?: string; page: Values}> = []; + const pattern = /(?:^|\n\n)([A-Z_]+) entities[^\n]*:\n(\{[\s\S]*?\})(?=\n\n[A-Z_]+ entities|$)/g; + let match: RegExpExecArray | null; + while ((match = pattern.exec(result)) !== null) { + const page = aiParse(match[2]); + if (isObject(page)) { + sections.push({entityType: match[1], page}); + } + } + return sections; +} + +function searchType(values: Values): string | undefined { + const filter = isObject(values.entityFilter) ? values.entityFilter : {}; + return FILTER_TYPES[values.filterType] ?? str(filter.entityType) ?? str(filter.singleEntity?.entityType) ?? str(filter.groupType && 'ENTITY_GROUP'); +} + + +function recordOf(row: Values, entityType: string): AiDetailRecord | null { + if (entityType === 'ALARM') { + const alarmName = str(row.type) ?? str(row.name); + return alarmName ? {entityType, id: idOf(row.id), name: alarmName, severity: str(row.severity)?.toUpperCase(), status: str(row.status)?.toUpperCase(), + since: timeOf(row.startTs) ? dateText(timeOf(row.startTs)) : undefined} : null; + } + const name = str(row.name) ?? str(row.title) ?? str(row.email) ?? str(row.label); + if (!name) { + return null; + } + const meta = [row.label && row.label !== name ? row.label : undefined, entityType === 'ALARM_RULE' ? undefined : row.type, row.email && row.email !== name ? row.email : undefined] + .filter(value => typeof value === 'string' && value.trim()).join(' · '); + return {entityType: entityType === 'ALARM_RULE' ? 'ALARM_RULE' : entityType, id: idOf(row.id), name, meta: meta || undefined}; +} + +function withoutCommonMeta(rows: AiDetailRecord[]): AiDetailRecord[] { + if (rows.length < 2) { + return rows; + } + const counts = new Map(); + rows.forEach(row => row.meta && counts.set(row.meta, (counts.get(row.meta) ?? 0) + 1)); + const common = [...counts].find(([, count]) => count > rows.length / 2)?.[0]; + return common ? rows.map(row => row.meta === common ? {...row, meta: undefined} : row) : rows; +} + +function searchEntities(values: Values, result: unknown, names: AiDetailNames): AiDetailView { + const filter = isObject(values.entityFilter) ? values.entityFilter : {}; + const type = searchType(values); + const what = FILTER_WORDS[values.filterType] ?? (type && SEARCHED[type]) ?? (values.filterType === 'entityType' && !filter.entityType ? 'devices-assets' : 'entities'); + const params: Record = {what: K + 'what.' + what}; + let key = 'search'; + if (values.filterType === 'singleEntity' && filter.singleEntity) { + key = 'search-one'; + params.entity = entity(filter.singleEntity.id, filter.singleEntity.entityType, names); + } else if (values.filterType === 'relationsQuery' && filter.rootEntity) { + key = filter.direction === 'TO' ? 'search-related-to' : 'search-related-from'; + params.entity = entity(filter.rootEntity.id, filter.rootEntity.entityType, names); + } else if (str(filter.nameFilter)) { + key = 'search-named'; + params.name = filter.nameFilter.replace(/%/g, ''); + } else if (Array.isArray(filter.types) && filter.types.length) { + key = 'search-typed'; + params.types = filter.types.join(', '); + } else if (str(values.pageLink?.textSearch)) { + key = 'search-text'; + params.text = values.pageLink.textSearch; + } else if (values.filterType === 'alarm') { + const words = [...(Array.isArray(filter.severityList) ? filter.severityList : []), ...(Array.isArray(filter.statusList) ? filter.statusList : [])] + .map(word => str(word)?.toUpperCase()).filter(word => !!word && ALARM_FILTER_WORDS.has(word)).map(word => K + 'alarm-filter.' + word); + const one = Array.isArray(filter.originatorIds) && filter.originatorIds.length === 1; + const window = timeOf(filter.startTs) ? `${dateText(timeOf(filter.startTs))} – ${endText(filter.endTs)}` : undefined; + const parts = [words.length ? 'filter' : '', one ? 'on' : '', window ? 'window' : ''].filter(Boolean); + if (parts.length) { + key = parts.length === 1 && parts[0] === 'filter' ? 'search-alarms' : 'search-alarms-' + parts.join('-'); + params.filter = {words, commas: true}; + params.entity = one ? entity(filter.originatorIds[0], filter.originatorType, names) : ''; + params.window = window ?? ''; + } + } + const sections = searchSections(result); + if (!sections.length) { + return {hood: text(key, params), blocks: generic(result, 'result')}; + } + const blocks: AiDetailBlock[] = []; + for (const section of sections) { + const entityType = section.entityType ?? type ?? 'DEVICE'; + const data: unknown[] = Array.isArray(section.page.data) ? section.page.data : []; + if (!data.length) { + if (sections.length === 1) { + blocks.push({type: 'found', text: text(entityType === 'ALARM' ? 'no-alarms' : 'nothing-found')}); + } + continue; + } + const groupType = entityType === 'ENTITY_GROUP' ? str(filter.groupType)?.toUpperCase() : undefined; + const rows = withoutCommonMeta(data.filter(isObject).map(row => recordOf(row, entityType)).filter(Boolean).slice(0, MAX_ROWS) + .map(row => groupType ? {...row, groupType} : row)); + const total = typeof section.page.totalElements === 'number' ? section.page.totalElements : data.length; + blocks.push(rows.length + ? {type: 'records', label: sections.length > 1 ? text('what-found.' + (SEARCHED[entityType] ?? 'entities')) : undefined, rows, total} + : {type: 'json', label: 'result', text: JSON.stringify(data, null, 2)}); + } + return {hood: text(key, params), blocks}; +} + +function relations(result: unknown): AiDetailBlock[] { + if (!isObject(result)) { + return generic(result, 'result'); + } + const blocks: AiDetailBlock[] = []; + for (const direction of ['from', 'to']) { + const byType = result[direction]; + if (!isObject(byType)) { + continue; + } + for (const [relationType, group] of Object.entries(byType)) { + const related: unknown[] = Array.isArray(group?.relatedEntities) ? group.relatedEntities : []; + const rows = related.filter(isObject).map(item => ({ + entityType: str(item.entityType) ?? 'DEVICE', + id: idOf(item.entityId ?? item.id), + name: str(item.name) ?? idOf(item.entityId ?? item.id) ?? '—' + })); + if (rows.length) { + blocks.push({type: 'records', label: text('relation-' + direction, {type: relationType}), rows}); + } + } + } + return blocks.length ? blocks : generic(result, 'result'); +} + +function attributes(result: unknown, label: 'values' | 'keys'): AiDetailBlock[] { + if (!isObject(result)) { + return generic(result, 'result'); + } + const blocks: AiDetailBlock[] = []; + for (const [scope, data] of Object.entries(result)) { + const scopeLabel = text('scope.' + (SCOPES[scope] ?? 'other')); + if (Array.isArray(data) && data.length) { + blocks.push({type: 'keys', label: scopeLabel, keys: data.map(String)}); + } else if (isObject(data) && Object.keys(data).length) { + blocks.push({ + type: 'values', label: scopeLabel, rows: Object.entries(data).map(([key, item]) => isObject(item) && 'value' in item + ? {key, value: aiValueText(item.value), time: timeOf(item.ts)} : {key, value: aiValueText(item)}) + }); + } + } + return blocks.length ? blocks : [{type: 'note', text: text(label === 'keys' ? 'no-attribute-keys' : 'no-attributes')}]; +} + +const PROTOCOLS: Record = { + coap: 'CoAP', + coaps: 'CoAPS', + lwm2m: 'LwM2M', + docker: 'Docker', + windows: 'Windows', + linux: 'Linux', + macos: 'macOS' +}; + +function commands(value: unknown, prefix: string[] = [], rows: AiDetailCommand[] = []): AiDetailCommand[] { + if (typeof value === 'string') { + rows.push({label: prefix.map(part => PROTOCOLS[part.toLowerCase()] ?? (part.length <= 5 ? part.toUpperCase() : aiHumanize(part))) + .filter((part, index, all) => all.indexOf(part) === index).join(' · '), text: value}); + } else if (isObject(value)) { + Object.entries(value).forEach(([key, item]) => commands(item, [...prefix, key], rows)); + } + return rows; +} + +function webResults(result: unknown): AiDetailBlock[] { + if (typeof result !== 'string' || !/^1\. /.test(result.trim())) { + return generic(result, 'result'); + } + const rows: AiDetailLink[] = []; + for (const chunk of result.trim().split(/\n\n(?=\d+\. )/)) { + const [head, url, ...rest] = chunk.split('\n'); + const title = head?.replace(/^\d+\.\s*/, '').trim(); + if (!title || !/^https?:\/\//.test(url ?? '')) { + continue; + } + let from = url; + try { + from = new URL(url).hostname.replace(/^www\./, ''); + } catch { + } + rows.push({title, url: url.trim(), from, snippet: rest.join(' ').trim() || undefined}); + } + return rows.length ? [{type: 'links', rows}] : generic(result, 'result'); +} + +function aliasFilter(filter: unknown, names: AiDetailNames): AiDetailFact[] { + if (!isObject(filter)) { + return []; + } + const rows: AiDetailFact[] = [{label: K + 'fact.resolves', value: aiHumanize(String(filter.type ?? ''))}]; + if (Array.isArray(filter.entityList)) { + const list = filter.entityList.map((id: unknown) => names.get(String(id))?.name ?? String(id)); + rows.push({label: K + 'fact.entities', value: list.join(', ')}); + } + for (const key of ['deviceTypes', 'assetTypes', 'entityViewTypes', 'deviceType', 'assetType', 'entityType', 'entityNameFilter', 'relationType', 'direction']) { + if (filter[key] !== undefined && filter[key] !== '') { + rows.push({label: aiHumanize(key), raw: true, value: Array.isArray(filter[key]) ? filter[key].join(', ') : aiValueText(filter[key])}); + } + } + const single = filter.singleEntity ?? filter.defaultStateEntity ?? filter.rootEntity; + if (isObject(single)) { + rows.push({label: K + 'fact.entity', entity: entity(single.id, single.entityType, names)}); + } + rows.push({label: K + 'fact.multiple', value: filter.resolveMultiple ? K + 'yes' : K + 'no'}); + return rows; +} + +function reportTemplateOverview(result: Values): AiDetailBlock[] { + const blocks: AiDetailBlock[] = []; + const settings = isObject(result.settings) ? result.settings : {}; + const page = isObject(settings.page) ? settings.page : null; + const rows: AiDetailFact[] = [{label: K + 'fact.format', value: [str(result.format), result.templateType === 'SUB_REPORT' ? text('sub-report') : null].filter(Boolean).join(' · ')}]; + if (page) { + rows.push({label: K + 'fact.page', value: [page.size, aiHumanize(String(page.orientation ?? ''))].filter(Boolean).join(' · ')}); + } + if (str(settings.fileName)) { + rows.push({label: K + 'fact.file-name', value: settings.fileName, mono: true}); + } + const sections = ['header', 'footer'].filter(section => isObject(settings[section]) && settings[section].enabled); + if (page) { + rows.push({label: K + 'fact.header-footer', value: sections.length ? sections.map(section => aiHumanize(section)).join(', ') : '—'}); + } + blocks.push({type: 'facts', rows}); + const components = isObject(result.components) ? Object.entries(result.components) : []; + blocks.push({ + type: 'list', label: text('report-components'), + rows: components.length ? components.slice(0, MAX_ROWS).map(([path, line]) => { + const item = isObject(line) ? line : {}; + return [path, aiHumanize(String(item.type ?? '')), str(item.is), str(item.alias)].filter(Boolean).join(' · '); + }) : ['—'] + }); + const aliases = (Array.isArray(result.entityAliases) ? result.entityAliases : []).filter(isObject); + if (aliases.length) { + blocks.push({type: 'list', label: text('aliases'), rows: aliases.map(alias => [str(alias.name) ?? alias.id, alias.filter?.type ? aiHumanize(alias.filter.type) : null].filter(Boolean).join(' · '))}); + } + const filters = (Array.isArray(result.filters) ? result.filters : []).filter(isObject); + if (filters.length) { + blocks.push({type: 'list', label: text('filters'), rows: filters.map(item => String(item.name ?? item.id))}); + } + const problems = (Array.isArray(result.problems) ? result.problems : []).map(String); + if (problems.length) { + blocks.push({type: 'list', label: text('report-problems'), rows: problems}); + } + return blocks; +} + +function reportComponentFacts(component: Values): AiDetailFact[] { + const rows: AiDetailFact[] = [{label: K + 'fact.component', value: aiHumanize(String(component.type ?? ''))}]; + rows.push({label: K + 'fact.path', value: String(component.path ?? '—'), mono: true}); + const config = isObject(component.config) ? component.config : {}; + const title = str(config.title) ?? str(config.text); + if (title) { + rows.push({label: K + 'fact.title', value: title}); + } + if (str(component.entityAlias) || str(component.entityAliasId)) { + rows.push(str(component.entityAlias) ? {label: K + 'fact.alias', value: component.entityAlias} + : {label: K + 'fact.alias', value: component.entityAliasId, mono: true}); + } + const entries = [config.keys, config.columns, config.series, config.latestColumns].filter(Array.isArray).flat(); + const keys = entries.map((item: any) => typeof item === 'string' ? item : item?.key).filter(Boolean); + if (str(config.key)) { + keys.push(config.key); + } + if (keys.length) { + rows.push({label: K + 'fact.keys', value: [...new Set(keys)].join(', '), mono: true}); + } + const history = isObject(config.timewindow) && isObject(config.timewindow.history) ? config.timewindow.history : null; + if (history) { + const window = history.interval ?? history.last ?? (isObject(history.range) ? `${history.range.from} – ${history.range.to}` : null); + const aggregation = isObject(config.timewindow.aggregation) && config.timewindow.aggregation.type && config.timewindow.aggregation.type !== 'NONE' + ? `${config.timewindow.aggregation.type}${config.timewindow.aggregation.grouping ? ' per ' + config.timewindow.aggregation.grouping : ''}` : null; + rows.push({label: K + 'fact.time-window', value: [window ? aiHumanize(String(window)) : null, aggregation].filter(Boolean).join(' · ')}); + } + if (typeof config.height === 'number') { + rows.push({label: K + 'fact.height', value: `${config.height} px`}); + } + return rows; +} + +function widgetFacts(widget: Values, names: AiDetailNames): AiDetailFact[] { + const rows: AiDetailFact[] = []; + if (str(widget.title)) { + rows.push({label: K + 'fact.title', value: widget.title}); + } + if (str(widget.widgetType)) { + rows.push({label: K + 'fact.widget-type', value: aiHumanize(widget.widgetType)}); + } + if (str(widget.stateId)) { + rows.push({label: K + 'fact.state', value: widget.stateId, mono: true}); + } + if (str(widget.entityAliasId)) { + const alias = names.get(widget.entityAliasId)?.name; + rows.push(alias ? {label: K + 'fact.alias', value: alias} : {label: K + 'fact.alias', value: widget.entityAliasId, mono: true}); + } + const config = isObject(widget.widgetConfig) ? widget.widgetConfig : {}; + const keys = (Array.isArray(config.keys) ? config.keys : []).map((item: any) => typeof item === 'string' ? item : item?.key).filter(Boolean); + ['latitudeKey', 'longitudeKey', 'valueKey', 'key'].forEach(field => str(config[field]) && keys.push(config[field])); + if (keys.length) { + rows.push({label: K + 'fact.keys', value: [...new Set(keys)].join(', '), mono: true}); + } + if (widget.sizeX && widget.sizeY) { + rows.push({label: K + 'fact.size', say: widget.col !== undefined + ? text('widget-size-at', {width: widget.sizeX, height: widget.sizeY, col: widget.col, row: widget.row ?? 0}) + : text('widget-size', {width: widget.sizeX, height: widget.sizeY})}); + } + return rows; +} + +function widgetRecords(widgets: unknown, result: unknown): AiDetailRecord[] { + const ids = typeof result === 'string' ? [...result.matchAll(/widgets\[(\d+)\][^:]*:\s*([0-9a-f-]{36})/g)] : []; + return (Array.isArray(widgets) ? widgets : []).filter(isObject).map((widget, index) => ({ + entityType: 'DASHBOARD_WIDGET', + id: ids.find(match => Number(match[1]) === index)?.[2], + name: str(widget.title) ?? aiHumanize(String(widget.widgetType ?? 'widget')), + meta: [widget.widgetType ? aiHumanize(widget.widgetType) : undefined, widget.stateId, + widget.sizeX && widget.sizeY ? `${widget.sizeX} × ${widget.sizeY}` : undefined].filter(Boolean).join(' · ') + })); +} + +function dashboardOverview(result: unknown, names: AiDetailNames): AiDetailBlock[] { + if (!isObject(result) || !Array.isArray(result.states)) { + return generic(result, 'result'); + } + const blocks: AiDetailBlock[] = []; + const rows: AiDetailFact[] = []; + if (str(result.theme)) { + rows.push({label: K + 'fact.theme', value: aiHumanize(result.theme)}); + } + const window = result.timewindow?.realtime?.last ?? result.timewindow?.realtime?.timewindowMs; + if (window) { + rows.push({label: K + 'fact.time-window', value: String(window)}); + } + if (rows.length) { + blocks.push({type: 'facts', rows}); + } + blocks.push({ + type: 'list', label: text('states'), rows: result.states.filter(isObject).map(state => { + const widgets = Array.isArray(state.widgets) ? state.widgets.length : 0; + return [str(state.name) ?? state.id, state.root ? '★' : '', `${widgets} widget${widgets === 1 ? '' : 's'}`, state.layout].filter(Boolean).join(' · '); + }) + }); + const aliases = (Array.isArray(result.aliases) ? result.aliases : []).filter(isObject); + if (aliases.length) { + blocks.push({type: 'list', label: text('aliases'), rows: aliases.map(alias => [alias.alias ?? alias.name ?? alias.id, alias.filter?.type ? aiHumanize(alias.filter.type) : alias.type].filter(Boolean).join(' · '))}); + } + const filters = (Array.isArray(result.filters) ? result.filters : []).filter(isObject); + if (filters.length) { + blocks.push({type: 'list', label: text('filters'), rows: filters.map(item => String(item.filter ?? item.name ?? item.id))}); + } + return blocks; +} + +function partialString(source: string, key: string): string | undefined { + const start = source.indexOf(`"${key}":"`); + if (start < 0) { + return undefined; + } + let body = source.slice(start + key.length + 4); + const end = /(?:^|[^\\])(?:\\\\)*"/.exec(body); + body = end ? body.slice(0, end.index + end[0].length - 1) : body.replace(/…$/, '').replace(/\\(u[0-9a-fA-F]{0,3})?$/, ''); + try { + return JSON.parse(`"${body}"`); + } catch { + return undefined; + } +} + +function htmlPage(result: unknown): AiDetailBlock[] { + if (typeof result === 'string' && result.trim().startsWith('{')) { + const html = partialString(result, 'html'); + if (html) { + return [{type: 'code', label: 'HTML', text: html}, {type: 'note', text: text('cut-short')}]; + } + } + const content = isObject(result) ? (isObject(result.content) ? result.content : result) : undefined; + if (!content || (!str(content.html) && !str(content.css) && !str(content.js))) { + return generic(result, 'result'); + } + return (['html', 'css', 'js'] as const).filter(part => str(content[part])).map(part => ({type: 'code', label: part.toUpperCase(), text: content[part]})); +} + +function savedObject(values: Values, nested?: string): Values { + const raw = nested ? values[nested] : values; + const parsed = aiParse(raw); + return isObject(parsed) ? parsed : values; +} + +function savedFacts(saved: Values, names: AiDetailNames): AiDetailFact[] { + const rows: AiDetailFact[] = []; + const config = isObject(aiParse(saved.configuration)) ? aiParse(saved.configuration) as Values : {}; + if (str(config.type)) { + rows.push({label: K + 'fact.type', value: aiHumanize(config.type)}); + } + if (saved.entityId) { + rows.push({label: K + 'fact.on', entity: entity(saved.entityId, saved.entityId?.entityType, names)}); + } + if (isObject(config.arguments) && Object.keys(config.arguments).length) { + rows.push({label: K + 'fact.arguments', value: Object.entries(config.arguments) + .map(([name, arg]: [string, any]) => arg?.refEntityKey?.key && arg.refEntityKey.key !== name ? `${name} = ${arg.refEntityKey.key}` : name).join(', '), mono: true}); + } + if (str(config.expression)) { + rows.push({label: K + 'fact.expression', value: config.expression, mono: true}); + } + if (isObject(config.output) && str(config.output.name)) { + rows.push({label: K + 'fact.output', value: config.output.name, mono: true}); + } + if (isObject(config.createRules)) { + rows.push({label: K + 'fact.severities', value: Object.keys(config.createRules).map(aiHumanize).join(', ')}); + } + if (config.clearRule) { + rows.push({label: K + 'fact.clears', value: K + 'yes'}); + } + for (const key of ['label', 'description', 'notificationType', 'triggerType', 'recipientsConfig', 'templateId']) { + if (saved[key] !== undefined && saved[key] !== null && saved[key] !== '') { + rows.push(...facts({[key]: saved[key]}, [], names)); + } + } + if (!rows.length) { + rows.push(...facts(saved, ['id', 'name', 'title', 'configuration', 'additionalInfo', 'tenantId', 'version', 'createdTime'], names)); + } + return rows; +} + +function changes(values: Values, skip: string[], names: AiDetailNames): AiDetailBlock[] { + const rows: AiDetailFact[] = []; + for (const [key, value] of Object.entries(values)) { + if (skip.includes(key) || value === undefined) { + continue; + } + if (key === 'widgetConfig' && isObject(value)) { + const shown = widgetFacts({widgetConfig: value}, names); + rows.push(...(shown.length ? shown : [{label: K + 'fact.settings', value: Object.keys(value).join(', '), mono: true}])); + } else if (key === 'filter') { + rows.push(...aliasFilter(value, names)); + } else if (key === 'entityAliasId') { + rows.push(...widgetFacts({entityAliasId: value}, names)); + } else { + rows.push(...facts({[key]: value}, [], names)); + } + } + return rows.length ? [{type: 'facts', rows}] : []; +} + +const MODEL_TEXT_FIELDS: ReadonlySet = new Set(['note']); + +function withoutModelText(value: unknown): unknown { + if (Array.isArray(value)) { + return value.map(withoutModelText); + } + if (!isObject(value)) { + return value; + } + return Object.fromEntries(Object.entries(value).filter(([key]) => !MODEL_TEXT_FIELDS.has(key)) + .map(([key, item]) => [key, withoutModelText(item)])); +} + +export function aiActionDetailView(action: AiAction, names: AiDetailNames): AiDetailView { + const values: Values = isObject(aiParse(action.arguments)) ? aiParse(action.arguments) as Values : {}; + const result = withoutModelText(aiParse(action.result)); + const failed = action.status === 'FAILURE'; + const view = describe(action.tool, values, result, names); + if (failed) { + const reason = typeof action.result === 'string' ? action.result.trim() : ''; + return {hood: view.hood, blocks: reason.includes('\n') ? [{type: 'text', text: reason}] : []}; + } + return view; +} + +function accessBlocks(report: unknown): AiDetailBlock[] { + if (!isObject(report)) { + return []; + } + const hidden = Array.isArray(report.notVisibleToCustomer) ? report.notVisibleToCustomer.filter(isObject) : []; + const blocks: AiDetailBlock[] = [{type: 'facts', rows: [ + ...(str(report.dashboard) ? [{label: K + 'fact.dashboard', value: report.dashboard}] : []), + {label: K + 'fact.entities-checked', value: String(report.entitiesChecked ?? 0)} + ]}]; + if (hidden.length) { + blocks.push({type: 'records', label: text('not-visible', {count: hidden.length}), rows: hidden.map(item => ({ + entityType: str(item.entityType) ?? 'DEVICE', id: str(item.id), name: str(item.name) ?? '—', + meta: [str(item.owner), ...(Array.isArray(item.groups) ? item.groups.filter(str) : [])].filter(Boolean).join(' · ') || undefined + }))}); + } else { + blocks.push({type: 'note', text: text('all-visible')}); + } + if (Array.isArray(report.aliasesResolvedOnlyOnTheDashboard) && report.aliasesResolvedOnlyOnTheDashboard.length) { + blocks.push({type: 'note', text: text('state-aliases', {aliases: report.aliasesResolvedOnlyOnTheDashboard.filter(str).join(', ')})}); + } + if (str(report.truncated)) { + blocks.push({type: 'note', text: text('access-truncated')}); + } + return blocks; +} + +function grantMeta(grant: Values): string | undefined { + return [str(grant.role), str(grant.appliesTo) ?? [str(grant.userGroup), str(grant.userGroupOwner)].filter(Boolean).join(' · ')] + .filter(Boolean).join(' · ') || undefined; +} + +function groupRows(groups: unknown): AiDetailRecord[] { + return (Array.isArray(groups) ? groups.filter(isObject) : []).map(group => ({ + entityType: 'ENTITY_GROUP', groupType: 'USER', id: str(group.id), name: str(group.name) ?? '—', + meta: (Array.isArray(group.grants) ? group.grants.filter(isObject) : []).map(grantMeta).filter(Boolean).join('; ') || undefined + })); +} + +function readAccess(target: string | undefined, result: unknown): AiDetailBlock[] { + if (!isObject(result)) { + return generic(result, 'result'); + } + const blocks: AiDetailBlock[] = []; + const fact = (key: string, value: unknown) => str(value) ? [{label: K + 'fact.' + key, value: String(value)}] : []; + switch (target) { + case 'USER': + blocks.push({type: 'facts', rows: [...fact('email', result.email), ...fact('owner', result.owner)]}); + blocks.push({type: 'records', label: text('user-groups'), rows: groupRows(result.userGroups)}); + break; + case 'USER_GROUP': + blocks.push({type: 'facts', rows: [...fact('owner', result.owner), ...fact('members', String(result.memberCount ?? ''))]}); + blocks.push({type: 'records', label: text('grants'), rows: (Array.isArray(result.grants) ? result.grants.filter(isObject) : []) + .map(grant => ({entityType: 'ROLE', name: str(grant.role) ?? '—', meta: str(grant.appliesTo)}))}); + blocks.push({type: 'records', label: text('members'), rows: (Array.isArray(result.members) ? result.members.filter(isObject) : []) + .map(member => ({entityType: 'USER', id: str(member.id), name: str(member.email) ?? '—'}))}); + break; + case 'ENTITY_GROUP': + blocks.push({type: 'facts', rows: [...fact('type', result.type), ...fact('owner', result.owner)]}); + blocks.push({type: 'records', label: text('shared-with'), rows: (Array.isArray(result.sharedWith) ? result.sharedWith.filter(isObject) : []) + .map(grant => ({entityType: 'ENTITY_GROUP', name: str(grant.userGroup) ?? '—', meta: [str(grant.userGroupOwner), str(grant.role)].filter(Boolean).join(' · ') || undefined}))}); + break; + case 'CUSTOMER': + blocks.push({type: 'records', label: text('user-groups'), rows: groupRows(result.userGroups)}); + break; + case 'ROLES': + blocks.push({type: 'records', label: text('roles'), rows: (Array.isArray(result.roles) ? result.roles.filter(isObject) : []).map(role => ({ + entityType: 'ROLE', id: str(role.id), name: str(role.name) ?? '—', + meta: [str(role.type), permissionsText(role.permissions)].filter(Boolean).join(' · ') || undefined + }))}); + break; + default: + return generic(result, 'result'); + } + return blocks.filter(block => block.type !== 'records' || block.rows.length); +} + +function permissionsText(permissions: unknown): string | undefined { + if (Array.isArray(permissions)) { + return permissions.filter(str).join(', '); + } + if (isObject(permissions)) { + return Object.entries(permissions).map(([resource, operations]) => + resource + ': ' + (Array.isArray(operations) ? operations.join(', ') : '')).join('; '); + } + return undefined; +} + +function sentNotification(result: unknown): AiDetailBlock[] { + if (!isObject(result) || !str(result.requestId)) { + return generic(result, 'result'); + } + const rows: AiDetailFact[] = []; + if (str(result.status)) { + rows.push({label: K + 'fact.status', value: K + 'notification-status.' + String(result.status).toLowerCase()}); + } + if (str(result.sendsAt)) { + rows.push({label: K + 'fact.sends-at', value: dateText(result.sendsAt)}); + } + if (str(result.usersTargetName)) { + rows.push({label: K + 'fact.recipients', value: result.usersTargetName}); + } + if (isObject(result.sent)) { + rows.push({label: K + 'fact.delivered', + value: Object.entries(result.sent).map(([method, count]) => `${aiHumanize(method)} ${count}`).join(', ')}); + } + if (isObject(result.errors)) { + Object.entries(result.errors).filter(([, byRecipient]) => isObject(byRecipient)).forEach(([method, byRecipient]) => + Object.entries(byRecipient as Record).forEach(([recipient, error]) => + rows.push({label: aiHumanize(method), raw: true, value: `${recipient}: ${aiValueText(error)}`}))); + } + if (str(result.error)) { + rows.push({label: K + 'fact.error', value: result.error}); + } + return rows.length ? [{type: 'facts', rows}] : []; +} + +function createdUser(user: unknown): AiDetailBlock[] { + if (!isObject(user)) { + return []; + } + const activation = isObject(user.activation) ? user.activation : null; + const rows: AiDetailFact[] = []; + if (str(user.email)) { + rows.push({label: K + 'fact.email', value: user.email}); + } + if (Array.isArray(user.userGroups) && user.userGroups.length) { + rows.push({label: K + 'fact.user-groups', value: user.userGroups.filter(str).join(', ')}); + } + if (activation?.emailSent) { + rows.push({label: K + 'fact.activation', value: K + 'activation-email'}); + } else if (str(activation?.link)) { + rows.push({label: K + 'fact.activation-link', value: activation.link, mono: true}); + } + return rows.length ? [{type: 'facts', rows}] : []; +} + +function describe(tool: string, values: Values, result: unknown, names: AiDetailNames): AiDetailView { + const of = (id: unknown, type?: unknown) => entity(id, type, names); + const target = of(values.entityId, values.entityType); + const dashboard = of(values.dashboardId, 'DASHBOARD'); + switch (tool) { + case 'send_notification': + return {blocks: sentNotification(result)}; + case 'check_dashboard_access': + return {hood: text('check-dashboard-access', {dashboard, customer: of(values.customerId, 'CUSTOMER')}), blocks: accessBlocks(result)}; + case 'change_owner': + case 'share_entity_group': { + const outcome = isObject(result) && str(result.result) ? [{type: 'text' as const, text: result.result.replace(/^OK:\s*/i, '')}] : generic(result, 'result'); + const reports = isObject(result) ? (Array.isArray(result.dashboardAccess) ? result.dashboardAccess : result.dashboardAccess ? [result.dashboardAccess] : []) : []; + return {blocks: [...outcome, ...reports.flatMap(accessBlocks)]}; + } + case 'save_entity_group': + case 'grant_role': + case 'update_group_members': + return {blocks: []}; + case 'save_role': { + const permissions = permissionsText(values.permissions); + return {blocks: permissions ? [{type: 'facts', rows: [{label: K + 'fact.permissions', value: permissions}]}] : []}; + } + case 'read_access': + return {blocks: readAccess(str(values.target)?.toUpperCase(), result)}; + case 'save_user': + return {blocks: isObject(result) && str(result.userId) ? createdUser(result) : generic(result, 'result')}; + case 'save_customer': + return {blocks: isObject(result) && str(result.customerId) ? [...createdUser(result.user), + ...(str(result.userError) ? [{type: 'note' as const, text: text('user-error', {reason: result.userError})}] : [])] : generic(result, 'result')}; + case 'search_iot_hub_devices': { + const data = isObject(result) && Array.isArray(result.data) ? result.data.filter(isObject) : null; + const rows: AiDetailHubItem[] = (data ?? []).filter(item => str(item.id)).map(item => ({ + id: item.id, name: str(item.model) ?? str(item.name) ?? item.id, vendor: str(item.vendor), description: str(item.description) + })); + return { + hood: text('iot-hub-query', {query: str(values.query) ?? '*'}), + blocks: data ? (rows.length ? [{type: 'hub', rows}] : [{type: 'note', text: text('nothing-found')}]) : generic(result, 'result') + }; + } + case 'search_iot_hub': + case 'list_installed_iot_hub_items': { + const data = isObject(result) && Array.isArray(result.data) ? result.data.filter(isObject) : null; + const rows: AiDetailHubItem[] = (data ?? []).filter(item => str(item.versionId)).map(item => ({ + id: item.versionId, name: str(item.name) ?? item.versionId, vendor: str(item.creator), description: str(item.description) + })); + const hood = tool === 'search_iot_hub' + ? (str(values.query) ? text('iot-hub-query', {query: str(values.query)}) : text('iot-hub-browse')) + : text('iot-hub-installed'); + return {hood, blocks: data ? (rows.length ? [{type: 'hub', rows}] : [{type: 'note', text: text('nothing-found')}]) : generic(result, 'result')}; + } + case 'read_iot_hub_item': { + const item = isObject(result) && str(result.versionId) ? result : null; + return { + hood: text('iot-hub-read', {name: str(item?.name) ?? '…'}), + blocks: item ? [{type: 'hub', rows: [{id: item.versionId, name: str(item.name) ?? item.versionId, vendor: str(item.creator), + description: str(item.description)}]}] : generic(result, 'result') + }; + } + case 'read_iot_hub_device': + case 'install_iot_hub_device': { + const item = isObject(result) && (str(result.name) ?? str(result.installed)) ? result : null; + const name = str(item?.name) ?? str(item?.installed); + return { + hood: text(tool === 'install_iot_hub_device' ? 'iot-hub-install' : 'iot-hub-read', {name: name ?? '…'}), + blocks: item && str(values.versionId) ? [{type: 'hub', rows: [{id: values.versionId, name, vendor: str(item.vendor), + description: str(item.description)}]}] : generic(result, 'result') + }; + } + case 'search_entities': + return searchEntities(values, result, names); + case 'read_entity': { + const read = isObject(result) ? result : null; + if (!read) { + return {hood: text('read-entity', {entity: target}), blocks: generic(result, 'result')}; + } + const record: AiDetailRecord = {entityType: target.entityType ?? 'DEVICE', id: target.id, name: str(read.name) ?? str(read.title) ?? target.name ?? '—', + meta: [read.label && read.label !== read.name ? read.label : undefined, read.deviceProfileName ?? read.assetProfileName ?? read.type].filter(Boolean).join(' · ') || undefined}; + const configured = isObject(aiParse(read.configuration)); + const rows = [ + ...(configured ? savedFacts(read, names) : []), + ...facts(read, ['id', 'name', 'title', 'label', 'createdTime', 'deviceProfileName', 'assetProfileName', 'tenantId', 'type', 'additionalInfo', + 'debugSettings', 'configuration', 'version', 'configurationVersion', ...(configured ? ['entityId', 'description'] : [])], names) + ]; + if (read.createdTime) { + rows.push({label: K + 'fact.created', value: dateText(read.createdTime)}); + } + return {hood: text('read-entity', {entity: {...target, name: record.name}}), blocks: [{type: 'records', rows: [record]}, ...(rows.length ? [{type: 'facts', rows} as AiDetailBlock] : [])]}; + } + case 'read_entity_relations': + return {hood: text('read-relations', {entity: target}), blocks: relations(result)}; + case 'read_timeseries': { + const keys = Array.isArray(values.keys) ? values.keys.join(', ') : ''; + const ids = Array.isArray(values.entityIds) ? values.entityIds.map(idOf).filter(Boolean) : []; + const subject: AiDetailParam = ids.length > 1 + ? {words: ids.map(id => names.get(id)?.name).every(Boolean) ? ids.map(id => names.get(id).name) : ['ai-assistant.detail.several'], commas: true} + : ids.length ? of(ids[0], values.entityType) : target; + const hood = values.mode === 'HISTORY' || values.startTime + ? text(keys ? 'read-history-keys' : 'read-history', {entity: subject, keys, from: dateText(values.startTime), to: endText(values.endTime)}) + : text(keys ? 'read-latest-keys' : 'read-latest', {entity: subject, keys}); + const blocks = isObject(result) ? telemetry(result, id => of(id, values.entityType)) : generic(result, 'result'); + return {hood, blocks: isObject(result) && !Object.keys(result).length ? [{type: 'note', text: text('no-data')}] : blocks}; + } + case 'read_timeseries_keys': { + const data = isObject(result) ? (isObject(result.timeseries) ? result.timeseries : result) : null; + let blocks: AiDetailBlock[]; + if (Array.isArray(data)) { + blocks = [{type: 'keys', keys: data.map(String)}]; + } else if (data && Object.keys(data).length) { + blocks = telemetry(data); + } else { + blocks = data ? [{type: 'note', text: text('no-data')}] : generic(result, 'result'); + } + return {hood: text('read-keys', {entity: target}), blocks}; + } + case 'read_attributes': + return {hood: text(values.scope ? 'read-attributes-scope' : 'read-attributes', {entity: target, scope: K + 'scope.' + (SCOPES[values.scope] ?? 'other')}), blocks: attributes(result, 'values')}; + case 'discover_attribute_keys': + return {hood: text('discover-attribute-keys', {entity: of(values.profileId, values.profileType)}), blocks: attributes(result, 'keys')}; + case 'save_attributes': { + const saved = aiParse(values.attributes); + const rows = isObject(saved) ? Object.entries(saved).map(([key, value]) => ({key, value: aiValueText(value)})) : []; + return { + hood: text('save-attributes.' + (SCOPES[values.scope] ?? 'other'), {entity: target, count: rows.length}), + blocks: rows.length ? [{type: 'values', rows}, ...generic(result, 'result')] : generic(result, 'result') + }; + } + case 'delete_attributes': { + const keys = Array.isArray(values.keys) ? values.keys.map(String) : []; + return {hood: text('delete-attributes', {entity: target, scope: K + 'scope.' + (SCOPES[values.scope] ?? 'other')}), blocks: [...(keys.length ? [{type: 'keys', keys} as AiDetailBlock] : []), ...generic(result, 'result')]}; + } + case 'read_device_credentials': { + const device = of(values.deviceId, 'DEVICE'); + if (!isObject(result)) { + return {hood: text('read-credentials', {entity: device}), blocks: generic(result, 'result')}; + } + const rows: AiDetailFact[] = []; + if (str(result.credentialsType)) { + rows.push({label: K + 'fact.type', value: aiHumanize(result.credentialsType)}); + } + for (const key of ['accessToken', 'credentialsId', 'clientId', 'userName', 'password', 'credentialsValue']) { + if (str(result[key])) { + rows.push({label: aiHumanize(key), raw: true, value: result[key], mono: true, secret: /token|password|value|credentialsId/i.test(key)}); + } + } + return {hood: text('read-credentials', {entity: device}), blocks: [{type: 'facts', rows}]}; + } + case 'read_transport_endpoints': { + if (!isObject(result)) { + return {hood: text('read-endpoints'), blocks: generic(result, 'result')}; + } + const rows: AiDetailFact[] = Object.entries(isObject(result.transports) ? result.transports : {}) + .map(([name, endpoint]: [string, any]) => ({label: name.toUpperCase(), raw: true, value: [endpoint?.host, endpoint?.port].filter(Boolean).join(':'), mono: true})); + if (Array.isArray(result.disabled) && result.disabled.length) { + rows.push({label: K + 'fact.disabled', value: result.disabled.map((name: string) => name.toUpperCase()).join(', ')}); + } + return {hood: text('read-endpoints'), blocks: [{type: 'facts', rows}]}; + } + case 'read_device_connect_commands': { + const rows = commands(result); + return {hood: text('read-connect-commands', {entity: of(values.deviceId, 'DEVICE')}), blocks: rows.length ? [{type: 'commands', rows}] : generic(result, 'result')}; + } + case 'research_device_connectivity': + return { + hood: text(str(values.question) ? 'research-question' : 'research', {device: str(values.device) ?? '—', question: str(values.question) ?? ''}), + blocks: typeof result === 'string' && result.trim() ? [{type: 'markdown', text: result.trim()}] : generic(result, 'result') + }; + case 'search_web': + return {hood: text('search-web', {query: str(values.query) ?? '—'}), blocks: webResults(result)}; + case 'fetch_web_page': + return { + hood: text('fetch-page', {url: str(values.url) ?? '—'}), + blocks: typeof result === 'string' && result.trim() ? [{type: 'markdown', text: result.trim()}] : generic(result, 'result') + }; + case 'create_dashboard': + return {hood: text('create-dashboard', {name: str(values.title) ?? '—'}), blocks: []}; + case 'generate_device_dashboard': { + const keys = Array.isArray(values.keys) ? values.keys.map(String) : []; + return {hood: text('generate-device-dashboard', {entity: of(values.deviceId, 'DEVICE')}), blocks: keys.length ? [{type: 'keys', keys}] : []}; + } + case 'update_dashboard': + return {hood: text('update-dashboard', {entity: dashboard}), blocks: changes(values, ['dashboardId'], names)}; + case 'read_dashboard_overview': + return {hood: text('read-dashboard', {entity: dashboard}), blocks: dashboardOverview(result, names)}; + case 'add_dashboard_state': { + const id = okId(result); + return {hood: text('add-state', {name: str(values.name) ?? '—', entity: dashboard}), blocks: id ? [{type: 'facts', rows: [{label: K + 'fact.state-id', value: id, mono: true}]}] : generic(result, 'result')}; + } + case 'update_dashboard_state': + return {hood: text('update-state', {state: str(values.stateId) ?? '—', entity: dashboard}), blocks: changes(values, ['dashboardId', 'stateId'], names)}; + case 'add_dashboard_entity_alias': + case 'update_dashboard_entity_alias': + return { + hood: text(tool === 'add_dashboard_entity_alias' ? 'add-alias' : 'update-alias', {name: str(values.alias) ?? names.get(values.aliasId)?.name ?? '—', entity: dashboard}), + blocks: [{type: 'facts', rows: aliasFilter(values.filter, names)}] + }; + case 'read_dashboard_entity_alias': { + const read = isObject(result) ? result : null; + return { + hood: text('read-alias', {name: str(read?.alias) ?? names.get(values.aliasId)?.name ?? '—'}), + blocks: read ? [{type: 'facts', rows: aliasFilter(read.filter, names)}] : generic(result, 'result') + }; + } + case 'add_dashboard_filter': + case 'update_dashboard_filter': + case 'read_dashboard_filter': { + const name = str(values.filter) ?? str(values.name) ?? (isObject(result) ? str(result.filter) ?? str(result.name) : undefined) ?? '—'; + const shown = tool === 'read_dashboard_filter' ? generic(result, 'result', ['id'], names) : changes(values, ['dashboardId', 'filterId'], names); + return {hood: text(tool.replace(/_dashboard_filter$/, '-filter'), {name, entity: dashboard}), blocks: shown}; + } + case 'add_dashboard_widgets': { + const rows = widgetRecords(values.widgets, result); + return {hood: text(rows.length === 1 ? 'add-widget' : 'add-widgets', {count: rows.length, entity: dashboard}), blocks: rows.length ? [{type: 'records', rows}] : generic(result, 'result')}; + } + case 'add_scada_connectors': { + const rows = (Array.isArray(values.lines) ? values.lines : []).filter(isObject) + .map((line, index) => `${str(line.name) ?? 'Line ' + (index + 1)} · ${isObject(line.from) && isObject(line.to) + ? `${names.get(str(line.from.widgetId) ?? '')?.name ?? str(line.from.widgetId) ?? '—'} ${str(line.from.side) ?? ''} → ` + + `${names.get(str(line.to.widgetId) ?? '')?.name ?? str(line.to.widgetId) ?? '—'} ${str(line.to.side) ?? ''}` + : `${Array.isArray(line.points) ? line.points.length : 0} points`}` + (isObject(line.flow) ? ' · flow' : '')); + return {hood: text('add-scada-connectors', {count: rows.length, entity: dashboard}), blocks: rows.length ? [{type: 'list', rows}] : generic(result, 'result')}; + } + case 'update_dashboard_widget': + return { + hood: text('update-widget', {name: str(values.title) ?? names.get(values.widgetId)?.name ?? '—', entity: dashboard}), + blocks: changes(values, ['dashboardId', 'widgetId'], names) + }; + case 'read_dashboard_widget': { + const read = isObject(result) ? result : null; + return { + hood: text('read-widget', {name: str(read?.title) ?? names.get(values.widgetId)?.name ?? '—'}), + blocks: read ? [{type: 'facts', rows: widgetFacts(read, names)}] : generic(result, 'result') + }; + } + case 'place_dashboard_widgets': { + const rows = (Array.isArray(values.placements) ? values.placements : []).filter(isObject) + .map(place => text('widget-placed', {name: names.get(place.widgetId)?.name ?? place.widgetId, width: place.sizeX, height: place.sizeY, + col: place.col, row: place.row})); + return {hood: text('place-widgets', {count: rows.length, entity: dashboard}), blocks: rows.length ? [{type: 'list', rows}] : generic(result, 'result')}; + } + case 'set_dashboard_html_page': { + const brief = isObject(values.brief) ? values.brief : {}; + const rows: AiDetailFact[] = []; + for (const key of ['description', 'design', 'embeds', 'aliases']) { + const value = brief[key]; + if (value !== undefined && value !== '' && !(Array.isArray(value) && !value.length)) { + rows.push({label: K + 'fact.' + key, value: Array.isArray(value) ? value.join(', ') : String(value)}); + } + } + return {hood: text('set-html-page', {state: str(values.stateId) ?? 'default', entity: dashboard}), blocks: rows.length ? [{type: 'facts', rows}] : []}; + } + case 'read_dashboard_html_page': + return {hood: text('read-html-page', {state: str(values.stateId) ?? 'default', entity: dashboard}), blocks: htmlPage(result)}; + case 'delete': { + if (values.targetType === 'IMAGE') { + const key = String(values.targetId ?? '').split('/').pop() || '—'; + return {hood: text('delete', {entity: {entityType: 'IMAGE', name: key}}), blocks: generic(result, 'result')}; + } + const type = DELETE_TYPES[values.targetType] ?? values.targetType; + return {hood: text('delete', {entity: of(values.targetId, type)}), blocks: generic(result, 'result')}; + } + case 'save_device': { + const saved = savedObject(values); + const rows: AiDetailFact[] = []; + if (str(saved.label) && saved.label !== saved.name) { + rows.push({label: K + 'fact.label', value: saved.label}); + } + const profile = saved.profileId ?? saved.deviceProfileId; + if (profile) { + rows.push({label: K + 'fact.profile', entity: of(profile, 'DEVICE_PROFILE')}); + } + if (saved.customerId) { + rows.push({label: K + 'fact.customer', entity: of(saved.customerId, 'CUSTOMER')}); + } + if (saved.additionalInfo?.gateway) { + rows.push({label: K + 'fact.gateway', value: K + 'yes'}); + } + return {hood: text(hasId(saved) ? 'update-device' : 'create-device', {name: str(saved.name) ?? '—'}), blocks: rows.length ? [{type: 'facts', rows}] : []}; + } + case 'save_calculated_field': + case 'save_alarm_rule': + case 'save_notification_target': + case 'save_notification_template': + case 'save_notification_rule': { + const nested = {save_alarm_rule: 'alarmRule', save_notification_target: 'target', save_notification_template: 'template', save_notification_rule: 'rule'}[tool]; + const saved = savedObject(values, nested); + const kind = tool.replace(/^save_/, '').replace(/_/g, '-'); + return {hood: text('save', {what: K + 'kind.' + kind, name: str(saved.name) ?? str(saved.title) ?? '—'}), blocks: [{type: 'facts', rows: savedFacts(saved, names)}]}; + } + case 'save_asset': + case 'save_entity_view': + case 'save_asset_profile': + case 'save_secret': + case 'save_ai_model': + case 'save_resource': { + const kind = tool.replace(/^save_/, '').replace(/_/g, '-'); + const saved = isObject(result) ? result : {}; + const name = str(values.name) ?? str(values.title) ?? str(saved.name) ?? str(saved.title) ?? '—'; + const rows: AiDetailFact[] = []; + if (str(saved.reference)) { + rows.push({label: K + 'fact.reference', value: saved.reference, mono: true}); + } + if (str(saved.link)) { + rows.push({label: K + 'fact.link', value: saved.link, mono: true}); + } + if (saved.tested === true) { + rows.push({label: K + 'fact.tested', value: K + 'yes'}); + } + const pictures = images([{value: values.image}]); + return {hood: text('save', {what: K + 'kind.' + kind, name}), blocks: rows.length ? [{type: 'facts', rows}, ...pictures] : [...generic(result, 'result'), ...pictures]}; + } + case 'save_relations': { + if (!isObject(result)) { + return {hood: text('save-relations'), blocks: generic(result, 'result')}; + } + const blocks: AiDetailBlock[] = []; + for (const [field, label] of [['added', 'relations-added'], ['removed', 'relations-removed']] as const) { + const rows = Array.isArray(result[field]) ? result[field].map(String) : []; + if (rows.length) { + blocks.push({type: 'list', label: text(label), rows: rows.slice(0, MAX_ROWS)}); + } + } + const failed = Array.isArray(result.failed) ? result.failed.filter(isObject) : []; + if (failed.length) { + blocks.push({type: 'list', label: text('relations-failed'), rows: failed.slice(0, MAX_ROWS).map(row => `${row.relation}: ${row.error}`)}); + } + return {hood: text('save-relations'), blocks}; + } + case 'read_gateway_status': { + if (!isObject(result)) { + return {hood: text('read-gateway-status'), blocks: generic(result, 'result')}; + } + const rows: AiDetailFact[] = [{label: K + 'fact.status', value: K + (result.online ? 'gateway-online' : 'gateway-offline')}]; + if (str(result.version)) { + rows.push({label: K + 'fact.version', value: result.version}); + } + if (str(result.lastConnect)) { + rows.push({label: K + 'fact.last-connect', value: dateText(result.lastConnect)}); + } + const blocks: AiDetailBlock[] = [{type: 'facts', rows}]; + const connectors = Array.isArray(result.connectors) ? result.connectors.filter(isObject) : []; + if (connectors.length) { + blocks.push({type: 'list', label: text('gateway-connectors'), rows: connectors.map(connector => [ + `${connector.name} (${connector.type})`, connector.active ? '●' : '○', + connector.applied === true ? '✓' : connector.applied === false ? '…' : undefined, str(connector.problem) + ].filter(Boolean).join(' '))}); + } + for (const [key, lines] of Object.entries(isObject(result.logs) ? result.logs : {})) { + if (Array.isArray(lines) && lines.length) { + blocks.push({type: 'code', label: key, text: lines.map(String).join('\n')}); + } + } + return {hood: text('read-gateway-status', {name: str(result.name) ?? '—'}), blocks}; + } + case 'read_white_labeling': + return {hood: text('read-white-labeling'), blocks: json('settings', result)}; + case 'read_website_brand': { + const site = str(isObject(result) ? result.url : undefined) ?? str(values.url) ?? '—'; + if (!isObject(result)) { + return {hood: text('read-website-brand', {site}), blocks: generic(result, 'result')}; + } + const blocks: AiDetailBlock[] = []; + if (str(result.pageNotRead)) { + blocks.push({type: 'note', text: text('website-not-read')}); + } + const colors = [str(result.themeColor) ? `${result.themeColor} · theme-color` : undefined, + ...(Array.isArray(result.iconColors) ? result.iconColors.filter(isObject).map(color => `${color.color} · icon ${color.percent}%`) : []), + ...Object.entries(isObject(result.colorVariables) ? result.colorVariables : {}).map(([name, color]) => `${color} · ${name}`), + ...(Array.isArray(result.colors) ? result.colors.filter(isObject).map(color => `${color.color} · ×${color.uses}`) : [])] + .filter(Boolean).slice(0, MAX_ROWS); + if (colors.length) { + blocks.push({type: 'list', label: text('website-colors'), rows: colors}); + } + const logos = (Array.isArray(result.logos) ? result.logos.filter(isObject) : []) + .map(logo => str(logo.url) ?? ` · ${logo.source}`).slice(0, MAX_ROWS); + if (logos.length) { + blocks.push({type: 'list', label: text('website-logos'), rows: logos}); + } + return {hood: text('read-website-brand', {site}), blocks}; + } + case 'save_white_labeling': { + const {target, reset, ...changes} = values; + if (reset) { + return {hood: text(target === 'LOGIN' ? 'reset-white-labeling-login' : 'reset-white-labeling'), blocks: []}; + } + return {hood: text(target === 'LOGIN' ? 'save-white-labeling-login' : 'save-white-labeling'), blocks: [{type: 'facts', rows: facts(changes)}, + ...images([{label: text('image-logo'), value: values.logoImage}, {label: text('image-collapsed-logo'), value: values.collapsedLogoImage}, + {label: text('image-favicon'), value: values.favicon}])]}; + } + case 'read_mail_templates': { + if (!isObject(result)) { + return {hood: text('read-mail-templates'), blocks: generic(result, 'result')}; + } + const note: AiDetailBlock[] = [{type: 'note', text: text(result.useSystemTemplates ? 'mail-system-in-use' : 'mail-own-in-use')}]; + if (str(result.template)) { + const blocks: AiDetailBlock[] = [...note, {type: 'facts', rows: [{label: K + 'fact.subject', value: str(result.subject) ?? '—', raw: true}]}]; + if (str(result.body)) { + blocks.push({type: 'code', label: 'HTML', text: result.body}); + } + return {hood: text('read-mail-template', {template: result.template}), blocks}; + } + const rows = (Array.isArray(result.templates) ? result.templates.filter(isObject) : []).map(item => `${item.template} · ${item.subject ?? '—'}`); + return {hood: text('read-mail-templates'), blocks: [...note, ...(rows.length ? [{type: 'list', rows} as AiDetailBlock] : [])]}; + } + case 'save_mail_template': { + if (values.useSystemTemplates) { + return {hood: text('mail-use-system'), blocks: []}; + } + const blocks: AiDetailBlock[] = []; + if (str(values.subject)) { + blocks.push({type: 'facts', rows: [{label: K + 'fact.subject', value: values.subject, raw: true}]}); + } + const replace = Array.isArray(values.replace) ? values.replace.filter(isObject) : []; + if (replace.length) { + blocks.push({type: 'list', label: text('mail-replaced'), rows: replace.map(item => `${item.from} → ${item.to}`)}); + } + if (str(values.body)) { + blocks.push({type: 'code', label: 'HTML', text: values.body}); + } + return {hood: str(values.template) ? text('save-mail-template', {template: values.template}) : text('save-mail-templates'), blocks}; + } + case 'read_custom_translation': { + const locale = str(isObject(result) ? result.locale : undefined) ?? str(values.locale) ?? '—'; + if (!isObject(result)) { + return {hood: text('read-custom-translation', {locale}), blocks: generic(result, 'result')}; + } + const blocks: AiDetailBlock[] = []; + const matches = (Array.isArray(result.matches) ? result.matches.filter(isObject) : []).slice(0, MAX_ROWS) + .map(match => `${match.key} · ${match.text}${match.customized ? ' ✎' : ''}`); + if (matches.length) { + blocks.push({type: 'list', label: text('translation-matches'), rows: matches}); + } + const customized = Object.entries(isObject(result.customized) ? result.customized : {}).slice(0, MAX_ROWS) + .map(([key, value]) => `${key} · ${value}`); + if (customized.length) { + blocks.push({type: 'list', label: text('translation-customized'), rows: customized}); + } + return {hood: text('read-custom-translation', {locale}), blocks}; + } + case 'save_custom_translation': { + const blocks: AiDetailBlock[] = []; + const set = (Array.isArray(values.set) ? values.set.filter(isObject) : []).map(item => `${item.key} → ${item.text}`); + if (set.length) { + blocks.push({type: 'list', label: text('translation-set'), rows: set.slice(0, MAX_ROWS)}); + } + const removed = Array.isArray(values.remove) ? values.remove.map(String) : []; + if (removed.length) { + blocks.push({type: 'list', label: text('translation-removed'), rows: removed.slice(0, MAX_ROWS)}); + } + return {hood: text('save-custom-translation', {locale: str(values.locale) ?? '—'}), blocks}; + } + case 'read_mobile_center': { + if (!isObject(result)) { + return {hood: text('read-mobile-center'), blocks: generic(result, 'result')}; + } + const blocks: AiDetailBlock[] = []; + const apps = (Array.isArray(result.apps) ? result.apps.filter(isObject) : []).slice(0, MAX_ROWS) + .map(app => [app.pkgName, app.platformType, aiHumanize(String(app.status)), str(app.versionInfo?.latestVersion)].filter(Boolean).join(' · ')); + if (apps.length) { + blocks.push({type: 'list', label: text('mobile-apps'), rows: apps}); + } else if (Array.isArray(result.apps)) { + blocks.push({type: 'note', text: text('no-mobile-apps')}); + } + if (Array.isArray(result.bundles) && !result.bundles.length) { + blocks.push({type: 'note', text: text('no-mobile-bundles')}); + } + for (const bundle of (Array.isArray(result.bundles) ? result.bundles.filter(isObject) : []).slice(0, MAX_ROWS)) { + const pages = (Array.isArray(bundle.menu) ? bundle.menu.filter(isObject) : []) + .map(page => `${str(page.label) ?? page.id}${page.hidden ? ' ⊘' : ''}`); + blocks.push({type: 'list', label: text('mobile-bundle-menu', {name: str(bundle.title) ?? '—'}), rows: pages}); + } + if (isObject(result.qrCode)) { + blocks.push(...json('qr-code', result.qrCode)); + } + return {hood: text('read-mobile-center'), blocks}; + } + case 'save_mobile_app': { + const rows = facts(values, ['appId']); + return {hood: str(values.appId) ? text('save-mobile-app') : text('register-mobile-app', {name: str(values.pkgName) ?? '—'}), + blocks: rows.length ? [{type: 'facts', rows}] : []}; + } + case 'save_mobile_bundle': { + const changes = (Array.isArray(values.changes) ? values.changes.filter(isObject) : []) + .map(change => [aiHumanize(String(change.action)), str(change.page) ?? str(change.label), str(change.page) && str(change.label) ? '→ ' + change.label : undefined, + str(change.dashboardId) ?? str(change.url) ?? str(change.path)].filter(Boolean).join(' ')); + const blocks: AiDetailBlock[] = []; + const rows = facts(values, ['bundleId', 'changes']); + if (rows.length) { + blocks.push({type: 'facts', rows}); + } + if (changes.length) { + blocks.push({type: 'list', label: text('menu-changes'), rows: changes.slice(0, MAX_ROWS)}); + } + return {hood: str(values.bundleId) ? text('save-mobile-bundle') : text('create-mobile-bundle', {name: str(values.title) ?? '—'}), blocks}; + } + case 'read_scheduler_events': { + if (!isObject(result)) { + return {hood: text('read-scheduler-events'), blocks: generic(result, 'result')}; + } + if (Array.isArray(result.events)) { + const rows = result.events.filter(isObject).slice(0, MAX_ROWS) + .map(event => [event.name, event.schedule, event.enabled === false ? '⏸' : undefined].filter(Boolean).join(' · ')); + return {hood: text('read-scheduler-events'), + blocks: rows.length ? [{type: 'list', rows}] : [{type: 'note', text: text('no-scheduler-events')}]}; + } + return {hood: text('read-scheduler-event', {name: str(result.name) ?? '—'}), blocks: json('event', result)}; + } + case 'read_mail_server': + return {hood: text('read-mail-server'), blocks: json('mail-server', result)}; + case 'save_mail_server': { + const rows = facts(values); + return {hood: text('save-mail-server'), blocks: rows.length ? [{type: 'facts', rows}] : []}; + } + case 'read_my_account': + return {hood: text('read-my-account'), blocks: json('account', result)}; + case 'save_my_profile': { + const rows = facts(values); + return {hood: text('save-my-profile'), blocks: rows.length ? [{type: 'facts', rows}] : []}; + } + case 'save_my_two_factor': { + const rows = facts(values); + return {hood: text('save-my-two-factor'), blocks: rows.length ? [{type: 'facts', rows}] : []}; + } + case 'update_api_key': { + const rows = facts(values, ['apiKeyId']); + return {hood: values.delete === true ? text('delete-api-key') : text('update-api-key'), blocks: rows.length ? [{type: 'facts', rows}] : []}; + } + case 'save_oauth2_domain': { + const rows = facts(values, ['domainId']); + return {hood: text('save-oauth2-domain'), blocks: rows.length ? [{type: 'facts', rows}] : []}; + } + case 'save_two_factor_settings': { + const rows = facts(values); + return {hood: text('save-two-factor-settings'), blocks: rows.length ? [{type: 'facts', rows}] : []}; + } + case 'create_report_template': + case 'update_report_template': { + const rows = facts(values, ['templateId']); + return {hood: tool === 'create_report_template' ? text('create-report-template', {name: str(values.name) ?? '—'}) : text('update-report-template'), + blocks: rows.length ? [{type: 'facts', rows}] : []}; + } + case 'read_report_template': { + if (!isObject(result)) { + return {hood: text(str(values.path) ? 'read-report-component' : 'read-report-template', {path: str(values.path) ?? '—', name: '—'}), blocks: generic(result, 'result')}; + } + if (str(values.path)) { + return {hood: text('read-report-component', {path: str(result.path) ?? str(values.path), name: str(result.template) ?? '—'}), + blocks: [{type: 'facts', rows: reportComponentFacts(result)}]}; + } + return {hood: text('read-report-template', {name: str(result.name) ?? '—'}), blocks: reportTemplateOverview(result)}; + } + case 'add_report_components': { + const rows = (Array.isArray(values.components) ? values.components.filter(isObject) : []).slice(0, MAX_ROWS).map(component => { + const config = isObject(component.config) ? component.config : {}; + const title = str(config.title) ?? str(config.text); + return [str(component.in), aiHumanize(String(component.type)), title].filter(Boolean).join(' · '); + }); + return {hood: text('add-report-components'), blocks: rows.length ? [{type: 'list', rows}] : []}; + } + case 'update_report_component': { + const rows = facts(isObject(values.config) ? values.config as Values : {}); + return {hood: text('update-report-component', {path: str(values.path) ?? '—'}), blocks: rows.length ? [{type: 'facts', rows}] : []}; + } + case 'move_report_component': + return {hood: text('move-report-component', {path: str(values.path) ?? '—', target: str(values.in) ?? '—'}), blocks: []}; + case 'save_report_entity_alias': + case 'save_report_filter': { + const rows = facts(values, ['templateId', 'aliasId', 'filterId']); + return {hood: text(tool === 'save_report_filter' ? 'save-report-filter' : 'save-report-alias', {name: str(values.name) ?? '—'}), + blocks: rows.length ? [{type: 'facts', rows}] : []}; + } + case 'test_report_template': { + if (!isObject(result)) { + return {hood: text('test-report-template'), blocks: generic(result, 'result')}; + } + const errors = (Array.isArray(result.errors) ? result.errors.filter(isObject) : []) + .map(error => [error.page !== undefined ? `p. ${error.page}` : error.row !== undefined ? `row ${error.row}` : undefined, str(error.message)] + .filter(Boolean).join(' · ')); + const pdf = result.pages !== undefined; + const count = Number(pdf ? result.pages : result.rows ?? 0); + const size = text((pdf ? 'report-pages' : 'report-rows') + (errors.length ? '' : '-clean'), {count}); + return {hood: text('test-report-template'), + blocks: [{type: 'note', text: size}, + ...(errors.length ? [{type: 'list' as const, label: text('report-errors'), rows: errors.slice(0, MAX_ROWS)}] : [])]}; + } + case 'read_reports': { + if (!isObject(result)) { + return {hood: text('read-reports'), blocks: generic(result, 'result')}; + } + if (Array.isArray(result.templates)) { + const rows = result.templates.filter(isObject).slice(0, MAX_ROWS) + .map(item => [item.name, item.format, item.templateType === 'SUB_REPORT' ? 'Sub-report' : undefined].filter(Boolean).join(' · ')); + return {hood: text('read-report-templates'), + blocks: rows.length ? [{type: 'list', rows}] : [{type: 'note', text: text('no-report-templates')}]}; + } + if (Array.isArray(result.scheduledReports)) { + const rows = result.scheduledReports.filter(isObject).slice(0, MAX_ROWS) + .map(item => [item.name, item.template, item.schedule, item.enabled === false ? '⏸' : undefined].filter(Boolean).join(' · ')); + return {hood: text('read-scheduled-reports'), + blocks: rows.length ? [{type: 'list', rows}] : [{type: 'note', text: text('no-scheduled-reports')}]}; + } + if (Array.isArray(result.reports)) { + const rows = result.reports.filter(isObject).slice(0, MAX_ROWS) + .map(item => [item.file, item.template, item.generated].filter(Boolean).join(' · ')); + return {hood: text('read-generated-reports'), + blocks: rows.length ? [{type: 'list', rows}] : [{type: 'note', text: text('no-generated-reports')}]}; + } + if (isObject(result.file)) { + return {hood: text('attach-report', {name: str(result.file.name) ?? '—'}), blocks: []}; + } + const rows = facts(result, ['eventId', 'templateId', 'rawSchedule', 'recipients', 'notificationTemplate', 'name']); + const recipients = Array.isArray(result.recipients) ? result.recipients.filter(isObject).map(item => str(item.name)).filter(Boolean) : []; + if (recipients.length) { + rows.push({label: aiHumanize('recipients'), raw: true, value: recipients.join(', ')}); + } + return {hood: text('read-scheduled-report', {name: str(result.name) ?? '—'}), blocks: rows.length ? [{type: 'facts', rows}] : []}; + } + case 'save_scheduled_report': { + const rows = facts(values, ['eventId', 'templateId', 'userId', 'recipientIds', 'notificationTemplateId']); + return {hood: str(values.eventId) ? text('save-scheduled-report') : text('create-scheduled-report', {name: str(values.name) ?? '—'}), + blocks: rows.length ? [{type: 'facts', rows}] : []}; + } + case 'generate_report': { + const raw = typeof result === 'string' && /^OK: [^\n]*\n/.test(result) ? aiParse(result.slice(result.indexOf('\n') + 1)) : result; + if (!isObject(raw)) { + return {hood: text('generate-report'), blocks: generic(raw, 'result')}; + } + const name = isObject(raw.file) ? str(raw.file.name) : str(raw.file); + const rows: AiDetailFact[] = []; + if (name) { + rows.push({label: aiHumanize('file'), raw: true, value: name}); + } + if (str(raw.sentTo)) { + rows.push({label: aiHumanize('sent to'), raw: true, value: str(raw.sentTo)}); + } + return {hood: text('generate-report'), blocks: rows.length ? [{type: 'facts', rows}] : [{type: 'note', text: text('report-still-running')}]}; + } + case 'read_widgets': { + if (!isObject(result)) { + return {hood: text('read-widgets'), blocks: generic(result, 'result')}; + } + if (Array.isArray(result.widgets) && str(result.title)) { + const rows = result.widgets.filter(isObject).slice(0, MAX_ROWS).map(item => [item.name, item.type].filter(Boolean).join(' · ')); + return {hood: text('read-widgets-bundle', {name: str(result.title)}), + blocks: rows.length ? [{type: 'list', rows}] : [{type: 'note', text: text('no-widgets')}]}; + } + if (Array.isArray(result.widgets)) { + const rows = result.widgets.filter(isObject).slice(0, MAX_ROWS) + .map(item => [item.name, item.type, item.system ? 'system' : undefined].filter(Boolean).join(' · ')); + return {hood: text('read-widgets'), blocks: rows.length ? [{type: 'list', rows}] : [{type: 'note', text: text('no-widgets')}]}; + } + const rows = (Array.isArray(result.bundles) ? result.bundles.filter(isObject) : []).slice(0, MAX_ROWS) + .map(item => [item.title, item.system ? 'system' : undefined].filter(Boolean).join(' · ')); + return {hood: text('read-widgets-bundles'), blocks: rows.length ? [{type: 'list', rows}] : [{type: 'note', text: text('no-widgets-bundles')}]}; + } + case 'read_scada_symbols': { + const rows = (isObject(result) && Array.isArray(result.symbols) ? result.symbols.filter(isObject) : []).slice(0, MAX_ROWS) + .map(item => [item.title, item.family === 'hp' ? 'HP' : item.family, item.size, item.system ? 'system' : undefined].filter(Boolean).join(' · ')); + return {hood: text('read-scada-symbols'), blocks: rows.length ? [{type: 'list', rows}] : [{type: 'note', text: text('no-scada-symbols')}]}; + } + case 'read_scada_symbol': { + if (!isObject(result)) { + const raw = typeof result === 'string' ? result : ''; + const name = /^SCADA symbol '([^']*)'/.exec(raw)?.[1] ?? '—'; + const parts = widgetParts(values).filter(part => part !== 'all'); + const sections = raw.split(/\n\n=== ([A-Za-z]+) ===\n/); + const blocks: AiDetailBlock[] = []; + for (let i = 1; i + 1 < sections.length; i += 2) { + const overview = sections[i] === 'overview' ? aiParse(sections[i + 1]) : undefined; + if (isObject(overview)) { + blocks.push(...scadaSymbolOverviewBlocks(overview)); + } else if (sections[i + 1].trim()) { + blocks.push({type: 'code', label: aiPartTitle(sections[i]), text: sections[i + 1], + lang: SCADA_SYMBOL_PART_LANGS[sections[i]] ?? 'json'}); + } + } + return {hood: text('read-scada-symbol-parts', {name, parts: aiWordList(parts.map(aiPartWord), true)}), blocks}; + } + return {hood: text('read-scada-symbol', {name: str(result.title) ?? '—'}), blocks: scadaSymbolOverviewBlocks(result)}; + } + case 'build_scada_symbol': + case 'create_scada_symbol': + case 'update_scada_symbol': { + const raw = typeof result === 'string' && result.startsWith('OK: ') ? aiParse(result.slice(4)) : result; + const name = (isObject(raw) ? str(raw.title) : undefined) ?? str(values.title) ?? '—'; + const hood = tool === 'create_scada_symbol' ? text('copy-scada-symbol', {name}) + : tool === 'update_scada_symbol' ? text('change-scada-symbol', {name}) + : str(values.symbol) ? text('update-scada-symbol', {name}) : text('create-scada-symbol', {name}); + if (!isObject(raw)) { + return {hood, blocks: generic(raw, 'result')}; + } + const warnings = Array.isArray(raw.warnings) ? raw.warnings.map(item => String(item)) : []; + const rows = facts(raw, ['warnings', 'link']); + return {hood, blocks: [...scadaSymbolPicture(raw), ...(rows.length ? [{type: 'facts' as const, rows}] : []), + ...(warnings.length ? [{type: 'list' as const, label: text('widget-warnings'), rows: warnings.slice(0, MAX_ROWS)}] : [])]}; + } + case 'read_widget': { + if (!isObject(result)) { + const raw = typeof result === 'string' ? result : ''; + const name = /^Widget '([^']*)'/.exec(raw)?.[1] ?? '—'; + const parts = widgetParts(values).filter(part => part !== 'all'); + const sections = raw.split(/\n\n=== ([A-Za-z]+) ===\n/); + const blocks: AiDetailBlock[] = []; + for (let i = 1; i + 1 < sections.length; i += 2) { + if (sections[i + 1].trim()) { + blocks.push({type: 'code', label: aiPartTitle(sections[i]), text: sections[i + 1], + lang: WIDGET_PART_LANGS[sections[i]] ?? 'json'}); + } + } + return {hood: text('read-widget-parts', {name, parts: aiWordList(parts.map(aiPartWord), true)}), blocks}; + } + const rows = facts(result, ['id', 'name', 'typeParameters', 'functions', 'problems', 'lines', 'settingsForm', 'dataKeySettingsForm', + 'latestDataKeySettingsForm', 'defaultConfig', 'resources', 'note', 'builtIn', 'description', 'image', 'tags']); + const problems = Array.isArray(result.problems) ? result.problems.map(item => String(item)) : []; + return {hood: text('read-widget-type', {name: str(result.name) ?? '—'}), + blocks: [...(rows.length ? [{type: 'facts' as const, rows}] : []), + ...(problems.length ? [{type: 'list' as const, label: text('widget-problems'), rows: problems.slice(0, MAX_ROWS)}] : [])]}; + } + case 'create_widget': + case 'build_widget': + case 'update_widget': { + const raw = typeof result === 'string' && /^OK: [^\n]*\n/.test(result) ? aiParse(result.slice(result.indexOf('\n') + 1)) : result; + const edits = Array.isArray(values.edits) ? values.edits.length : 0; + const hood = tool === 'create_widget' || (tool === 'build_widget' && !values.widgetTypeId) ? text('create-widget', {name: str(values.name) ?? '—'}) + : edits ? text('update-widget-edits', {count: edits}) : text('update-widget-type'); + if (!isObject(raw)) { + return {hood, blocks: generic(raw, 'result')}; + } + const warnings = Array.isArray(raw.warnings) ? raw.warnings.map(item => String(item)) : []; + const rows = facts(raw, ['typeParameters', 'warnings', 'note', 'next', 'id', 'name', 'fqn', 'type']); + return {hood, blocks: [...(rows.length ? [{type: 'facts' as const, rows}] : []), + ...(warnings.length ? [{type: 'list' as const, label: text('widget-warnings'), rows: warnings.slice(0, MAX_ROWS)}] : [])]}; + } + case 'create_scada_symbol_widget': { + const raw = typeof result === 'string' && result.startsWith('OK: ') ? aiParse(result.slice(4)) : result; + const name = (isObject(raw) ? str(raw.name) : undefined) ?? str(values.name) ?? '—'; + if (!isObject(raw)) { + return {hood: text('create-scada-symbol-widget', {name}), blocks: generic(raw, 'result')}; + } + const rows = facts(raw, ['widgetTypeId']); + return {hood: text('create-scada-symbol-widget', {name}), blocks: rows.length ? [{type: 'facts', rows}] : []}; + } + case 'check_scada_symbol': { + if (!isObject(result)) { + return {hood: text('check-scada-symbol'), blocks: generic(result, 'result')}; + } + const errors = Array.isArray(result.errors) ? result.errors.map(item => String(item)) : []; + const outcome = errors.length ? text('widget-check-errors', {count: errors.length}) + : result.result === 'rendered without errors' ? text('scada-symbol-check-clean') : text('scada-symbol-check-not-rendered'); + return {hood: text('check-scada-symbol'), blocks: [{type: 'note', text: outcome}, + ...(errors.length ? [{type: 'list' as const, label: text('widget-errors'), rows: errors.slice(0, MAX_ROWS)}] : [])]}; + } + case 'check_widget': { + if (!isObject(result)) { + return {hood: text('check-widget'), blocks: generic(result, 'result')}; + } + const errors = Array.isArray(result.errors) ? result.errors.map(item => String(item)) : []; + const consoleErrors = Array.isArray(result.consoleErrors) ? result.consoleErrors.map(item => String(item)) : []; + const outcome = errors.length ? text('widget-check-errors', {count: errors.length}) + : result.result === 'ran without errors' ? text('widget-check-clean') : text('widget-check-not-run'); + return {hood: text('check-widget'), blocks: [{type: 'note', text: outcome}, + ...(errors.length ? [{type: 'list' as const, label: text('widget-errors'), rows: errors.slice(0, MAX_ROWS)}] : []), + ...(consoleErrors.length ? [{type: 'list' as const, label: text('widget-console'), rows: consoleErrors.slice(0, MAX_ROWS)}] : [])]}; + } + case 'save_widgets_bundle': { + const raw = typeof result === 'string' && /^OK: [^\n]*\n/.test(result) ? aiParse(result.slice(result.indexOf('\n') + 1)) : result; + const hood = str(values.bundleId) ? text('save-widgets-bundle') : text('create-widgets-bundle', {name: str(values.title) ?? '—'}); + if (!isObject(raw)) { + return {hood, blocks: generic(raw, 'result')}; + } + const rows = Array.isArray(raw.widgets) ? raw.widgets.map(item => String(item)).slice(0, MAX_ROWS) : []; + return {hood, blocks: rows.length ? [{type: 'list', label: text('widgets'), rows}] : [{type: 'note', text: text('no-widgets')}]}; + } + case 'save_scheduler_event': { + const rows = facts(values, ['eventId']); + return {hood: str(values.eventId) ? text('save-scheduler-event') : text('create-scheduler-event', {name: str(values.name) ?? '—'}), + blocks: rows.length ? [{type: 'facts', rows}] : []}; + } + case 'save_mobile_qr_code': { + const rows = facts(values); + return {hood: text('save-mobile-qr-code'), blocks: rows.length ? [{type: 'facts', rows}] : []}; + } + case 'read_security_settings': + return {hood: text('read-security-settings'), blocks: json('settings', result)}; + case 'read_custom_menus': { + if (!isObject(result)) { + return {hood: text('read-custom-menus'), blocks: generic(result, 'result')}; + } + if (Array.isArray(result.menus)) { + const rows = result.menus.filter(isObject).slice(0, MAX_ROWS).map(menu => `${menu.name} · ${aiHumanize(String(menu.scope))} · ${aiHumanize(String(menu.assigneeType))}`); + return {hood: text('read-custom-menus'), blocks: rows.length ? [{type: 'list', rows}] : [{type: 'note', text: text('nothing-found')}]}; + } + const rows: string[] = []; + const walk = (items: unknown, depth: number) => { + for (const item of Array.isArray(items) ? items.filter(isObject) : []) { + rows.push(`${' '.repeat(depth)}${str(item.custom) ?? str(item.name) ?? item.id}${item.hidden ? ' ⊘' : ''}`); + walk(item.pages, depth + 1); + } + }; + walk(result.items, 0); + return {hood: text('read-custom-menu', {name: str(result.name) ?? '—'}), blocks: rows.length ? [{type: 'list', rows: rows.slice(0, 80)}] : []}; + } + case 'save_custom_menu': { + const changes = (Array.isArray(values.changes) ? values.changes.filter(isObject) : []) + .map(change => [aiHumanize(String(change.action)), str(change.item) ?? str(change.name), str(change.item) && str(change.name) ? '→ ' + change.name : undefined, + str(change.url) ?? str(change.dashboardId)].filter(Boolean).join(' ')); + const blocks: AiDetailBlock[] = []; + const rows = facts(values, ['menuId', 'changes']); + if (rows.length) { + blocks.push({type: 'facts', rows}); + } + if (changes.length) { + blocks.push({type: 'list', label: text('menu-changes'), rows: changes.slice(0, MAX_ROWS)}); + } + return {hood: str(values.menuId) ? text('save-custom-menu') : text('create-custom-menu', {name: str(values.name) ?? '—'}), blocks}; + } + case 'read_edges': { + if (!isObject(result)) { + return {hood: text('read-edges'), blocks: generic(result, 'result')}; + } + if (Array.isArray(result.edges)) { + const counts: AiDetailFact[] = Object.entries(isObject(result.connection) ? result.connection : {}) + .map(([state, count]) => ({label: aiHumanize(state), raw: true, value: String(count)})); + const rows = result.edges.filter(isObject).slice(0, MAX_ROWS) + .map(edge => [edge.name, edge.connection, str(edge.version)].filter(Boolean).join(' · ')); + const blocks: AiDetailBlock[] = counts.length ? [{type: 'facts', rows: counts}] : []; + if (rows.length) { + blocks.push({type: 'list', rows}); + } + return {hood: text('read-edges'), blocks}; + } + const rows = facts(result, ['id', 'assigned', 'missingRuleChains']); + const blocks: AiDetailBlock[] = rows.length ? [{type: 'facts', rows}] : []; + const assigned = isObject(result.assigned) ? result.assigned : {}; + const lines: string[] = []; + for (const [kind, items] of Object.entries(assigned)) { + if (Array.isArray(items) && items.length) { + lines.push(`${aiHumanize(kind)}: ${items.filter(isObject).map(item => item.name).join(', ')}`); + } else if (isObject(items)) { + for (const [groupType, groups] of Object.entries(items)) { + if (Array.isArray(groups) && groups.length) { + lines.push(`${aiHumanize(groupType)}: ${groups.filter(isObject).map(group => group.name).join(', ')}`); + } + } + } + } + if (lines.length) { + blocks.push({type: 'list', label: text('edge-assigned'), rows: lines.slice(0, MAX_ROWS)}); + } + return {hood: text('read-edge', {name: str(result.name) ?? '—'}), blocks}; + } + case 'read_edge_events': { + if (!isObject(result)) { + return {hood: text('read-edge-events'), blocks: generic(result, 'result')}; + } + const counts: AiDetailFact[] = Object.entries(isObject(result.counts) ? result.counts : {}) + .map(([state, count]) => ({label: aiHumanize(state), raw: true, value: String(count)})); + const rows = (Array.isArray(result.downlinks) ? result.downlinks.filter(isObject) : []).slice(0, MAX_ROWS) + .map(event => [event.status, event.type, event.action, str(event.time) ? dateText(event.time) : undefined] + .filter(Boolean).join(' · ')); + const blocks: AiDetailBlock[] = counts.length ? [{type: 'facts', rows: counts}] : []; + if (rows.length) { + blocks.push({type: 'list', rows}); + } + return {hood: text('read-edge-events'), blocks}; + } + case 'read_edge_instructions': + return {hood: text(values.upgrade ? 'read-edge-upgrade-instructions' : 'read-edge-install-instructions'), + blocks: typeof result === 'string' && result.trim() ? [{type: 'markdown', text: result}] : []}; + case 'read_ota': { + if (!isObject(result)) { + return {hood: text('read-ota'), blocks: generic(result, 'result')}; + } + if (Array.isArray(result.packages)) { + const rows = result.packages.filter(isObject).slice(0, MAX_ROWS) + .map(pkg => `${pkg.title} ${pkg.version} · ${pkg.type} · ${pkg.source}`); + return {hood: text('read-ota-packages'), blocks: rows.length ? [{type: 'list', rows}] : []}; + } + const states = isObject(result.states) ? result.states : {}; + const facts: AiDetailFact[] = Object.entries(states).map(([state, count]) => ({label: aiHumanize(state), raw: true, value: String(count)})); + const rows = (Array.isArray(result.list) ? result.list.filter(isObject) : []).slice(0, MAX_ROWS) + .map(device => [device.name, device.state, str(device.current), str(device.target) ? '→ ' + device.target : undefined].filter(Boolean).join(' · ')); + const blocks: AiDetailBlock[] = facts.length ? [{type: 'facts', rows: facts}] : []; + if (rows.length) { + blocks.push({type: 'list', rows}); + } + return {hood: text('read-ota', {count: Number(result.devices) || 0}), blocks}; + } + case 'save_edge': + return {hood: text(str(values.edgeId) ? 'update-edge' : 'create-edge', {name: str(values.name) ?? '—'}), blocks: generic(result, 'result')}; + case 'assign_to_edge': { + const done = isObject(result) && Array.isArray(result.done) ? result.done.map(String) : []; + const failed = isObject(result) && Array.isArray(result.failed) ? result.failed.filter(isObject) : []; + const blocks: AiDetailBlock[] = []; + if (done.length) { + blocks.push({type: 'list', label: text('alarms-done'), rows: done.slice(0, MAX_ROWS)}); + } + if (failed.length) { + blocks.push({type: 'list', label: text('alarms-failed'), rows: failed.slice(0, MAX_ROWS).map(row => `${row.item}: ${row.error}`)}); + } + if (isObject(result) && result.missingRuleChains) { + blocks.push({type: 'list', label: text('edge-missing-rule-chains'), rows: [typeof result.missingRuleChains === 'string' + ? result.missingRuleChains : JSON.stringify(result.missingRuleChains)]}); + } + return {hood: text('assign-to-edge'), blocks: blocks.length ? blocks : generic(result, 'result')}; + } + case 'read_agents': { + if (!isObject(result)) { + return {hood: text('read-agents'), blocks: generic(result, 'result')}; + } + if (Array.isArray(result.agents)) { + const rows = result.agents.filter(isObject).slice(0, MAX_ROWS) + .map(agent => [agent.name, agent.online ? '●' : '○', str(agent.version), str(agent.profile)].filter(Boolean).join(' · ')); + return {hood: text('read-agents'), blocks: rows.length ? [{type: 'list', rows}] : []}; + } + const blocks: AiDetailBlock[] = []; + const apps = Array.isArray(result.applications) ? result.applications.filter(isObject) : []; + if (apps.length) { + blocks.push({type: 'list', label: text('agent-applications'), rows: apps.slice(0, MAX_ROWS) + .map(app => [app.name, app.appType, str(app.version), str(app.upgradeTo) ? '→ ' + app.upgradeTo : undefined].filter(Boolean).join(' · '))}); + } + const units = Array.isArray(result.units) ? result.units.filter(isObject) : []; + if (units.length) { + blocks.push({type: 'list', label: text('agent-units'), rows: units.slice(0, MAX_ROWS) + .map(unit => [unit.type, unit.name, str(unit.state)].filter(Boolean).join(' · '))}); + } + const ops = Array.isArray(result.recentOperations) ? result.recentOperations.filter(isObject) : []; + if (ops.length) { + blocks.push({type: 'list', label: text('agent-operations'), rows: ops.slice(0, MAX_ROWS) + .map(op => [op.action, str(op.application), op.status, str(op.error)].filter(Boolean).join(' · '))}); + } + return {hood: text('read-agent', {name: str(result.name) ?? '—'}), blocks}; + } + case 'read_agent_instructions': + return {hood: text('read-agent-instructions'), blocks: typeof result === 'string' && result.trim() ? [{type: 'markdown', text: result}] : []}; + case 'read_agent_profiles': { + if (!isObject(result)) { + return {hood: text('read-agent-profiles'), blocks: generic(result, 'result')}; + } + const list = (key: string) => Array.isArray(result[key]) ? (result[key] as unknown[]).filter(isObject) : []; + const rows = [...list('agentProfiles').map(profile => [profile.name, profile.provisionType, profile.default ? '★' : undefined]), + ...list('appProfiles').map(profile => [profile.name, profile.appType, str(profile.templateVersion)])] + .slice(0, MAX_ROWS).map(row => row.filter(Boolean).map(String).join(' · ')); + if (Array.isArray(result.versions)) { + rows.push(...result.versions.map(String).slice(0, MAX_ROWS)); + } + return {hood: text('read-agent-profiles'), blocks: rows.length ? [{type: 'list', rows}] : generic(result, 'result')}; + } + case 'save_agent': + return {hood: text(str(values.agentId) ? 'update-agent' : 'create-agent', {name: str(values.name) ?? '—'}), blocks: generic(result, 'result')}; + case 'install_agent_application': + case 'run_agent_operation': + case 'save_agent_profile': + case 'save_agent_app_profile': + case 'run_agent_bulk_action': + return {hood: text(tool.replace(/_/g, '-')), blocks: generic(result, 'result')}; + case 'wait_agent_operation': { + if (!isObject(result)) { + return {hood: text('wait-agent-operation'), blocks: typeof result === 'string' && result.trim() ? [{type: 'markdown', text: result}] : []}; + } + const rows = facts(result, ['operationId']); + return {hood: text('wait-agent-operation'), blocks: rows.length ? [{type: 'facts', rows}] : []}; + } + case 'read_rule_chain_templates': { + if (!isObject(result)) { + return {hood: text('read-rule-chain-templates'), blocks: generic(result, 'result')}; + } + const templates = Array.isArray(result.templates) ? result.templates.filter(isObject) : []; + if (templates.length || !str(result.name)) { + const blocks: AiDetailBlock[] = []; + const roots = templates.filter(template => template.edgeTemplateRoot).map(template => String(template.name)); + const auto = templates.filter(template => template.autoAssignToNewEdges).map(template => String(template.name)); + if (roots.length) { + blocks.push({type: 'list', label: text('rule-chain-template-root'), rows: roots}); + } + if (auto.length) { + blocks.push({type: 'list', label: text('rule-chain-template-auto'), rows: auto.slice(0, MAX_ROWS)}); + } + const rows = templates.slice(0, MAX_ROWS).map(template => String(template.name)); + if (rows.length) { + blocks.push({type: 'list', rows}); + } + return {hood: text('read-rule-chain-templates'), blocks}; + } + const blocks: AiDetailBlock[] = []; + const edges = Array.isArray(result.assignedToEdges) ? result.assignedToEdges.map(String) : []; + if (edges.length) { + blocks.push({type: 'list', label: text('rule-chain-template-edges'), rows: edges.slice(0, MAX_ROWS)}); + } + const nodes = Array.isArray(result.nodes) ? result.nodes.map(String) : []; + if (nodes.length) { + blocks.push({type: 'list', label: text('rule-chain-template-nodes'), rows: nodes.slice(0, MAX_ROWS)}); + } + return {hood: text('read-rule-chain-template', {name: str(result.name) ?? '—'}), blocks}; + } + case 'set_rule_chain_template': + return {hood: text('set-rule-chain-template'), blocks: typeof result === 'string' && result.trim() ? [{type: 'markdown', text: result}] : []}; + case 'sync_edge': + return {hood: text('sync-edge'), blocks: []}; + case 'save_ota_package': + return {hood: text('save-ota-package', {name: [str(values.title), str(values.version)].filter(Boolean).join(' ') || '—'}), blocks: generic(result, 'result')}; + case 'assign_ota_package': { + const updated = isObject(result) && Array.isArray(result.updated) ? result.updated.map(String) : []; + const failed = isObject(result) && Array.isArray(result.failed) ? result.failed.filter(isObject) : []; + const blocks: AiDetailBlock[] = []; + if (updated.length) { + blocks.push({type: 'list', label: text('alarms-done'), rows: updated.slice(0, MAX_ROWS)}); + } + if (failed.length) { + blocks.push({type: 'list', label: text('alarms-failed'), rows: failed.slice(0, MAX_ROWS).map(row => `${row.target}: ${row.error}`)}); + } + return {hood: text(values.clear ? 'clear-ota-package' : 'assign-ota-package'), blocks: blocks.length ? blocks : generic(result, 'result')}; + } + case 'read_versions': { + const versions = isObject(result) && Array.isArray(result.versions) ? result.versions.filter(isObject) : undefined; + if (!versions) { + return {hood: text('read-versions'), blocks: generic(result, 'result')}; + } + const rows = versions.slice(0, MAX_ROWS).map(version => [str(version.name), str(version.author), + str(version.time) ? dateText(version.time) : undefined].filter(Boolean).join(' · ')); + return {hood: text('read-versions'), blocks: rows.length ? [{type: 'list', rows}] : []}; + } + case 'commit_version': { + const saved = isObject(result) ? result : {}; + const rows: AiDetailFact[] = []; + if (str(saved.versionId)) { + rows.push({label: K + 'fact.version', value: saved.versionId, mono: true}); + } + if (str(saved.branch)) { + rows.push({label: K + 'fact.branch', value: saved.branch}); + } + for (const field of ['added', 'modified', 'removed']) { + if (typeof saved[field] === 'number') { + rows.push({label: K + 'fact.' + field, value: String(saved[field])}); + } + } + return {hood: text('commit-version', {name: str(values.name) ?? '—'}), blocks: rows.length ? [{type: 'facts', rows}] : generic(result, 'result')}; + } + case 'restore_version': { + const types = isObject(result) && Array.isArray(result.result) ? result.result.filter(isObject) : undefined; + const rows = (types ?? []).map(type => `${type.entityType}: +${type.created} · ~${type.updated} · −${type.deleted}`); + return {hood: text('restore-version', {version: String(values.versionId ?? '').slice(0, 8)}), blocks: types ? [{type: 'list', rows}] : generic(result, 'result')}; + } + case 'read_platform_settings': + return {hood: text('read-platform-settings'), blocks: json('settings', result)}; + case 'save_platform_settings': + return {hood: text('save-platform-settings'), blocks: json('settings', result)}; + case 'update_alarms': { + const action = alarmUpdateAction(values.action); + const count = Array.isArray(values.alarmIds) ? values.alarmIds.length : 0; + if (!isObject(result)) { + return {hood: text('update-alarms.' + action, {count}), blocks: generic(result, 'result')}; + } + const blocks: AiDetailBlock[] = []; + const done = Array.isArray(result.done) ? result.done.map(String) : []; + const skipped = Array.isArray(result.skipped) ? result.skipped.map(String) : []; + const failed = Array.isArray(result.failed) ? result.failed.filter(isObject) : []; + if (done.length) { + blocks.push({type: 'list', label: text('alarms-done'), rows: done.slice(0, MAX_ROWS)}); + } + if (skipped.length) { + blocks.push({type: 'list', label: text('alarms-skipped'), rows: skipped.slice(0, MAX_ROWS)}); + } + if (failed.length) { + blocks.push({type: 'list', label: text('alarms-failed'), rows: failed.slice(0, MAX_ROWS).map(row => `${row.alarm}: ${row.error}`)}); + } + if (str(values.comment)) { + blocks.push({type: 'facts', rows: [{label: K + 'fact.comment', value: values.comment}]}); + } + return {hood: text('update-alarms.' + action, {count}), blocks}; + } + case 'read_api_usage': + return {hood: text('read-api-usage'), blocks: apiUsageBlocks(result)}; + case 'read_audit_logs': + return {hood: values.entityId ? text('read-audit-logs-of', {entity: target}) : text('read-audit-logs'), blocks: auditLogBlocks(result)}; + case 'read_tasks': + return {hood: text('read-tasks'), blocks: taskBlocks(result)}; + case 'save_image': { + const saved = isObject(result) ? result : {}; + const rows: AiDetailFact[] = str(saved.link) ? [{label: K + 'fact.link', value: saved.link, mono: true}] : []; + return {hood: text('save-image', {name: str(saved.title) ?? str(values.title) ?? '—'}), + blocks: rows.length ? [{type: 'facts', rows}, ...images([{value: saved.link}])] : generic(result, 'result')}; + } + case 'test_converter': + return {blocks: converterBlocks(values, result)}; + case 'save_converter': + return {blocks: [...converterBlocks(values, undefined), ...generic(result, 'result', [], names)]}; + case 'reprocess_calculated_field': + return {hood: text('reprocess', {entity: of(values.calculatedFieldId, 'CALCULATED_FIELD'), from: dateText(values.startTime ?? values.startTs), to: endText(values.endTime ?? values.endTs)}), blocks: generic(result, 'result')}; + } + const request = Object.keys(values).length ? (flat(values) ? [{type: 'facts', rows: facts(values, [...CODE_KEYS], names)} as AiDetailBlock, ...codeBlocks(values)] : json('request', values)) : []; + return {blocks: [...request, ...generic(result, 'result', [], names)]}; +} + +const USAGE_LIMIT = (limit: unknown): string => limit === 'unlimited' || limit === undefined ? '∞' : aiValueText(limit); + +function apiUsageBlocks(result: unknown): AiDetailBlock[] { + if (!isObject(result)) { + return generic(result, 'result'); + } + const rows: AiDetailFact[] = []; + const warned: string[] = []; + for (const [name, entry] of Object.entries(isObject(result.entities) ? result.entities : {})) { + if (isObject(entry)) { + rows.push({label: K + 'usage.' + name, value: `${aiValueText(entry.count)} / ${USAGE_LIMIT(entry.limit)}`}); + } + } + for (const entry of Array.isArray(result.monthly) ? result.monthly : []) { + if (isObject(entry) && str(entry.name)) { + rows.push({label: K + 'usage.' + entry.name, value: `${aiValueText(entry.count)} / ${USAGE_LIMIT(entry.limit)}`}); + if (entry.state === 'WARNING' || entry.state === 'DISABLED') { + warned.push(entry.name); + } + } + } + const blocks: AiDetailBlock[] = rows.length ? [{type: 'facts', rows}] : []; + if (warned.length) { + blocks.push({type: 'note', text: text('usage.limited', {count: warned.length})}); + } + return blocks; +} + +function auditLogBlocks(result: unknown): AiDetailBlock[] { + const logs = isObject(result) && Array.isArray(result.logs) ? result.logs.filter(isObject) : undefined; + if (!logs) { + return generic(result, 'result'); + } + const rows: AiDetailRecord[] = logs.slice(0, MAX_ROWS).map(log => { + const target = isObject(log.entity) ? log.entity : {}; + const when = str(log.time) ? dateText(log.time) : undefined; + const meta = [str(log.action) ? aiHumanize(log.action) : undefined, str(log.user), when, log.status === 'FAILURE' ? '✕' : undefined] + .filter(Boolean).join(' · '); + return {entityType: str(target.type) ?? 'USER', id: str(target.id), name: str(target.name) ?? str(target.type) ?? '—', meta}; + }); + return [{type: 'records', rows, total: logs.length}]; +} + +function taskBlocks(result: unknown): AiDetailBlock[] { + const tasks = isObject(result) && Array.isArray(result.tasks) ? result.tasks.filter(isObject) : undefined; + if (!tasks) { + return generic(result, 'result'); + } + const rows: AiDetailRecord[] = tasks.slice(0, MAX_ROWS).map(task => { + const target = isObject(task.entity) ? task.entity : {}; + const progress = isObject(task.progress) ? task.progress : undefined; + const done = progress ? `${aiValueText(progress.successful)}${progress.total !== undefined ? ' / ' + aiValueText(progress.total) : ''}` : undefined; + const meta = [str(task.status) ? aiHumanize(task.status) : undefined, done, str(task.error)].filter(Boolean).join(' · '); + return {entityType: str(target.type) ?? 'CALCULATED_FIELD', id: str(target.id), name: str(target.name) ?? (str(task.type) ? aiHumanize(task.type) : '—'), meta}; + }); + return [{type: 'records', rows, total: tasks.length}]; +} + +function hasId(saved: Values): boolean { + return !!idOf(saved.id); +} + +function endText(value: unknown): string { + const shown = dateText(value); + return shown === '—' ? K + 'now' : shown; +} + +export function aiDateText(date: Date, locale?: string): string { + const now = new Date(); + const today = now.toDateString() === date.toDateString(); + const options: Intl.DateTimeFormatOptions = today ? {hour: 'numeric', minute: '2-digit'} + : date.getFullYear() === now.getFullYear() ? {day: 'numeric', month: 'short', hour: 'numeric', minute: '2-digit'} + : {day: 'numeric', month: 'short', year: 'numeric', hour: 'numeric', minute: '2-digit'}; + return new Intl.DateTimeFormat(locale || undefined, options).format(date); +} + +function dateText(value: unknown): string { + const parsed = typeof value === 'string' && /^\d+$/.test(value) ? Number(value) : value; + const date = typeof parsed === 'number' ? new Date(parsed) : typeof parsed === 'string' ? new Date(parsed) : null; + return date && !isNaN(date.getTime()) ? aiDateText(date) : '—'; +} + +const NAMES_CACHE = new Map>(); + +const MAX_CACHED = 500; + +export function aiDetailNames(messages: Array<{from: string; data?: any; references?: Array<{id: string; name: string; entityType: string}>}>, + previous?: AiDetailNames): AiDetailNames { + const names = new Map(); + for (const message of messages) { + let found: Map; + if (message.from === 'ACTION' && message.data?.executionId) { + const key = message.data.executionId + ':' + message.data.status; + found = NAMES_CACHE.get(key); + if (!found) { + found = namesOf(message); + if (NAMES_CACHE.size >= MAX_CACHED) { + NAMES_CACHE.delete(NAMES_CACHE.keys().next().value); + } + NAMES_CACHE.set(key, found); + } + } else if (message.references?.length) { + found = namesOf(message); + } else { + continue; + } + found.forEach((value, id) => !names.has(id) && names.set(id, value)); + } + if (previous && previous.size === names.size && [...names].every(([id, value]) => { + const old = previous.get(id); + return old && old.name === value.name && old.entityType === value.entityType; + })) { + return previous; + } + return names; +} + +function namesOf(message: {from: string; data?: any; references?: Array<{id: string; name: string; entityType: string}>}): Map { + const names = new Map(); + const put = (id: unknown, name: unknown, entityType?: unknown) => { + const key = idOf(id); + const label = str(name); + if (key && label && !names.has(key)) { + names.set(key, {id: key, name: label, entityType: str(entityType) ?? (isObject(id) ? str(id.entityType) : undefined)}); + } + }; + const walk = (value: unknown, entityType: string | undefined, depth: number) => { + if (depth > 6 || !value || typeof value !== 'object') { + return; + } + if (Array.isArray(value)) { + value.forEach(item => walk(item, entityType, depth + 1)); + return; + } + const object = value as Values; + const id = object.entityId ?? object.id; + if (idOf(id) && UUID.test(idOf(id))) { + put(id, object.name ?? object.title ?? object.alias, object.entityType ?? entityType); + } + Object.values(object).forEach(item => walk(item, undefined, depth + 1)); + }; + message.references?.forEach(reference => put(reference.id, reference.name, reference.entityType)); + if (message.from === 'ACTION' && message.data) { + const action = message.data as AiAction; + const values: Values = isObject(aiParse(action.arguments)) ? aiParse(action.arguments) as Values : {}; + const result = aiParse(action.result); + const created = okId(result); + switch (action.tool) { + case 'create_dashboard': + put(created, values.title, 'DASHBOARD'); + break; + case 'generate_device_dashboard': + put(created, undefined, 'DASHBOARD'); + break; + case 'save_device': + put(created ?? savedObject(values).id, savedObject(values).name, 'DEVICE'); + break; + case 'add_dashboard_entity_alias': + put(created, values.alias, 'DASHBOARD_ENTITY_ALIAS'); + break; + case 'add_dashboard_widgets': + widgetRecords(values.widgets, result).forEach(row => put(row.id, row.name, 'DASHBOARD_WIDGET')); + break; + case 'read_entity': + if (isObject(result)) { + put(result.id ?? values.entityId, result.name ?? result.title, values.entityType); + } + break; + case 'search_entities': + for (const section of searchSections(result)) { + walk(section.page.data, section.entityType ?? searchType(values), 0); + } + return names; + } + walk(result, undefined, 0); + } + return names; +} diff --git a/ui-ngx/src/app/modules/home/components/ai/ai-action-line.component.html b/ui-ngx/src/app/modules/home/components/ai/ai-action-line.component.html new file mode 100644 index 0000000000..f944b1445f --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/ai/ai-action-line.component.html @@ -0,0 +1,85 @@ + +@switch (action().status) { + @case ('RUNNING') { + + @if (action().progress) { +
    + @for (stage of action().stages ?? []; track $index) { +
  • {{ stage }}
  • + } +
  • {{ action().progress }}
  • +
+ } + } + @case ('STOPPED') { + + } + @default { +
+ @switch (mark()) { + @case ('fail') { + + } + @case ('web') { + + } + @case ('auto') { + check + } + @default { + + } + } + @let parts = lineParts(); + {{ parts.head }}@if (parts.chip; as chip) {}{{ parts.middle }}{{ parts.tail }}@if (parts.chipLast; as chip) {}@if (hasDetails()) {} +
+
+ @if (failure() !== null || arrival()?.readings?.length || listing() || detail().under.length) { +
+ @if (failure(); as why) { +
+

{{ why }}

+ +
+ } + @if (arrival()?.readings?.length) { +
+ @for (reading of arrival().readings; track reading.key) { + {{ reading.key }}{{ reading.value }} + } +
+ } + @if (listing(); as hub) { +
+ +
+ } + @if (detail().under.length) { + + } +
+ } + @if (hasDetails() && open()) { +
+ @if (grouped()) { + @for (member of groupViews(); track member.id) { +

{{ member.words }}

+ + } + } @else { + + } + @if (took(); as time) { +

{{ time }}

+ } +
+ } +
+ } +} +@if (chip.link) {{{ chip.name }}} @else {{{ chip.name }}} diff --git a/ui-ngx/src/app/modules/home/components/ai/ai-action-line.component.scss b/ui-ngx/src/app/modules/home/components/ai/ai-action-line.component.scss new file mode 100644 index 0000000000..9c2ad20d60 --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/ai/ai-action-line.component.scss @@ -0,0 +1,207 @@ +// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: BUSL-1.1 +:host { + display: block; + font-family: var(--tb-mono); + font-size: 15px; + letter-spacing: var(--chat-text-ls); +} + +.k-out { + display: flex; + align-items: flex-start; + gap: 8px; + margin-top: 0; + font-family: var(--tb-font); + font-size: var(--chat-line); + line-height: var(--chat-line-lh); + color: var(--tb-ink); + + &.opens { + cursor: pointer; + } + + .k-mark { + flex: none; + display: inline-flex; + justify-content: center; + width: 20px; + height: 22px; + font-size: 22px; + line-height: 22px; + margin-top: 0; + color: var(--tb-ok); + + &.fail { + color: var(--tb-crit); + } + + &.auto { + position: relative; + + > .mat-icon { + display: inline-flex; + justify-content: center; + width: 20px; + height: 22px; + font-size: 22px; + line-height: 22px; + overflow: visible; + color: inherit; + } + } + } + + .k-mark-bolt { + position: absolute; + right: -5px; + bottom: -2px; + display: inline-flex; + align-items: center; + justify-content: center; + width: 11px; + height: 11px; + border-radius: 50%; + background: var(--tb-surface); + box-shadow: 0 0 0 1.5px var(--tb-surface); + color: var(--tb-ok); + + > .mat-icon { + width: 11px; + height: 11px; + font-size: 11px; + line-height: 11px; + } + } + + .k-say { + flex: 1; + min-width: 0; + overflow-wrap: anywhere; + color: var(--tb-ink-76); + } + + .k-keep { + white-space: nowrap; + } + + code.k-ent .k-ent-t { + display: inline-block; + max-width: 180px; + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; + vertical-align: top; + } + + &.opens:hover .k-chev { + color: var(--tb-ink); + } +} + +.k-chev { + display: inline-flex; + align-items: center; + justify-content: center; + margin: 0 0 0 4px; + padding: 0; + border: 0; + border-radius: 4px; + background: none; + color: var(--tb-ink-38); + vertical-align: -2px; + cursor: pointer; + transition: color var(--motion-base, 150ms) var(--ease-standard, ease); + + svg { + display: block; + transition: transform var(--motion-base, 150ms) var(--ease-standard, ease); + } + + &[aria-expanded="true"] svg { + transform: rotate(90deg); + } + + &:focus-visible { + outline: 2px solid var(--ai-focus); + outline-offset: 1px; + } +} + +.k-stepcol { + margin: 0 0 0 9px; + padding-left: 18px; + border-left: 1px solid transparent; + font-family: var(--tb-font); + + &.open { + border-left-color: var(--tb-line); + } +} + +.k-under { + display: grid; + gap: 8px; + justify-items: start; + margin-top: 6px; + + > * { + margin: 0; + max-width: 100%; + } +} + +.k-det { + margin: 6px 0 4px; + max-width: 100%; + + > * + * { + margin-top: 8px; + } +} + +.k-took { + margin: 0; + font-family: var(--tb-mono); + font-size: var(--chat-meta); + line-height: var(--chat-meta-lh); + color: var(--tb-text-secondary); + font-variant-numeric: tabular-nums; +} + +.k-arrived { + display: flex; + flex-wrap: wrap; + gap: 4px 14px; + margin: 0; + font-size: var(--chat-line, 14px); + line-height: 22px; + + .k-reading { + display: inline-flex; + align-items: baseline; + gap: 6px; + } + + code { + padding: 0 6px; + border-radius: 5px; + background: rgba(0, 0, 0, 0.06); + font: 13px/18px var(--tb-mono); + color: var(--tb-ink); + } + + b { + font: 600 13px/18px var(--tb-mono); + color: var(--tb-ink); + } +} + +.k-group-h { + margin: 0; + font-family: var(--tb-font); + font-size: var(--chat-line); + line-height: var(--chat-line-lh); + font-weight: 500; + color: var(--tb-ink); +} diff --git a/ui-ngx/src/app/modules/home/components/ai/ai-action-line.component.ts b/ui-ngx/src/app/modules/home/components/ai/ai-action-line.component.ts new file mode 100644 index 0000000000..57d8e87421 --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/ai/ai-action-line.component.ts @@ -0,0 +1,287 @@ +// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: BUSL-1.1 +import { ChangeDetectionStrategy, Component, computed, ElementRef, inject, input } from '@angular/core'; +import { toObservable, toSignal } from '@angular/core/rxjs-interop'; +import { of } from 'rxjs'; +import { catchError, distinctUntilChanged, switchMap } from 'rxjs/operators'; +import { AiRecordLoaderService } from '@home/components/ai/ai-record-loader.service'; +import { AiRecordView } from '@home/components/ai/ai-record.models'; +import { EntityId } from '@shared/models/id/entity-id'; +import { TranslateService } from '@ngx-translate/core'; +import { baseDetailsPageByEntityType, EntityType } from '@shared/models/entity-type.models'; +import { AiDetailFact, AiDetailNames, aiParse, aiStepView } from '@home/components/ai/ai-action-detail.models'; +import { aiFold, aiRevealOpened } from '@home/components/ai/ai-disclosure.component'; +import { + AiAction, + aiConnectionCheckOf, + aiEntityKind, + aiActionDuration, + aiActionText, + aiActionWords, + HUB_INSTALL_TOOLS +} from '@home/components/ai/ai-action.models'; + +@Component({ + selector: 'tb-ai-action-line', + templateUrl: './ai-action-line.component.html', + styleUrls: ['./ai-action-line.component.scss'], + standalone: false, + changeDetection: ChangeDetectionStrategy.OnPush, + host: { + '[class.run]': 'action().status === "RUNNING"', + '[class.fail]': 'action().status === "FAILURE"', + '[class.stopped]': 'action().status === "STOPPED"' + } +}) +export class AiActionLineComponent { + + action = input.required(); + + private translate = inject(TranslateService); + + private loader = inject(AiRecordLoaderService); + + hubVersionId = computed(() => { + const action = this.action(); + const id = HUB_INSTALL_TOOLS.has(action.tool) && action.status !== 'RUNNING' ? (action.arguments as {versionId?: unknown})?.versionId : null; + return typeof id === 'string' && id ? id : null; + }); + + private groupId = computed(() => { + const affected = this.action().status === 'SUCCESS' ? this.action().affectedEntities ?? [] : []; + const entity = this.action().tool === 'update_group_members' ? affected.find(item => item.entityType === EntityType.ENTITY_GROUP) : affected[0]; + return entity?.entityType === EntityType.ENTITY_GROUP ? entity.id : null; + }); + + private groupView = toSignal(toObservable(this.groupId).pipe( + distinctUntilChanged(), + switchMap(id => id ? this.loader.entity({entityType: EntityType.ENTITY_GROUP, id} as EntityId).pipe(catchError(() => of(null))) : of(null)) + ), {initialValue: null as AiRecordView | null}); + + listing = toSignal(toObservable(this.hubVersionId).pipe( + distinctUntilChanged(), + switchMap(id => id ? this.loader.hub(id).pipe(catchError(() => of(null))) : of(null)) + ), {initialValue: null as AiRecordView | null}); + + words = computed(() => aiActionWords(this.action().tool, this.action().arguments)); + + more = input(0); + + group = input([]); + + grouped = computed(() => this.group().length > 1); + + groupViews = computed(() => this.grouped() ? this.group().map(action => ({ + id: action.executionId, + words: aiActionText(this.translate, aiActionWords(action.tool, action.arguments), 'done'), + view: aiStepView(action, this.names()) + })) : []); + + outcomeText = input(); + + autoApproved = input(false); + + linkEntity = input(true); + + outcomeChip = computed(() => { + if (this.grouped()) { + return null; + } + const affected = this.action().affectedEntities ?? []; + const entity = this.action().tool === 'update_group_members' + ? affected.find(item => item.entityType === EntityType.ENTITY_GROUP) ?? affected[0] + : affected[0]; + const text = this.outcome(); + const match = entity && this.action().status === 'SUCCESS' ? /(?:^|\s)'(.{1,120}?)'(?=$|[\s.,:;!?)])/.exec(text) : null; + if (!match) { + return null; + } + const start = match.index + match[0].indexOf('\''); + const alarmRule = entity.entityType === EntityType.CALCULATED_FIELD && this.isAlarmRule(); + const kind = aiEntityKind(entity.entityType, alarmRule); + const base = alarmRule ? '/alarms/alarm-rules' : baseDetailsPageByEntityType.get(entity.entityType as EntityType); + const groupUrl = entity.entityType === EntityType.ENTITY_GROUP ? this.groupView()?.url : undefined; + return { + before: text.slice(0, start), + name: match[1], + after: text.slice(match.index + match[0].length), + icon: kind.icon, + palette: kind.palette, + link: this.linkEntity() ? (groupUrl ?? (base ? `${base}/${entity.id}` : null)) : null + }; + }); + + private isAlarmRule(): boolean { + const action = this.action(); + if (action.tool === 'save_alarm_rule') { + return true; + } + const result = aiParse(action.result) as {type?: unknown} | null; + return action.tool === 'install_iot_hub_item' && result?.type === 'ALARM_RULE'; + } + + readonly runWords = computed(() => aiActionText(this.translate, this.words(), 'run')); + + running = computed(() => this.more() > 0 + ? this.translate.instant('ai-assistant.work.more', {words: this.runWords(), count: this.more()}) + : this.action().progress ? `${this.runWords()} · ${this.action().progress}` : this.runWords()); + + outcome = computed(() => { + const group = this.group(); + if (group.length < 2) { + return this.outcomeWords(); + } + const words = this.outcomeWords(); + const said = (action: AiAction) => JSON.stringify(aiActionWords(action.tool, action.arguments)); + return group.every(action => said(action) === said(group[0])) + ? this.translate.instant('ai-assistant.action.times', {words, count: group.length}) + : this.translate.instant('ai-assistant.work.more', {words, count: group.length - 1}); + }); + + arrival = computed(() => { + const action = this.action(); + const values = aiParse(action.arguments) as {waitSeconds?: unknown} | null; + if (action.tool !== 'check_connection' || action.status !== 'SUCCESS' || !(Number(values?.waitSeconds) > 0)) { + return null; + } + const check = aiConnectionCheckOf(action.result); + if (!check?.dataArriving) { + return null; + } + const time = new Date(action.startedAt + (action.durationMs ?? 0)).toLocaleTimeString([], {hour: '2-digit', minute: '2-digit', hourCycle: 'h23'}); + if (check.gateway) { + return {text: this.translate.instant('ai-assistant.hand-over.gateway-connected', {name: check.name, time}), readings: []}; + } + return { + text: this.translate.instant('ai-assistant.hand-over.' + (!check.keyCount ? 'arrived-message' : check.keyCount === 1 ? 'arrived-key' : 'arrived-keys') + + (check.name ? '-from' : ''), {name: check.name, time, count: check.keyCount}), + readings: check.readings + }; + }); + + private outcomeWords(): string { + const action = this.action(); + if (this.outcomeText()) { + return this.outcomeText(); + } + if (this.arrival()) { + return this.arrival().text; + } + if (action.status === 'FAILURE') { + return this.translate.instant('ai-assistant.action.failed', {words: this.lowerFirst(this.runWords())}); + } + const words = this.words(); + return aiActionText(this.translate, words, 'done'); + } + + names = input(new Map()); + + facts = input([]); + + detail = computed(() => { + const view = aiStepView(this.action(), this.names()); + const facts = this.facts(); + const stages = this.action().stages ?? []; + const done = this.action().status === 'SUCCESS' && this.action().progress ? [...stages, this.action().progress] : stages; + const labelOf = (fact: AiDetailFact) => (fact.raw ? fact.label : this.translate.instant(fact.label) as string).trim().toLowerCase(); + const changed = new Set(facts.filter(fact => fact.change).map(labelOf)); + const own = changed.size ? view.blocks.map(block => block.type === 'facts' ? {...block, rows: block.rows.filter(fact => !changed.has(labelOf(fact)))} : block) + .filter(block => block.type !== 'facts' || block.rows.length) : view.blocks; + const blocks = [...(done.length ? [{type: 'list' as const, label: {key: 'ai-assistant.detail.stages'}, rows: done}] : []), + ...own, ...(facts.length ? [{type: 'facts' as const, rows: facts}] : [])]; + return {...view, blocks}; + }); + + failure = computed(() => { + const action = this.action(); + if (action.status !== 'FAILURE') { + return null; + } + const reason = this.reason(action.result); + const unchanged = this.translate.instant('ai-assistant.failed.nothing-changed'); + return reason ? `${/[.!?…]$/.test(reason) ? reason : reason + '.'} ${unchanged}` : unchanged; + }); + + took = computed(() => { + const group = this.group(); + const ms = group.length > 1 + ? Math.max(...group.map(action => action.startedAt + (action.durationMs ?? 0))) - Math.min(...group.map(action => action.startedAt)) + : this.action().durationMs; + if (this.action().status === 'FAILURE') { + return ''; + } + if (ms == null) { + return this.autoApproved() ? this.translate.instant('ai-assistant.action.done-auto') : ''; + } + const time = aiActionDuration(this.translate, ms); + return this.translate.instant(this.autoApproved() ? 'ai-assistant.action.took-auto' : 'ai-assistant.action.took', {time}); + }); + + hasDetails = computed(() => this.grouped() || !!this.detail().askedFor || !!this.detail().blocks.length || !!this.took()); + + private host = inject(ElementRef); + + panelId = 'k-det-' + Math.random().toString(36).slice(2, 10); + + private key = computed(() => 'action:' + this.action().executionId); + + private fold = aiFold(() => this.key()); + + open = this.fold.open; + + mark = computed<'check' | 'fail' | 'web' | 'auto'>(() => { + if (this.action().status === 'FAILURE') { + return 'fail'; + } + if (this.action().tool === 'search_web') { + return 'web'; + } + return this.autoApproved() ? 'auto' : 'check'; + }); + + lineParts = computed(() => { + const chip = this.outcomeChip(); + const split = (text: string) => { + const trimmed = text.trimEnd(); + const cut = trimmed.lastIndexOf(' ') + 1; + return {start: trimmed.slice(0, cut), last: trimmed.slice(cut)}; + }; + if (!chip) { + const {start, last} = split(this.outcome()); + return {head: start, chip: null, middle: '', tail: last, chipLast: null}; + } + if (!chip.after.trim()) { + return {head: chip.before, chip: null, middle: '', tail: '', chipLast: chip}; + } + const {start, last} = split(chip.after); + return {head: chip.before, chip, middle: start, tail: last, chipLast: null}; + }); + + toggle(event?: Event): void { + event?.stopPropagation(); + if (this.fold.toggle()) { + setTimeout(() => aiRevealOpened(this.host.nativeElement)); + } + } + + lineClicked(event: MouseEvent): void { + if (!this.hasDetails() || (event.target as HTMLElement).closest('a, button, input')) { + return; + } + this.toggle(); + } + + + private reason(result?: string): string | undefined { + const text = result?.trim(); + if (!text || text.startsWith('{') || text.startsWith('[')) { + return undefined; + } + const line = text.split('\n')[0].trim(); + return line.length > 300 ? line.slice(0, 300) + '…' : line; + } + + private lowerFirst(words: string): string { + return words ? words.charAt(0).toLocaleLowerCase() + words.slice(1) : words; + } +} diff --git a/ui-ngx/src/app/modules/home/components/ai/ai-action.models.ts b/ui-ngx/src/app/modules/home/components/ai/ai-action.models.ts new file mode 100644 index 0000000000..06f4f75667 --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/ai/ai-action.models.ts @@ -0,0 +1,930 @@ +// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: BUSL-1.1 +import { SEVERITY_MARK } from '@home/components/ai/ai-text'; +import { aiQuestionKind } from '@home/components/ai/ai-question.models'; +import { AiQuestion } from '@shared/models/solution-creator.models'; +import { TranslateService } from '@ngx-translate/core'; +import type { AiAction } from '@shared/models/ai-chat.models'; + +export type { AiAction, AiActionStatus } from '@shared/models/ai-chat.models'; + +export type AiSpinKind = 'think' | 'gen' | 'install' | 'listen' | 'stop'; + +export interface AiActionWords { + key: string; + params?: Record; + kind: AiSpinKind; +} + +export type AiWorkMoment = 'reading-request' | 'going-through-results' | 'applying-change' | 'reading-what-to-change'; + +export interface AiWorkState { + moment: AiWorkMoment; + since: number; + headline?: string; +} +const HIDDEN_TOOLS = new Set(['read_current_time']); + +const TOOL_WORDS: Record = { + create_solution: 'create-solution', + install_solution: 'install-solution', + read_entity: 'read-entity', + read_timeseries_keys: 'read-telemetry-keys', + read_attributes: 'read-attributes', + discover_attribute_keys: 'discover-attribute-keys', + save_attributes: 'save-attributes', + delete_attributes: 'delete-attributes', + read_entity_relations: 'read-relations', + read_device_credentials: 'read-credentials', + save_device_credentials: 'save-credentials', + test_converter: 'test-converter', + read_converter_library: 'read-converter-library', + create_dashboard: 'create-dashboard', + generate_device_dashboard: 'generate-device-dashboard', + update_dashboard: 'update-dashboard', + add_dashboard_state: 'add-dashboard-state', + update_dashboard_state: 'update-dashboard-state', + add_dashboard_entity_alias: 'add-entity-alias', + update_dashboard_entity_alias: 'update-entity-alias', + read_dashboard_entity_alias: 'read-entity-alias', + add_dashboard_filter: 'add-dashboard-filter', + update_dashboard_filter: 'update-dashboard-filter', + read_dashboard_filter: 'read-dashboard-filter', + read_dashboard_overview: 'read-dashboard', + update_dashboard_widget: 'update-widget', + place_dashboard_widgets: 'place-widgets', + read_dashboard_widget: 'read-widget', + read_dashboard_html_page: 'read-dashboard-page', + search_iot_hub_devices: 'search-iot-hub', + search_iot_hub: 'search-iot-hub', + read_iot_hub_item: 'read-iot-hub-item', + read_iot_hub_device: 'read-iot-hub-device', + list_installed_iot_hub_items: 'list-installed-iot-hub-items', + install_iot_hub_item: 'install-iot-hub-item', + install_iot_hub_device: 'install-iot-hub-device', + update_group_members: 'update-group-members', + change_owner: 'change-owner', + share_entity_group: 'share-group', + grant_role: 'grant-role', + read_access: 'read-access', + check_dashboard_access: 'check-dashboard-access', + read_transport_endpoints: 'read-connection-settings', + read_api_usage: 'read-api-usage', + read_audit_logs: 'read-audit-logs', + read_tasks: 'read-tasks', + save_image: 'save-image', + read_platform_settings: 'read-platform-settings', + save_relations: 'save-relations', + read_versions: 'read-versions', + read_gateway_status: 'read-gateway-status', + read_ota: 'read-ota', + read_edges: 'read-edges', + read_edge_events: 'read-edge-events', + read_edge_instructions: 'read-edge-instructions', + save_edge: 'save-edge', + assign_to_edge: 'assign-to-edge', + sync_edge: 'sync-edge', + read_rule_chain_templates: 'read-rule-chain-templates', + set_rule_chain_template: 'set-rule-chain-template', + read_agents: 'read-agents', + read_agent_instructions: 'read-agent-instructions', + save_agent: 'save-agent', + install_agent_application: 'install-agent-application', + run_agent_operation: 'run-agent-operation', + read_agent_profiles: 'read-agent-profiles', + save_agent_profile: 'save-agent-profile', + save_agent_app_profile: 'save-agent-app-profile', + run_agent_bulk_action: 'run-agent-bulk-action', + wait_agent_operation: 'wait-agent-operation', + read_white_labeling: 'read-white-labeling', + read_website_brand: 'read-website-brand', + save_white_labeling: 'save-white-labeling', + read_mail_templates: 'read-mail-templates', + save_mail_template: 'save-mail-template', + read_custom_translation: 'read-custom-translation', + save_custom_translation: 'save-custom-translation', + read_custom_menus: 'read-custom-menus', + read_security_settings: 'read-security-settings', + read_mobile_center: 'read-mobile-center', + save_mobile_app: 'save-mobile-app', + save_mobile_bundle: 'save-mobile-bundle', + save_mobile_qr_code: 'save-mobile-qr-code', + read_scheduler_events: 'read-scheduler-events', + save_scheduler_event: 'save-scheduler-event', + create_report_template: 'create-report-template', + update_report_template: 'update-report-template', + add_report_components: 'add-report-components', + update_report_component: 'update-report-component', + move_report_component: 'move-report-component', + save_report_entity_alias: 'save-report-alias', + save_report_filter: 'save-report-filter', + test_report_template: 'test-report-template', + read_reports: 'read-reports', + save_scheduled_report: 'save-scheduled-report', + generate_report: 'generate-report', + read_widgets: 'read-widgets', + read_widget: 'read-widget-type', + create_widget: 'create-widget', + build_widget: 'build-widget', + update_widget: 'update-widget-type', + check_widget: 'check-widget', + save_widgets_bundle: 'save-widgets-bundle', + read_scada_symbols: 'read-scada-symbols', + build_scada_symbol: 'build-scada-symbol', + create_scada_symbol: 'copy-scada-symbol', + update_scada_symbol: 'update-scada-symbol', + check_scada_symbol: 'check-scada-symbol', + create_scada_symbol_widget: 'create-scada-symbol-widget', + save_two_factor_settings: 'save-two-factor-settings', + save_oauth2_domain: 'save-oauth2-domain', + read_my_account: 'read-my-account', + save_my_profile: 'save-my-profile', + save_my_two_factor: 'save-my-two-factor', + update_api_key: 'update-api-key', + read_mail_server: 'read-mail-server', + save_mail_server: 'save-mail-server', + save_custom_menu: 'save-custom-menu', + save_ota_package: 'save-ota-package', + assign_ota_package: 'assign-ota-package', + save_platform_settings: 'save-platform-settings', + read_device_connect_commands: 'read-connect-commands', + read_billing: 'read-billing', + search_web: 'search-web', + send_notification: 'send-notification', + read_notifications: 'read-notifications', + mark_notifications_read: 'mark-notifications-read', + save_notification_settings: 'save-notification-settings', + save_notification_preferences: 'save-notification-preferences' +}; + +const GENERATING_TOOLS: Record = { + set_dashboard_html_page: 'lay-out-dashboard', + reprocess_calculated_field: 'recalculate-history', + commit_version: 'commit-version', + restore_version: 'restore-version', + research_device_connectivity: 'research-device' +}; + +const SAVED_KINDS: Record = { + save_device: ['device', ''], + save_calculated_field: ['calculated-field', ''], + save_alarm_rule: ['alarm-rule', 'alarmRule'], + save_notification_target: ['notification-target', 'target'], + save_notification_template: ['notification-template', 'template'], + save_notification_rule: ['notification-rule', 'rule'], + save_customer: ['customer', ''], + save_user: ['user', ''], + save_entity_group: ['entity-group', ''], + save_role: ['role', ''], + save_entity_view: ['entity-view', ''], + save_asset: ['asset', ''], + save_asset_profile: ['asset-profile', ''], + save_device_profile: ['device-profile', ''], + save_converter: ['converter', ''], + save_integration: ['integration', ''], + save_secret: ['secret', ''], + save_ai_model: ['ai-model', ''], + save_resource: ['resource', ''] +}; + +const SEARCHED_TYPES: Record = { + DEVICE: 'search-devices', + ASSET: 'search-assets', + DASHBOARD: 'search-dashboards', + CUSTOMER: 'search-customers', + USER: 'search-users', + ENTITY_VIEW: 'search-entity-views', + EDGE: 'search-edges', + TENANT: 'search-tenants', + DEVICE_PROFILE: 'search-device-profiles', + ASSET_PROFILE: 'search-asset-profiles', + ENTITY_GROUP: 'search-groups' +}; + +const SEARCHED_FILTERS: Record = { + gateway: 'search-gateways', + alarm: 'search-alarms', + alarmRule: 'search-alarm-rules', + calculatedField: 'search-calculated-fields', + notificationTarget: 'search-notification-targets', + notificationTemplate: 'search-notification-templates', + notificationRule: 'search-notification-rules', + image: 'search-images' +}; + +const DELETED_TARGETS: Record = { + CALCULATED_FIELD: 'delete-calculated-field', + ALARM_RULE: 'delete-alarm-rule', + NOTIFICATION_RULE: 'delete-notification-rule', + NOTIFICATION_TARGET: 'delete-notification-target', + NOTIFICATION_TEMPLATE: 'delete-notification-template', + NOTIFICATION_REQUEST: 'delete-sent-notification', + NOTIFICATION: 'delete-inbox-notification', + DASHBOARD: 'delete-dashboard', + DASHBOARD_WIDGET: 'delete-widget', + DASHBOARD_STATE: 'delete-dashboard-state', + DASHBOARD_ENTITY_ALIAS: 'delete-entity-alias', + DASHBOARD_FILTER: 'delete-dashboard-filter', + DEVICE: 'delete-device', + CUSTOMER: 'delete-customer', + USER: 'delete-user', + ENTITY_GROUP: 'delete-entity-group', + ROLE: 'delete-role', + GROUP_PERMISSION: 'delete-grant', + ALARM: 'delete-alarm', + ASSET: 'delete-asset', + OTA_PACKAGE: 'delete-ota-package', + EDGE: 'delete-edge', + AGENT: 'delete-agent', + AGENT_PROFILE: 'delete-agent-profile', + AGENT_APP_PROFILE: 'delete-agent-app-profile', + IMAGE: 'delete-image', + ENTITY_VIEW: 'delete-entity-view', + ASSET_PROFILE: 'delete-asset-profile', + DEVICE_PROFILE: 'delete-device-profile', + INTEGRATION: 'delete-integration', + CONVERTER: 'delete-converter', + SECRET: 'delete-secret', + AI_MODEL: 'delete-ai-model', + RESOURCE: 'delete-resource', + CUSTOM_MENU: 'delete-custom-menu', + MOBILE_APP: 'delete-mobile-app', + MOBILE_BUNDLE: 'delete-mobile-bundle', + SCHEDULER_EVENT: 'delete-scheduler-event', + REPORT_TEMPLATE: 'delete-report-template', + REPORT_COMPONENT: 'delete-report-component', + REPORT_ENTITY_ALIAS: 'delete-report-alias', + REPORT_FILTER: 'delete-report-filter', + REPORT: 'delete-report', + WIDGET_TYPE: 'delete-widget-type', + WIDGETS_BUNDLE: 'delete-widgets-bundle' +}; + +const ACTION_PREFIX = 'ai-assistant.action.'; + +export const isHiddenAiAction = (tool: string): boolean => HIDDEN_TOOLS.has(tool); + +const READ_VERBS = /^(read|search|discover|fetch|list|check_dashboard_access|research)_/; + +const NEVER_GROUPED: ReadonlySet = new Set(['read_device_credentials', 'read_device_connect_commands', 'check_connection', + 'research_device_connectivity', 'read_iot_hub_device']); + +export function aiGroupableRead(action: AiAction): boolean { + if (action.status !== 'SUCCESS' || NEVER_GROUPED.has(action.tool)) { + return false; + } + return action.readOnly ?? READ_VERBS.test(action.tool + '_'); +} + +export const SUGGEST_PROMPTS_TOOL = 'suggest_next_prompts'; + +export const ASK_USER_TOOL = 'ask_user'; + +export const PROPOSE_PLAN_TOOL = 'propose_plan'; + +export const CITE_SOURCES_TOOL = 'cite_sources'; + +export const HUB_INSTALL_TOOLS: ReadonlySet = new Set(['install_iot_hub_item', 'install_iot_hub_device']); + +export interface AiSource { + url: string; + title: string; + from: string; + quote?: string; + icon: string; + external: boolean; +} + +const humanize = (segment: string): string => { + const words = decodeURIComponent(segment).replace(/\.[a-z]+$/i, '').replace(/[-_]+/g, ' ').trim(); + return words ? words.charAt(0).toUpperCase() + words.slice(1) : ''; +}; + +export function aiSourcesOf(args: unknown): AiSource[] { + const sources = (args as {sources?: unknown})?.sources; + if (!Array.isArray(sources)) { + return []; + } + return sources.flatMap(source => { + if (typeof source?.url !== 'string' || typeof source?.title !== 'string') { + return []; + } + let url: URL; + try { + url = new URL(source.url); + } catch { + return []; + } + if (url.protocol !== 'https:' && url.protocol !== 'http:') { + return []; + } + const host = url.hostname.replace(/^www\./, ''); + const product = host === 'thingsboard.io' || host.endsWith('.thingsboard.io') || host.endsWith('thingsboard.cloud'); + const path = url.pathname.split('/').filter(segment => segment.length > 2).slice(0, 2).map(humanize).filter(Boolean); + return [{ + url: url.href, + title: source.title.trim(), + from: [host, ...path].join(' › '), + quote: typeof source.quote === 'string' && source.quote.trim() ? source.quote.trim() : undefined, + icon: !product ? 'public' : /pricing/i.test(url.pathname) ? 'sell' : 'menu_book', + external: !product + }]; + }).slice(0, 3); +} + +export const UPDATE_PLAN_TOOL = 'update_plan'; + +export const HAND_OVER_TOOL = 'hand_over'; + +export const CHECK_CONNECTION_TOOL = 'check_connection'; + +const KIT_CARD_TOOLS = new Set([SUGGEST_PROMPTS_TOOL, ASK_USER_TOOL, PROPOSE_PLAN_TOOL, UPDATE_PLAN_TOOL, 'write_file', 'create_file', CITE_SOURCES_TOOL, 'show_records', + HAND_OVER_TOOL]); + +export interface AiHandOverValue { + label: string; + value: string; + secret: boolean; + icon: string; +} + +export interface AiHandOverStep { + title: string; + detail?: string; + markdown?: string; + values: AiHandOverValue[]; + file?: string; + done: boolean; +} + +export interface AiHandOverOption { + id: string; + label: string; + icon?: string; + text: string; + steps?: AiHandOverStep[]; +} + +export interface AiHandOver { + title: string; + text?: string; + choice?: {question: string; icon: string; value: string; options: AiHandOverOption[]}; + steps: AiHandOverStep[]; + waitFor?: 'message' | 'uplink' | 'gateway'; + intervalSeconds?: number; + test?: AiHandOverTest; + paste?: {label: string; icon: string; intro: string}; +} + +export interface AiHandOverTest { + hint?: string; + commands: {os: 'macos' | 'windows' | 'linux'; command: string}[]; + sample?: Record; + accessToken?: string; +} + +function handOverTestOf(value: any): AiHandOverTest | undefined { + const commands = (Array.isArray(value?.commands) ? value.commands : []) + .filter(item => ['macos', 'windows', 'linux'].includes(item?.os) && text(item?.command)) + .slice(0, 3) + .map(item => ({os: item.os, command: item.command.trim()})); + if (!commands.length) { + return undefined; + } + let sample: Record | undefined; + try { + const parsed = typeof value.sample === 'string' ? JSON.parse(value.sample) : value.sample; + sample = parsed && typeof parsed === 'object' && !Array.isArray(parsed) ? parsed : undefined; + } catch { + sample = undefined; + } + const accessToken = text(value.accessToken); + return {hint: text(value.hint), commands, ...(sample && accessToken ? {sample, accessToken} : {})}; +} + +const text = (value: unknown): string | undefined => typeof value === 'string' && value.trim() ? value.trim() : undefined; + +const ICON_NAME = /^[a-z0-9_]{2,40}$/; + +const iconOf = (value: unknown, fallback: string): string => typeof value === 'string' && ICON_NAME.test(value) ? value : fallback; + +export function aiHandOverOf(args: unknown): AiHandOver | null { + const values = (args ?? {}) as Record; + const title = text(values.title); + if (!title) { + return null; + } + const steps = handOverStepsOf(values.steps); + const options: AiHandOverOption[] = (Array.isArray(values.choice?.options) ? values.choice.options : []) + .filter(option => text(option?.id) && text(option?.label)) + .slice(0, 4) + .map(option => ({id: text(option.id), label: text(option.label), icon: typeof option.icon === 'string' && ICON_NAME.test(option.icon) ? option.icon : undefined, + text: text(option.text) ?? '', steps: handOverStepsOf(option.steps)})); + const choice = options.length >= 2 ? { + question: text(values.choice.question) ?? '', + icon: iconOf(values.choice.icon, 'tune'), + value: options.some(option => option.id === values.choice.value) ? values.choice.value : options[0].id, + options + } : undefined; + const waitFor = ['message', 'uplink', 'gateway'].includes(values.waitFor) ? values.waitFor : undefined; + const interval = Number(values.intervalSeconds); + return {title, text: text(values.text), choice, steps, waitFor, + intervalSeconds: Number.isFinite(interval) && interval > 0 ? interval : undefined, + test: handOverTestOf(values.test), paste: handOverPasteOf(values.paste)}; +} + +function handOverPasteOf(value: any): AiHandOver['paste'] { + const label = text(value?.label); + const intro = text(value?.intro); + return label && intro ? {label, intro, icon: iconOf(value.icon, 'terminal')} : undefined; +} + +function handOverStepsOf(list: unknown): AiHandOverStep[] { + return (Array.isArray(list) ? list : []) + .filter(step => text(step?.title)) + .slice(0, 6) + .map(step => ({ + title: text(step.title), + detail: text(step.detail), + markdown: text(step.markdown), + file: text(step.file), + done: step.done === true, + values: (Array.isArray(step.values) ? step.values : []) + .filter(value => text(value?.label) && typeof value?.value === 'string' && value.value) + .slice(0, 4) + .map(value => ({label: text(value.label), value: value.value, secret: value.secret === true, + icon: iconOf(value.icon, value.secret === true ? 'key' : /^https?:\/\//.test(value.value) ? 'link' : 'label')})) + })); +} + +export interface AiConnectionCheck { + dataArriving: boolean; + failedStep?: string; + name?: string; + note?: string; + readings: {key: string; value: string}[]; + keyCount: number; + gateway: boolean; +} + +export function aiConnectionCheckOf(result: unknown): AiConnectionCheck | null { + let values: any = result; + if (typeof result === 'string') { + try { + values = JSON.parse(result); + } catch { + return null; + } + } + if (!values || typeof values !== 'object' || !values.steps) { + return null; + } + const readings: {key: string; value: string}[] = []; + const add = (telemetry: unknown) => Object.entries(telemetry && typeof telemetry === 'object' ? telemetry : {}) + .map(([key, item]) => ({key, value: String((item as any)?.value ?? '')})) + .filter(reading => !/^\s*[{[]/.test(reading.value)) + .forEach(reading => readings.push(reading)); + const gateway = values.gateway === true; + if (!gateway) { + add(values.telemetry); + } + (Array.isArray(values.devices) ? values.devices : []).forEach(device => add(device?.telemetry)); + return {dataArriving: values.steps.dataArriving === true, failedStep: text(values.failedStep), name: text(values.name), + note: text(values.note), readings: readings.slice(0, 6), keyCount: new Set(readings.map(reading => reading.key)).size, gateway}; +} + +export const isKitCardTool = (tool: string): boolean => KIT_CARD_TOOLS.has(tool); + +const PLAN_NEEDS = new Set(['device', 'account', 'computer', 'phone']); + +export interface AiPlanStep { + text: string; + by: 'agent' | 'user'; + needs?: string; + optional?: boolean; + makes?: {type: string; name: string}[]; +} + +export interface AiPlanProgress { + done: number[]; + now?: number; + skipped: number[]; +} + +export type AiPlanMark = 'todo' | 'now' | 'done' | 'off'; + +export interface AiPlanStatus { + marks: AiPlanMark[]; + done: number; + counted: number; + now: number; + finished: boolean; +} + +export function aiPlanStatus(steps: AiPlanStep[], progress: AiPlanProgress | null): AiPlanStatus { + const marks = steps.map((_, index): AiPlanMark => { + const number = index + 1; + if (progress?.done.includes(number)) { + return 'done'; + } + if (progress?.skipped.includes(number)) { + return 'off'; + } + return progress?.now === number ? 'now' : 'todo'; + }); + return { + marks, + done: marks.filter(mark => mark === 'done').length, + counted: marks.filter(mark => mark !== 'off').length, + now: progress?.now ?? marks.findIndex(mark => mark !== 'done' && mark !== 'off') + 1, + finished: !!progress && marks.every(mark => mark === 'done' || mark === 'off') + }; +} + +export function aiPlanOf(args: unknown): AiPlanStep[] { + const steps = (args as {steps?: unknown})?.steps; + if (!Array.isArray(steps)) { + return []; + } + return steps + .filter(step => typeof step?.text === 'string' && step.text.trim()) + .slice(0, 8) + .map(step => ({ + text: step.text.trim(), + by: step.by === 'user' ? 'user' : 'agent', + needs: step.by === 'user' && PLAN_NEEDS.has(step.needs) ? step.needs : undefined, + optional: step.optional === true, + makes: Array.isArray(step.makes) + ? step.makes.filter(made => typeof made?.type === 'string' && typeof made?.name === 'string' && made.name.trim()).slice(0, 4) + : [] + })); +} + +export function aiPlanProgressOf(args: unknown): AiPlanProgress { + const values = (args ?? {}) as {done?: unknown; now?: unknown; skipped?: unknown}; + const numbers = (list: unknown): number[] => Array.isArray(list) ? list.filter(item => Number.isInteger(item) && item > 0) : []; + return { + done: numbers(values.done), + now: Number.isInteger(values.now) && (values.now as number) > 0 ? values.now as number : undefined, + skipped: numbers(values.skipped) + }; +} + +export type AiSeverityWord = (severity: string) => string; + +const PLAIN_SEVERITY_WORD: AiSeverityWord = severity => severity.charAt(0) + severity.slice(1).toLowerCase(); + +export function aiQuestionsOf(args: unknown, word: AiSeverityWord = PLAIN_SEVERITY_WORD): AiQuestion[] { + const questions = (args as {questions?: unknown})?.questions; + if (!Array.isArray(questions)) { + return []; + } + return questions + .filter(question => typeof question?.question === 'string' && question.question.trim()) + .slice(0, 3) + .map((question, index) => ({ + id: typeof question.id === 'string' && question.id ? question.id : 'q' + index, + question: aiSeverityWords(question.question.trim(), word), + parts: aiSeverityParts(question.question.trim()), + why: typeof question.why === 'string' ? aiSeverityWords(question.why, word) : undefined, + options: (Array.isArray(question.options) ? question.options : []) + .filter(option => typeof option?.label === 'string' && option.label.trim()) + .slice(0, 6) + .map(option => ({label: aiSeverityWords(option.label.trim(), word), hint: typeof option.hint === 'string' ? aiSeverityWords(option.hint, word) : undefined})), + recommended: Array.isArray(question.recommended) ? question.recommended.filter(label => typeof label === 'string') : undefined, + multiple: question.multiple === true, + secret: question.secret === true && !(Array.isArray(question.options) && question.options.length), + color: question.color === true && question.multiple !== true, + other: aiQuestionOther(question.other), + number: aiQuestionNumber(question.number), + date: question.date === true && question.multiple !== true && Array.isArray(question.options) && question.options.length > 0 + } as AiQuestion)) + .map(question => ({...question, kind: aiQuestionKind(question)})); +} + +const SEVERITY_MARKS = new RegExp(SEVERITY_MARK.source, 'g'); + +export function aiSeverityWords(text: string, word: AiSeverityWord = PLAIN_SEVERITY_WORD): string { + return text.replace(SEVERITY_MARKS, (_, severity: string) => word(severity)); +} + +function aiSeverityParts(text: string): Array<{text?: string; severity?: string}> | undefined { + if (!new RegExp(SEVERITY_MARKS.source).test(text)) { + return undefined; + } + return text.split(new RegExp(SEVERITY_MARKS.source)).map((part, index) => index % 2 ? {severity: part} : {text: part}).filter(part => part.severity || part.text); +} + +function aiQuestionOther(other: any): AiQuestion['other'] { + const label = typeof other?.label === 'string' && other.label.trim() ? other.label.trim() : undefined; + const placeholder = typeof other?.placeholder === 'string' && other.placeholder.trim() ? other.placeholder.trim() : undefined; + return label || placeholder ? {label, placeholder} : undefined; +} + +function aiQuestionNumber(number: any): AiQuestion['number'] { + if (!number || typeof number !== 'object') { + return undefined; + } + const finite = (value: unknown) => typeof value === 'number' && isFinite(value) ? value : undefined; + const size = number.size === 'short' || number.size === 'medium' ? number.size : 'long'; + return {suggested: finite(number.suggested), unit: typeof number.unit === 'string' && number.unit.trim() ? number.unit.trim() : undefined, + step: finite(number.step), size}; +} + +const MAX_PROMPTS = 4; + +const PROMPT_ICONS: Record = {domain: 'mdi:cube-outline', rule: 'mdi:bell-cog', functions: 'mdi:function-variant'}; + +export interface AiPrompt { + text: string; + icon?: string; +} + +export function aiTurnPrompts(messages: Array<{from: string; data?: any}>): AiPrompt[] { + for (let i = messages.length - 1; i >= 0; i--) { + const message = messages[i]; + if (message.from === 'USER') { + return []; + } + if (message.from === 'ACTION' && message.data?.tool === SUGGEST_PROMPTS_TOOL) { + return aiPromptsOf(message.data.arguments); + } + } + return []; +} + +export function aiPromptsOf(args: unknown): AiPrompt[] { + const prompts = (args as {prompts?: unknown})?.prompts; + if (!Array.isArray(prompts)) { + return []; + } + return prompts + .filter(prompt => typeof prompt?.text === 'string' && prompt.text.trim()) + .map(prompt => ({text: prompt.text.trim(), icon: typeof prompt.icon === 'string' && /^[a-z0-9_]+$/.test(prompt.icon) ? PROMPT_ICONS[prompt.icon] ?? prompt.icon : undefined})) + .slice(0, MAX_PROMPTS); +} + +const ALARM_UPDATE_ACTIONS = ['acknowledge', 'assign', 'clear', 'comment', 'unassign']; + +export const alarmUpdateAction = (action: unknown): string => { + const name = String(action ?? '').toLowerCase(); + return ALARM_UPDATE_ACTIONS.includes(name) ? name : 'other'; +}; + +const PART_WORDS = new Set(['html', 'css', 'js', 'resources', 'settingsForm', 'dataKeySettingsForm', 'latestDataKeySettingsForm', + 'defaultConfig', 'svg', 'metadata', 'functions', 'behavior', 'properties']); + +export interface AiWordList { + words: string[]; + commas?: boolean; +} + +export const aiPartWord = (part: string): string => PART_WORDS.has(part) ? 'ai-assistant.part.' + part : part; + +export const aiPartTitle = (part: string): string => PART_WORDS.has(part) ? 'ai-assistant.part-title.' + part : part.charAt(0).toUpperCase() + part.slice(1); + +export const aiWordList = (words: string[], commas = false): AiWordList => commas ? {words, commas} : {words}; + +export const isAiWordList = (value: unknown): value is AiWordList => !!value && typeof value === 'object' && Array.isArray((value as AiWordList).words); + +export function aiJoinWords(translate: TranslateService, list: AiWordList): string { + const said = list.words.map(word => word.startsWith('ai-assistant.') ? translate.instant(word) as string : word); + if (said.length < 2) { + return said.join(''); + } + const more = (first: string, rest: string) => translate.instant('ai-assistant.list.more', {first, rest}) as string; + const last = list.commas ? more(said[said.length - 2], said[said.length - 1]) + : translate.instant('ai-assistant.list.pair', {first: said[said.length - 2], second: said[said.length - 1]}) as string; + return said.slice(0, -2).reduceRight((rest, first) => more(first, rest), last); +} + +const THING_KEYS: Record = { + DASHBOARD_WIDGET: 'widget', + DASHBOARD_STATE: 'state', + DASHBOARD_ENTITY_ALIAS: 'alias', + DASHBOARD_FILTER: 'filter' +}; + +export function aiThingWord(translate: TranslateService, entityType: string | undefined, fallback: string): string { + if (!entityType) { + return translate.instant(fallback); + } + const key = 'ai-assistant.detail.thing.' + (THING_KEYS[entityType] ?? entityType.toLowerCase().replace(/_/g, '-')); + const word: string = translate.instant(key); + return word !== key ? word : translate.instant(fallback); +} + +export function aiActionText(translate: TranslateService, words: AiActionWords, phase: 'run' | 'done'): string { + const params: Record = {}; + for (const [key, value] of Object.entries(words.params ?? {})) { + params[key] = isAiWordList(value) ? aiJoinWords(translate, value) : value; + } + return translate.instant(words.key + '.' + phase, params); +} + +export function widgetParts(values: Record): string[] { + const parts = Array.isArray(values.sections) ? values.sections.map(String) : []; + return parts.length ? parts : typeof values.section === 'string' ? [values.section] : ['overview']; +} + +export function aiActionWords(tool: string, args: unknown): AiActionWords { + const values = (args && typeof args === 'object' ? args : {}) as Record; + if (GENERATING_TOOLS[tool]) { + return {key: ACTION_PREFIX + GENERATING_TOOLS[tool], kind: 'gen'}; + } + if (SAVED_KINDS[tool]) { + const [kind, nested] = SAVED_KINDS[tool]; + return {key: ACTION_PREFIX + (hasId(nested ? values[nested] : values) ? 'update-' : 'create-') + kind, kind: 'think'}; + } + switch (tool) { + case 'add_dashboard_widgets': + return {key: ACTION_PREFIX + (Array.isArray(values.widgets) && values.widgets.length === 1 ? 'add-widget' : 'add-widgets'), kind: 'think'}; + case 'add_scada_connectors': + return {key: ACTION_PREFIX + 'add-scada-connectors', kind: 'think'}; + case 'read_widget': { + const parts = widgetParts(values).filter(part => part !== 'overview'); + return parts.length && !parts.includes('all') + ? {key: ACTION_PREFIX + 'read-widget-parts', params: {parts: aiWordList(parts.map(aiPartWord))}, kind: 'think'} + : {key: ACTION_PREFIX + 'read-widget-type', kind: 'think'}; + } + case 'read_scada_symbol': { + const parts = widgetParts(values).filter(part => part !== 'overview'); + return parts.length && !parts.includes('all') + ? {key: ACTION_PREFIX + 'read-scada-symbol-parts', params: {parts: aiWordList(parts.map(aiPartWord))}, kind: 'think'} + : {key: ACTION_PREFIX + 'read-scada-symbol', kind: 'think'}; + } + case 'read_report_template': + return {key: ACTION_PREFIX + (typeof values.path === 'string' && values.path ? 'read-report-component' : 'read-report-template'), kind: 'think'}; + case 'search_entities': + return {key: ACTION_PREFIX + searchedWords(values), kind: 'think'}; + case 'update_alarms': + return {key: ACTION_PREFIX + 'update-alarms.' + alarmUpdateAction(values.action), kind: 'think'}; + case 'read_timeseries': + return {key: ACTION_PREFIX + telemetryWords(values), kind: 'think'}; + case 'delete': + return {key: ACTION_PREFIX + (DELETED_TARGETS[values.targetType] ?? 'delete-other'), kind: 'think'}; + case 'check_connection': + return {key: ACTION_PREFIX + (Number(values.waitSeconds) > 0 ? 'wait-for-data' : 'check-connection'), kind: 'think'}; + case 'fetch_web_page': { + const site = siteOf(values.url); + return site ? {key: ACTION_PREFIX + 'read-site', params: {site}, kind: 'think'} : {key: ACTION_PREFIX + 'read-page', kind: 'think'}; + } + } + return {key: ACTION_PREFIX + (TOOL_WORDS[tool] ?? 'other'), kind: 'think'}; +} + +export function aiActionDuration(translate: TranslateService, ms: number): string { + if (ms < 1000) { + return translate.instant('ai-assistant.duration.seconds', {seconds: Math.max(Math.round(ms / 100), 1) / 10}); + } + const seconds = Math.round(ms / 1000); + if (seconds < 60) { + return translate.instant('ai-assistant.duration.seconds', {seconds}); + } + const rest = seconds % 60; + return rest ? translate.instant('ai-assistant.duration.minutes-seconds', {minutes: Math.floor(seconds / 60), seconds: rest}) + : translate.instant('ai-assistant.duration.minutes', {minutes: seconds / 60}); +} + +export function aiWorkClock(ms: number): string { + const seconds = Math.round(ms / 1000); + return `${Math.floor(seconds / 60)}:${String(seconds % 60).padStart(2, '0')}`; +} + +function hasId(value: unknown): boolean { + let object = value; + if (typeof value === 'string') { + try { + object = JSON.parse(value); + } catch { + return false; + } + } + const id = (object as {id?: unknown})?.id; + return !!id && (typeof id === 'string' || typeof (id as {id?: unknown}).id === 'string'); +} + +function searchedWords(values: Record): string { + const filter = values.entityFilter ?? values; + if (typeof filter?.filterType === 'string' && SEARCHED_FILTERS[filter.filterType]) { + return SEARCHED_FILTERS[filter.filterType]; + } + if (filter?.statusList || filter?.severityList || filter?.typeList || filter?.searchPropagatedAlarms !== undefined) { + return 'search-alarms'; + } + const types = new Set(); + const add = (type: unknown) => typeof type === 'string' && types.add(type); + add(filter?.entityType); + add(filter?.singleEntity?.entityType); + if (filter?.deviceType || filter?.deviceTypes || filter?.filterType === 'deviceType') { + types.add('DEVICE'); + } + if (filter?.assetType || filter?.assetTypes || filter?.filterType === 'assetType') { + types.add('ASSET'); + } + (filter?.filters ?? []).forEach((relationFilter: any) => (relationFilter?.entityTypes ?? []).forEach(add)); + if (types.size === 1) { + return SEARCHED_TYPES[[...types][0]] ?? 'search-tenant'; + } + return 'search-tenant'; +} + +function telemetryWords(values: Record): string { + switch (values.mode) { + case 'LATEST': + return 'read-latest-values'; + case 'KEYS': + return 'read-telemetry-keys'; + default: + return values.mode ? 'read-history' : 'read-latest-values'; + } +} + +function siteOf(url: unknown): string | undefined { + if (typeof url !== 'string') { + return undefined; + } + try { + return new URL(url).hostname.replace(/^www\./, '') || undefined; + } catch { + return undefined; + } +} + +export type AiEntityPalette = 'device' | 'path' | 'chain' | 'rule' | 'view' | 'people' | 'solution' | 'none'; + +export interface AiEntityKind { + icon: string; + palette: AiEntityPalette; +} + +const ENTITY_KINDS: Record = { + DEVICE: {icon: 'memory', palette: 'device'}, + GATEWAY: {icon: 'lan', palette: 'device'}, + ENTITY_VIEW: {icon: 'view_quilt', palette: 'device'}, + EDGE: {icon: 'router', palette: 'device'}, + DEVICE_PROFILE: {icon: 'mdi:alpha-d-box', palette: 'device'}, + ASSET: {icon: 'mdi:cube-outline', palette: 'device'}, + ASSET_PROFILE: {icon: 'mdi:alpha-a-box', palette: 'device'}, + AGENT: {icon: 'settings_applications', palette: 'device'}, + AGENT_APPLICATION: {icon: 'apps', palette: 'device'}, + AGENT_PROFILE: {icon: 'group_work', palette: 'device'}, + AGENT_APP_PROFILE: {icon: 'description', palette: 'device'}, + OTA_PACKAGE: {icon: 'system_update_alt', palette: 'device'}, + INTEGRATION: {icon: 'input', palette: 'path'}, + CONVERTER: {icon: 'transform', palette: 'path'}, + CALCULATED_FIELD: {icon: 'mdi:function-variant', palette: 'path'}, + RULE_CHAIN: {icon: 'settings_ethernet', palette: 'chain'}, + EDGE_RULE_CHAIN: {icon: 'settings_ethernet', palette: 'chain'}, + SCHEDULER_EVENT: {icon: 'schedule', palette: 'chain'}, + ALARM_RULE: {icon: 'mdi:bell-cog', palette: 'rule'}, + ALARM: {icon: 'notification_important', palette: 'rule'}, + NOTIFICATION_RULE: {icon: 'mdi:message-cog', palette: 'rule'}, + DASHBOARD: {icon: 'dashboard', palette: 'view'}, + DASHBOARD_WIDGET: {icon: 'widgets', palette: 'view'}, + WIDGET_TYPE: {icon: 'widgets', palette: 'view'}, + WIDGETS_BUNDLE: {icon: 'now_widgets', palette: 'view'}, + DASHBOARD_STATE: {icon: 'layers', palette: 'view'}, + DASHBOARD_ENTITY_ALIAS: {icon: 'label', palette: 'view'}, + DASHBOARD_FILTER: {icon: 'filter_list', palette: 'view'}, + REPORT_TEMPLATE: {icon: 'edit_document', palette: 'view'}, + REPORT_COMPONENT: {icon: 'view_agenda', palette: 'view'}, + REPORT_ENTITY_ALIAS: {icon: 'label', palette: 'view'}, + REPORT_FILTER: {icon: 'filter_list', palette: 'view'}, + SCHEDULED_REPORT: {icon: 'mdi:file-clock', palette: 'view'}, + REPORT: {icon: 'summarize', palette: 'view'}, + MAIL_TEMPLATE: {icon: 'drafts', palette: 'view'}, + NOTIFICATION_TEMPLATE: {icon: 'mdi:message-draw', palette: 'view'}, + CUSTOM_TRANSLATION: {icon: 'translate', palette: 'view'}, + CUSTOM_MENU: {icon: 'menu', palette: 'view'}, + MOBILE_APP: {icon: 'smartphone', palette: 'view'}, + MOBILE_BUNDLE: {icon: 'phonelink_setup', palette: 'view'}, + MOBILE_QR_CODE: {icon: 'qr_code', palette: 'view'}, + IMAGE: {icon: 'image', palette: 'view'}, + SCADA_SYMBOL: {icon: 'view_in_ar', palette: 'view'}, + CUSTOMER: {icon: 'supervisor_account', palette: 'people'}, + USER: {icon: 'account_circle', palette: 'people'}, + TENANT: {icon: 'business', palette: 'people'}, + MY_PROFILE: {icon: 'account_circle', palette: 'people'}, + NOTIFICATION_TARGET: {icon: 'contacts', palette: 'people'}, + ROLE: {icon: 'badge', palette: 'people'}, + GROUP_PERMISSION: {icon: 'verified_user', palette: 'people'}, + SOLUTION_TEMPLATE: {icon: 'dashboard_customize', palette: 'solution'}, + IOT_HUB: {icon: 'hub', palette: 'solution'}, + MAIL_SERVER: {icon: 'mail', palette: 'none'}, + TWO_FACTOR_SETTINGS: {icon: 'mdi:two-factor-authentication', palette: 'none'}, + MY_TWO_FACTOR: {icon: 'mdi:two-factor-authentication', palette: 'none'}, + DOMAIN: {icon: 'language', palette: 'none'}, + API_KEY: {icon: 'vpn_key', palette: 'none'}, + TB_RESOURCE: {icon: 'mdi:rhombus-split', palette: 'none'}, + SECRET: {icon: 'lock', palette: 'none'}, + ENTITY_GROUP: {icon: 'folder', palette: 'none'} +}; + +export function aiEntityKind(entityType: string, alarmRule = false, groupType?: string | null): AiEntityKind { + if (entityType === 'ENTITY_GROUP') { + return {icon: 'folder', palette: (groupType && ENTITY_KINDS[groupType]?.palette) || 'none'}; + } + return ENTITY_KINDS[alarmRule ? 'ALARM_RULE' : entityType] ?? {icon: 'category', palette: 'none'}; +} + diff --git a/ui-ngx/src/app/modules/home/components/ai/ai-approval-card.component.html b/ui-ngx/src/app/modules/home/components/ai/ai-approval-card.component.html index ce8881931c..5f60cad9e6 100644 --- a/ui-ngx/src/app/modules/home/components/ai/ai-approval-card.component.html +++ b/ui-ngx/src/app/modules/home/components/ai/ai-approval-card.component.html @@ -4,47 +4,102 @@ SPDX-License-Identifier: BUSL-1.1 --> -@switch (state) { - @case ('pending') { -
{{ data.title ?? ('ai-assistant.action-approval-required' | translate) }}
-
{{ data.message }}
-
- - -
- +@if (handedOver) { + +} @else { +
+
{{ headText }}
+ @if (listing; as hub) { + + } @else if (review) { + } - @case ('executing') { -
- - {{ data.executing ?? ('ai-assistant.processing' | translate) }} -
+ @if (state === 'pending' || state === 'waiting') { + @if (!review) { +

{{ data.message }}

+ } + @if (facts.length) { +
+ @for (fact of facts; track $index) { +
@if (fact.labelCode) { {{ fact.label }} } @else { {{ fact.label }} }
+
@if (fact.chip; as chip) { @if (chip.image) { } @else if (chip.icon) { }{{ fact.value }} } @else if (fact.image) { } @else if (fact.valueCode) { {{ fact.value }} } @else { {{ fact.value }} }
+ } +
+ } + @for (block of codeBlocks; track $index) { + @if (block.current !== undefined) { +
{{ block.current }}
+ } +
{{ block.value }}
+ } + @if (changes.length) { +
+ @for (change of changes; track $index) { +
+
@if (change.labelCode) { {{ change.label }} } @else { {{ change.label }} }
+
+ @if (change.currentImage) { } @else { {{ change.current }} } + + {{ 'ai-assistant.review.changes-to' | translate }} + @if (change.image) { } @else { {{ change.value }} } +
+
+ } + @if (unchanged.length && showUnchanged) { + + } +
+ @if (unchanged.length) { + + } + } @else if (unchanged.length) { +
+ +
+ } +
+ + +
+ @if (denying) { +
+ +
+ } + } @else if (state === 'denied') { +

{{ 'ai-assistant.review.denied-text' | translate }}

} - @case ('approved') { -
- {{ resultIcon }} - {{ completedExecution?.message || ('ai-assistant.approved' | translate) }} -
- } - @case ('denied') { -
- {{ resultIcon }} - {{ completedExecution?.message || ('ai-assistant.denied' | translate) }} -
- } - @case ('error') { -
- {{ resultIcon }} - {{ completedExecution?.message || ('ai-assistant.error' | translate) }} -
+ @if (data.time) { + } +
} + +
+ @for (same of unchanged; track $index) { +
+
@if (same.labelCode) { {{ same.label }} } @else { {{ same.label }} }
+
{{ same.value }}
+
+ } +
+
diff --git a/ui-ngx/src/app/modules/home/components/ai/ai-approval-card.component.scss b/ui-ngx/src/app/modules/home/components/ai/ai-approval-card.component.scss index 41b1e862cf..829dc96e3c 100644 --- a/ui-ngx/src/app/modules/home/components/ai/ai-approval-card.component.scss +++ b/ui-ngx/src/app/modules/home/components/ai/ai-approval-card.component.scss @@ -2,82 +2,4 @@ // SPDX-License-Identifier: BUSL-1.1 :host { display: block; - border: 1px solid rgba(0, 0, 0, 0.12); - border-radius: 12px; - padding: 16px; - - &.executing { - color: rgba(0, 0, 0, 0.76); - } - - &.approved { - color: #198038; - background-color: rgba(25, 128, 56, 0.06); - } - - &.denied { - color: rgba(0, 0, 0, 0.54); - background-color: rgba(0, 0, 0, 0.06); - } - - &.error { - color: var(--tb-crit); - background-color: color-mix(in srgb, var(--tb-crit) 8%, transparent); - } - - .approval-title { - margin-bottom: 8px; - font-weight: 500; - font-size: 16px; - line-height: 24px; - letter-spacing: 0.25px; - } - - .approval-content { - font-size: 14px; - line-height: 20px; - margin-bottom: 16px; - color: rgba(0, 0, 0, 0.54); - letter-spacing: 0.25px; - } - - .approval-actions { - display: flex; - gap: 8px; - justify-content: flex-end; - - .approved { - flex: 1; - --mat-button-filled-label-text-color: #FFF; - --mat-button-filled-container-color: #198038; - } - - .danger { - flex: 1; - --mat-button-filled-label-text-color: #FFF; - --mat-button-filled-container-color: #d32f2f; - } - - .denied { - flex: 1; - --mat-button-outlined-label-text-color: #FF5722; - } - } - - .approve-all { - width: 100%; - margin-top: 8px; - --mat-button-text-label-text-color: rgba(0, 0, 0, 0.54); - --mat-button-text-container-height: 32px; - } - - .approval-result { - display: flex; - align-items: center; - gap: 8px; - font-size: 16px; - font-weight: 500; - line-height: 24px; - letter-spacing: 0.25px; - } } diff --git a/ui-ngx/src/app/modules/home/components/ai/ai-approval-card.component.ts b/ui-ngx/src/app/modules/home/components/ai/ai-approval-card.component.ts index fe6b67e07b..b8d19aa09f 100644 --- a/ui-ngx/src/app/modules/home/components/ai/ai-approval-card.component.ts +++ b/ui-ngx/src/app/modules/home/components/ai/ai-approval-card.component.ts @@ -1,99 +1,543 @@ // SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. // SPDX-License-Identifier: BUSL-1.1 import { + AfterViewChecked, + ChangeDetectionStrategy, ChangeDetectorRef, Component, + ElementRef, EventEmitter, - HostBinding, inject, Input, OnChanges, Output, - SimpleChanges + SimpleChanges, + ViewChild } from '@angular/core'; +import { aiRevealOpened } from '@home/components/ai/ai-disclosure.component'; +import { TranslateService } from '@ngx-translate/core'; +import { ClipboardService } from 'ngx-clipboard'; +import { IntegrationType, integrationTypeInfoMap } from '@shared/models/integration.models'; +import { ConverterType, converterTypeTranslationMap } from '@shared/models/converter.models'; +import { decorateCodeBlocks } from '@home/components/ai/ai-code-block'; import { + AiApprovalReview, + AiReviewField, ApprovalResult, ToolApprovalResult, ToolExecutionRequested, ToolExecutionResult } from '@shared/models/ai-chat.models'; +import { AiAction, HUB_INSTALL_TOOLS } from '@home/components/ai/ai-action.models'; +import { EntityType, entityTypeTranslations } from '@shared/models/entity-type.models'; +import { MailTemplate, mailTemplateTranslations } from '@shared/models/settings.models'; -export type ApprovalCardState = 'pending' | 'executing' | 'approved' | 'denied' | 'error'; +export type ApprovalCardState = 'pending' | 'waiting' | 'approved' | 'auto' | 'denied'; + +import { AiDetailFact } from '@home/components/ai/ai-action-detail.models'; +import { AiRecordLoaderService } from '@home/components/ai/ai-record-loader.service'; +import { AiRecordView } from '@home/components/ai/ai-record.models'; + +export interface AiReviewRow { + label: string; + labelCode: boolean; + valueCode: boolean; + current?: string; + value: string; + image?: boolean; + currentImage?: boolean; + code?: boolean; + lang?: string; + chip?: {icon?: string; image?: string}; +} + +const MAX_FIELDS = 5; + +const DETAIL_TOKENS = new Set(['server-attributes', 'shared-attributes']); + +const ATTRIBUTE_TOOLS = new Set(['save_attributes', 'delete_attributes']); + +const VALUE_TOKENS: Record = { + undo: ['none'], + defaultDashboard: ['none'], + homeDashboard: ['none'], + clears: ['yes', 'no'], + edgeTemplateRoot: ['yes'], + autoAssign: ['yes', 'no'], + removeVolumes: ['yes', 'no'], + default: ['yes'], + operation: ['restart', 'update', 'upgrade', 'delete', 'cancel', 'upgrade agent'] +}; + +const CODE_FIELDS = new Set(['arguments', 'expression', 'output']); + +const HEAD_VERBS = new Set(['create', 'update', 'delete', 'install', 'acknowledge', 'clear', 'assign', 'unassign']); +const REVIEW_VERBS = new Set(['install', 'restart', 'update', 'upgrade', 'upgrade-agent', 'delete', 'cancel', 'sync', 'acknowledge', 'clear', 'assign', 'unassign']); + +const IMAGE_FIELDS = new Set(['widget-image', 'scada-symbol', 'dashboard-image']); + +const BLOCK_FIELDS = new Set(['script']); + +const DETAILED_TOOLS = new Set(['save_converter']); + +const JSON_BLOCK_AT = 80; + +function prettyJson(value: string | undefined | null): string | null { + const trimmed = value?.trim() ?? ''; + if (trimmed.length < JSON_BLOCK_AT || !/^[[{]/.test(trimmed)) { + return null; + } + try { + const parsed = JSON.parse(trimmed); + return parsed && typeof parsed === 'object' ? JSON.stringify(parsed, null, 2) : null; + } catch { + return null; + } +} + +const DIFF_CONTEXT = 2; + +function withoutTs(text: string): string { + try { + const parsed = JSON.parse(text); + if (parsed && typeof parsed === 'object' && !Array.isArray(parsed) && 'ts' in parsed) { + const rest = {...parsed}; + delete rest.ts; + return JSON.stringify(rest, null, 2); + } + } catch { + } + return text; +} + +function lineDiff(before: string, after: string): string { + const a = before.split('\n'); + const b = after.split('\n'); + const table: number[][] = Array.from({length: a.length + 1}, () => new Array(b.length + 1).fill(0)); + for (let i = a.length - 1; i >= 0; i--) { + for (let j = b.length - 1; j >= 0; j--) { + table[i][j] = a[i] === b[j] ? table[i + 1][j + 1] + 1 : Math.max(table[i + 1][j], table[i][j + 1]); + } + } + const rows: {mark: ' ' | '-' | '+'; text: string}[] = []; + let i = 0; + let j = 0; + while (i < a.length || j < b.length) { + if (i < a.length && j < b.length && a[i] === b[j]) { + rows.push({mark: ' ', text: a[i++]}); + j++; + } else if (i < a.length && (j >= b.length || table[i + 1][j] >= table[i][j + 1])) { + rows.push({mark: '-', text: a[i++]}); + } else { + rows.push({mark: '+', text: b[j++]}); + } + } + const keep = rows.map((row, index) => row.mark !== ' ' + || rows.slice(Math.max(0, index - DIFF_CONTEXT), index + DIFF_CONTEXT + 1).some(near => near.mark !== ' ')); + const out: string[] = []; + rows.forEach((row, index) => { + if (keep[index]) { + out.push(row.mark + ' ' + row.text); + } else if (keep[index - 1] || index === 0) { + out.push(' …'); + } + }); + return out.join('\n'); +} + +const isBlock = (field: AiReviewField): boolean => BLOCK_FIELDS.has(field.id) || !!prettyJson(field.value) || !!prettyJson(field.current); + +const CONVERTER_ICONS: Record = {UPLINK: 'call_received', DOWNLINK: 'call_made'}; + +const IMAGE_VALUE = /^(tb-image;|\/api\/images\/|data:image\/)/; + +const LONG_CHANGE_AT = 36; +const COMMON_VALUES = new Set(['on', 'off', 'automatic', 'set', 'not set', 'default']); +const OWN_TYPE_LABELS = new Set(['ALARM_RULE', 'DASHBOARD_WIDGET', 'DASHBOARD_STATE', 'DASHBOARD_ENTITY_ALIAS', 'DASHBOARD_FILTER', 'NOTIFICATION', 'NOTIFICATION_SETTINGS', 'NOTIFICATION_PREFERENCES', 'IMAGE', 'PLATFORM_SETTINGS', 'RELATION', 'VERSION', 'WHITE_LABELING', 'MAIL_TEMPLATE', 'CUSTOM_TRANSLATION', 'CUSTOM_MENU', 'MOBILE_APP', 'MOBILE_BUNDLE', 'MOBILE_QR_CODE', 'TWO_FACTOR_SETTINGS', 'MY_PROFILE', 'MY_TWO_FACTOR', 'MAIL_SERVER', 'REPORT_COMPONENT', 'REPORT_ENTITY_ALIAS', 'REPORT_FILTER', 'SCHEDULED_REPORT', 'SCADA_SYMBOL']); + +const PROFILE_TYPES = new Set([EntityType.DEVICE_PROFILE, EntityType.ASSET_PROFILE]); + +function aiApproveLabel(data: ToolExecutionRequested): string { + const review = data?.review; + const versionId = HUB_INSTALL_TOOLS.has(data?.tool) ? (data.arguments as {versionId?: unknown})?.versionId : null; + if (typeof versionId === 'string' && versionId) { + return 'ai-assistant.record.install'; + } + if (review?.verb && REVIEW_VERBS.has(review.verb)) { + return 'ai-assistant.review.verb.' + review.verb; + } + if (data?.destructive) { + return 'ai-assistant.review.delete'; + } + switch (review?.change) { + case 'CREATE': + return 'ai-assistant.review.create'; + case 'UPDATE': + return 'ai-assistant.review.update'; + default: + return 'ai-assistant.approve'; + } +} + +function aiReviewTypeLabel(translate: TranslateService, entityType: string): string { + if (OWN_TYPE_LABELS.has(entityType)) { + return translate.instant('ai-assistant.review.type.' + entityType); + } + const translation = entityTypeTranslations.get(entityType as EntityType)?.type; + return translation ? translate.instant(translation) : entityType; +} + +function aiChangeHead(translate: TranslateService, data: ToolExecutionRequested): string | null { + const review = data?.review; + const label = aiApproveLabel(data); + if (!review?.entityType || label === 'ai-assistant.approve') { + return null; + } + const verb = label.split('.').pop(); + if (!HEAD_VERBS.has(verb)) { + return translate.instant(label); + } + if (DETAIL_TOKENS.has(review.detail) || ATTRIBUTE_TOOLS.has(data.tool)) { + const kind = DETAIL_TOKENS.has(review.detail) ? translate.instant('ai-assistant.review.detail.' + review.detail) + : translate.instant('ai-assistant.review.kind.attributes'); + return translate.instant('ai-assistant.review.head-change.' + verb, {kind}); + } + const type = review.detail === 'alarm-rule' ? 'ALARM_RULE' : review.entityType; + const key = 'ai-assistant.review.kind.' + type; + const phrase = translate.instant(key); + const kind = phrase !== key ? phrase : aiReviewTypeLabel(translate, type); + return translate.instant('ai-assistant.review.head-change.' + verb, {kind}); +} + +export function aiReviewHead(translate: TranslateService, data: ToolExecutionRequested): string { + return aiChangeHead(translate, data) ?? translate.instant('ai-assistant.review.head.pending'); +} @Component({ + changeDetection: ChangeDetectionStrategy.OnPush, selector: 'tb-ai-approval-card', templateUrl: './ai-approval-card.component.html', styleUrls: ['./ai-approval-card.component.scss'], standalone: false }) -export class AiApprovalCardComponent implements OnChanges { +export class AiApprovalCardComponent implements OnChanges, AfterViewChecked { @Input() data: ToolExecutionRequested; @Input() completedExecution: ToolExecutionResult | null = null; + @Input() durationMs?: number; + @Input() autoApprove = false; + @Input() answered = false; + + @Input() busy = false; + + @ViewChild('denyInput') denyInput: ElementRef; + @Output() approvalAction = new EventEmitter(); - @HostBinding('class') state: ApprovalCardState = 'pending'; + @Output() answerLater = new EventEmitter(); + + denying = false; + + showUnchanged = false; + + state: ApprovalCardState = 'pending'; + + handedOver: AiAction | null = null; + + handedFacts: AiDetailFact[] = []; + + private autoApproved = false; private readonly cd = inject(ChangeDetectorRef); + private readonly translate = inject(TranslateService); + private readonly clipboard = inject(ClipboardService); + private readonly host = inject(ElementRef); + + private readonly loader = inject(AiRecordLoaderService); + + listing: AiRecordView | null = null; + + private listingId: string | null = null; + + ngAfterViewChecked(): void { + decorateCodeBlocks(this.host.nativeElement, this.translate, text => this.clipboard.copyFromContent(text)); + } ngOnChanges(changes: SimpleChanges): void { - if (this.autoApprove && this.state === 'pending' && !this.completedExecution) { - this.approve(); + this.loadListing(); + if ((this.data?.autoApproved || this.autoApprove) && this.state === 'pending' && !this.completedExecution) { + this.autoApproved = true; + this.denying = false; + this.state = 'auto'; + } + if (this.answered && this.state === 'pending' && !this.completedExecution) { + this.denying = false; + this.state = 'denied'; + } + if (changes.durationMs && this.handedOver && !changes.completedExecution) { + this.handedOver = {...this.handedOver, durationMs: this.durationMs}; } if (changes.completedExecution && this.completedExecution?.executionId === this.data.executionId) { const result = this.completedExecution; - if (result.approvalStatus === ToolApprovalResult.DENIED || result.approvalStatus === ToolApprovalResult.TIMEOUT) { + if (result.approvalStatus === ToolApprovalResult.TIMEOUT) { + this.state = 'waiting'; + } else if (result.approvalStatus === ToolApprovalResult.DENIED) { this.state = 'denied'; - } else if (result.approvalStatus === ToolApprovalResult.APPROVED && result.executionStatus === 'SUCCESS') { - this.state = 'approved'; } else { - this.state = 'error'; + this.autoApproved = this.autoApproved || !!this.data?.autoApproved; + this.state = this.autoApproved ? 'auto' : 'approved'; + this.handedOver = { + executionId: result.executionId, + tool: this.data.tool ?? '', + arguments: this.data.arguments, + result: result.result, + status: result.executionStatus, + startedAt: this.data.time ?? Date.now(), + durationMs: this.durationMs ?? result.durationMs, + affectedEntities: result.affectedEntities ?? [] + }; + this.handedFacts = DETAILED_TOOLS.has(this.data.tool ?? '') ? [] : this.reviewFacts(); } this.cd.detectChanges(); } } - get isDestructive(): boolean { - return this.data.destructive; + get review(): AiApprovalReview | undefined { + return this.data.review; } - get approveIcon(): string { - return this.data.icon || (this.isDestructive ? 'delete' : 'check'); + get isDestructive(): boolean { + return this.data.destructive; } - get resultIcon(): string { - if (this.completedExecution?.icon) { - return this.completedExecution.icon; - } + get headIcon(): string { switch (this.state) { case 'approved': - return this.approveIcon; + return 'check_circle'; + case 'auto': + return 'bolt'; case 'denied': return 'block'; default: - return 'error_outline'; + return 'rate_review'; } } - approve(): void { - this.emitApproval(); + get headText(): string { + if (this.state === 'pending' || this.state === 'waiting') { + return this.changeHead() ?? this.translate.instant('ai-assistant.review.head.pending'); + } + return this.translate.instant('ai-assistant.review.head.' + this.state); + } + + private changeHead(): string | null { + return aiChangeHead(this.translate, this.data); + } + + + get outcomeText(): string { + const result = this.completedExecution; + const failed = result?.executionStatus !== 'SUCCESS'; + return result?.message || this.translate.instant(failed ? 'ai-assistant.error' : 'ai-assistant.approved'); + } + + get planned(): boolean { + return this.review?.change === 'CREATE'; + } + + get hubVersionId(): string | null { + const id = HUB_INSTALL_TOOLS.has(this.data?.tool) ? (this.data.arguments as {versionId?: unknown})?.versionId : null; + return typeof id === 'string' && id ? id : null; + } + + get approveLabel(): string { + return aiApproveLabel(this.data); + } + + + get recordName(): string { + const name = this.review?.name; + if (this.review?.entityType === 'WHITE_LABELING' && (name === 'GENERAL' || name === 'LOGIN')) { + return this.translate.instant('ai-assistant.review.white-labeling-target.' + name); + } + const template = this.review?.entityType === 'MAIL_TEMPLATE' && name ? mailTemplateTranslations.get(name as MailTemplate) : undefined; + return template ? this.translate.instant(template) : name; + } + + get alarmRule(): boolean { + return this.review?.detail === 'alarm-rule'; + } + + get meta(): string { + const review = this.review; + if (!review) { + return ''; + } + const parts = [this.alarmRule ? this.translate.instant('ai-assistant.review.type.ALARM_RULE') : this.typeLabel(review.entityType)]; + if (review.detail && !this.alarmRule) { + const integration = review.entityType === 'INTEGRATION' ? integrationTypeInfoMap.get(review.detail as IntegrationType) : undefined; + parts.push(DETAIL_TOKENS.has(review.detail) ? this.translate.instant('ai-assistant.review.detail.' + review.detail) + : integration ? this.translate.instant(integration.name) : review.detail); + } + if (review.target) { + parts.push(this.translate.instant(PROFILE_TYPES.has(review.entityType) ? 'ai-assistant.record.on-profile' : 'ai-assistant.record.on', + {name: review.target})); + } + return parts.join(' · '); + } + + get facts(): AiReviewRow[] { + const rows = [...this.rows('FACT', field => !isBlock(field)).slice(0, MAX_FIELDS), + ...this.rows('CHANGE', field => !isBlock(field) && (field.current === undefined || field.current === null))]; + if (this.listing && this.review?.target) { + rows.push({label: this.translate.instant('ai-assistant.record.set-up-on'), labelCode: false, valueCode: false, value: this.review.target}); + } + return rows; + } + + get codeBlocks(): AiReviewRow[] { + return [...this.rows('FACT', field => isBlock(field)), + ...this.rows('CHANGE', field => isBlock(field)).map(row => row.current === undefined ? row + : {...row, value: row.lang === 'json' ? lineDiff(withoutTs(row.current), withoutTs(row.value)) : lineDiff(row.current, row.value), + current: undefined, lang: 'diff'})]; + } + + private reviewFacts(): AiDetailFact[] { + return [ + ...this.rows('FACT', field => !isBlock(field)).map(row => row.image ? {label: row.label, raw: true, images: {value: row.value}} + : {label: row.label, raw: true, value: row.value, mono: row.valueCode, chip: row.chip}), + ...this.rows('CHANGE', field => !isBlock(field)).map(row => row.image || row.currentImage + ? {label: row.label, raw: true, change: true, images: {current: row.currentImage ? row.current : undefined, value: row.image ? row.value : undefined}} + : {label: row.label, raw: true, change: true, was: row.current ?? '—', value: row.value, mono: row.valueCode, long: this.isLongChange(row)}) + ]; + } + + isLongChange(change: AiReviewRow): boolean { + return !change.image && !change.currentImage && (change.current?.length ?? 0) + (change.value?.length ?? 0) > LONG_CHANGE_AT; } - approveAll(): void { - this.emitApproval(true); + get changes(): AiReviewRow[] { + return this.rows('CHANGE', field => !isBlock(field) && field.current !== undefined && field.current !== null); + } + + get unchanged(): AiReviewRow[] { + return this.rows('UNCHANGED'); + } + + get recordClosed(): boolean { + return this.state === 'pending' || this.state === 'denied' || this.state === 'waiting'; + } + + toggleUnchanged(): void { + this.showUnchanged = !this.showUnchanged; + if (this.showUnchanged) { + aiRevealOpened(this.host.nativeElement); + } + } + + approve(): void { + const later = this.state === 'waiting'; + this.state = this.autoApproved ? 'auto' : 'approved'; + this.denying = false; + (later ? this.answerLater : this.approvalAction).emit({executionId: this.data.executionId, approved: true}); } deny(): void { - this.state = 'executing'; - this.approvalAction.emit({executionId: this.data.executionId, approved: false}); + if (this.denying) { + this.sendDeny(this.denyInput?.nativeElement.value ?? ''); + return; + } + this.denying = true; + setTimeout(() => this.denyInput?.nativeElement.focus()); + } + + sendDeny(words: string): void { + const reason = words.trim(); + const later = this.state === 'waiting'; + this.denying = false; + this.state = 'denied'; + (later ? this.answerLater : this.approvalAction).emit(reason + ? {executionId: this.data.executionId, approved: false, reason} + : {executionId: this.data.executionId, approved: false}); + } + + closeDeny(): void { + this.denying = false; + } + + private loadListing(): void { + const id = this.hubVersionId; + if (!id || id === this.listingId) { + return; + } + this.listingId = id; + this.loader.hub(id).subscribe({ + next: listing => { + this.listing = listing; + this.cd.markForCheck(); + }, + error: () => { + this.listing = null; + this.cd.markForCheck(); + } + }); } - private emitApproval(autoApprove = false): void { - this.state = 'executing'; - this.approvalAction.emit({executionId: this.data.executionId, approved: true, autoApprove}); + private rows(kind: AiReviewField['kind'], include: (field: AiReviewField) => boolean = () => true): AiReviewRow[] { + return (this.review?.fields ?? []).filter(field => field.kind === kind && include(field)).map(field => ({ + label: field.name ?? this.translate.instant('ai-assistant.review.field.' + field.id), + labelCode: !!field.name, + valueCode: CODE_FIELDS.has(field.id) && field.value !== undefined && field.value !== null, + current: kind !== 'CHANGE' || (isBlock(field) && (field.current === undefined || field.current === null)) ? undefined + : prettyJson(field.current) ?? this.value(field, field.current), + value: prettyJson(field.value) ?? this.value(field, field.value), + image: IMAGE_FIELDS.has(field.id) && IMAGE_VALUE.test(field.value ?? ''), + currentImage: IMAGE_FIELDS.has(field.id) && IMAGE_VALUE.test(field.current ?? ''), + code: isBlock(field), + lang: BLOCK_FIELDS.has(field.id) ? 'tbel' : 'json', + chip: this.chip(field) + })); } + + private chip(field: AiReviewField): {icon?: string; image?: string} | undefined { + if (field.id === 'integrationType') { + const info = integrationTypeInfoMap.get(field.value as IntegrationType); + return info ? {image: info.icon} : undefined; + } + if (field.id === 'type' && converterTypeTranslationMap.has(field.value as ConverterType)) { + return {icon: CONVERTER_ICONS[field.value]}; + } + return undefined; + } + + private value(field: AiReviewField, value: string | undefined): string { + if (value === undefined || value === null) { + return this.translate.instant('ai-assistant.review.not-set'); + } + if (field.id === 'when' && !isNaN(Date.parse(value))) { + return new Date(value).toLocaleString(); + } + if (field.id === 'integrationType' && integrationTypeInfoMap.has(value as IntegrationType)) { + return this.translate.instant(integrationTypeInfoMap.get(value as IntegrationType).name); + } + if (field.id === 'type' && converterTypeTranslationMap.has(value as ConverterType)) { + return this.translate.instant(converterTypeTranslationMap.get(value as ConverterType)); + } + if (field.id && VALUE_TOKENS[field.id]?.includes(value)) { + return this.translate.instant(`ai-assistant.review.value.${field.id}-${value.replace(/ /g, '-')}`); + } + if (COMMON_VALUES.has(value)) { + return this.translate.instant(`ai-assistant.review.value.${value.replace(/ /g, '-')}`); + } + return value; + } + + private typeLabel(entityType: string): string { + return aiReviewTypeLabel(this.translate, entityType); + } + } diff --git a/ui-ngx/src/app/modules/home/components/ai/ai-artifact-pane.component.html b/ui-ngx/src/app/modules/home/components/ai/ai-artifact-pane.component.html new file mode 100644 index 0000000000..11489f55ee --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/ai/ai-artifact-pane.component.html @@ -0,0 +1,23 @@ + + +
+ + +
+
+ +
+ diff --git a/ui-ngx/src/app/modules/home/components/ai/ai-artifact-pane.component.ts b/ui-ngx/src/app/modules/home/components/ai/ai-artifact-pane.component.ts new file mode 100644 index 0000000000..c44118f7a4 --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/ai/ai-artifact-pane.component.ts @@ -0,0 +1,160 @@ +// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: BUSL-1.1 +import { readStored, writeStored } from '@core/local-storage/stored'; +import { AfterViewInit, Component, DestroyRef, ElementRef, EventEmitter, inject, input, Output, signal, ViewChild } from '@angular/core'; + +const PANE_MIN = 360; +const CHAT_MIN = 340; +const WIDTH_KEY = 'tbSolutionPaneWidth'; +const ESCAPE_OWNERS = ['mat-mdc-dialog-container', 'mat-mdc-menu-panel', 'mat-mdc-select-panel', 'mat-mdc-autocomplete-panel'] + .map(owner => '.cdk-overlay-container .' + owner).join(', '); + +@Component({ + selector: 'tb-ai-artifact-pane', + templateUrl: './ai-artifact-pane.component.html', + standalone: false, + host: { + class: 'art-pane', + '[class.scrolled]': 'scrolled()', + '[class.more]': 'more()', + '[style.flex-basis]': 'width() ? width() + "px" : null', + '(keydown.escape)': 'onEscape($event)', + '(document:keydown.escape)': 'onDocumentEscape($event)' + } +}) +export class AiArtifactPaneComponent implements AfterViewInit { + + dark = input(false); + + @Output() closed = new EventEmitter(); + + @ViewChild('body', {static: true}) body: ElementRef; + + width = signal(AiArtifactPaneComponent.storedWidth()); + scrolled = signal(false); + more = signal(false); + + private host = inject(ElementRef); + private destroyRef = inject(DestroyRef); + + ngAfterViewInit(): void { + setTimeout(() => this.refreshEdges(), 50); + const columns = (this.host.nativeElement as HTMLElement).parentElement; + columns?.addEventListener('keydown', this.onColumnsEscape); + this.destroyRef.onDestroy(() => columns?.removeEventListener('keydown', this.onColumnsEscape)); + } + + refreshEdges(): void { + const body = this.body?.nativeElement; + if (body) { + this.scrolled.set(body.scrollTop > 0); + this.more.set(body.scrollTop + body.clientHeight < body.scrollHeight - 1); + } + } + + onEscape(event: Event): void { + if (event.defaultPrevented) { + return; + } + event.stopPropagation(); + this.closed.emit(); + } + + onDocumentEscape(event: KeyboardEvent): void { + if (event.target === document.body || event.target === document.documentElement) { + this.closeOnEscape(event); + } + } + + private onColumnsEscape = (event: KeyboardEvent): void => { + if (event.key === 'Escape' && !(this.host.nativeElement as HTMLElement).contains(event.target as Node)) { + this.closeOnEscape(event); + } + }; + + private closeOnEscape(event: KeyboardEvent): void { + if (event.defaultPrevented || document.querySelector(ESCAPE_OWNERS)) { + return; + } + this.closed.emit(); + } + + startResize(event: PointerEvent): void { + event.preventDefault(); + const edge = event.target as HTMLElement; + const pane = this.host.nativeElement as HTMLElement; + const cols = pane.parentElement; + if (!cols) { + return; + } + const startX = event.clientX; + const startWidth = pane.getBoundingClientRect().width; + const max = cols.getBoundingClientRect().width - CHAT_MIN; + edge.setPointerCapture(event.pointerId); + edge.classList.add('held'); + let closing = false; + const move = (e: PointerEvent) => { + const width = startWidth + (startX - e.clientX); + closing = width < PANE_MIN - 72; + pane.classList.toggle('closing', closing); + this.width.set(Math.round(Math.min(max, Math.max(PANE_MIN, width)))); + }; + const up = () => { + edge.removeEventListener('pointermove', move); + edge.removeEventListener('pointerup', up); + edge.removeEventListener('pointercancel', up); + edge.classList.remove('held'); + pane.classList.remove('closing'); + if (closing) { + this.width.set(startWidth); + this.closed.emit(); + } else { + this.storeWidth(); + } + }; + edge.addEventListener('pointermove', move); + edge.addEventListener('pointerup', up); + edge.addEventListener('pointercancel', up); + } + + resetWidth(): void { + this.width.set(null); + this.storeWidth(); + } + + onEdgeKey(event: KeyboardEvent): void { + if (event.key === 'Enter') { + this.resetWidth(); + return; + } + const pane = this.host.nativeElement as HTMLElement; + const cols = pane.parentElement; + if (!cols) { + return; + } + const max = cols.getBoundingClientRect().width - CHAT_MIN; + let width: number; + if (event.key === 'Home') { + width = max; + } else if (event.key === 'End') { + width = PANE_MIN; + } else if (event.key === 'ArrowLeft' || event.key === 'ArrowRight') { + const step = event.shiftKey ? 64 : 16; + width = pane.getBoundingClientRect().width + (event.key === 'ArrowLeft' ? step : -step); + } else { + return; + } + event.preventDefault(); + this.width.set(Math.round(Math.min(max, Math.max(PANE_MIN, width)))); + this.storeWidth(); + } + + private static storedWidth(): number | null { + return Number(readStored(WIDTH_KEY)) || null; + } + + private storeWidth(): void { + const width = this.width(); + writeStored(WIDTH_KEY, width ? String(width) : null); + } +} diff --git a/ui-ngx/src/app/modules/home/components/ai/ai-assistant-button.component.ts b/ui-ngx/src/app/modules/home/components/ai/ai-assistant-button.component.ts new file mode 100644 index 0000000000..0b2439f73e --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/ai/ai-assistant-button.component.ts @@ -0,0 +1,256 @@ +// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: BUSL-1.1 +import { + ChangeDetectionStrategy, + Component, + computed, + DestroyRef, + effect, + ElementRef, + inject, + Renderer2, + signal, + untracked, + viewChild, + ViewContainerRef +} from '@angular/core'; +import { takeUntilDestroyed, toSignal } from '@angular/core/rxjs-interop'; +import { NavigationEnd, NavigationStart, Router } from '@angular/router'; +import { filter } from 'rxjs/operators'; +import { TranslateService } from '@ngx-translate/core'; +import { AiChatsService } from '@core/services/ai-chats.service'; +import { ChatLevel } from '@shared/models/ai-chat.models'; +import { MatDialog } from '@angular/material/dialog'; +import { Store } from '@ngrx/store'; +import { AppState } from '@core/core.state'; +import { getCurrentAuthState, selectAiTourStepSeen } from '@core/auth/auth.selectors'; +import { ActionPreferencesUpdateAiTour } from '@core/auth/auth.actions'; +import { AiTourStep } from '@shared/models/user-settings.models'; +import { UserPermissionsService } from '@core/http/user-permissions.service'; +import { AiAssistantPanelService } from '@core/services/ai-assistant-panel.service'; +import { escapeTourText, TourPopupRef, TourPopupService } from '@shared/components/tour/tour-popup.service'; +import { TourService } from '@core/services/tour.service'; +import { AiAssistantContextService } from '@home/components/ai/ai-assistant-context.service'; +import { AiSlashService } from '@core/services/ai-slash.service'; +import { AiMarkCue } from '@home/components/ai/ai-mark.component'; + +const INTRO_DELAY_MS = 900; + +const intro: { owner: AiAssistantButtonComponent | null } = {owner: null}; + +@Component({ + selector: 'tb-ai-assistant-button', + template: ` + @if (available() && !panelService.open() && !panelService.suppressed()) { + @let status = cue(); + + +
+
+ {{ status ? ('ai-assistant.ai-assistant-cue' | translate: {cue: status.tip}) : ('ai-assistant.ai-assistant' | translate) }} + / +
+
+
+ } + `, + styles: [` + :host { + display: contents; + } + `], + standalone: false, + changeDetection: ChangeDetectionStrategy.OnPush +}) +export class AiAssistantButtonComponent { + + panelService = inject(AiAssistantPanelService); + + private store = inject(Store); + + private readonly authState = getCurrentAuthState(this.store); + + readonly available = inject(UserPermissionsService).aiAvailable; + + private dialog = inject(MatDialog); + + private chats = inject(AiChatsService); + + private translate = inject(TranslateService); + + private context = inject(AiAssistantContextService); + + private tourPopup = inject(TourPopupService); + + private tourService = inject(TourService); + + private renderer = inject(Renderer2); + + private viewContainerRef = inject(ViewContainerRef); + + private buttonRef = viewChild('aiButton', {read: ElementRef}); + + private introSeen = toSignal(this.store.select(selectAiTourStepSeen(AiTourStep.AI_BUTTON)), {initialValue: true}); + + private welcomeSeen = toSignal(this.store.select(selectAiTourStepSeen(AiTourStep.WELCOME)), {initialValue: false}); + + readonly introOpen = signal(false); + + private introPopup: TourPopupRef | null = null; + + private introTimer: ReturnType | null = null; + + readonly cue = computed<{level: ChatLevel; tip: string} | null>(() => { + const chats = this.chats.statusChats(); + const titleOf = (title: string) => title || this.translate.instant('ai-assistant.new-chat'); + const attention = chats.filter(chat => this.chats.needsAttention(chat)); + if (attention.length) { + const level: AiMarkCue = attention.some(chat => this.chats.levelOf(chat) === 'needs') ? 'needs' : 'error'; + return { + level, + tip: attention.length === 1 + ? this.translate.instant('ai-assistant.waiting-one-tip', {title: titleOf(attention[0].title), status: this.chats.tipOf(attention[0])}) + : this.translate.instant('ai-assistant.waiting-many', {count: attention.length}) + }; + } + const running = chats.filter(chat => this.chats.levelOf(chat) === 'running'); + if (running.length) { + return { + level: 'running', + tip: running.length === 1 + ? this.translate.instant('ai-assistant.running-one-tip', {title: titleOf(running[0].title)}) + : this.translate.instant('ai-assistant.running-many', {count: running.length}) + }; + } + return null; + }); + + readonly markCue = computed(() => { + const level = this.cue()?.level; + return level === 'needs' || level === 'error' ? level : null; + }); + + private introWanted = computed(() => this.available() && this.welcomeSeen() && !this.tourService.active() && !this.introSeen() && this.cue()?.level !== 'running' && !this.panelService.open() + && !this.panelService.suppressed() && !!this.buttonRef()); + + private introEffect = effect(() => { + const wanted = this.introWanted(); + untracked(() => { + this.clearIntroTimer(); + if (wanted && !this.introOpen()) { + this.introTimer = setTimeout(() => this.showIntro(), INTRO_DELAY_MS); + } else if (!wanted && this.introOpen()) { + this.hideIntro(); + } + }); + }); + + private statusWatch = effect(() => { + if (this.available()) { + untracked(() => this.chats.watchStatus()); + } + }); + + constructor() { + inject(Router).events.pipe( + filter(event => event instanceof NavigationStart || event instanceof NavigationEnd), + takeUntilDestroyed() + ).subscribe(event => { + this.clearIntroTimer(); + if (event instanceof NavigationStart) { + this.hideIntro(); + } else if (this.introWanted()) { + this.introTimer = setTimeout(() => this.showIntro(), INTRO_DELAY_MS); + } + }); + const removeOpener = inject(AiSlashService).setOpener({ + canOpen: () => this.available() && !this.panelService.open() && !this.panelService.suppressed(), + open: () => this.openChat() + }); + inject(DestroyRef).onDestroy(() => { + removeOpener(); + this.clearIntroTimer(); + this.hideIntro(); + }); + } + + toggle($event: Event): void { + $event.stopPropagation(); + this.openChat(); + } + + private openChat(): void { + if (this.introOpen()) { + this.closeIntro(); + } + this.panelService.openPanel(); + } + + private showIntro(): void { + this.introTimer = null; + const trigger: HTMLElement | undefined = this.buttonRef()?.nativeElement; + if (!this.introWanted() || !trigger || intro.owner || this.dialog.openDialogs.length || !this.visible(trigger)) { + return; + } + intro.owner = this; + const welcome = this.context.welcome(); + const example = welcome.examples[0]?.label?.trim(); + const lead = this.translate.instant(`ai-assistant.intro.lead-${welcome.place}${example ? '-example' : ''}`, {example}); + const keys = matchMedia('(hover: hover) and (pointer: fine)').matches ? ' ' + this.translate.instant('ai-assistant.intro.keys') : ''; + this.introOpen.set(true); + this.introPopup = this.tourPopup.show({ + target: trigger, + hostView: this.viewContainerRef, + renderer: this.renderer, + placement: ['bottomRight', 'bottom', 'bottomLeft'], + title: welcome.title || this.translate.instant('ai-assistant.panel-title'), + text: escapeTourText(lead) + keys, + skipLabel: this.translate.instant('ai-assistant.intro.got-it'), + nextLabel: this.translate.instant('ai-assistant.intro.open-chat'), + onSkip: () => this.closeIntro(), + onClose: () => this.closeIntro(), + onNext: () => this.openChat(), + onHidden: () => { + if (this.introOpen()) { + this.introPopup = null; + this.hideIntro(); + } + } + }); + } + + private closeIntro(): void { + this.hideIntro(); + if (!this.introSeen()) { + this.store.dispatch(new ActionPreferencesUpdateAiTour({step: AiTourStep.AI_BUTTON, seen: true})); + } + } + + private hideIntro(): void { + if (intro.owner === this) { + intro.owner = null; + } + this.introOpen.set(false); + const popup = this.introPopup; + this.introPopup = null; + popup?.close(); + } + + private clearIntroTimer(): void { + if (this.introTimer) { + clearTimeout(this.introTimer); + this.introTimer = null; + } + } + + private visible(element: HTMLElement): boolean { + const rect = element.getBoundingClientRect(); + return rect.width > 0 && rect.height > 0 && (element.checkVisibility?.({visibilityProperty: true}) ?? element.offsetParent !== null); + } +} diff --git a/ui-ngx/src/app/modules/home/components/ai/ai-assistant-context.service.ts b/ui-ngx/src/app/modules/home/components/ai/ai-assistant-context.service.ts new file mode 100644 index 0000000000..cd8cdc97b8 --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/ai/ai-assistant-context.service.ts @@ -0,0 +1,58 @@ +// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: BUSL-1.1 +import { computed, inject, Injectable } from '@angular/core'; +import { toSignal } from '@angular/core/rxjs-interop'; +import { NavigationEnd, Router } from '@angular/router'; +import { TranslateService } from '@ngx-translate/core'; +import { filter, map, startWith } from 'rxjs/operators'; +import { aiClientOs, aiPageView, AiChatClientContext } from '@shared/models/ai-chat.models'; +import { getDefaultTimezone } from '@shared/models/time/time.models'; +import { BreadCrumb } from '@shared/components/breadcrumb'; +import { BreadcrumbService } from '@core/services/breadcrumb.service'; +import { UtilsService } from '@core/services/utils.service'; +import { AiAssistantPanelService } from '@core/services/ai-assistant-panel.service'; +import { aiWelcome } from '@home/components/ai/ai-welcome.models'; + +@Injectable({providedIn: 'root'}) +export class AiAssistantContextService { + + private panelService = inject(AiAssistantPanelService); + private translate = inject(TranslateService); + private utils = inject(UtilsService); + private router = inject(Router); + + private pageTitle = toSignal(inject(BreadcrumbService).breadcrumbs$.pipe( + map(crumbs => crumbs.map(crumb => this.crumbLabel(crumb)).filter(label => !!label).join(' › ')) + ), {initialValue: ''}); + + readonly pagePath = toSignal(this.router.events.pipe( + filter((event): event is NavigationEnd => event instanceof NavigationEnd), + map(event => event.urlAfterRedirects), + startWith(this.router.url), + map(url => (url || '/').split(/[?#]/)[0]) + ), {initialValue: '/'}); + + readonly clientContext = computed(() => { + const context = this.panelService.clientContext(); + if (context) { + const name = this.panelService.viewName(); + return context.view?.entityId && name && !context.view.title ? {...context, view: {...context.view, title: name}} : context; + } + const title = this.pageTitle(); + const path = this.pagePath(); + const type = aiPageView(path); + return title || path !== '/' ? {view: {type, title, path}, timeZone: getDefaultTimezone(), os: aiClientOs()} : undefined; + }); + + readonly welcome = computed(() => aiWelcome(this.clientContext()?.view, this.panelService.viewName(), this.panelService.config(), + this.translate)); + + private crumbLabel(crumb: BreadCrumb): string { + try { + return crumb.labelFunction ? crumb.labelFunction() : crumb.customTranslate ? this.utils.customTranslation(crumb.label, crumb.label) + : this.translate.instant(crumb.label); + } catch { + return ''; + } + } +} diff --git a/ui-ngx/src/app/modules/home/components/ai/ai-assistant-panel.component.html b/ui-ngx/src/app/modules/home/components/ai/ai-assistant-panel.component.html index 2e848e106f..346fc7deb5 100644 --- a/ui-ngx/src/app/modules/home/components/ai/ai-assistant-panel.component.html +++ b/ui-ngx/src/app/modules/home/components/ai/ai-assistant-panel.component.html @@ -4,105 +4,29 @@ SPDX-License-Identifier: BUSL-1.1 --> -
-
- - - - @for (group of groupedChats(); track group.label) { -
{{ group.label | translate }}
- @for (chat of group.chats; track chat.id) { - - } - } @empty { -
{{ 'ai-assistant.no-chats' | translate }}
- } -
-
-
- - - - - - - - -
-
-
- @if (messages().length) { -
-
- - -
- } @else { -
-
-
- - - -
-
ai-assistant.main-title
-
{{ subTitle() }}
-
-
-
- } - @if (!messages().length && promptExamples().length) { -
- @for (example of promptExamples(); track example.message) { - - } -
- } -
- - + +
+ +
diff --git a/ui-ngx/src/app/modules/home/components/ai/ai-assistant-panel.component.scss b/ui-ngx/src/app/modules/home/components/ai/ai-assistant-panel.component.scss index 0e5550eb38..4bf26c3c6b 100644 --- a/ui-ngx/src/app/modules/home/components/ai/ai-assistant-panel.component.scss +++ b/ui-ngx/src/app/modules/home/components/ai/ai-assistant-panel.component.scss @@ -3,223 +3,97 @@ @import '../../../../../scss/constants'; :host { - width: 480px; - overflow: hidden; - transform: translateX(100%); - transition: transform 400ms cubic-bezier(0.25, 0.8, 0.25, 1); position: absolute; top: 0; right: 0; bottom: 0; + z-index: 20; + width: var(--tb-ai-panel-w, 364px); display: flex; flex-direction: column; - z-index: 20; + background: var(--tb-surface, #fff); + transform: translateX(100%); + transition: transform 400ms cubic-bezier(0.25, 0.8, 0.25, 1), box-shadow 400ms ease; - &.open { - transform: translateX(0); + &.suppressed { + visibility: hidden; + transition: none; } - .image-main-color { - color: var(--tb-primary-500); + &.restored { + transition: none; } - .ai-assistant-container { - background: #fff; - margin: 16px 16px 16px 0; - box-shadow: 0 0 0 0 rgba(0, 0, 0, 0.2), 0 0 0 0 rgba(0, 0, 0, 0.14), 0 0 0 0 rgba(0, 0, 0, 0.12); - border: solid 1px #e0e0e0; - border-radius: 4px; - display: flex; - flex-direction: column; - // :host is a flex column, so fill its height via flex (which subtracts the card margins) - // instead of height:100% (which ignores margins and overflows the host, clipping the input). - flex: 1; - min-height: 0; - width: 464px; - overflow: hidden; + &.open { + transform: translateX(0); + box-shadow: -1px 0 0 rgba(16, 24, 40, 0.06), -12px 0 32px rgba(16, 24, 40, 0.06); + } - &.fill { - margin: 0; - width: 480px; + .tb-ai-grip { + position: absolute; + top: 0; + bottom: 0; + left: -4px; + z-index: 6; + width: 8px; + cursor: ew-resize; + touch-action: none; + + &::after { + content: ''; + position: absolute; + top: 50%; + left: 2px; + width: 4px; + height: 36px; + margin-top: -18px; + border-radius: 2px; + background: var(--tb-ink-38); + opacity: 0; + transition: opacity .12s ease; } - &.details-open { - padding: 16px 16px 16px 0; + &:hover::after, &:focus-visible::after { + opacity: 1; } - } - - .ai-assistant-composer { - flex: none; - } - .ai-assistant-header { - display: flex; - align-items: center; - justify-content: space-between; - padding: 12px; - white-space: nowrap; + &:focus-visible { + outline: 0; + } - .chat-selector { - font-size: 16px; - min-width: 0; - max-width: 280px; - --mat-button-text-with-icon-horizontal-padding: 12px; - --mat-button-text-label-text-weight: 400; - flex: 1; + @media (max-width: 1100px) { + display: none; } } - .ai-assistant-content { - width: 100%; - height: 100%; - display: flex; + .ai-assistant-container { overflow: hidden; flex: 1; - padding: 0 24px 16px; - gap: 16px; + min-height: 0; + display: flex; flex-direction: column; - - .chat-messages-container { - position: relative; - display: flex; - flex: 1 1 0; - min-height: 0; - width: calc(100% + 24px); - } - - .ai-chat-messages { - padding-right: 20px; - scrollbar-gutter: stable; - } - - .example-chips { - display: flex; - flex-wrap: wrap; - justify-content: center; - gap: 8px; - width: 100%; - --mat-button-outlined-label-text-color: rgba(0, 0, 0, 0.76); - --mat-button-outlined-container-height: 32px; - --mat-button-outlined-outline-color: rgba(0, 0, 0, 0.16); - --mat-button-outlined-container-shape: 20px; - - .example-chip { - background-color: #fff; - opacity: 0; - animation: exampleChipFadeIn 220ms ease-out forwards; - - &:nth-child(2) { - animation-delay: 60ms; - } - - @media (prefers-reduced-motion: reduce) { - opacity: 1; - animation: none; - } - } - } - - @keyframes exampleChipFadeIn { - from { - opacity: 0; - transform: translateY(6px); - } - to { - opacity: 1; - transform: translateY(0); - } - } } - // <= 1279px: slide-in overlay above the content (which no longer reserves space here), - // keeping the 480px card size of the normal display mode. - @media #{$mat-lt-lg} { - - .ai-assistant-container { - width: 480px; - margin: 0; - - &.fill { - width: 480px; - } - } - - .ai-assistant-content { - min-width: 0; - } + .ai-assistant-chat { + flex: 1; + min-height: 0; } - // <= 599px: full-screen panel, the card fills the whole width. - @media #{$mat-xs} { - width: 100%; + @media (max-width: 1100px) { + top: auto; + left: 0; + width: auto; + height: clamp(min(340px, 70vh), 50vh, 600px); + transform: translateY(100%); - .ai-assistant-container { - margin: 0; - width: auto; - - &.fill { - width: auto; - } - - &.details-open { - padding: 8px; - } + &.open { + transform: translateY(0); + box-shadow: 0 -1px 0 rgba(16, 24, 40, 0.06), 0 -12px 32px rgba(16, 24, 40, 0.08); } } } -:host::ng-deep { - .ai-assistant-header { - .chat-selector { - .mdc-button__label { - width: 100%; - text-align: start; - text-overflow: ellipsis; - overflow: hidden; - } - } - } -} - -::ng-deep { - .ai-chat-list-menu.mat-mdc-menu-panel { - min-width: var(--chat-menu-dynamic-width); - max-height: 65vh; - - .chat-group-label { - padding: 8px 16px; - font-size: 14px; - color: rgba(0, 0, 0, 0.76); - font-weight: 500; - } - - .mat-mdc-menu-item.chat-item { - padding-left: 32px; - min-height: 32px; - --mat-menu-item-label-text-size: 14px; - --mat-menu-item-label-text-line-height: 20px; - padding-top: 4px; - padding-bottom: 4px; - - &.selected { - --mat-menu-item-label-text-color: var(--tb-primary-500); - background-color: rgba(0,0,0,0.04); - } - } - - .chat-group-empty { - padding: 16px; - text-align: center; - color: rgba(0, 0, 0, 0.54); - font-size: 14px; - line-height: 20px; - } - } - - .ai-chat-action-menu { - .delete { - --mat-menu-item-icon-color: #FF5722; - --mat-menu-item-label-text-color: #FF5722; - } - } +:host(.closing) > :not(.tb-ai-grip) { + opacity: .4; + transition: opacity .2s ease; } diff --git a/ui-ngx/src/app/modules/home/components/ai/ai-assistant-panel.component.ts b/ui-ngx/src/app/modules/home/components/ai/ai-assistant-panel.component.ts index fb7dadc790..5d3d56b737 100644 --- a/ui-ngx/src/app/modules/home/components/ai/ai-assistant-panel.component.ts +++ b/ui-ngx/src/app/modules/home/components/ai/ai-assistant-panel.component.ts @@ -1,55 +1,13 @@ // SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. // SPDX-License-Identifier: BUSL-1.1 -import { - Component, - computed, - DestroyRef, - effect, - ElementRef, - inject, - OnInit, - SecurityContext, - signal, - untracked, - ViewChild -} from '@angular/core'; -import { ApprovalChatMessage, ChatMessage } from '@shared/models/solution-creator.models'; -import { EMPTY, Observable, of, Subject, throwError, timer } from 'rxjs'; -import { catchError, concatMap, finalize, retry, switchMap, takeUntil, tap } from 'rxjs/operators'; -import { HttpErrorResponse } from '@angular/common/http'; -import { AiChatService } from '@core/http/ai-chat.service'; -import { - AiAssistantPromptExample, - AiChatClientContext, - AiPromptMessage, - ApprovalResult, - ChatEvent, - ChatInfo, - ChatTitleGeneratedEvent, - SendChatMessageRequest, - ToolExecutionRequestedEvent, - ToolExecutionResult -} from '@shared/models/ai-chat.models'; -import { DialogService } from '@core/services/dialog.service'; -import { TranslateService } from '@ngx-translate/core'; -import { MatDialog } from '@angular/material/dialog'; -import { AiRenameDialogComponent, AiRenameDialogData } from '@home/components/ai/ai-rename-dialog.component'; -import { Store } from '@ngrx/store'; -import { AppState } from '@core/core.state'; -import { ActionNotificationShow } from '@core/notification/notification.actions'; -import { DAY, WEEK } from '@shared/models/time/time.models'; -import { takeUntilDestroyed } from '@angular/core/rxjs-interop'; -import { isEqual, isNotEmptyStr, parseHttpErrorMessage } from '@core/utils'; +import { AI_TOOLTIP_PROVIDERS } from '@home/components/ai/ai-tooltip'; +import { Component, computed, effect, ElementRef, inject, NgZone, signal, untracked, ViewChild } from '@angular/core'; +import { MatTooltip } from '@angular/material/tooltip'; import { AiAssistantPanelService } from '@core/services/ai-assistant-panel.service'; -import { DomSanitizer } from '@angular/platform-browser'; -import { AiPromptInputComponent } from '@home/components/ai/ai-prompt-input.component'; -import { MatButton } from '@angular/material/button'; -import { EntityId } from '@shared/models/id/entity-id'; - -export interface ChatGroup { - label: string; - chats: ChatInfo[]; -} +import { AiChatsService } from '@core/services/ai-chats.service'; +import { AiChatComponent } from '@home/components/ai/ai-chat.component'; +import { readStored, writeStored } from '@core/local-storage/stored'; +import { AiAssistantContextService } from '@home/components/ai/ai-assistant-context.service'; @Component({ selector: 'tb-ai-assistant-panel', @@ -58,499 +16,332 @@ export interface ChatGroup { standalone: false, host: { '[class.open]': 'isOpen', + '[class.suppressed]': 'panelService.suppressed()', + '[class.restored]': 'panelService.restored()', '[attr.inert]': 'isOpen ? null : ""', - '(transitionend)': 'onSlideEnd($event)' - } + '[class.split]': 'split()', + '(transitionend)': 'onSlideEnd($event)', + '(window:resize)': 'fit()', + '(click)': 'onClick($event)', + '(keydown.escape)': '$event.stopPropagation()' + }, + providers: AI_TOOLTIP_PROVIDERS }) -export class AiAssistantPanelComponent implements OnInit { +export class AiAssistantPanelComponent { panelService = inject(AiAssistantPanelService); - @ViewChild(AiPromptInputComponent) promptInput: AiPromptInputComponent; + @ViewChild(AiChatComponent) chat: AiChatComponent; - get isOpen() { return this.panelService.open(); } + @ViewChild('gripTip', {read: MatTooltip}) gripTip: MatTooltip; - slideDone = signal(false); + private zone = inject(NgZone); - loading = signal(false); + private static readonly PAGE_REFLOW_MS = 50; - isCreatingNew = signal(false); + private static readonly COMPOSE_DELAY_MS = 60; - messages = signal([]); + private static readonly CLOSE_PAST = 72; - completedExecutions = signal>({}); + resizing = signal(false); - chatId = signal(undefined); + get isOpen() { return this.panelService.open(); } - subTitle = computed(() => { - return this.panelService.config()?.subTitle ?? this.translate.instant('ai-assistant.sub-title'); - }); + readonly defaultWidth = 364; - activePlaceholder = computed(() => { - const config = this.panelService.config(); - if (this.messages().length) { - return config?.followUpPromptPlaceholder ?? this.translate.instant('ai-assistant.follow-up-prompt-placeholder'); - } - return config?.initialPromptPlaceholder ?? ''; - }); + readonly minWidth = 320; - promptExamples = computed(() => this.panelService.config()?.promptExamples ?? []); + readonly maxWidth = 480; - autoApprove = computed(() => this.panelService.isAutoApprove(this.chatId())); + private static readonly SPLIT_MAX = 880; + private static readonly SPLIT_MIN = 540; + private static readonly PAGE_MIN = 560; + private static readonly SHEET_MAX_WINDOW = 1100; - selectedChatTitle = computed(() => { - const id = this.chatId(); - if (!id) return null; - return (this.panelService.chats() ?? []).find(c => c.id === id)?.title ?? null; - }); + width = signal(this.defaultWidth); - groupedChats = computed(() => { - const chats = this.panelService.chats() ?? []; - if (!chats.length) return []; - - const now = new Date(); - const today = new Date(now.getFullYear(), now.getMonth(), now.getDate()).getTime(); - const yesterday = today - DAY; - const lastWeek = today - WEEK; - - const groups: ChatGroup[] = [ - {label: 'ai-assistant.today', chats: []}, - {label: 'ai-assistant.yesterday', chats: []}, - {label: 'ai-assistant.last-7-days', chats: []}, - {label: 'ai-assistant.older', chats: []} - ]; - - for (const chat of chats) { - if (chat.createdTime >= today) { - groups[0].chats.push(chat); - } else if (chat.createdTime >= yesterday) { - groups[1].chats.push(chat); - } else if (chat.createdTime >= lastWeek) { - groups[2].chats.push(chat); - } else { - groups[3].chats.push(chat); - } - } + room = signal(0); - return groups.filter(g => g.chats.length > 0); + splitWidth = computed(() => { + const room = this.room(); + return Math.min(AiAssistantPanelComponent.SPLIT_MAX, Math.floor(room / 2), room - AiAssistantPanelComponent.PAGE_MIN); }); - private aiChat = inject(AiChatService); - private dialog = inject(DialogService); - private translate = inject(TranslateService); - private matDialog = inject(MatDialog); - private store = inject(Store); - private destroyRef = inject(DestroyRef); - private sanitizer = inject(DomSanitizer); - private elementRef = inject(ElementRef); + splitAvailable = computed(() => this.room() > 0 && window.innerWidth > AiAssistantPanelComponent.SHEET_MAX_WINDOW + && this.splitWidth() >= AiAssistantPanelComponent.SPLIT_MIN); - private loadChat$ = new Subject(); - private cancelMessage$ = new Subject(); - private sessionAffectedEntities: EntityId[] = []; - private messageCancelled = false; - private resumeOnOpen = false; + split = computed(() => this.width() > this.maxWidth); - private static readonly RESUME_ATTEMPTS = 4; - private static readonly RESUME_DELAY_MS = 2000; + private wanted = this.defaultWidth; - private openEffect = effect(() => { - if (this.panelService.open()) { - this.dropChatFromOtherContext(); - this.loadChats(); - const chatId = untracked(() => this.chatId()); - if (this.resumeOnOpen && chatId) { - this.resumeOnOpen = false; - this.loadChat$.next(chatId); - } - } else { - this.slideDone.set(false); - this.suspendOnClose(); - } - }); + private panelWidth = this.defaultWidth; - private lastContextKey: string | null = null; + chatId = signal(undefined); - // Realign the open chat when the context changes in place while the panel stays open - // (e.g. switching between dashboards). List/entity toggles collapse to the same key, so they - // do not trigger this. Guarded on a non-null key to avoid reacting to teardown clearing context. - private contextSwitchEffect = effect(() => { - const key = this.panelService.contextKey(); - if (this.panelService.open() && this.lastContextKey !== null && key !== null && key !== this.lastContextKey) { - this.reset(); - this.loadChats(); - } - this.lastContextKey = key; - }); + private context = inject(AiAssistantContextService); - ngOnInit() { - this.loadChat$.pipe( - switchMap(id => this.aiChat.getChatMessages(id, {ignoreLoading: true, ignoreErrors: true}).pipe( - catchError(err => { - this.messages.set([]); - this.completedExecutions.set({}); - setTimeout(() => this.showErrorMessage(err), 0); - return EMPTY; - }) - )), - takeUntilDestroyed(this.destroyRef) - ).subscribe(messages => { - this.showHistory(messages); - this.resumeTurn(this.chatId()); - }); - } + clientContext = this.context.clientContext; - close(): void { - this.panelService.close(); - } + welcome = this.context.welcome; - // Credit subscription and focus wait for the slide so they do not stutter it. - onSlideEnd(event: TransitionEvent): void { - if (event.target !== this.elementRef.nativeElement || event.propertyName !== 'transform' || !this.isOpen) { - return; - } - this.slideDone.set(true); - this.promptInput?.focus(); - } + private chats = inject(AiChatsService); + private elementRef = inject(ElementRef); - onApprovalAction(event: ApprovalResult): void { - const chatId = this.chatId(); - if (event.autoApprove && chatId) { - this.panelService.setAutoApprove(chatId, true); - } - this.aiChat.resolveToolApproval( - {executionId: event.executionId, approved: event.approved}, - {ignoreLoading: true, ignoreErrors: true} - ).subscribe(); - } + private static readonly WIDTH_KEY = 'tbAiPanelWidth'; - setMenuWidth(triggerEl: MatButton): void { - const width = triggerEl._elementRef.nativeElement.offsetWidth; - document.documentElement.style.setProperty('--chat-menu-dynamic-width', `${width}px`); - } + private static readonly APPLIED_WIDTH_KEY = 'tb-ai-panel-applied-width'; - selectChat(chat: ChatInfo): void { - this.messageCancelled = true; - this.cancelMessage$.next(); - this.isCreatingNew.set(false); - this.chatId.set(chat.id); - this.panelService.setLastChatId(chat.id); - this.loadChat$.next(chat.id); - } + private lastContextKey: string | null = null; - useExample(example: AiAssistantPromptExample): void { - this.promptInput?.setValue(example.message); - } + private dockedEffect = effect(onCleanup => { + const docked = this.panelService.open() && !this.panelService.suppressed(); + document.documentElement.classList.toggle('tb-ai-docked', docked); + onCleanup(() => document.documentElement.classList.remove('tb-ai-docked')); + }); - sendMsgFromUser(prompt: AiPromptMessage): void { - const userMessage: ChatMessage = prompt.resources.length - ? {from: 'USER', content: prompt.message, resources: prompt.resources} - : {from: 'USER', content: prompt.message}; - this.messages.update(list => [...list, userMessage]); - this.sendMessage(prompt).subscribe({ - error: (err) => { - if (this.isConnectionLost(err) && this.chatId()) { - this.showErrorToast(this.translate.instant('ai-assistant.connection-lost')); - this.resumeTurn(this.chatId(), true); - return; - } - this.messages.update(list => list.filter(message => message !== userMessage)); - setTimeout(() => { - this.showErrorMessage(err); - }, 0); - }, - complete: () => { - if (!this.messageCancelled && this.sessionAffectedEntities.length) { - this.panelService.emitUpdatedData(this.sessionAffectedEntities); - } + private wasOpen = false; + + private openEffect = effect(() => { + const open = this.panelService.open(); + const composed = this.panelService.composed(); + untracked(() => { + const opened = open && !this.wasOpen; + this.wasOpen = open; + if (!open) { + return; + } + if (composed) { + this.startComposed(this.panelService.takeComposed(), opened); + } else if (opened) { + this.restoreChat(); } }); - } + }); - reset(createNew?: boolean): void { - this.cancelActiveMessage(); - this.isCreatingNew.set(!!createNew); + private startComposed(text: string, opened: boolean): void { + this.chat?.keepDraftForCompose(); this.chatId.set(undefined); - this.messages.set([]); - } - - private cancelActiveMessage(): void { - this.messageCancelled = true; - this.cancelMessage$.next(); - this.stopLoadingState(); - this.promptInput?.reset(); - } - - // Keeps the open chat so reopening shows it right away. A reply interrupted by closing keeps running on the - // server, so reopening reloads the chat and follows that reply. - private suspendOnClose(): void { - this.resumeOnOpen = this.loading(); - this.cancelActiveMessage(); - } - - private dropChatFromOtherContext(): void { - const chatId = this.chatId(); - if (chatId && chatId !== this.panelService.lastChatIdForContext()) { - this.reset(); + if (opened) { + this.chats.load().subscribe(); } + setTimeout(() => this.chat?.composeText(text), AiAssistantPanelComponent.COMPOSE_DELAY_MS); } - renameChat(): void { - const chatId = this.chatId(); - if (!chatId) return; - this.matDialog.open(AiRenameDialogComponent, { - disableClose: true, - panelClass: ['tb-dialog', 'tb-fullscreen-dialog'], - data: { - title: this.translate.instant('ai-assistant.rename-chat-title'), - value: this.selectedChatTitle() || this.translate.instant('ai-assistant.new-chat') - } - }).afterClosed().subscribe(newTitle => { - if (newTitle && newTitle !== this.selectedChatTitle()) { - this.aiChat.updatedChat(chatId, {title: newTitle}, {ignoreLoading: true, ignoreErrors: true}).subscribe({ - next: () => { - this.panelService.updateChatTitle(chatId, newTitle); - }, - error: (err) => { - this.showErrorMessage(err); - } - }); - } - }); - } - - deleteChat(): void { - const chatId = this.chatId(); - if (!chatId) return; - const chatTitle = this.selectedChatTitle() || this.translate.instant('ai-assistant.new-chat'); - this.dialog.confirm( - this.translate.instant('ai-assistant.delete-chat-title', {name: chatTitle}), - this.translate.instant('ai-assistant.delete-chat-text'), - this.translate.instant('action.no'), - this.translate.instant('ai-assistant.delete-chat-confirm') - ).subscribe(value => { - if (value) { - this.aiChat.deleteChat(chatId, {ignoreLoading: true, ignoreErrors: true}).subscribe(() => { - this.panelService.removeChat(chatId); - this.reset(); - }); + private restoreChat(): void { + const carried = this.panelService.hasCarriedChat(); + if (!carried) { + this.dropChatFromOtherContext(); + } + this.chats.load().subscribe(() => { + if (carried) { + const chatId = this.panelService.takeCarriedChat(); + if (chatId && this.chats.find(chatId)) { + this.chatId.set(chatId); + return; + } } + this.selectLastChat(); }); } - private loadChats(): void { - const chats = this.panelService.chats(); - if (chats !== null) { - this.selectLastChat(chats); - return; + private contextSwitchEffect = effect(() => { + const key = this.panelService.contextKey(); + if (this.panelService.open() && this.lastContextKey !== null && key !== null && key !== this.lastContextKey) { + untracked(() => { + const carried = this.panelService.takeCarriedChat(); + if (carried && carried === this.chatId()) { + return; + } + this.chatId.set(undefined); + this.selectLastChat(); + }); } - this.aiChat.listChats({ignoreLoading: true, ignoreErrors: true}).subscribe(chats => { - this.panelService.setChats(chats); - this.selectLastChat(chats); - }); - } + this.lastContextKey = key; + }); - private selectLastChat(chats: ChatInfo[]): void { - if (!this.chatId() && !this.isCreatingNew()) { - const lastId = this.panelService.lastChatIdForContext(); - const lastChat = lastId ? chats.find(c => c.id === lastId) : null; - if (lastChat) { - this.selectChat(lastChat); - } + constructor() { + let stored = 0; + stored = Number(readStored(AiAssistantPanelComponent.WIDTH_KEY)) || 0; + this.wanted = stored || this.defaultWidth; + this.panelWidth = Math.min(this.wanted, this.maxWidth); + let applied = 0; + try { + applied = Number(sessionStorage.getItem(AiAssistantPanelComponent.APPLIED_WIDTH_KEY)) || 0; + } catch { + applied = 0; + } + if (applied) { + this.width.set(applied); + document.documentElement.style.setProperty('--tb-ai-panel-w', applied + 'px'); } + setTimeout(() => this.fit()); } - private sendMessage(prompt: AiPromptMessage): Observable { - this.initLoadingState(); - this.sessionAffectedEntities = []; - this.messageCancelled = false; + fit(): void { + this.room.set(this.elementRef.nativeElement.parentElement?.clientWidth ?? window.innerWidth); + this.show(this.wanted); + } - const startOrContinue$ = this.chatId() - ? of(null) - : this.aiChat.createChat({title: 'New chat'}, {ignoreLoading: true, ignoreErrors: true}).pipe( - tap(chatId => { - this.isCreatingNew.set(false); - this.chatId.set(chatId); - this.panelService.setLastChatId(chatId); - this.panelService.addChat({id: chatId, title: 'New chat', createdTime: Date.now()}); - }) - ); - - const request: SendChatMessageRequest = { - message: prompt.message, - clientContext: this.resolveClientContextToSend() - }; - if (prompt.resources.length) { - request.resources = prompt.resources.map(resource => resource.id); + toggleSplit(): void { + if (this.split()) { + this.setWidth(this.panelWidth, true); + } else if (this.splitAvailable()) { + this.panelWidth = this.width(); + this.setWidth(this.splitWidth(), true); } + } - return startOrContinue$.pipe( - switchMap(() => this.aiChat.sendChatMessage(this.chatId(), request, {ignoreLoading: true, ignoreErrors: true})), - tap(() => { - if (request.clientContext) { - this.panelService.markClientContextSent(this.chatId(), request.clientContext); - } - }), - takeUntil(this.cancelMessage$), - concatMap(chatMsg => this.handleChatEvent(chatMsg)), - finalize(() => this.stopLoadingState()) - ); + private widest(): number { + return this.splitAvailable() ? this.splitWidth() : Math.min(this.maxWidth, Math.max(this.minWidth, Math.round(this.room() / 2) || this.maxWidth)); } - private resolveClientContextToSend(): AiChatClientContext | undefined { - const currentContext = this.panelService.clientContext(); - if (!currentContext) { - return undefined; + private show(width: number): number { + const value = Math.round(Math.min(this.widest(), Math.max(this.minWidth, width))); + this.width.set(value); + document.documentElement.style.setProperty('--tb-ai-panel-w', value + 'px'); + try { + sessionStorage.setItem(AiAssistantPanelComponent.APPLIED_WIDTH_KEY, String(value)); + } catch { + return value; } - const chatId = this.chatId(); - const alreadySent = chatId ? this.panelService.getSentClientContext(chatId) : undefined; - return (!chatId || !isEqual(currentContext, alreadySent)) ? currentContext : undefined; + return value; } - private showHistory(messages: ChatMessage[]): void { - const completed: Record = {}; - for (const message of messages) { - if (message.from === 'APPROVAL' && (message as ApprovalChatMessage).result) { - const result = (message as ApprovalChatMessage).result; - completed[result.executionId] = result; + setWidth(width: number, keep = false): void { + this.room.set(this.elementRef.nativeElement.parentElement?.clientWidth ?? window.innerWidth); + const value = this.show(width); + if (keep) { + this.wanted = value; + if (value <= this.maxWidth) { + this.panelWidth = value; } + writeStored(AiAssistantPanelComponent.WIDTH_KEY, value === this.defaultWidth ? null : String(value)); } - this.completedExecutions.set(completed); - this.messages.set(messages); } - // Follows the reply still running in the chat, if any: after a reload, a reopened panel or a lost connection. - // The server replays the whole reply, so what the history already shows of it is dropped first. - private resumeTurn(chatId: string, afterConnectionLoss = false): void { - if (!chatId) { - return; + onGripKey(event: KeyboardEvent): void { + if (event.key === 'ArrowLeft' || event.key === 'ArrowRight') { + event.preventDefault(); + this.setWidth(this.width() + (event.key === 'ArrowLeft' ? 16 : -16), true); + } else if (event.key === 'Home' || event.key === 'End') { + event.preventDefault(); + this.setWidth(event.key === 'Home' ? this.widest() : this.minWidth, true); } - let resumed = false; - this.messageCancelled = false; - this.sessionAffectedEntities = []; - const attempt$ = timer(afterConnectionLoss ? AiAssistantPanelComponent.RESUME_DELAY_MS : 0).pipe( - tap(() => { - if (afterConnectionLoss) { - this.initLoadingState(); - } - }), - switchMap(() => this.aiChat.resumeChat(chatId, {ignoreLoading: true, ignoreErrors: true})) - ); - attempt$.pipe( - retry({ - count: afterConnectionLoss ? AiAssistantPanelComponent.RESUME_ATTEMPTS : 0, - delay: (error, attempt) => this.isConnectionLost(error) - ? timer(attempt * AiAssistantPanelComponent.RESUME_DELAY_MS) - : throwError(() => error) - }), - takeUntil(this.cancelMessage$), - concatMap(event => { - if (event.event === 'turnResumed') { - resumed = true; - this.initLoadingState(); - this.dropRunningReply(); - return of(event); - } - return this.handleChatEvent(event); - }), - finalize(() => { - if (resumed || afterConnectionLoss) { - this.stopLoadingState(); - } - }) - ).subscribe({ - error: () => { - if (afterConnectionLoss) { - this.showErrorToast(this.translate.instant('ai-assistant.reconnect-failed')); - } - }, - complete: () => { - if (this.messageCancelled || this.chatId() !== chatId) { - return; - } - if (this.sessionAffectedEntities.length) { - this.panelService.emitUpdatedData(this.sessionAffectedEntities); - } - if (resumed || afterConnectionLoss) { - this.aiChat.getChatMessages(chatId, {ignoreLoading: true, ignoreErrors: true}) - .pipe(takeUntil(this.cancelMessage$)) - .subscribe(messages => this.showHistory(messages)); - } - } - }); } - private dropRunningReply(): void { - this.messages.update(list => { - const lastUser = list.map(message => message.from).lastIndexOf('USER'); - return lastUser >= 0 ? list.slice(0, lastUser + 1) : list; - }); - } - - private isConnectionLost(error: any): boolean { - return error instanceof HttpErrorResponse && error.status === 0; - } - - private handleChatEvent(chatMsg: ChatEvent): Observable { - switch (chatMsg.event) { - case 'assistantMessage': - this.messages.update(list => [...list, {from: 'AI', content: chatMsg.data.message}]); - return of(chatMsg); - case 'toolExecutionRequested': - return this.handleToolApproval(chatMsg); - case 'toolExecutionResult': - this.completedExecutions.update(map => ({...map, [chatMsg.data.executionId]: chatMsg.data})); - if (chatMsg.data.affectedEntities?.length) { - this.sessionAffectedEntities.push(...chatMsg.data.affectedEntities); + startResize(event: PointerEvent): void { + event.preventDefault(); + this.gripTip?.hide(0); + this.resizing.set(true); + const grip = event.target as HTMLElement; + const host = this.elementRef.nativeElement as HTMLElement; + const root = document.documentElement; + const startX = event.clientX; + const startWidth = this.width(); + this.room.set(host.parentElement?.clientWidth ?? window.innerWidth); + const widest = this.widest(); + let current = startWidth; + let closing = false; + let frame = 0; + let pageTimer: ReturnType | undefined; + let pageAt = 0; + const reflowPage = () => { + pageTimer = undefined; + pageAt = performance.now(); + root.style.setProperty('--tb-ai-panel-w', current + 'px'); + }; + const paint = () => { + frame = 0; + host.style.width = current + 'px'; + if (!pageTimer) { + pageTimer = setTimeout(reflowPage, Math.max(0, AiAssistantPanelComponent.PAGE_REFLOW_MS - (performance.now() - pageAt))); + } + }; + grip.setPointerCapture(event.pointerId); + document.body.classList.add('tb-ai-resizing'); + this.zone.runOutsideAngular(() => { + const move = (e: PointerEvent) => { + const wanted = startWidth + (startX - e.clientX); + const past = wanted < this.minWidth - AiAssistantPanelComponent.CLOSE_PAST; + if (past !== closing) { + closing = past; + host.classList.toggle('closing', past); } - return of(chatMsg); - case 'chatTitleGenerated': - this.handleChatTitleGenerated(chatMsg); - return of(chatMsg); - default: - if (chatMsg.event === 'error') { - this.showErrorToast(this.sanitizer.sanitize(SecurityContext.HTML, chatMsg.data?.message) ?? chatMsg.data?.message); + current = Math.round(Math.min(widest, Math.max(this.minWidth, wanted))); + if (!frame) { + frame = requestAnimationFrame(paint); } - return of(chatMsg); - } + }; + const up = () => { + grip.removeEventListener('pointermove', move); + grip.removeEventListener('pointerup', up); + grip.removeEventListener('pointercancel', up); + cancelAnimationFrame(frame); + clearTimeout(pageTimer); + document.body.classList.remove('tb-ai-resizing'); + host.classList.remove('closing'); + host.style.width = ''; + this.zone.run(() => { + this.resizing.set(false); + if (closing) { + this.setWidth(startWidth); + this.close(); + return; + } + this.setWidth(current, current !== startWidth); + }); + }; + grip.addEventListener('pointermove', move); + grip.addEventListener('pointerup', up); + grip.addEventListener('pointercancel', up); + }); } - private handleChatTitleGenerated(chatMsg: ChatTitleGeneratedEvent): void { - const chatId = this.chatId(); - const title = chatMsg.data.title; - if (!chatId || !title) return; - this.panelService.updateChatTitle(chatId, title); + close(): void { + this.panelService.close(); } - private handleToolApproval(chatMsg: ToolExecutionRequestedEvent): Observable { - if (!chatMsg.data.needsApproval) { - return of(chatMsg); + onClick(event: MouseEvent): void { + const chatId = this.chatId(); + const link = (event.target as HTMLElement | null)?.closest?.('a[href]') as HTMLAnchorElement | null; + if (!chatId || !link || link.target === '_blank' || link.origin !== window.location.origin + || event.button !== 0 || event.metaKey || event.ctrlKey || event.shiftKey || event.altKey) { + return; } - this.messages.update(list => [...list, {from: 'APPROVAL', data: chatMsg.data}]); - return of(chatMsg); + this.panelService.carryChat(chatId); } - private initLoadingState(): void { - this.loading.set(true); + onChatId(chatId: string | undefined): void { + this.chatId.set(chatId); + this.panelService.setLastChatId(chatId); } - private stopLoadingState(): void { - this.loading.set(false); + onSlideEnd(event: TransitionEvent): void { + if (event.target !== this.elementRef.nativeElement || event.propertyName !== 'transform' || !this.isOpen) { + return; + } + this.chat?.focus(); } - showErrorMessage(error: any): void { - const responseType = isNotEmptyStr(error?.error) ? 'text' : undefined; - const message = parseHttpErrorMessage(error, this.translate, responseType, this.sanitizer).message; - this.showErrorToast(message); + private dropChatFromOtherContext(): void { + const chatId = this.chatId(); + if (chatId && chatId !== this.panelService.lastChatIdForContext()) { + this.chatId.set(undefined); + } } - private showErrorToast(message: string): void { - this.store.dispatch(new ActionNotificationShow({ - message, - target: 'aiAssistant', - modern: true, - type: 'error', - verticalPosition: 'bottom', - horizontalPosition: 'center' - })); + private selectLastChat(): void { + if (this.chatId()) { + return; + } + const carried = this.panelService.takeCarriedChat(); + if (carried && this.chats.find(carried)) { + this.chatId.set(carried); + return; + } + const lastId = this.panelService.lastChatIdForContext(); + if (lastId && this.chats.find(lastId)) { + this.chatId.set(lastId); + } } } diff --git a/ui-ngx/src/app/modules/home/components/ai/ai-attachment-preview-dialog.component.html b/ui-ngx/src/app/modules/home/components/ai/ai-attachment-preview-dialog.component.html index e81e8a2cf7..2b89549dd6 100644 --- a/ui-ngx/src/app/modules/home/components/ai/ai-attachment-preview-dialog.component.html +++ b/ui-ngx/src/app/modules/home/components/ai/ai-attachment-preview-dialog.component.html @@ -5,12 +5,23 @@ --> -

{{ data.resource.name }}

+

{{ title }}

- + @if (data.downloadPng) { + + + + + + } @else { + + }
+ + {{ fileName(item.resource.name).base }}{{ fileName(item.resource.name).ext }} + @if (!item.image && item.extension) { {{ item.extension }} · }{{ factOf(item) ?? (item.resource.size | fileSize) }} + + }
diff --git a/ui-ngx/src/app/modules/home/components/ai/ai-attachments.component.scss b/ui-ngx/src/app/modules/home/components/ai/ai-attachments.component.scss index 9da645eb8a..0d9b0dcfcd 100644 --- a/ui-ngx/src/app/modules/home/components/ai/ai-attachments.component.scss +++ b/ui-ngx/src/app/modules/home/components/ai/ai-attachments.component.scss @@ -2,100 +2,84 @@ // SPDX-License-Identifier: BUSL-1.1 :host { display: block; - max-width: 100%; - - .attachments { - display: flex; - flex-wrap: wrap; - gap: 8px; - justify-content: inherit; - } - - .attachment { - position: relative; - display: flex; - align-items: center; - border-radius: 10px; - border: 1px solid rgba(0, 0, 0, 0.12); - background: #fff; - overflow: hidden; - flex: none; - cursor: pointer; - - &:hover { - border-color: var(--tb-primary-500); - } +} - &.image { - width: 64px; - height: 64px; - justify-content: center; - background: rgba(0, 0, 0, 0.04); +.k-files { + display: flex; + flex-wrap: wrap; + justify-content: flex-end; + gap: 6px; + font-size: 14px; + line-height: 20px; + color: var(--tb-ink); +} - img { - width: 100%; - height: 100%; - object-fit: cover; - } +.k-file { + display: flex; + align-items: center; + gap: 10px; + max-width: 100%; + min-width: 0; + padding: 6px 10px 6px 8px; + border: 1px solid var(--tb-line); + border-radius: 8px; + background: var(--tb-surface); + font: 400 13.5px/20px var(--tb-font); + letter-spacing: var(--chat-text-ls); + color: var(--tb-ink); + text-align: left; + cursor: pointer; - .placeholder { - color: rgba(0, 0, 0, 0.38); - } - } + &:hover { + border-color: rgba(0, 0, 0, 0.2); + } - &.file { - gap: 8px; - height: 48px; - max-width: 220px; - padding: 0 12px 0 8px; + &:focus-visible { + outline: 2px solid var(--ai-focus); + outline-offset: 1px; + } - .file-icon { - display: flex; - align-items: center; - justify-content: center; - flex: none; - width: 32px; - height: 32px; - border-radius: 8px; - color: var(--tb-primary-500); - position: relative; + > .mat-icon { + flex: none; + color: var(--tb-ink-54); + } +} - &:before { - content: ""; - position: absolute; - inset: 0; - border-radius: inherit; - background: var(--tb-primary-500); - opacity: 0.1; - } +.k-file-pic { + flex: none; + width: 32px; + height: 32px; + overflow: hidden; + border-radius: 6px; + background: linear-gradient(135deg, #cfd8dc, #90a4ae); + box-shadow: inset 0 0 0 1px rgba(0, 0, 0, 0.06); - mat-icon { - font-size: 20px; - width: 20px; - height: 20px; - } - } + img { + display: block; + width: 100%; + height: 100%; + object-fit: cover; + } +} - .file-meta { - display: flex; - flex-direction: column; - min-width: 0; - line-height: 16px; +.k-file-text { + display: flex; + flex-direction: column; + min-width: 0; - .file-name { - font-size: 13px; - color: rgba(0, 0, 0, 0.87); - white-space: nowrap; - overflow: hidden; - text-overflow: ellipsis; - } + b { + max-width: 240px; + overflow: hidden; + font-size: 13.5px; + line-height: 18px; + font-weight: 500; + text-overflow: ellipsis; + white-space: nowrap; + } - .file-info { - font-size: 11px; - color: rgba(0, 0, 0, 0.54); - white-space: nowrap; - } - } - } + small { + font-size: 12px; + line-height: 16px; + color: var(--tb-ink-76); } } diff --git a/ui-ngx/src/app/modules/home/components/ai/ai-attachments.component.ts b/ui-ngx/src/app/modules/home/components/ai/ai-attachments.component.ts index 86db1c6232..7ceb5185ef 100644 --- a/ui-ngx/src/app/modules/home/components/ai/ai-attachments.component.ts +++ b/ui-ngx/src/app/modules/home/components/ai/ai-attachments.component.ts @@ -1,12 +1,14 @@ // SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. // SPDX-License-Identifier: BUSL-1.1 +import { aiFileName } from '@home/components/ai/ai-file.models'; import { Component, EventEmitter, Input, OnChanges, Output, SimpleChanges } from '@angular/core'; import { MatDialog } from '@angular/material/dialog'; import { Observable } from 'rxjs'; import { catchError } from 'rxjs/operators'; import { AiResourceInfo, isAiImageResource } from '@shared/models/ai-chat.models'; import { AiResourceService } from '@core/http/ai-resource.service'; -import { aiAttachmentExtension, aiAttachmentKind } from '@home/components/ai/ai-attachment.models'; +import { aiAttachmentExtension, aiAttachmentKind, aiResourceFact } from '@home/components/ai/ai-attachment.models'; +import { TranslateService } from '@ngx-translate/core'; import { AiAttachmentPreviewDialogComponent, AiAttachmentPreviewDialogData @@ -28,14 +30,21 @@ interface AiAttachmentItem { }) export class AiAttachmentsComponent implements OnChanges { + readonly fileName = aiFileName; + @Input() resources: AiResourceInfo[]; @Output() resourceError = new EventEmitter(); shown: AiAttachmentItem[] = []; + factOf(item: AiAttachmentItem): string | null { + return item.image ? null : aiResourceFact(item.resource.facts, this.translateService); + } + constructor(private aiResourceService: AiResourceService, - private dialog: MatDialog) { + private dialog: MatDialog, + private translateService: TranslateService) { } ngOnChanges(changes: SimpleChanges): void { diff --git a/ui-ngx/src/app/modules/home/components/ai/ai-breakpoints.ts b/ui-ngx/src/app/modules/home/components/ai/ai-breakpoints.ts new file mode 100644 index 0000000000..25163607eb --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/ai/ai-breakpoints.ts @@ -0,0 +1,5 @@ +// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: BUSL-1.1 + +// The chat head is narrow below this width (px); the CSS breakpoints of the AI chat are in _ai-breakpoints.scss. +export const AI_NARROW_HEAD_WIDTH = 500; diff --git a/ui-ngx/src/app/modules/home/components/ai/ai-card-actions.component.ts b/ui-ngx/src/app/modules/home/components/ai/ai-card-actions.component.ts new file mode 100644 index 0000000000..fa7b749311 --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/ai/ai-card-actions.component.ts @@ -0,0 +1,52 @@ +// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: BUSL-1.1 +import { ChangeDetectionStrategy, Component, input, output } from '@angular/core'; + +export interface AiCardAction { + id: string; + label: string; + icon?: string; + quiet?: boolean; + compose?: string; + pressed?: boolean; + tip?: string; +} + +@Component({ + selector: 'tb-ai-card-actions', + template: ` + @for (action of actions(); track action.id) { + + } + `, + standalone: false, + changeDetection: ChangeDetectionStrategy.OnPush, + host: { + 'class': 'k-chips', + 'role': 'group' + } +}) +export class AiCardActionsComponent { + + actions = input.required(); + + act = output(); + + compose = output(); + + press(action: AiCardAction): void { + if (action.compose) { + this.compose.emit(action.compose); + } else { + this.act.emit(action.id); + } + } +} diff --git a/ui-ngx/src/app/modules/home/components/ai/ai-chat-messages.component.html b/ui-ngx/src/app/modules/home/components/ai/ai-chat-messages.component.html index 7fd251f846..59a674dcf7 100644 --- a/ui-ngx/src/app/modules/home/components/ai/ai-chat-messages.component.html +++ b/ui-ngx/src/app/modules/home/components/ai/ai-chat-messages.component.html @@ -5,47 +5,339 @@ --> @for (msg of messages; track $index) { - @if (msg.from === 'USER') { + @if (dayLines[$index]; as day) { + + } + @if (msg.from === 'USER' && (msg.answers?.length || answersAt[$index])) { + + } @else if (msg.from === 'USER') { + @if (msg.startedFrom) { + + }
- @if (msg.resources?.length) { - - } - @if (msg.content) { -
{{ msg.content }}
+
+ @if (quotes[$index]; as quoted) { + + + {{ fileName(quoted.name).base }}{{ fileName(quoted.name).ext }}{{ (quoted.from === quoted.to ? 'ai-assistant.file.line' : 'ai-assistant.file.lines-range') | translate: {from: quoted.from, to: quoted.to} }} + + } + @if (quotes[$index] ? quotes[$index].message : msg.content; as words) { +
{{ words }}
+ @if (isFolded($index, words)) { + + } + } + @if (msg.resources?.length) { + + } +
+
+ @if (msg.content) { + + + + + } + @if (msg.time) { + + } +
+
+ } @else if (msg.from === 'ACTION' && files[$index] && inCard.has(files[$index].name)) { + } @else if (msg.from === 'ACTION' && files[$index]; as file) { +
+ +
+ } @else if (msg.from === 'ACTION' && madeFiles[$index]?.preview === 'image') { + @let pic = madeFiles[$index]; +
+ +
+ } @else if (msg.from === 'ACTION' && madeFiles[$index]; as made) { +
+
+ + +
+
+ } @else if (msg.from === 'ACTION' && plans[$index]; as plan) { +
+ +
+ } @else if (msg.from === 'ACTION' && handOvers[$index]; as card) { +
+ +
+ @if (waitAfterCard[$index] !== undefined && messages[waitAfterCard[$index]]; as moved) { + @if (moved.from === 'ACTION' && !waitsInCards.has(waitAfterCard[$index])) { +
+ +
} + } + } @else if (msg.from === 'ACTION' && asking?.index === $index) { +
+
+ } @else if (msg.from === 'ACTION') { + @if (isListedAction(msg, $index) && !groupedAway.has($index) && (msg.data.status !== 'RUNNING' || $index === runningLead)) { +
+ + @if ($index === retryIndex) { +
+ } +
+
+ } } @else { -
+ @if ($index === offerIndex) { +
+
+ + {{ 'ai-assistant.offer.text' | translate }} + +
+
+ } +
@if (msg.from === 'APPROVAL') { + [answered]="!!denyReasons[getApprovalData(msg).executionId]" + [busy]="loading" + (approvalAction)="approval($event)" + (answerLater)="answerLater.emit($event)"> - } @else if (msg.status === 'INCOMPLETE') { -
- warning_amber - {{ msg.content }} -
+ } @else if (msg.status === 'RETRIED' || msg.status === 'RESUMED') { +

{{ (msg.status === 'RETRIED' ? 'ai-assistant.failed.tried-again' : 'ai-assistant.failed.resumed') | translate: {time: clockText(msg.time)} }}

+ } @else if (msg.status === 'INCOMPLETE' || msg.status === 'STOPPED') { + @if (msg.status === 'INCOMPLETE') { +
+

{{ 'ai-assistant.failed.headline' | translate }} {{ failText($index, msg) }}

+ @if ($last && !loading && retry.observed) { +
+ } +
+ } @else { +

{{ stoppedText($index, msg.content) }}

+ } + @if (summaries[$index]; as entities) { + + } + @if (msg.status === 'STOPPED' && $last && !loading) { + @if (msg.chips?.length) { + + } @else { + + } + } } @else { - +
+ @if (msg.done) { + + } +
+ @if (msg.lead) { +

{{ msg.lead }}

+ } + @for (key of [decorationKey(msg)]; track key) { + + } + @let madeHere = made[$index] ?? []; + @for (shown of records[$index] ?? []; track $index) { + + } + @if (summaries[$index]; as entities) { + + } + @if (msg.entities?.length) { + + } + @if (msg.hint; as hint) { +
+ + {{ hint.lead }} {{ hint.text }} +
+ } +
+
+ @if (msg.note) { +

{{ msg.note }}

+ } + @if (sources[$index]; as cited) { +
+ @for (source of cited; track source.url) { +
+
+ + + +
+ @if (source.quote) { +
{{ source.quote }}
+ } +
+ } +
+ } + @if (!msg.streaming) { +
+ @if (msg.time) { + + } + + + @if (feedback) { + + + + } + +
+ } + @if (prompts?.index === $index) { +
+ @for (option of prompts.items; track $index) { + + } +
+ } + @if (msg.chips?.length) { + + } + @if (reportingIndex === $index) { +
+
{{ 'ai-assistant.feedback.what-went-wrong' | translate }}
+
+ @for (problem of problems; track problem) { + + } +
+ +

{{ 'ai-assistant.feedback.sent-with' | translate }}

+
+ + +
+
+ } }
+ @if (msg.from === 'APPROVAL' && denyReasonOf(msg); as reason) { +
+
{{ reason }}
+
+ } } } -@if (loading && !waitApproval) { -
- @if (loadingLongTime) { - +@if (dock && dockVisible) { +
+
+ + @if (dock.kind === 'hand' && dock.state !== 'stopped') {{{ 'ai-assistant.plan.you' | translate }}}{{ dock.text }} + @if (dock.count) { + {{ dock.count }} + } + @if (dock.kind === 'hand' && dock.state === 'listen' && dock.canTest) { + + } + @if (dock.kind === 'hand' && dock.state === 'stopped' && !loading) { + + } + +
+
+} +@if (loading && !waitApproval && !actionRunning && !streaming) { +
+ @if (work) { + } @else { - - - +
{{ 'ai-assistant.thinking' | translate }}
}
} + + + + diff --git a/ui-ngx/src/app/modules/home/components/ai/ai-chat-messages.component.scss b/ui-ngx/src/app/modules/home/components/ai/ai-chat-messages.component.scss index c9b42e734e..5583c127d2 100644 --- a/ui-ngx/src/app/modules/home/components/ai/ai-chat-messages.component.scss +++ b/ui-ngx/src/app/modules/home/components/ai/ai-chat-messages.component.scss @@ -1,94 +1,316 @@ // SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. // SPDX-License-Identifier: BUSL-1.1 +@use './ai-code-blocks' as *; + :host { display: flex; flex-direction: column; - gap: 24px; + gap: var(--chat-turn-gap); overflow: auto; + font-family: var(--tb-font); + font-size: var(--chat-text); + line-height: var(--chat-text-lh); + letter-spacing: var(--chat-text-ls); + color: var(--tb-ink); width: 100%; margin-top: 8px; flex: 1 1 auto; - .image-main-color { - color: var(--tb-primary-500); - } - .user { display: flex; flex-direction: column; align-items: flex-end; gap: 6px; - .user-attachments { - max-width: 80%; + .turn { + display: grid; + justify-items: end; + gap: 6px; + max-width: 85%; + font-size: 14px; + line-height: 20px; - ::ng-deep .attachments { - justify-content: flex-end; + tb-ai-attachments { + margin-top: 8px; + } - .attachment.image { - width: 120px; - height: 90px; - } + @container k-chat (max-width: 599px) { + max-width: 88%; + } + + .msg { + max-width: none; + font-size: var(--chat-text); + line-height: var(--chat-text-lh); } } + .msg .words { + display: block; + white-space: pre-line; + } + + .msg.folded .words { + display: block; + max-height: calc(6 * var(--chat-text-lh)); + overflow: hidden; + mask-image: linear-gradient(to bottom, #000 calc(100% - var(--chat-text-lh)), transparent); + } + + .show-all { + margin: 0; + } + .msg { - max-width: 80%; - padding: 10px 18px; - border-radius: 12px 12px 0 12px; - position: relative; + max-width: 85%; + padding: 12px 16px; + border-radius: 16px 16px 4px 16px; + background: var(--ai-person); overflow: hidden; - white-space: pre-line; - word-break: break-word; - line-height: 24px; - color: rgba(0, 0, 0, 0.76); + overflow-wrap: anywhere; - &:before { - display: block; - height: auto; - content: ""; - position: absolute; - inset: 0; - background: var(--tb-primary-500); - opacity: 0.1; - pointer-events: none; + @container k-chat (max-width: 599px) { + max-width: 88%; + padding: 10px 14px; } + color: var(--tb-ink); + } + } + + .msg-foot { + display: flex; + align-items: center; + gap: 2px; + min-height: 24px; + margin-top: 0; + font-size: var(--chat-caption); + line-height: var(--chat-caption-lh); + color: var(--k-faint); + font-variant-numeric: tabular-nums; + + &.agent-foot { + margin-top: 0; + } + + time { + margin-right: 6px; + } + } + + .foot-tools { + display: inline-flex; + align-items: center; + gap: 2px; + opacity: 0; + transition: opacity .12s ease; + + &.show { + opacity: 1; + } + + @media (prefers-reduced-motion: reduce) { + transition: none; } } - .incomplete { - padding: 10px 14px; + .user-foot { + justify-content: flex-end; + + time { + order: 2; + } + } + + .k-day { + display: flex; + align-items: center; + gap: 12px; + font-size: 12px; + line-height: 16px; + letter-spacing: .25px; + color: var(--tb-ink-54); + + &::before, &::after { + content: ''; + flex: 1 1 0%; + height: 1px; + background: var(--tb-line); + } + } + + .user:hover .foot-tools, .user:focus-within .foot-tools, + .ai:hover .foot-tools, .ai:focus-within .foot-tools { + opacity: 1; + } + + .foot-tool { + font-size: 12px; + display: inline-flex; + align-items: center; + justify-content: center; + width: 24px; + height: 24px; + padding: 0; + border: 0; + border-radius: 6px; + background: none; + color: var(--tb-ink-54); + cursor: pointer; + + &:hover { + background: rgba(0, 0, 0, 0.05); + color: var(--tb-ink); + } + + &:focus-visible { + outline: 2px solid var(--ai-focus); + outline-offset: 1px; + } + + &.done { + color: var(--tb-ok); + } + + &[aria-pressed="true"] { + color: var(--ai-selected); + } + + &.muted:not([aria-pressed="true"]) { + color: var(--tb-ink-38); + } + + &:disabled { + cursor: default; + background: none; + } + } + + .k-report { + display: grid; + gap: 10px; + max-width: 560px; + margin-top: 8px; + padding: 14px 16px; + border: 1px solid var(--tb-line); border-radius: 12px; - line-height: 20px; - color: rgba(0, 0, 0, 0.76); - background: rgba(255, 152, 0, 0.08); + background: var(--tb-surface); + + .k-report-t { + font: 500 var(--chat-line)/var(--chat-line-lh) var(--tb-font); + color: var(--tb-ink); + } + + .k-chips { + gap: 6px; + } - .incomplete-icon { - flex: none; - color: #FF9800; - font-size: 20px; - width: 20px; - height: 20px; + .k-report-note { + margin: 0; + font-size: var(--chat-meta); + line-height: var(--chat-meta-lh); + color: var(--k-faint); } + + .k-actions { + margin-top: 0; + } + } + + .agent { + display: block; + + .agent-body { + min-width: 0; + } + + &.done { + display: flex; + align-items: flex-start; + gap: 8px; + + > .done-mark { + flex: none; + margin-top: 2px; + font-size: 20px; + width: 20px; + height: 20px; + line-height: 20px; + color: var(--tb-ok-text); + } + + > .agent-body { + flex: 1; + } + } + + .lead { + margin: 0 0 14px; + font-size: var(--chat-text); + line-height: var(--chat-text-lh); + letter-spacing: var(--chat-text-ls); + font-weight: 500; + color: var(--tb-ink); + } + } + + .agent-card { + display: block; + margin-top: 12px; + } + + .agent-hint { + margin: 12px 0 4px; + } + + .agent-chips { + margin-top: 8px; + } + + .agent-note { + margin: 14px 0 4px; + letter-spacing: .25px; + font-size: var(--chat-line); + line-height: var(--chat-line-lh); + color: var(--k-grey); + } + + .stop-note { + margin: 0; + font-size: var(--chat-line); + line-height: var(--chat-line-lh); + color: var(--tb-ink); + } + + .ai.action + .ai.action { + margin-top: calc(6px - var(--chat-turn-gap)); } .generating { + gap: 10px; + + .work { + flex: 1; + min-width: 0; + } + + .tb-ai-mark { + --m: var(--chat-mark); + } + + font-size: var(--chat-line); + line-height: var(--chat-line-lh); transition: all 0.3s ease-in-out; .glow-container { color: transparent; overflow: hidden; position: relative; - background: linear-gradient(90deg, #3D3D3D -40.76%, #808080 -23.64%, #3D3D3D -6.52%); + background: linear-gradient(90deg, var(--tb-ink-76) -40.76%, var(--tb-ink-38) -23.64%, var(--tb-ink-76) -6.52%); background-clip: text; animation: fadeInScale 0.3s ease-in-out forwards; opacity: 0; transform: scale(0.95); - &.ng-leave { - animation: fadeOutScale 0.3s ease-in-out forwards; - } - &:before { content: ""; display: block; @@ -99,7 +321,7 @@ height: 100%; flex-shrink: 0; opacity: 0.5; - background: #FFF; + background: var(--tb-surface); filter: blur(2px); transform: skewX(-25deg); animation: glow-move 3s ease-in-out infinite; @@ -121,26 +343,300 @@ } - &::ng-deep { - .tb-markdown-view { - h2 { - font-size: 28px; + .user .msg-foot time { + margin: 0 0 0 6px; + } + + &::ng-deep .ai .agent-body:has(> .lead) .tb-markdown-view [class*="tb-markdown-view-"] ol { + padding-left: 20px; + + li + li { + margin-top: 6px; + } + } + + &::ng-deep .ai .agent-body .tb-markdown-view { + font-family: var(--tb-font); + font-size: var(--chat-text); + line-height: var(--chat-text-lh); + letter-spacing: var(--chat-text-ls); + color: var(--tb-ink); + + [class*="tb-markdown-view-"] { + > p, > div, > ul, > ol, > table, > pre, > h1, > h2, > h3, > h4, > h5, > h6, > div.code-wrapper { + padding-left: 0; + padding-right: 0; + margin-left: 0; } - h3 { - font-size: 24px; + p, div, li { + font-size: var(--chat-text); + line-height: var(--chat-text-lh); + letter-spacing: var(--chat-text-ls); + color: var(--tb-ink); } - h4 { - font-size: 20px; + p { + margin: 0; + } + + > * + *, > * + p { + margin-top: 14px; + } + + h1, h2, h3, h4, h5, h6 { + padding: 0; + font-size: var(--chat-text); + line-height: var(--chat-text-lh); + font-weight: 500; + color: var(--tb-ink); + } + + ul, ol { + margin: 0; + padding-left: 24px; + padding-right: 0; + color: var(--tb-ink); + } + + > p + ul, > p + ol { + margin-top: 6px; } - h5, h6 { - font-size: 18px; + li { + padding-bottom: 0; + + & + li { + margin-top: 4px; + } + + &::marker { + color: var(--tb-text-muted); + } + } + + strong, b { + font-weight: 500; + } + + code:not([class*=language-]):not(.k-ent):not(pre code) { + display: inline-block; + white-space: nowrap; + padding: var(--chat-chip-pad, 1px) 7px; + border-radius: 5px; + background: rgba(0, 0, 0, 0.06); + font-family: var(--tb-mono); + font-size: var(--chat-chip-mono, 14px); + line-height: var(--chat-chip-lh, 18px); + color: var(--tb-ink); + } + + a.tb-chiplink { + font-weight: 400; + color: var(--tb-ink); + } + + code.k-ent { + display: inline-block; + max-width: 100%; + box-sizing: border-box; + padding: var(--chat-chip-pad, 1px) 7px; + border-radius: 5px; + background: var(--tb-surface); + box-shadow: inset 0 0 0 1px var(--tb-line); + font: 400 var(--chat-chip, 14px)/var(--chat-chip-lh, 18px) var(--tb-font); + color: var(--tb-ink); + white-space: nowrap; } - a { + a.tb-chiplink > code.k-ent { + padding-right: 2px; + } + + a.tb-chiplink:hover > code.k-ent, a.tb-chiplink:focus-visible > code.k-ent { + box-shadow: inset 0 0 0 1px var(--tb-ink-38); + } + + .k-ext-tail { + white-space: nowrap; + } + + .k-ext-tail > .k-ext { + display: inline-block; + width: 13px; + height: 13px; + margin-left: 1px; + font-size: 13px; + line-height: 13px; + vertical-align: -1px; + opacity: .82; + text-decoration: none; + } + + a:not(.tb-chiplink) { + font-weight: 400; + color: var(--ai-link); + text-decoration: none; + border-bottom: 1px solid transparent; word-break: break-word; + + &:hover { + color: var(--ai-link-strong); + text-decoration: none; + border-bottom-color: currentColor; + } + } + + > table { + display: block; + width: fit-content; + max-width: 100%; + box-sizing: border-box; + overflow-x: auto; + scrollbar-width: thin; + margin: 14px 0 0; + border: 1px solid var(--tb-line); + border-radius: 8px; + background: var(--tb-surface); + border-collapse: separate; + border-spacing: 0; + table-layout: auto; + font-size: 14px; + line-height: 20px; + font-variant-numeric: tabular-nums; + + > thead { + background: none; + + > tr > th { + padding: 8px 20px 8px 0; + font-size: 12.5px; + line-height: 16px; + font-weight: 500; + color: var(--tb-text-secondary); + border: 0; + border-bottom: 1px solid var(--tb-line); + text-align: left; + white-space: nowrap; + } + } + + > tbody > tr > td { + padding: 7px 20px 7px 0; + font-size: 14px; + line-height: 20px; + color: var(--tb-ink); + border: 0; + border-bottom: 1px solid rgba(0, 0, 0, 0.06); + vertical-align: top; + white-space: nowrap; + } + + > tbody > tr:last-child > td { + border-bottom: 0; + } + + th:first-child, td:first-child { + padding-left: 12px; + } + + th:last-child, td:last-child { + padding-right: 12px; + } + + td.long { + white-space: normal; + min-width: 16em; + } + + th[align="right"], td[align="right"] { + text-align: right; + } + + th[align="center"], td[align="center"] { + text-align: center; + } + + td code.k-ent { + padding: 0; + background: none; + box-shadow: none; + font-weight: 400; + } + + td:first-child code.k-ent { + font-weight: 500; + } + + td .tb-chip-go { + display: none; + } + + td a.tb-chiplink > code.k-ent { + padding: 0; + text-decoration: underline; + text-decoration-thickness: 1px; + text-underline-offset: 3px; + text-decoration-color: color-mix(in srgb, currentColor 28%, transparent); + transition: text-decoration-color .12s ease; + } + + td a.tb-chiplink:hover > code.k-ent, td a.tb-chiplink:focus-visible > code.k-ent { + box-shadow: none; + text-decoration-color: currentColor; + } + + @container k-col (max-width: 480px) { + th:first-child, td:first-child { + position: sticky; + left: 0; + z-index: 1; + padding-left: 8px; + padding-right: 10px; + background: var(--tb-surface); + border-right: 1px solid var(--tb-line); + white-space: normal; + } + + th:nth-child(2), td:nth-child(2) { + padding-left: 12px; + } + + th:last-child, td:last-child { + padding-right: 8px; + } + + td:first-child > .k-md-lead { + display: inline-block; + width: max-content; + max-width: 172px; + vertical-align: top; + } + } + } + + @include ai-code-blocks; + } + } + + &::ng-deep tb-ai-action-detail { + @include ai-code-blocks; + } + + &::ng-deep tb-ai-hand-over { + @include ai-code-blocks; + } + + &::ng-deep tb-ai-approval-card { + @include ai-code-blocks; + + .k-review-code { + margin-top: 10px; + + .tb-code { + max-height: 320px; + overflow-y: auto; + scrollbar-width: thin; } } } diff --git a/ui-ngx/src/app/modules/home/components/ai/ai-chat-messages.component.ts b/ui-ngx/src/app/modules/home/components/ai/ai-chat-messages.component.ts index 7818491ccc..9540bfc852 100644 --- a/ui-ngx/src/app/modules/home/components/ai/ai-chat-messages.component.ts +++ b/ui-ngx/src/app/modules/home/components/ai/ai-chat-messages.component.ts @@ -1,47 +1,521 @@ // SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. // SPDX-License-Identifier: BUSL-1.1 -import { Component, ElementRef, EventEmitter, Input, OnChanges, Output, SimpleChanges } from '@angular/core'; -import { ApprovalChatMessage, ChatMessage } from '@shared/models/solution-creator.models'; -import { ApprovalResult, ToolExecutionRequested, ToolExecutionResult } from '@shared/models/ai-chat.models'; +import { aiClockText, aiLocale } from '@home/components/ai/ai-text'; +import { ChangeDetectionStrategy, ChangeDetectorRef, Component, ElementRef, EventEmitter, HostListener, inject, Input, OnChanges, OnDestroy, Output, SimpleChanges } from '@angular/core'; +import { ActionChatMessage, AiQuestion, AiQuestionAnswer, ApprovalChatMessage, ChatMessage, GeneralChatMessage } from '@shared/models/solution-creator.models'; +import { ClipboardService } from 'ngx-clipboard'; +import { Observable, of } from 'rxjs'; +import { catchError, shareReplay } from 'rxjs/operators'; +import { TranslateService } from '@ngx-translate/core'; +import { + ANSWER_PROBLEMS, + AnswerProblem, + AnswerRating, + ApprovalResult, + aiQuoteOf, + ToolExecutionRequested, + ToolApprovalResult, + ToolExecutionResult +} from '@shared/models/ai-chat.models'; +import { + aiConnectionCheckOf, + AiHandOver, + aiHandOverOf, + AiHandOverStep, + aiPlanOf, + AiPlanProgress, + aiPlanProgressOf, + AiPlanStep, + AiPrompt, + aiPromptsOf, + aiQuestionsOf, + AiSource, + aiSourcesOf, + AiWorkState, + ASK_USER_TOOL, + CHECK_CONNECTION_TOOL, + CITE_SOURCES_TOOL, + HAND_OVER_TOOL, + AiAction, + aiGroupableRead, + isHiddenAiAction, + isKitCardTool, + aiPlanStatus, + PROPOSE_PLAN_TOOL, + SUGGEST_PROMPTS_TOOL, + UPDATE_PLAN_TOOL +} from '@home/components/ai/ai-action.models'; +import { AiPlanRun } from '@home/components/ai/ai-plan.component'; +import { aiRecordKey, AiShownRecords, aiShownRecordsOf, SHOW_RECORDS_TOOL } from '@home/components/ai/ai-record.models'; +import { AiCardAction } from '@home/components/ai/ai-card-actions.component'; +import { decorateSections } from '@home/components/ai/ai-disclosure.component'; +import { AiFile, aiFileMark, aiFileName, aiFileOf, AiMadeFile, aiMadeFileOf, FILE_MAKING_TOOLS, WRITE_FILE_TOOL } from '@home/components/ai/ai-file.models'; +import { MatDialog } from '@angular/material/dialog'; +import { AiResourceService } from '@core/http/ai-resource.service'; +import { + AiAttachmentPreviewDialogComponent, + AiAttachmentPreviewDialogData +} from '@home/components/ai/ai-attachment-preview-dialog.component'; +import { aiAnswersOf, aiAnswersPrompt } from '@home/components/ai/ai-question.component'; +import { EntityId } from '@shared/models/id/entity-id'; + +export interface AnswerRatingEvent { + index: number; + rating: AnswerRating; +} + +export interface AnswerReportEvent { + index: number; + problem: AnswerProblem; + comment?: string; +} +import { aiFenceMeta, announceCopied, decorateCodeBlocks, decorateTables, fileLanguage } from '@home/components/ai/ai-code-block'; +import { AiHandOverWait } from '@home/components/ai/ai-hand-over.component'; +import { aiDetailNames, AiDetailNames } from '@home/components/ai/ai-action-detail.models'; +import { decorateFileChips, decorateHints, decorateLinks, decorateReferences, decorateSeverities, decorateValues } from '@home/components/ai/ai-references'; +import { AlarmSeverity, alarmSeverityTranslations } from '@shared/models/alarm.models'; +import { Router } from '@angular/router'; + +const SOLUTION_STEP_TOOLS = ['create_solution', 'install_solution']; + +interface AiDockRow { + kind: 'hand' | 'plan'; + index: number; + text: string; + state: 'listen' | 'stopped' | 'run' | 'idle'; + count?: string; + canTest?: boolean; +} @Component({ + changeDetection: ChangeDetectionStrategy.OnPush, selector: 'tb-ai-chat-messages', templateUrl: './ai-chat-messages.component.html', styleUrls: ['./ai-chat-messages.component.scss'], standalone: false }) -export class AiChatMessagesComponent implements OnChanges { +export class AiChatMessagesComponent implements OnChanges, OnDestroy { @Input() messages: ChatMessage[] = []; @Input() loading = false; - @Input() loadingLongTime = false; @Input() additionalStyles: string[]; @Input() completedExecutions: Record = {}; + + @Input() toolDurations: Record = {}; @Input() autoApprove = false; + @Input() scrollContainer: HTMLElement; + @Input() initialScroll: 'lastUserMessage' | 'bottom' = 'lastUserMessage'; + @Input() denyReasons: Record = {}; + @Input() work: AiWorkState | undefined; + @Input() feedback = false; + @Input() shownFile: string | null = null; + + latestFiles = new Map(); + + readonly fileMark = aiFileMark; + + readonly fileName = aiFileName; + + shownFileName(): string | null { + return this.shownFile ? Object.values(this.files).find(file => file.executionId === this.shownFile)?.name ?? null : null; + } + @Input() ghostFirst = false; + + detailNames: AiDetailNames = new Map(); + @Output() rate = new EventEmitter(); + @Output() chip = new EventEmitter(); + @Output() report = new EventEmitter(); @Output() approvalAction = new EventEmitter(); + @Output() answerLater = new EventEmitter(); + @Output() editMessage = new EventEmitter(); + @Output() resume = new EventEmitter(); + @Output() dockShown = new EventEmitter(); + @Output() listen = new EventEmitter(); + @Input() slotTaken = false; + testRequests: Record = {}; + + private readonly severityWord = (severity: string): string => this.translate.instant('alarm.severity-' + severity.toLowerCase()); + dock: AiDockRow | null = null; + private madeUrls = new Map>(); + dockVisible = false; + dockBelow = false; + private dockScroller: HTMLElement | null = null; + private readonly placeDockOnScroll = () => this.placeDock(); + @Output() retry = new EventEmitter(); + @Output() autoApproveRest = new EventEmitter(); + @Output() runPlan = new EventEmitter<{run: AiPlanRun; steps: AiPlanStep[]}>(); + @Output() changePlan = new EventEmitter(); + @Output() openFile = new EventEmitter(); + @Output() prompt = new EventEmitter(); + @Output() stopRun = new EventEmitter(); + + @Output() compose = new EventEmitter(); + @Output() answer = new EventEmitter<{message: string; secrets?: Record}>(); @Output() resourceError = new EventEmitter(); waitApproval = false; - constructor(private elementRef: ElementRef) {} + actionRunning = false; + + runningLead = -1; + + readGroups: Record = {}; + + groupedAway = new Set(); + + runningCount = 0; + + summaries: Record = {}; + prompts: {index: number; items: AiPrompt[]} | null = null; + asking: {index: number; questions: AiQuestion[]} | null = null; + retryIndex = -1; + stoppedSteps: Record = {}; + answersAt: Record = {}; + offerIndex = -1; + streaming = false; + files: Record = {}; + madeFiles: Record = {}; + inCard = new Set(); + private handledMadeFiles = new Set(); + quotes: Record = {}; + sources: Record = {}; + + records: Record = {}; + + made: Record = {}; + plans: Record = {}; + handOvers: Record = {}; + waitsInCards = new Set(); + private movedWaits = new Set(); + waitAfterCard: Record = {}; + + private keptAsking = new Set(); + + dayLines: Record = {}; + + private unfolded = new Set(); + + private dayTimer: ReturnType; + + private static readonly PIN_TO_BOTTOM_MS = 1500; + private static readonly COPIED_MS = 1500; + private static readonly FOLD_LINES = 6; + private static readonly FOLD_CHARS = 600; + + private releaseBottom: () => void; + private releaseAsk: () => void; + + lastAnswerIndex = -1; + + readonly problems = ANSWER_PROBLEMS; + + reportingIndex = -1; + + reportProblem: AnswerProblem | null = null; + + copiedIndex = -1; + + private cd = inject(ChangeDetectorRef); + + private copiedTimeout: ReturnType; + + constructor(private elementRef: ElementRef, + private clipboard: ClipboardService, + private translate: TranslateService, + private router: Router, + private dialog: MatDialog, + private aiResourceService: AiResourceService) {} + + madeUrl(file: AiMadeFile): Observable { + let url = this.madeUrls.get(file.executionId); + if (!url) { + url = this.aiResourceService.getUrl(file.resource.id).pipe(catchError(() => of(null)), shareReplay(1)); + this.madeUrls.set(file.executionId, url); + } + return url; + } + + openMadeFile(file: AiMadeFile): void { + if (file.preview === 'image') { + this.dialog.open(AiAttachmentPreviewDialogComponent, { + panelClass: ['tb-dialog', 'tb-ai-attachment-preview-dialog'], + maxWidth: '92vw', + data: {resource: file.resource} + }); + } else { + this.downloadMadeFile(file); + } + } + + private downloadRequestedFiles(): void { + for (const file of Object.values(this.madeFiles)) { + if (this.handledMadeFiles.has(file.executionId)) { + continue; + } + this.handledMadeFiles.add(file.executionId); + if (file.download && this.loading) { + this.downloadMadeFile(file); + } + } + } + + downloadMadeFile(file: AiMadeFile): void { + this.aiResourceService.download(file.resource).subscribe({ + error: error => this.resourceError.emit(error) + }); + } + + copyText(text: string, index: number): void { + if (this.clipboard.copyFromContent(text)) { + this.copiedIndex = index; + announceCopied(this.translate.instant('ai-assistant.copied')); + clearTimeout(this.copiedTimeout); + this.copiedTimeout = setTimeout(() => { + this.copiedIndex = -1; + this.cd.markForCheck(); + }, AiChatMessagesComponent.COPIED_MS); + } + } + + decorationKey(message: ChatMessage): string { + const general = message as GeneralChatMessage; + return `${general.references?.length ?? 0}:${general.severities?.length ?? 0}:${general.readings?.length ?? 0}`; + } + + decorateCode(answer: HTMLElement, message?: ChatMessage): void { + decorateCodeBlocks(answer, this.translate, text => this.clipboard.copyFromContent(text)); + decorateTables(answer); + decorateSections(answer, this.sectionScope(message)); + decorateReferences(answer, (message as GeneralChatMessage)?.references); + decorateLinks(answer, this.translate.instant('ai-assistant.opens-new-tab')); + decorateHints(answer); + decorateValues(answer, (message as GeneralChatMessage)?.readings); + decorateFileChips(answer, this.latestFiles, this.shownFileName()); + decorateSeverities(answer, (message as GeneralChatMessage)?.severities, + severity => this.translate.instant(alarmSeverityTranslations.get(severity as AlarmSeverity) ?? severity)); + } + + private sectionScope(message?: ChatMessage): string { + const general = message as GeneralChatMessage; + return String(general?.time ?? ''); + } + + @HostListener('click', ['$event']) + openInApp(event: MouseEvent): void { + if (event.defaultPrevented || event.button !== 0 || event.metaKey || event.ctrlKey || event.shiftKey || event.altKey) { + return; + } + const chip = (event.target as HTMLElement)?.closest('.agent .art-chip[data-file]'); + const chipFile = chip ? this.latestFiles.get(chip.dataset.file) : undefined; + if (chipFile) { + event.preventDefault(); + this.openFile.emit(chipFile); + return; + } + const link = (event.target as HTMLElement)?.closest('.agent a[href]') as HTMLAnchorElement | null; + if (!link || link.target === '_blank' || link.origin !== location.origin) { + return; + } + event.preventDefault(); + this.router.navigateByUrl(link.pathname + link.search + link.hash); + } + + isFolded(index: number, content: string): boolean { + return !this.unfolded.has(index) && (content.split('\n').length > AiChatMessagesComponent.FOLD_LINES || content.length > AiChatMessagesComponent.FOLD_CHARS); + } + + unfold(index: number): void { + this.unfolded.add(index); + } + + withoutDoneMark(content: string): string { + return (content ?? '').replace(/^\s*(✅|🛠️|🛠|🤔|💡|🛑)\s*/u, ''); + } + + copyAnswer(answer: HTMLElement, index: number): void { + const text = (answer.querySelector('tb-markdown') ?? answer).innerText.trim(); + if (this.clipboard.copyFromContent(text)) { + this.copiedIndex = index; + announceCopied(this.translate.instant('ai-assistant.copied')); + clearTimeout(this.copiedTimeout); + this.copiedTimeout = setTimeout(() => { + this.copiedIndex = -1; + this.cd.markForCheck(); + }, AiChatMessagesComponent.COPIED_MS); + } + } + + toggleRating(index: number, current: string | undefined, rating: 'UP' | 'DOWN'): void { + this.rate.emit({index, rating: current === rating ? 'NONE' : rating}); + } + + openReport(index: number): void { + this.reportingIndex = index; + this.reportProblem = null; + setTimeout(() => this.revealReport()); + } + + private revealReport(): void { + this.reveal(this.elementRef.nativeElement.querySelector('.k-report')); + } + + private keepAskInView(): void { + const ask = this.elementRef.nativeElement.querySelector('.ai.ask'); + if (!ask) { + return; + } + this.releaseAsk?.(); + const scroller = this.scroller; + const show = () => this.reveal(ask, 'auto'); + const observer = new ResizeObserver(show); + observer.observe(this.elementRef.nativeElement); + const release = () => { + observer.disconnect(); + clearTimeout(timeout); + scroller.removeEventListener('wheel', release); + scroller.removeEventListener('touchstart', release); + scroller.removeEventListener('keydown', release); + scroller.removeEventListener('pointerdown', release); + this.releaseAsk = undefined; + }; + const timeout = setTimeout(release, AiChatMessagesComponent.PIN_TO_BOTTOM_MS); + scroller.addEventListener('wheel', release, {passive: true}); + scroller.addEventListener('touchstart', release, {passive: true}); + scroller.addEventListener('keydown', release); + scroller.addEventListener('pointerdown', release, {passive: true}); + this.releaseAsk = release; + this.reveal(ask); + } + + private reveal(report: HTMLElement | null, behavior: ScrollBehavior = 'smooth'): void { + const scroller = report?.closest('.ai-chat-body') ?? (report ? this.scroller : null); + if (!report || !scroller) { + return; + } + const composer = scroller.querySelector('.ai-chat-composer'); + const cover = composer?.querySelector('.k-pill') ?? composer; + const limit = Math.min(scroller.getBoundingClientRect().bottom, cover?.getBoundingClientRect().top ?? Infinity) - 12; + const rect = report.getBoundingClientRect(); + const top = scroller.getBoundingClientRect().top + 12; + const overflow = Math.min(rect.bottom - limit, rect.top - top); + if (overflow > 0) { + scroller.scrollBy({top: overflow, behavior: this.motion(behavior)}); + } + } + + closeReport(): void { + this.reportingIndex = -1; + this.reportProblem = null; + } + + sendReport(index: number, comment: string): void { + if (!this.reportProblem) { + return; + } + const words = comment.trim(); + this.report.emit(words ? {index, problem: this.reportProblem, comment: words} : {index, problem: this.reportProblem}); + this.closeReport(); + } + + fullTime(time: number): string { + const zone = Intl.DateTimeFormat().resolvedOptions().timeZone; + const text = new Intl.DateTimeFormat(undefined, { + weekday: 'long', day: 'numeric', month: 'long', year: 'numeric', hour: '2-digit', minute: '2-digit', second: '2-digit' + }).format(time); + return zone ? `${text} (${zone})` : text; + } getApprovalData(msg: ApprovalChatMessage): ToolExecutionRequested { return msg.data; } + denyReasonOf(msg: ApprovalChatMessage): string | undefined { + return this.completedExecutions[msg.data.executionId]?.reason ?? this.denyReasons[msg.data.executionId]; + } + getCompletedExecution(msg: ApprovalChatMessage): ToolExecutionResult | undefined { return this.completedExecutions[msg.data.executionId]; } ngOnChanges(changes: SimpleChanges): void { - if (changes.loadingLongTime?.currentValue) { - if (this.isNearBottom()) { - setTimeout(() => this.scrollToBottom('smooth'), 0); + if (changes.loading && !changes.loading.firstChange && changes.loading.previousValue && !changes.loading.currentValue + && !changes.messages?.firstChange && this.isNearBottom()) { + setTimeout(() => this.followTurnEnd(), 0); + } + if (changes.slotTaken && !changes.slotTaken.firstChange) { + setTimeout(() => this.placeDock()); + } + if (changes.messages) { + this.refreshDayLines(); + this.detailNames = aiDetailNames(this.messages as Array<{from: string; data?: any; references?: Array<{id: string; name: string; entityType: string}>}>, this.detailNames); + } + if (changes.messages || changes.completedExecutions || changes.loading || changes.autoApprove || changes.denyReasons) { + this.offerIndex = this.findOffer(); + } + if (changes.shownFile) { + const shown = this.shownFileName(); + this.elementRef.nativeElement.querySelectorAll('.art-chip[data-file]').forEach((chip: HTMLElement) => { + chip.classList.toggle('on', chip.dataset.file === shown); + chip.setAttribute('aria-pressed', String(chip.dataset.file === shown)); + }); + } + if (changes.messages || changes.completedExecutions || changes.loading) { + this.summaries = this.findSummaries(); + this.prompts = this.findPrompts(); + const asked = this.asking?.index; + this.asking = this.findAsking(); + if (this.asking && this.asking.index !== asked && !changes.messages?.firstChange) { + setTimeout(() => this.keepAskInView()); } + this.plans = this.findPlans(); + this.handOvers = this.findHandOvers(); + this.dock = this.findDock(); + this.followDock(); + this.files = this.findFiles(); + this.latestFiles = new Map(Object.values(this.files).map(file => [file.name, file])); + this.madeFiles = this.findMadeFiles(); + this.inCard = this.placeFiles(); + this.downloadRequestedFiles(); + this.quotes = this.findQuotes(); + this.sources = this.findSources(); + this.records = this.findRecords(); + this.made = {}; + Object.entries(this.records).forEach(([index, shown]) => { + const entities = this.summaries[Number(index)]; + if (!entities?.length) { + return; + } + const keys = new Set(shown.flatMap(item => item.refs.map(aiRecordKey))); + this.made[Number(index)] = entities.map(entity => `${entity.entityType}:${entity.id}`); + const rest = entities.filter(entity => !keys.has(`${entity.entityType}:${entity.id}`)); + if (rest.length) { + this.summaries[Number(index)] = rest; + } else { + delete this.summaries[Number(index)]; + } + }); + this.answersAt = this.findAnswers(); + this.retryIndex = this.findRetry(); + this.stoppedSteps = this.findStoppedSteps(); } if (changes.messages) { + this.lastAnswerIndex = this.findLastAnswerIndex(); + const tail = this.messages[this.messages.length - 1]; + this.streaming = tail?.from === 'AI' && !!tail.streaming; + const running = this.messages.map((message, index) => message.from === 'ACTION' && message.data.status === 'RUNNING' ? index : -1) + .filter(index => index >= 0); + this.actionRunning = running.length > 0; + this.runningLead = running.length ? running[0] : -1; + this.runningCount = running.length; + this.findReadGroups(); + const last = this.messages[this.messages.length - 1]; + this.waitApproval = last?.from === 'APPROVAL' && !this.autoApprove && !this.isAnswered(last as ApprovalChatMessage); if (changes.messages.firstChange) { - setTimeout(() => this.scrollToLastUserMessage(), 0); + if (this.initialScroll === 'bottom') { + this.pinToBottom(); + } else { + setTimeout(() => this.scrollToLastUserMessage(), 0); + } return; } const wasNearBottom = this.isNearBottom(); @@ -49,12 +523,10 @@ export class AiChatMessagesComponent implements OnChanges { const prevLastMsg = prevMsgs?.[prevMsgs.length - 1]; const msgs = changes.messages.currentValue as ChatMessage[]; const lastMsg = msgs[msgs.length - 1]; - // In auto-approve we are not blocked on the user, so the assistant keeps working: the - // thinking indicator must stay visible (waitApproval false) and the view must follow the - // stream of auto-generated cards down to the bottom. - this.waitApproval = lastMsg?.from === 'APPROVAL' && !this.autoApprove; if (this.autoApprove) { - setTimeout(() => this.scrollToBottom('auto'), 0); + if (wasNearBottom) { + setTimeout(() => this.scrollToBottom('auto'), 0); + } } else if (lastMsg?.from === 'USER') { setTimeout(() => this.scrollToBottom('smooth'), 0); } else if (lastMsg?.from === 'AI') { @@ -63,6 +535,14 @@ export class AiChatMessagesComponent implements OnChanges { } else if (wasNearBottom) { setTimeout(() => this.scrollToLastAiMessage(), 0); } + } else if (lastMsg?.from === 'ACTION') { + if (wasNearBottom) { + setTimeout(() => this.scrollToBottom('smooth'), 0); + } + } else if (lastMsg?.from === 'APPROVAL' && this.waitApproval) { + if (wasNearBottom) { + setTimeout(() => this.revealLastApproval(), 0); + } } else if (lastMsg?.from === 'APPROVAL') { if (prevLastMsg?.from === 'USER') { setTimeout(() => this.scrollToLastUserMessage(), 0); @@ -73,28 +553,696 @@ export class AiChatMessagesComponent implements OnChanges { } } + keepAsking(): void { + this.keptAsking.add(this.turnStart(this.offerIndex)); + this.offerIndex = -1; + } + + private findOffer(): number { + const last = this.messages.length - 1; + const pending = this.messages[last]; + if (this.autoApprove || pending?.from !== 'APPROVAL' || !pending.data.needsApproval || pending.data.autoApproved + || this.approvalResult(pending) || this.denyReasons[pending.data.executionId]) { + return -1; + } + const start = this.turnStart(last); + if (this.keptAsking.has(start)) { + return -1; + } + const approvedBefore = this.messages.slice(start + 1, last).some(message => message.from === 'APPROVAL' + && !message.data.autoApproved && this.approvalResult(message)?.approvalStatus === ToolApprovalResult.APPROVED); + return approvedBefore ? last : -1; + } + + private approvalResult(message: ApprovalChatMessage): ToolExecutionResult | undefined { + return this.completedExecutions[message.data.executionId] ?? message.result; + } + + private turnStart(index: number): number { + for (let i = index; i >= 0; i--) { + if (this.messages[i].from === 'USER') { + return i; + } + } + return -1; + } + + private answeredApprovals = new Set(); + + private isAnswered(message: ApprovalChatMessage): boolean { + const executionId = message.data?.executionId; + return !!message.result || this.answeredApprovals.has(executionId) || !!this.completedExecutions?.[executionId]; + } + approval($event: ApprovalResult) { + this.answeredApprovals.add($event.executionId); this.waitApproval = false; this.approvalAction.emit($event); } + private refreshDayLines(): void { + const lines: Record = {}; + let previous: string | undefined; + let first = true; + this.messages.forEach((message, index) => { + const time = (message as {time?: number}).time; + if (!time) { + return; + } + const day = new Date(time).toDateString(); + if (!first && day !== previous) { + lines[index] = this.dayLabel(time); + } + previous = day; + first = false; + }); + this.dayLines = lines; + clearTimeout(this.dayTimer); + const midnight = new Date(); + midnight.setHours(24, 0, 1, 0); + this.dayTimer = setTimeout(() => this.refreshDayLines(), midnight.getTime() - Date.now()); + } + + private dayLabel(time: number): string { + const date = new Date(time); + const today = new Date(); + today.setHours(0, 0, 0, 0); + const day = new Date(date); + day.setHours(0, 0, 0, 0); + const days = Math.round((today.getTime() - day.getTime()) / 86_400_000); + if (days === 0) { + return this.translate.instant('ai-assistant.today'); + } + if (days === 1) { + return this.translate.instant('ai-assistant.yesterday'); + } + const options: Intl.DateTimeFormatOptions = days > 1 && days <= 6 + ? {weekday: 'long', day: 'numeric', month: 'long'} + : date.getFullYear() === today.getFullYear() ? {day: 'numeric', month: 'long'} : {day: 'numeric', month: 'long', year: 'numeric'}; + return new Intl.DateTimeFormat(aiLocale(this.translate.currentLang), options).format(date).replace(',', ''); + } + + private findSummaries(): Record { + const summaries: Record = {}; + let entities: EntityId[] = []; + let seen = new Set(); + let lastAi = -1; + const close = (finished: boolean) => { + if (finished && lastAi >= 0 && entities.length) { + summaries[lastAi] = entities; + } + entities = []; + seen = new Set(); + lastAi = -1; + }; + const add = (ids?: EntityId[]) => (ids ?? []).forEach(id => { + const key = `${id.entityType}:${id.id}`; + if (!seen.has(key)) { + seen.add(key); + entities.push(id); + } + }); + this.messages.forEach((message, index) => { + switch (message.from) { + case 'USER': + close(true); + break; + case 'APPROVAL': + add((this.completedExecutions[message.data.executionId] ?? message.result)?.affectedEntities); + break; + case 'ACTION': + if (!SOLUTION_STEP_TOOLS.includes(message.data.tool)) { + add(message.data.affectedEntities); + } + break; + case 'AI': + lastAi = index; + break; + } + }); + close(!this.loading); + return summaries; + } + + private findReadGroups(): void { + const groups: Record = {}; + const away = new Set(); + const turns: number[][] = [[]]; + this.messages.forEach((message, index) => { + if (message.from === 'USER') { + turns.push([]); + } + turns[turns.length - 1].push(index); + }); + for (const turn of turns) { + const answered = turn.some(index => this.messages[index].from === 'AI' && !(this.messages[index] as GeneralChatMessage).streaming + && turn.indexOf(index) === turn.length - 1); + let lead = -1; + for (const index of turn) { + const message = this.messages[index]; + const action = message.from === 'ACTION' ? (message as ActionChatMessage).data : null; + if (action && isHiddenAiAction(action.tool)) { + continue; + } + if (action && this.isListedAction(message, index) && aiGroupableRead(action)) { + if (lead >= 0) { + groups[lead].push(action); + away.add(index); + } else { + lead = index; + groups[lead] = [action]; + } + continue; + } + if (!answered || message.from === 'USER' || message.from === 'AI') { + lead = -1; + } + } + } + Object.keys(groups).forEach(key => { + if (groups[Number(key)].length < 2) { + delete groups[Number(key)]; + } + }); + this.readGroups = groups; + this.groupedAway = away; + } + + isListedAction(message: ChatMessage, index = -1): boolean { + return message.from === 'ACTION' && !isKitCardTool(message.data.tool) && !isHiddenAiAction(message.data.tool) + && !(index >= 0 && (this.waitsInCards.has(index) || this.movedWaits.has(index))); + } + + answerQuestions(answers: AiQuestionAnswer[]): void { + this.answer.emit(aiAnswersPrompt(answers)); + } + + failText(index: number, message: GeneralChatMessage): string { + let steps = false; + for (let i = index - 1; i >= 0 && this.messages[i].from !== 'USER'; i--) { + if (this.messages[i].from === 'APPROVAL' || (this.messages[i].from === 'ACTION' && this.isListedAction(this.messages[i] as ActionChatMessage))) { + steps = true; + break; + } + } + const reason = message.failure?.reason; + const words = reason === 'TIMED_OUT' || reason === 'MODEL_ERROR' || reason === 'CREDITS_USED_UP' ? [this.translate.instant('ai-assistant.failed.reason.' + reason)] : []; + words.push(this.translate.instant(steps ? 'ai-assistant.failed.steps-done' : 'ai-assistant.failed.nothing-changed')); + return words.join(' '); + } + + clockText(time?: number): string { + return aiClockText(time, this.translate.currentLang); + } + + stoppedText(index: number, content: string): string { + const steps = this.stoppedSteps[index]; + if (steps === undefined) { + return content; + } + return steps ? this.translate.instant('ai-assistant.stopped-after', {count: steps}) : this.translate.instant('ai-assistant.stopped-before'); + } + + private findRetry(): number { + if (this.loading) { + return -1; + } + for (let i = this.messages.length - 1; i >= 0; i--) { + const message = this.messages[i]; + if (message.from === 'USER' || (message as GeneralChatMessage).status === 'INCOMPLETE' || !this.retry.observed) { + return -1; + } + if (message.from === 'ACTION' && this.isListedAction(message)) { + return message.data.status === 'FAILURE' ? i : -1; + } + } + return -1; + } + + private findStoppedSteps(): Record { + const steps: Record = {}; + let done = 0; + this.messages.forEach((message, index) => { + if (message.from === 'USER') { + done = 0; + } else if (message.from === 'ACTION' && this.isListedAction(message) && message.data.status === 'SUCCESS') { + done++; + } else if (message.from === 'APPROVAL' && (this.completedExecutions[message.data.executionId] ?? message.result)?.executionStatus === 'SUCCESS') { + done++; + } else if ((message as GeneralChatMessage).status === 'STOPPED') { + steps[index] = done; + } + }); + return steps; + } + + private findAsking(): {index: number; questions: AiQuestion[]} | null { + if (this.loading) { + return null; + } + for (let i = this.messages.length - 1; i >= 0; i--) { + const message = this.messages[i]; + if (message.from === 'USER') { + return null; + } + if (message.from === 'ACTION' && message.data.tool === ASK_USER_TOOL) { + const questions = aiQuestionsOf(message.data.arguments, this.severityWord); + return questions.length ? {index: i, questions} : null; + } + } + return null; + } + + private findRecords(): Record { + const records: Record = {}; + let answer = -1; + let pending: AiShownRecords[] = []; + const place = () => { + if (pending.length && answer >= 0) { + records[answer] = [...(records[answer] ?? []), ...pending]; + pending = []; + } + }; + this.messages.forEach((message, index) => { + if (message.from === 'USER') { + place(); + answer = -1; + pending = []; + } else if (message.from === 'AI' && !message.status) { + answer = index; + place(); + } else if (message.from === 'ACTION' && message.data.tool === SHOW_RECORDS_TOOL && message.data.status !== 'FAILURE') { + const shown = aiShownRecordsOf(message.data.arguments); + if (shown) { + pending.push(shown); + } + place(); + } + }); + return records; + } + + offerActions(): AiCardAction[] { + return [ + {id: 'approve-rest', icon: 'bolt', label: this.translate.instant('ai-assistant.offer.approve-rest')}, + {id: 'keep-asking', quiet: true, label: this.translate.instant('ai-assistant.offer.keep-asking')} + ]; + } + + offerAct(id: string): void { + if (id === 'approve-rest') { + this.autoApproveRest.emit(); + } else { + this.keepAsking(); + } + } + + listenAgain(): void { + this.listen.emit(); + } + + resumeActions(): AiCardAction[] { + return [{id: 'resume', icon: 'play_arrow', label: this.translate.instant('ai-assistant.resume')}]; + } + + chipActions(chips: Array<{id: string; label: string; icon?: string}>): AiCardAction[] { + return chips.map(option => ({id: option.id, label: option.label, icon: option.icon})); + } + + private findSources(): Record { + const sources: Record = {}; + let answer = -1; + let pending: AiSource[] = []; + const place = () => { + if (pending.length && answer >= 0) { + sources[answer] = [...(sources[answer] ?? []), ...pending]; + pending = []; + } + }; + this.messages.forEach((message, index) => { + if (message.from === 'USER') { + place(); + answer = -1; + pending = []; + } else if (message.from === 'AI' && !message.status) { + answer = index; + place(); + } else if (message.from === 'ACTION' && message.data.tool === CITE_SOURCES_TOOL && message.data.status !== 'FAILURE') { + pending.push(...aiSourcesOf(message.data.arguments)); + place(); + } + }); + return sources; + } + + private findQuotes(): Record { + const quotes: Record = {}; + this.messages.forEach((message, index) => { + if (message.from === 'USER') { + const found = aiQuoteOf(message.content); + if (found) { + quotes[index] = {name: found.quote.name, icon: fileLanguage(found.quote.name).icon, from: found.quote.from, to: found.quote.to, message: found.message}; + } + } + }); + return quotes; + } + + private findFiles(): Record { + const files: Record = {}; + this.messages.forEach((message, index) => { + if (message.from === 'ACTION' && message.data.tool === WRITE_FILE_TOOL) { + const file = aiFileOf(message.data.executionId, message.data.arguments, !!message.data.edited); + if (file) { + files[index] = file; + } + } + }); + return files; + } + + private placeFiles(): Set { + const placed = new Set(); + const names = [...this.latestFiles.keys()]; + const mentions = (step: AiHandOverStep, name: string) => [step.title, step.detail, step.markdown].some(part => part?.includes(name)); + Object.values(this.handOvers).forEach(card => { + const groups = [card.handOver.steps, ...(card.handOver.choice?.options.map(option => option.steps ?? []) ?? [])]; + groups.forEach(steps => { + steps.filter(step => step.file && !this.latestFiles.has(step.file)).forEach(step => step.file = undefined); + names.filter(name => !steps.some(step => step.file === name)).forEach(name => { + const last = [...steps].reverse().find(step => !step.file && mentions(step, name)); + if (last) { + last.file = name; + } + }); + steps.filter(step => step.file).forEach(step => placed.add(step.file)); + }); + }); + return placed; + } + + private findMadeFiles(): Record { + const files: Record = {}; + this.messages.forEach((message, index) => { + if (message.from === 'ACTION' && FILE_MAKING_TOOLS.has(message.data.tool) && message.data.status === 'SUCCESS') { + const file = aiMadeFileOf(message.data.executionId, message.data.result); + if (file) { + files[index] = file; + } + } + }); + return files; + } + + private findHandOvers(): Record { + const cards: Record = {}; + const waits = new Set(); + let current = -1; + let early = -1; + const moved = new Set(); + const after: Record = {}; + const waitOf = (message: ActionChatMessage, index: number): AiHandOverWait => { + const running = message.data.status === 'RUNNING' && this.loading; + if (running) { + waits.add(index); + } + return {running, startedAt: message.data.startedAt, progress: message.data.progress, + endedAt: message.data.durationMs != null ? message.data.startedAt + message.data.durationMs : undefined, + check: running ? null : aiConnectionCheckOf(message.data.result)}; + }; + this.messages.forEach((message, index) => { + if (message.from === 'USER') { + if (current >= 0 && (!cards[current].handOver.waitFor || cards[current].wait?.check?.dataArriving)) { + current = -1; + } + early = -1; + return; + } + if (message.from !== 'ACTION') { + return; + } + if (message.data.tool === HAND_OVER_TOOL) { + const handOver = aiHandOverOf(message.data.arguments); + if (handOver) { + cards[index] = {handOver, wait: null}; + current = index; + if (early >= 0 && handOver.waitFor) { + cards[index].wait = waitOf(this.messages[early] as ActionChatMessage, early); + moved.add(early); + after[index] = early; + early = -1; + } + } + } else if (message.data.tool === CHECK_CONNECTION_TOOL + && Number((message.data.arguments as {waitSeconds?: unknown})?.waitSeconds) > 0) { + if (current >= 0 && cards[current].handOver.waitFor) { + cards[current].wait = waitOf(message, index); + } else if (current < 0) { + early = index; + } + } + }); + this.waitsInCards = waits; + this.movedWaits = moved; + this.waitAfterCard = after; + return cards; + } + + private findPlans(): Record { + const plans: Record = {}; + let current = -1; + this.messages.forEach((message, index) => { + if (message.from !== 'ACTION') { + return; + } + if (message.data.tool === PROPOSE_PLAN_TOOL) { + const steps = aiPlanOf(message.data.arguments); + if (steps.length) { + if (current >= 0 && plans[current].progress && !this.planFinished(plans[current])) { + plans[current].replacedAfter = plans[current].progress.done.length; + } + plans[index] = {steps, progress: null, gate: false, replacedAfter: null}; + current = index; + } + } else if (message.data.tool === UPDATE_PLAN_TOOL && current >= 0) { + plans[current].progress = aiPlanProgressOf(message.data.arguments); + } + }); + if (current >= 0 && !this.loading && !plans[current].progress + && !this.messages.slice(current + 1).some(message => message.from === 'USER')) { + plans[current].gate = true; + } + return plans; + } + + private planFinished(plan: {steps: AiPlanStep[]; progress: AiPlanProgress | null}): boolean { + return aiPlanStatus(plan.steps, plan.progress).finished; + } + + private findAnswers(): Record { + const answers: Record = {}; + let questions: AiQuestion[] = []; + this.messages.forEach((message, index) => { + if (message.from === 'ACTION' && message.data.tool === ASK_USER_TOOL) { + questions = aiQuestionsOf(message.data.arguments, this.severityWord); + } else if (message.from === 'USER') { + const found = questions.length ? aiAnswersOf(message.content, questions) : null; + if (found) { + answers[index] = found; + } + questions = []; + } + }); + return answers; + } + + private findPrompts(): {index: number; items: AiPrompt[]} | null { + if (this.loading) { + return null; + } + let items: AiPrompt[] = []; + let answer = -1; + for (let i = this.messages.length - 1; i >= 0; i--) { + const message = this.messages[i]; + if (message.from === 'USER') { + break; + } + if (message.from === 'ACTION' && message.data.tool === SUGGEST_PROMPTS_TOOL && !items.length) { + items = aiPromptsOf(message.data.arguments); + } + if (message.from === 'AI' && !message.status && answer < 0) { + answer = i; + } + } + const shown = this.ghostFirst ? items.slice(1) : items; + return shown.length && answer >= 0 ? {index: answer, items: shown} : null; + } + + private findLastAnswerIndex(): number { + for (let i = this.messages.length - 1; i >= 0; i--) { + const message = this.messages[i]; + if (message.from === 'AI' && !message.status) { + return i; + } + } + return -1; + } + + dockClicked(event: MouseEvent): void { + if (!(event.target as HTMLElement).closest('a, button')) { + this.toDockCard(); + } + } + + toDockCard(): void { + const card = this.dock ? this.elementRef.nativeElement.querySelector(`[data-dock="${this.dock.index}"]`) : null; + card?.scrollIntoView({block: 'start', behavior: matchMedia('(prefers-reduced-motion: reduce)').matches ? 'auto' : 'smooth'}); + } + + dockTest(): void { + const id = this.dock ? (this.messages[this.dock.index] as ActionChatMessage)?.data.executionId : null; + if (id) { + this.testRequests = {...this.testRequests, [id]: (this.testRequests[id] ?? 0) + 1}; + } + } + + private findDock(): AiDockRow | null { + const lastUser = this.messages.map(message => message.from).lastIndexOf('USER'); + const handIndex = Object.keys(this.handOvers).map(Number).pop(); + const card = handIndex !== undefined ? this.handOvers[handIndex] : undefined; + if (card?.handOver.waitFor && card.wait && !card.wait.check?.dataArriving && (card.wait.running || handIndex > lastUser)) { + return {kind: 'hand', index: handIndex, text: card.handOver.title, state: card.wait.running ? 'listen' : 'stopped', + canTest: !!card.handOver.test?.sample && card.handOver.waitFor === 'message'}; + } + const planIndex = Object.keys(this.plans).map(Number).pop(); + const plan = planIndex !== undefined ? this.plans[planIndex] : undefined; + if (!plan?.progress || plan.replacedAfter !== null || this.planFinished(plan)) { + return null; + } + const status = aiPlanStatus(plan.steps, plan.progress); + const step = plan.steps[Math.max(0, status.now - 1)]; + return {kind: 'plan', index: planIndex, text: step?.text.replace(/`/g, '') ?? '', state: this.loading ? 'run' : 'idle', + count: this.translate.instant('ai-assistant.plan.done-of', {done: status.done, count: status.counted})}; + } + + private followDock(): void { + const scroller = this.scroller; + if (scroller !== this.dockScroller) { + this.dockScroller?.removeEventListener('scroll', this.placeDockOnScroll); + scroller.addEventListener('scroll', this.placeDockOnScroll, {passive: true}); + this.dockScroller = scroller; + } + setTimeout(() => this.placeDock()); + } + + private placeDock(): void { + let visible = false; + let below = this.dockBelow; + if (this.dock && !this.slotTaken) { + const card = this.elementRef.nativeElement.querySelector(`[data-dock="${this.dock.index}"]`); + if (card) { + const box = this.scroller.getBoundingClientRect(); + const rect = card.getBoundingClientRect(); + visible = Math.min(rect.bottom, box.bottom) - Math.max(rect.top, box.top) <= 40; + below = rect.top >= box.bottom - 40; + } + } + if (below !== this.dockBelow) { + this.dockBelow = below; + this.cd.markForCheck(); + } + if (visible !== this.dockVisible) { + this.dockVisible = visible; + this.dockShown.emit(visible); + this.cd.markForCheck(); + } + } + + ngOnDestroy(): void { + this.dockScroller?.removeEventListener('scroll', this.placeDockOnScroll); + clearTimeout(this.copiedTimeout); + clearTimeout(this.dayTimer); + this.releaseBottom?.(); + this.releaseAsk?.(); + } + + private pinToBottom(place?: () => void): void { + this.releaseBottom?.(); + const scroller = this.scroller; + const stick = place ?? (() => scroller.scrollTop = scroller.scrollHeight); + const observer = new ResizeObserver(stick); + observer.observe(this.elementRef.nativeElement); + const release = () => { + observer.disconnect(); + clearTimeout(timeout); + scroller.removeEventListener('wheel', release); + scroller.removeEventListener('touchstart', release); + scroller.removeEventListener('keydown', release); + scroller.removeEventListener('pointerdown', release); + this.releaseBottom = undefined; + }; + const timeout = setTimeout(release, AiChatMessagesComponent.PIN_TO_BOTTOM_MS); + scroller.addEventListener('wheel', release, {passive: true}); + scroller.addEventListener('touchstart', release, {passive: true}); + scroller.addEventListener('keydown', release); + scroller.addEventListener('pointerdown', release, {passive: true}); + this.releaseBottom = release; + stick(); + } + + private followTurnEnd(): void { + const scroller = this.scroller; + const answers = this.elementRef.nativeElement.querySelectorAll('.ai'); + const answer = answers[answers.length - 1] as HTMLElement | undefined; + this.pinToBottom(() => { + let target = scroller.scrollHeight - scroller.clientHeight; + if (answer?.isConnected) { + const top = answer.getBoundingClientRect().top - scroller.getBoundingClientRect().top + scroller.scrollTop - 8; + target = Math.min(target, top); + } + if (target > scroller.scrollTop) { + scroller.scrollTop = target; + } + }); + } + scrollToBottom(behavior: ScrollBehavior = 'smooth'): void { - const el = this.elementRef.nativeElement; - el.scrollTo({top: el.scrollHeight, behavior}); + const el = this.scroller; + el.scrollTo({top: el.scrollHeight, behavior: this.motion(behavior)}); } - scrollToLastUserMessage(): void { - const userMessages = this.elementRef.nativeElement.querySelectorAll('.user'); - if (userMessages.length) { - userMessages[userMessages.length - 1].scrollIntoView({block: 'start', behavior: 'smooth'}); + private revealLastApproval(): void { + const cards = this.elementRef.nativeElement.querySelectorAll('tb-ai-approval-card'); + const card = cards[cards.length - 1] as HTMLElement | undefined; + if (!card) { + return; } + const scroller = this.scroller; + this.pinToBottom(() => { + scroller.scrollTop = scroller.scrollHeight; + const top = card.getBoundingClientRect().top - scroller.getBoundingClientRect().top; + if (top < 0) { + scroller.scrollTop += top - 8; + } + }); + } + + scrollToLastUserMessage(): void { + this.scrollToStart(this.elementRef.nativeElement.querySelectorAll('.user')); } private scrollToLastAiMessage(): void { - const aiMessages = this.elementRef.nativeElement.querySelectorAll('.ai'); - if (aiMessages.length) { - aiMessages[aiMessages.length - 1].scrollIntoView({block: 'start', behavior: 'smooth'}); + this.scrollToStart(this.elementRef.nativeElement.querySelectorAll('.ai')); + } + + private scrollToStart(messages: NodeListOf): void { + const message = messages[messages.length - 1]; + const scroller = this.scroller; + if (!message || !scroller) { + return; } + const top = scroller.scrollTop + message.getBoundingClientRect().top - scroller.getBoundingClientRect().top; + scroller.scrollTo({top, behavior: this.motion('smooth')}); } parseResult(msg: string): string { @@ -115,12 +1263,20 @@ export class AiChatMessagesComponent implements OnChanges { '```'; } } else { - return msg; + return aiFenceMeta(msg); } } + private motion(behavior: ScrollBehavior): ScrollBehavior { + return behavior === 'smooth' && matchMedia('(prefers-reduced-motion: reduce)').matches ? 'auto' : behavior; + } + + private get scroller(): HTMLElement { + return this.scrollContainer ?? this.elementRef.nativeElement; + } + private isNearBottom(threshold = 150): boolean { - const el = this.elementRef.nativeElement; + const el = this.scroller; return el.scrollHeight - el.scrollTop - el.clientHeight <= threshold; } diff --git a/ui-ngx/src/app/modules/home/components/ai/ai-chat-session.ts b/ui-ngx/src/app/modules/home/components/ai/ai-chat-session.ts new file mode 100644 index 0000000000..320c3a2842 --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/ai/ai-chat-session.ts @@ -0,0 +1,56 @@ +// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: BUSL-1.1 +import { WritableSignal } from '@angular/core'; +import { Observable } from 'rxjs'; +import { AnswerRatingEvent, AnswerReportEvent } from '@home/components/ai/ai-chat-messages.component'; +import { AnswerFeedback, AnswerRating } from '@shared/models/ai-chat.models'; + +const END_IN_VIEW = 160; + +export interface AiLogScrollState { + scrolled: WritableSignal; + atEnd: WritableSignal; + newTurns: WritableSignal; +} + +export function aiTrackLogScroll(area: HTMLElement, state: AiLogScrollState, reachedEnd: () => void): void { + const scrolled = area.scrollTop > 0; + if (scrolled !== state.scrolled()) { + state.scrolled.set(scrolled); + } + const atEnd = area.scrollHeight - area.scrollTop - area.clientHeight < END_IN_VIEW; + if (atEnd !== state.atEnd()) { + state.atEnd.set(atEnd); + } + if (atEnd) { + state.newTurns.set(0); + reachedEnd(); + } +} + +export interface AiAnswerFeedback { + patch: (patch: {rating?: Exclude; reported?: boolean}) => void; + send: (feedback: Omit) => Observable; + failed: () => void; +} + +export function aiRateAnswer(event: AnswerRatingEvent, before: Exclude | undefined, feedback: AiAnswerFeedback): void { + feedback.patch({rating: event.rating === 'NONE' ? undefined : event.rating}); + feedback.send({rating: event.rating}).subscribe({ + error: () => { + feedback.patch({rating: before}); + feedback.failed(); + } + }); +} + +export function aiReportAnswer(event: AnswerReportEvent, feedback: AiAnswerFeedback, reported: () => void): void { + feedback.patch({reported: true}); + feedback.send({problem: event.problem, comment: event.comment}).subscribe({ + next: () => reported(), + error: () => { + feedback.patch({reported: false}); + feedback.failed(); + } + }); +} diff --git a/ui-ngx/src/app/modules/home/components/ai/ai-chat-title.component.html b/ui-ngx/src/app/modules/home/components/ai/ai-chat-title.component.html new file mode 100644 index 0000000000..35bd1082fd --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/ai/ai-chat-title.component.html @@ -0,0 +1,46 @@ + +@if (title(); as name) { + @if (renaming()) { + + + + + + } @else { + + + @if (renamable()) { + + } + + @if (level(); as current) { + + + {{ ('ai-assistant.status-' + current) | translate }} + + } + } +} @else { + {{ placeholder() }} +} diff --git a/ui-ngx/src/app/modules/home/components/ai/ai-chat-title.component.scss b/ui-ngx/src/app/modules/home/components/ai/ai-chat-title.component.scss new file mode 100644 index 0000000000..e1f96644e4 --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/ai/ai-chat-title.component.scss @@ -0,0 +1,151 @@ +// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: BUSL-1.1 +@use './ai-icon-button' as *; +@use './ai-breakpoints' as *; +:host { + display: contents; +} + +.ai-chat-name-wrap { + position: relative; + padding-right: 28px; + display: inline-flex; + align-items: center; + flex: 0 1 auto; + min-width: 0; + + &:hover .ai-chat-name-pen, &:focus-within .ai-chat-name-pen { + opacity: 1; + } +} + +.ai-chat-name { + flex: 0 1 auto; + min-width: 0; + overflow: hidden; + white-space: nowrap; + padding: 0; + border: 0; + background: none; + font: 500 15px/20px var(--tb-font); + letter-spacing: normal; + text-align: left; + color: var(--tb-ink); + cursor: default; + + &.clipped { + mask-image: linear-gradient(90deg, #000 calc(100% - 44px), transparent calc(100% - 8px)); + } + + &:focus-visible { + outline: 2px solid var(--ai-focus); + outline-offset: 2px; + border-radius: 4px; + } +} + +.ai-chat-name-pen { + position: absolute; + right: 0; + width: 24px; + height: 24px; + padding: 0; + border: 0; + border-radius: 6px; + background: transparent; + color: var(--tb-ink-60); + display: inline-flex; + align-items: center; + justify-content: center; + opacity: 0; + cursor: pointer; + transition: opacity .12s ease; + + .mat-icon { + width: 18px; + height: 18px; + font-size: 18px; + } + + &:hover { + background: rgba(0, 0, 0, 0.06); + color: var(--tb-ink); + } + + &:focus-visible { + opacity: 1; + outline: 2px solid var(--ai-focus); + outline-offset: 1px; + } +} + +.ai-chat-renaming { + display: inline-flex; + align-items: center; + gap: 2px; + flex: 1; + min-width: 0; + max-width: 480px; +} + +.ai-chat-name.compact { + font-size: var(--chat-line); + line-height: 18px; +} + +.ai-chat-status { + flex: none; + margin-left: auto; + display: inline-flex; + align-items: center; + gap: 6px; + font: 400 12.5px/20px var(--tb-font); + color: var(--tb-ink-54); + white-space: nowrap; + + &.error { + color: var(--tb-crit); + } + + .tb-ai-status-mark { + width: 10px; + height: 10px; + + &.running::before { + width: 8px; + height: 8px; + border-width: 1.5px; + } + } +} + +.ai-chat-rename { + flex: 1; + min-width: 0; + height: 28px; + box-sizing: border-box; + padding: 0; + border: 0; + border-bottom: 1.5px solid var(--tb-primary-500); + border-radius: 0; + outline: 0; + background: none; + font: 500 15px/20px var(--tb-font); + letter-spacing: normal; + color: var(--tb-ink); +} + + +.ai-chat-name-wrap.static { + padding-right: 0; +} + +.ai-ib { + @include ai-icon-button; +} + +@container k-head (max-width: #{$ai-head-status-hidden-below - 1px}) { + .ai-chat-status > span:last-child { + display: none; + } +} diff --git a/ui-ngx/src/app/modules/home/components/ai/ai-chat-title.component.ts b/ui-ngx/src/app/modules/home/components/ai/ai-chat-title.component.ts new file mode 100644 index 0000000000..63e562cb2a --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/ai/ai-chat-title.component.ts @@ -0,0 +1,89 @@ +// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: BUSL-1.1 +import { afterNextRender, Component, DestroyRef, effect, ElementRef, EventEmitter, inject, input, Output, signal } from '@angular/core'; +import { ChatLevel } from '@shared/models/ai-chat.models'; + +@Component({ + selector: 'tb-ai-chat-title', + templateUrl: './ai-chat-title.component.html', + styleUrls: ['./ai-chat-title.component.scss'], + standalone: false +}) +export class AiChatTitleComponent { + + title = input(null); + placeholder = input(''); + level = input(null); + statusTip = input(''); + renamable = input(true); + compact = input(false); + + @Output() renamed = new EventEmitter(); + + private host = inject>(ElementRef); + + renaming = signal(false); + nameClipped = signal(false); + + constructor() { + const head = typeof ResizeObserver !== 'undefined' ? new ResizeObserver(() => this.measure()) : null; + afterNextRender(() => { + const parent = this.host.nativeElement.parentElement; + if (parent) { + head?.observe(parent); + } + this.measure(); + }); + effect(() => { + this.title(); + this.renaming(); + setTimeout(() => this.measure()); + }); + inject(DestroyRef).onDestroy(() => head?.disconnect()); + } + + measure(): void { + const name = this.host.nativeElement.querySelector('.ai-chat-name'); + this.nameClipped.set(!!name && name.scrollWidth > name.clientWidth + 1); + } + + startRename(): void { + if (!this.title() || !this.renamable()) { + return; + } + this.renaming.set(true); + setTimeout(() => { + const field = this.host.nativeElement.querySelector('.ai-chat-rename'); + field?.focus(); + field?.select(); + }); + } + + cancelRename(): void { + this.renaming.set(false); + } + + onRenameKeydown(event: KeyboardEvent): void { + if (event.isComposing) { + return; + } + if (event.key === 'Enter') { + event.preventDefault(); + this.finishRename((event.target as HTMLInputElement).value); + } else if (event.key === 'Escape') { + event.stopPropagation(); + this.renaming.set(false); + } + } + + finishRename(value: string): void { + if (!this.renaming()) { + return; + } + this.renaming.set(false); + const title = value.trim(); + if (title && title !== this.title()) { + this.renamed.emit(title); + } + } +} diff --git a/ui-ngx/src/app/modules/home/components/ai/ai-chat.component.html b/ui-ngx/src/app/modules/home/components/ai/ai-chat.component.html new file mode 100644 index 0000000000..0b0ccb7268 --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/ai/ai-chat.component.html @@ -0,0 +1,508 @@ + +
+
+
+ + @if (variant() === 'panel') { + + } + +
+ @if (chatFiles().length && !titleRef?.renaming()) { + + } + @if (variant() === 'panel') { + @if (!titleRef?.renaming()) { + @if (chat()) { + + } + + @if (fullscreen() || !headNarrow()) { + + } + @if (!fullscreen()) { + + } + } + } @else if (chat() && !titleRef?.renaming()) { + + } + + @if (showGetStarted()) { + + } + @if (fullscreenEnabled()) { + + } +
+
+
+
+ @if (messages().length || loading()) { + + + } @else if (historyLoading()) { +
+ + {{ 'ai-assistant.loading-chat' | translate }} +
+ } @else if (!chatId() && docked()) { +
+ +

{{ startTitle() || ('ai-assistant.panel-title' | translate) }}

+

{{ startLine() || ('ai-assistant.panel-line' | translate) }}

+ @if (prompts().length) { +
+ @for (example of prompts(); track example.message) { + + } +
+ } +
+ } @else if (!chatId()) { +
+ + @if (variant() === 'panel') { +

{{ startTitle() || ('ai-assistant.panel-title' | translate) }}

+

{{ startLine() || ('ai-assistant.panel-line' | translate) }}

+ } @else { +

{{ (showGetStarted() ? 'ai-assistant.get-started.heading' : 'ai-assistant.what-to-work-on') | translate }}

+ } +
+ } +
+ @if (pill(); as current) { + + } + @if (creditsOut(); as limitType) { + + } @else if (limitOut(); as platformLimit) { + + } @else if (notice(); as current) { +
+ {{ current.text }} +
+ } @else if (keptEdits(); as kept) { +
+ {{ ('ai-assistant.kept-edits.' + kept.kind) | translate }} + + +
+ } + + +
+ @if (variant() === 'panel' && !docked() && !chatId() && !messages().length && !loading() && prompts().length) { +
+
+ @for (example of prompts(); track example.message) { + + } +
+
+ } + @if (showGetStarted() && !messages().length && !loading()) { +
+
+

{{ 'ai-assistant.get-started.examples' | translate }}

+

{{ 'ai-assistant.get-started.examples-hint' | translate }}

+
+
+ @for (example of examples; track example.key) { + + } +
+
+
+ +
+

{{ 'ai-assistant.cli.band.heading' | translate }}

+

{{ 'ai-assistant.cli.band.line' | translate }}

+
+ +
+ } + @if (variant() === 'page' && !showGetStarted() && !chatId() && !messages().length && !loading()) { +
+

{{ 'ai-assistant.start-a-task' | translate }}

+
+ @for (task of tasks; track task) { + + } +
+
+ } + @if (variant() === 'page' && !showGetStarted() && !chatId() && !messages().length && !loading()) { + + } +
+
+@if (shownFile(); as file) { + @if (fileOpen()) { + +

+ + {{ fileName(file.name).base }}{{ fileName(file.name).ext }} +

+
+ @if (!file.previewed) { +
+ @if (!fileBody()?.editing()) { + + } + + +
+ } +
+ + {{ fileCopied() ? ('ai-assistant.copied' | translate) : '' }} + @if (file.image) { + + } @else { + + } +
+
+ + + @if (fileMarks(); as marks) { +
+ + {{ (marks.from === marks.to ? 'ai-assistant.file.line' : 'ai-assistant.file.lines-range') | translate: {from: marks.from, to: marks.to} }} + {{ 'ai-assistant.file.marked' | translate }} + + + + + +
+ } @else { +
+ + @if (fileBody()?.editing()) { + @if (fileBody()?.dirty()) { + {{ 'ai-assistant.file.unsaved' | translate }} + } @else { + {{ 'ai-assistant.file.editing' | translate }} + } + @if (fileBody()?.caret(); as caret) { + + {{ 'ai-assistant.file.position' | translate: {line: caret.line, col: caret.col} }}@if (caret.selected) { ({{ 'ai-assistant.file.selected' | translate: {count: caret.selected} }})} + } + } @else if (fileBody()?.saved()) { + {{ 'ai-assistant.file.saved' | translate }} + } @else { + {{ 'ai-assistant.file.lines' | translate: {count: file.lines} }} + + {{ file.size }} + @if (file.edited) { + + {{ 'ai-assistant.file.edited-in-chat' | translate }} + } + } + + + @if (fileBody()?.editing()) { + @if (fileBody()?.dirty()) { + + + } @else { + + } + } @else if (chatId()) { + + } + +
+ } +
+
+ + + + + + @if (!fileBody()?.editing()) { + + } +
+ + {{ 'ai-assistant.file.theme' | translate }} +
+ + +
+
+
+ } +} +
+ + + @if (!fullscreen() && headNarrow()) { + + } + @if (docked() && (split() || splitAvailable())) { + + } + @if (chat()) { + + + + } + @for (group of otherChats(); track group.label) { +
{{ group.label | translate }}
+ @for (other of group.chats; track other.id) { + + } + } + +
+ + + + + + + + +
{{ 'ai-assistant.file.files-in-chat' | translate: {count: chatFiles().length} }}
+ @for (entry of chatFiles(); track entry.file.name) { + @if (unlisting() === entry.file.name) { +
+ + {{ 'ai-assistant.file.unlist-ask' | translate }} + {{ fileName(entry.file.name).base }}{{ fileName(entry.file.name).ext }} + + +
+ } @else { +
+ + +
+ } + } +
diff --git a/ui-ngx/src/app/modules/home/components/ai/ai-chat.component.scss b/ui-ngx/src/app/modules/home/components/ai/ai-chat.component.scss new file mode 100644 index 0000000000..928d69fb9d --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/ai/ai-chat.component.scss @@ -0,0 +1,793 @@ +// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: BUSL-1.1 +@use './ai-icon-button' as *; +:host { + position: relative; + display: flex; + flex-direction: column; + min-width: 0; + min-height: 0; + background: var(--tb-surface); + font-family: var(--tb-font); + font-size: var(--chat-line); + line-height: var(--chat-line-lh); + letter-spacing: var(--chat-text-ls); + color: var(--tb-ink); +} + +:host(.tb-fullscreen) { + margin: 0 !important; + border-radius: 0 !important; + box-shadow: none !important; +} + +.ai-chat-head { + position: relative; + container: k-head / inline-size; + flex: none; + display: flex; + align-items: center; + gap: 8px; + height: 48px; + box-sizing: border-box; + padding: 0 8px 0 16px; + border-bottom: 1px solid rgba(0, 0, 0, 0.06); + + @media (max-width: 599px) { + padding: 0 4px 0 8px; + } +} + +.ai-chat-head::after { + content: ''; + position: absolute; + left: 0; + right: 0; + top: 100%; + z-index: 3; + height: 12px; + background: linear-gradient(to bottom, color-mix(in srgb, var(--tb-ink) 9%, transparent), transparent); + opacity: 0; + transition: opacity .15s ease; + pointer-events: none; +} + +.ai-chat-head.scrolled::after { + opacity: 1; +} + +:host(.v-panel) .ai-chat-head { + height: 56px; + gap: 10px; + padding: 0 8px 0 12px; + border-bottom-color: rgba(0, 0, 0, 0.08); +} + +tb-ai-chat-title:has(.ai-chat-status) + .ai-chat-actions { + margin-left: 0; +} + +.ai-chat-actions { + flex: none; + margin-left: auto; + display: flex; + align-items: center; + gap: 2px; +} + +:host ::ng-deep .ai-ib { + @include ai-icon-button; + + &.more .mat-icon { + font-size: 20px; + width: 20px; + height: 20px; + } +} + +:host(.v-panel) ::ng-deep .ai-ib { + width: 28px; + height: 28px; +} + +.ai-chat-body { + position: relative; + flex: 1; + min-height: 0; + display: flex; + flex-direction: column; + align-items: center; + overflow-x: hidden; + overflow-y: auto; + padding: 20px 20px 0; + container: k-chat / inline-size; + + &.empty { + justify-content: flex-start; + padding-top: 64px; + padding-bottom: 24px; + } +} + +:host(.v-panel) .ai-chat-body { + padding: 12px 12px 0; + + &.empty { + padding-top: 0; + padding-bottom: 0; + } +} + +.ai-chat-log { + flex: 1 0 auto; + width: 100%; + max-width: 760px; + margin: 4px 0 24px; + overflow: visible; + + @container k-chat (min-width: 900px) { + max-width: 712px; + } +} + +.k-newchat, .k-prompts { + .prompts { + align-self: stretch; + display: flex; + flex-direction: column; + border-top: 1px solid var(--tb-line); + } + + .prompt { + display: flex; + align-items: center; + gap: 12px; + min-height: 44px; + padding: 0 8px; + border: 0; + border-bottom: 1px solid var(--tb-line); + background: none; + font: 400 14px/20px var(--tb-font); + color: var(--tb-ink); + text-align: left; + cursor: pointer; + transition: background .12s ease; + + > .mat-icon { + flex: none; + font-size: 18px; + width: 18px; + height: 18px; + color: var(--tb-ink-54); + } + + > span { + flex: 1; + min-width: 0; + } + + .go { + font-size: 16px; + width: 16px; + height: 16px; + color: var(--tb-ink); + opacity: 0; + transform: translateY(2px); + transition: opacity .12s ease, transform .12s ease; + } + + &:hover, &:focus-visible { + background: rgba(0, 0, 0, .035); + outline: none; + + .go { + opacity: .7; + transform: none; + } + } + } +} + +.k-newchat { + flex: 1 0 auto; + align-self: stretch; + margin: auto 0; + padding: 24px 6px 12px; + display: flex; + flex-direction: column; + align-items: center; + justify-content: center; + text-align: center; + + h3 { + margin: 14px 0 4px; + font: 500 var(--chat-title)/var(--chat-title-lh) var(--tb-font); + letter-spacing: 0; + color: var(--tb-ink); + } + + p { + margin: 0 0 20px; + max-width: 300px; + font-size: var(--chat-line); + line-height: var(--chat-line-lh); + color: var(--tb-ink-54); + } +} + +.ai-chat-start { + display: flex; + flex-direction: column; + align-items: center; + gap: 12px; + text-align: center; +} + +.ai-chat-start-title { + margin: 0; + font: 500 var(--chat-title)/var(--chat-title-lh) var(--tb-font); + letter-spacing: 0; + color: var(--tb-ink); +} + +.ai-chat-composer { + position: sticky; + bottom: 0; + z-index: 1; + flex: none; + width: 100%; + max-width: 760px; + padding: 12px 0 14px; + background: linear-gradient(color-mix(in srgb, var(--tb-surface) 0%, transparent), var(--tb-surface) 40%); +} + +.ai-chat-body:not(.empty) .ai-chat-composer ::ng-deep .composer-field:not(:focus-within) { + border-color: var(--tb-line); + box-shadow: 0 1px 2px rgba(16, 24, 40, 0.06), 0 10px 28px rgba(16, 24, 40, 0.10); +} + +.ai-sec { + width: 100%; + max-width: 680px; + margin-top: 16px; + text-align: left; +} + +.ai-sec-head h2 { + margin: 0; + font: 500 14px/20px var(--tb-font); + letter-spacing: normal; + color: var(--tb-text-secondary); +} + +.ai-tasks { + margin-top: 8px; + border-radius: 12px; + background: var(--tb-surface); + box-shadow: 0 0 0 1px rgba(16, 24, 40, 0.03), 0 1px 2px rgba(16, 24, 40, 0.06), 0 2px 10px rgba(16, 24, 40, 0.06); +} + +.ai-task { + display: grid; + grid-template-columns: minmax(0, 1fr) auto 20px; + align-items: center; + gap: 12px; + width: 100%; + min-height: 44px; + padding: 0 10px 0 16px; + border: 0; + background: none; + font: 400 14px/20px var(--tb-font); + letter-spacing: normal; + text-align: left; + color: var(--tb-ink); + cursor: pointer; + transition: background-color .12s ease; + + & + .ai-task { + border-top: 1px solid rgba(0, 0, 0, 0.06); + } + + &:first-child { + border-radius: 12px 12px 0 0; + } + + &:last-child { + border-radius: 0 0 12px 12px; + } + + &:hover { + background: rgba(0, 0, 0, 0.03); + + .mat-icon { + color: var(--tb-ink); + transform: translateX(2px); + } + } + + &:focus-visible { + outline: 0; + box-shadow: inset 0 0 0 2px var(--ai-focus); + } + + b { + min-width: 0; + overflow: hidden; + font-weight: 400; + text-overflow: ellipsis; + white-space: nowrap; + } + + small { + max-width: 280px; + overflow: hidden; + font-size: 12.5px; + line-height: 18px; + color: var(--tb-ink-76); + text-overflow: ellipsis; + white-space: nowrap; + + @media (max-width: 599px) { + display: none; + } + } + + .mat-icon { + width: 20px; + height: 20px; + font-size: 20px; + color: var(--tb-ink-38); + transition: transform .15s ease, color .15s ease; + } + + @media (prefers-reduced-motion: reduce) { + transition: none; + + .mat-icon { + transition: none; + } + } +} + +.ai-chat-body.empty .ai-chat-composer { + position: static; + max-width: 680px; + padding-top: 20px; + background: none; +} + +@media (max-width: 599px) { + .ai-chat-body { + padding: 16px 16px 0; + } +} + +:host(.v-panel) .ai-chat-composer, +:host(.v-panel) .ai-chat-body.empty .ai-chat-composer { + position: sticky; + width: auto; + max-width: none; + align-self: stretch; + margin: 0 -12px; + padding: 0; + background: var(--tb-surface); +} + +.ai-chat-start-line { + margin: -4px 0 0; + max-width: 420px; + font-size: var(--chat-line); + line-height: var(--chat-line-lh); + color: var(--tb-ink-54); +} + +.ai-chat-col { + position: relative; + flex: 1 1 0; + min-width: 0; + min-height: 0; + display: flex; + flex-direction: column; +} + +.art-cols.with-pane:not(.narrow) .ai-chat-col { + min-width: var(--chat-col-min, 340px); +} + +:host ::ng-deep .ai-ib.art-files-btn { + width: auto; + gap: 4px; + padding: 0 9px 0 8px; + border-radius: 10px; + color: var(--tb-ink-76); + + &:hover { + color: var(--tb-ink); + } + + &.shown, &[aria-expanded="true"] { + color: var(--ai-action); + } + + &[aria-expanded="true"] { + background: color-mix(in srgb, var(--ai-action) 10%, transparent); + } +} + +:host(.v-panel.split) .ai-chat-body { + padding: 20px 20px 0; +} + +:host(.v-panel.split) .ai-chat-log { + max-width: 712px; +} + +:host(.v-panel.split) .ai-chat-composer, +:host(.v-panel.split) .ai-chat-body.empty .ai-chat-composer { + width: 100%; + max-width: 760px; + align-self: center; + margin: 0; + padding: 12px 0 14px; + background: linear-gradient(color-mix(in srgb, var(--tb-surface) 0%, transparent), var(--tb-surface) 40%); +} + +:host(.v-panel.split) .k-newchat { + width: 100%; + max-width: 712px; + margin-left: auto; + margin-right: auto; +} + + +@container k-col (min-width: 481px) { + :host(.v-panel:not(.split)) { + .ai-chat-body { + padding: 20px 24px 0; + } + + .ai-chat-log { + max-width: var(--chat-read-log); + margin-bottom: 64px; + } + + .ai-chat-composer, .ai-chat-body.empty .ai-chat-composer { + margin: 0 -24px; + padding: 0 24px 16px; + background: var(--tb-surface); + pointer-events: none; + + > * { + pointer-events: auto; + } + + > tb-ai-prompt-input { + max-width: var(--chat-read); + margin: 0 auto; + } + } + + .ai-chat-body:not(.empty) .ai-chat-composer { + margin-top: -32px; + padding-top: 32px; + background: linear-gradient(180deg, color-mix(in srgb, var(--tb-surface) 0%, transparent), var(--tb-surface) 32px); + } + } +} + +.ai-sol-card { + display: grid; + grid-template-columns: 44px minmax(0, 1fr) auto; + align-items: center; + column-gap: 14px; + width: 100%; + max-width: 680px; + margin-top: 24px; + padding: 14px 16px 14px 14px; + border: 0; + border-radius: 12px; + background: var(--tb-surface); + text-align: left; + font: inherit; + cursor: pointer; + box-shadow: 0 0 0 1px rgba(16, 24, 40, 0.03), 0 1px 2px rgba(16, 24, 40, 0.06), 0 2px 10px rgba(16, 24, 40, 0.06); + transition: box-shadow .15s ease; + + &:hover { + box-shadow: 0 0 0 1px rgba(16, 24, 40, 0.05), 0 2px 4px rgba(16, 24, 40, 0.06), 0 8px 24px rgba(16, 24, 40, 0.10); + + .ai-sol-card-go .mat-icon { + transform: translateX(2px); + } + } + + &:focus-visible { + outline: 0; + box-shadow: 0 0 0 2px var(--ai-focus); + } +} + +.ai-sol-card-mark { + --ai-mark-fill: radial-gradient(80% 80% at 16% 10%, color-mix(in srgb, var(--tb-surface) 16%, transparent), transparent 62%), + linear-gradient(135deg in oklab, + color-mix(in oklab, var(--ai-light-teal) 34%, var(--tb-ink)) 0%, + color-mix(in oklab, var(--ai-light-aqua) 32%, var(--tb-ink)) 36%, + color-mix(in oklab, var(--ai-light-lilac) 36%, var(--tb-ink)) 68%, + color-mix(in oklab, var(--ai-light-peach) 34%, var(--tb-ink)) 100%); + --ai-mark-edge: 0 4px 12px color-mix(in oklab, var(--tb-ink) 18%, transparent); + --ai-mark-ink: var(--ai-on-action); + --ai-mark-ink-fill: linear-gradient(var(--ai-on-action), var(--ai-on-action)); +} + +.ai-sol-card-text { + display: grid; + gap: 2px; + min-width: 0; + + b { + font: 500 var(--chat-text)/var(--chat-text-lh) var(--tb-font); + color: var(--tb-ink); + } + + small { + font: 400 var(--chat-line)/var(--chat-line-lh) var(--tb-font); + color: var(--tb-ink-54); + } +} + +.ai-sol-card-go { + display: inline-flex; + align-items: center; + gap: 6px; + padding: 0 4px; + font: 500 var(--chat-line)/var(--chat-line-lh) var(--tb-font); + color: var(--ai-link); + + .mat-icon { + font-size: 18px; + width: 18px; + height: 18px; + transition: transform .12s cubic-bezier(.2, 0, 0, 1); + } +} + +@media (max-width: 599px) { + .ai-sol-card-go-t { + display: none; + } +} + +.ai-sec-lg { + margin-top: 32px; + + .ai-sec-head h2 { + font: 500 16px/22px var(--tb-font); + color: var(--tb-ink); + } + + .ai-sec-head p { + margin: 2px 0 0; + font: 400 14px/20px var(--tb-font); + color: var(--tb-ink-60); + } +} + +.k-pcards { + display: grid; + grid-template-columns: repeat(2, minmax(0, 1fr)); + grid-auto-rows: 1fr; + gap: 10px; + margin-top: 14px; +} + +.k-pcard { + display: flex; + flex-direction: column; + align-items: flex-start; + gap: 12px; + padding: 16px; + border: 1px solid rgba(0, 0, 0, 0.08); + border-radius: 12px; + background: var(--tb-surface); + text-align: left; + font: inherit; + cursor: pointer; + transition: border-color .15s ease; + + &:hover { + border-color: rgba(0, 0, 0, 0.18); + + .k-pcard-tile::before { + background-position: 100% 100%; + } + } + + &:focus-visible { + outline: 2px solid var(--ai-focus); + outline-offset: 2px; + } +} + +.k-pcard-tile { + position: relative; + isolation: isolate; + overflow: hidden; + flex: none; + display: inline-flex; + align-items: center; + justify-content: center; + width: 40px; + height: 40px; + border-radius: 11px; + background: var(--tb-surface); + color: var(--tb-ink); + box-shadow: var(--ai-mark-edge); + + &::before { + content: ''; + position: absolute; + inset: 0; + z-index: -1; + background: var(--ai-mark-fill); + background-size: 240% 240%; + background-position: 0% 0%; + transition: background-position 1.2s cubic-bezier(.4, 0, .2, 1); + } + + .mat-icon { + font-size: 22px; + width: 22px; + height: 22px; + } +} + +.k-pcard-body { + display: grid; + gap: 4px; + min-width: 0; + + b { + font: 500 15px/21px var(--tb-font); + color: var(--tb-ink); + } + + span { + font: 400 13.5px/19px var(--tb-font); + color: var(--tb-ink-76); + } +} + +@container k-col (max-width: 560px) { + .k-pcards { + grid-template-columns: minmax(0, 1fr); + } +} + +.ai-tour-link { + display: inline-flex; + align-items: center; + gap: 6px; + margin: 0 4px 0 0; + padding: 4px 10px; + border: 0; + border-radius: 16px; + background: none; + white-space: nowrap; + cursor: pointer; + font: 500 var(--chat-line)/var(--chat-line-lh) var(--tb-font); + color: var(--ai-link); + + &:hover { + background: var(--ai-selected-wash); + } + + &:focus-visible { + outline: 2px solid var(--ai-focus); + outline-offset: 2px; + } + + .mat-icon { + font-size: 18px; + width: 18px; + height: 18px; + } +} + +.ai-cli-band { + display: grid; + grid-template-columns: 40px minmax(0, 1fr) auto; + column-gap: 14px; + align-items: center; + width: 100%; + max-width: 680px; + box-sizing: border-box; + margin-top: 32px; + padding: 14px 14px 14px 16px; + border-radius: 14px; + text-align: left; + color: var(--tb-ink); + background: linear-gradient(160deg, color-mix(in srgb, var(--ai-dark-accent-pale) 62%, var(--tb-surface)), color-mix(in srgb, var(--ai-dark-accent-pale) 34%, var(--tb-surface))); + box-shadow: inset 0 0 0 1px color-mix(in srgb, var(--ai-dark-accent-soft) 40%, transparent); + + @media (max-width: 599px) { + grid-template-columns: 40px minmax(0, 1fr); + row-gap: 12px; + } +} + +.ai-cli-band-tile { + width: 40px; + height: 40px; + border-radius: 38%; + display: inline-flex; + align-items: center; + justify-content: center; + background: var(--ai-dark); + color: var(--ai-dark-accent); + + .mat-icon { + font-size: 22px; + width: 22px; + height: 22px; + } +} + +.ai-cli-band-text { + display: grid; + gap: 2px; + min-width: 0; + + h2 { + margin: 0; + font: 500 var(--chat-text)/var(--chat-text-lh) var(--tb-font); + color: var(--tb-ink); + } + + p { + margin: 0; + font: 400 var(--chat-line)/var(--chat-line-lh) var(--tb-font); + color: var(--tb-ink-54); + } +} + +.ai-cli-band-btn { + display: inline-flex; + align-items: center; + gap: 6px; + height: 36px; + padding: 0 12px 0 16px; + border: 0; + border-radius: 10px; + background: var(--ai-dark); + color: var(--ai-on-dark); + font: 500 var(--chat-line)/1 var(--tb-font); + letter-spacing: normal; + white-space: nowrap; + cursor: pointer; + transition: background-color .15s cubic-bezier(.2, 0, 0, 1); + + .mat-icon { + font-size: 18px; + width: 18px; + height: 18px; + transition: transform .15s cubic-bezier(.2, 0, 0, 1); + } + + &:hover { + background: color-mix(in srgb, var(--ai-dark) 86%, var(--ai-on-dark)); + + .mat-icon { + transform: translateX(2px); + } + } + + &:focus-visible { + outline: 2px solid var(--ai-focus); + outline-offset: 2px; + } + + @media (max-width: 599px) { + grid-column: 1 / -1; + justify-content: center; + } +} diff --git a/ui-ngx/src/app/modules/home/components/ai/ai-chat.component.ts b/ui-ngx/src/app/modules/home/components/ai/ai-chat.component.ts new file mode 100644 index 0000000000..7e914f5760 --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/ai/ai-chat.component.ts @@ -0,0 +1,1769 @@ +// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: BUSL-1.1 +import { escapeHtml } from '@core/utils'; +import { AI_TOOLTIP_PROVIDERS } from '@home/components/ai/ai-tooltip'; +import { AI_NARROW_HEAD_WIDTH } from '@home/components/ai/ai-breakpoints'; +import { aiCreditsLimitOf, AiCreditsLimitType } from '@home/components/ai/ai-credits.models'; +import { aiClientOs, aiPageView, isAiTitledView } from '@shared/models/ai-chat.models'; +import { getDefaultTimezone } from '@shared/models/time/time.models'; +import { + ChangeDetectionStrategy, + Component, + computed, + DestroyRef, + effect, + ElementRef, + inject, + input, + model, + OnDestroy, + OnInit, + output, + signal, + untracked, + ViewChild, + viewChild +} from '@angular/core'; +import { Router } from '@angular/router'; +import { DomSanitizer } from '@angular/platform-browser'; +import { TranslateService } from '@ngx-translate/core'; +import { Store } from '@ngrx/store'; +import { HttpErrorResponse } from '@angular/common/http'; +import { takeUntilDestroyed } from '@angular/core/rxjs-interop'; +import { EMPTY, Observable, of, Subject, throwError, timer } from 'rxjs'; +import { catchError, concatMap, finalize, retry, switchMap, takeUntil, tap } from 'rxjs/operators'; +import { AppState } from '@core/core.state'; +import { AiChatService } from '@core/http/ai-chat.service'; +import { AiChatsService } from '@core/services/ai-chats.service'; +import { AiAssistantPanelService } from '@core/services/ai-assistant-panel.service'; +import { AiWidgetCheckService } from '@home/components/ai/ai-widget-check.service'; +import { aiParse } from '@home/components/ai/ai-action-detail.models'; +import { WhiteLabelingService } from '@core/http/white-labeling.service'; +import { CustomMenuService } from '@core/http/custom-menu.service'; +import { UserService } from '@core/http/user.service'; +import { UnitService } from '@core/services/unit.service'; +import { AuthService } from '@core/auth/auth.service'; +import { ActionAuthUpdateUserDetails } from '@core/auth/auth.actions'; +import { ActionSettingsChangeLanguage } from '@core/settings/settings.actions'; +import { getCurrentAuthUser } from '@core/auth/auth.selectors'; +import { environment as env } from '@env/environment'; +import { ActionNotificationShow } from '@core/notification/notification.actions'; +import { isNotEmptyStr, parseHttpErrorMessage } from '@core/utils'; +import { aiChatNameOf } from '@home/components/ai/ai-text'; +import { ActionChatMessage, AiStartedFrom, ApprovalChatMessage, ChatMessage, GeneralChatMessage } from '@shared/models/solution-creator.models'; +import { + AiAssistantPromptExample, + AiChatClientContext, + AiPlatformLimit, + AiLinesQuote, + AiNotice, + AiPromptMessage, + aiQuoteText, + ChatInfo, + ChatLevel, + ApprovalResult, + ChatEvent, + SendChatMessageRequest, + ToolApprovalResult, + AiAction, + ToolExecutionRequestedEvent, + ToolExecutionResult, + ToolFinished, + ToolStarted +} from '@shared/models/ai-chat.models'; +import { aiActionText, aiActionWords, aiQuestionsOf, AiPlanStep, AiSpinKind, AiWorkMoment, AiWorkState, aiTurnPrompts, isHiddenAiAction, isKitCardTool, ASK_USER_TOOL, HAND_OVER_TOOL } from '@home/components/ai/ai-action.models'; +import { aiHandOverProgress } from '@home/components/ai/ai-hand-over.component'; +import { AiPlanRun } from '@home/components/ai/ai-plan.component'; +import { AiFile, aiFileMark, aiFileName, aiFileOf, downloadAiFile, downloadAiFileAsPng, WRITE_FILE_TOOL } from '@home/components/ai/ai-file.models'; +import { AiFileBodyComponent, AiFileMarks, AiFileSaver } from '@home/components/ai/ai-file-body.component'; +import { ClipboardService } from 'ngx-clipboard'; +import { AiChatMessagesComponent, AnswerRatingEvent, AnswerReportEvent } from '@home/components/ai/ai-chat-messages.component'; +import { EntityId } from '@shared/models/id/entity-id'; +import { EntityType } from '@shared/models/entity-type.models'; +import { AiAssistantViewType, AiRunAgain } from '@shared/models/ai-chat.models'; +import { aiReviewHead } from '@home/components/ai/ai-approval-card.component'; +import { AiChatTitleComponent } from '@home/components/ai/ai-chat-title.component'; +import { readStored, writeStored } from '@core/local-storage/stored'; +import { AiAnswerFeedback, aiRateAnswer, aiReportAnswer, aiTrackLogScroll } from '@home/components/ai/ai-chat-session'; +import { AiPromptInputComponent } from '@home/components/ai/ai-prompt-input.component'; + +const PROGRESS_TOOLS = new Set(['wait_agent_operation']); + +export type AiChatVariant = 'page' | 'panel'; + +interface AiGetStartedExample { + key: string; + icon: string; + file?: boolean; +} + +interface AiRefusal { + undo: () => void; + rerun?: boolean; +} + +@Component({ + changeDetection: ChangeDetectionStrategy.OnPush, + selector: 'tb-ai-chat', + templateUrl: './ai-chat.component.html', + styleUrls: ['./ai-chat.component.scss'], + standalone: false, + host: { + 'data-ai': '', + 'class': 'tb-ai-chat', + '[class.split]': 'split() && docked()', + '[class.v-page]': '!docked()', + '[class.v-panel]': 'docked()' + }, + providers: AI_TOOLTIP_PROVIDERS +}) +export class AiChatComponent implements OnInit, OnDestroy { + + private static readonly RESUME_ATTEMPTS = 4; + private static readonly RESUME_DELAY_MS = 2000; + private static readonly NOTICE_MS = 6000; + private static readonly MENU_CHATS = 4; + + private static readonly NEW_CHAT_TITLE = 'New chat'; + + @ViewChild(AiPromptInputComponent) promptInput: AiPromptInputComponent; + @ViewChild(AiChatTitleComponent) titleRef: AiChatTitleComponent; + + chatId = model(undefined); + + variant = input('page'); + + clientContext = input(undefined); + + toastTarget = input('aiChat'); + + fullscreenEnabled = input(true); + + prompts = input([]); + + startTitle = input(); + + startLine = input(); + + startPlaceholder = input(); + + startSuggestion = input(null); + + closed = output(); + + split = input(false); + + splitAvailable = input(false); + + splitToggle = output(); + + newSolution = output(); + + openCli = output(); + + getStarted = input(false); + + takeTour = output(); + + showGetStarted = computed(() => this.variant() === 'page' && this.getStarted() && !this.chatId()); + + readonly examples: AiGetStartedExample[] = [ + {key: 'mqtt', icon: 'memory'}, + {key: 'things-stack', icon: 'input'}, + {key: 'modbus', icon: 'lan'}, + {key: 'datasheet', icon: 'attach_file', file: true} + ]; + + otherChats = computed<{label: string; chats: ChatInfo[]}[]>(() => { + const others = this.chats.chats() + .filter(chat => chat.id !== this.chatId()) + .sort((a, b) => (b.updatedTime ?? b.createdTime) - (a.updatedTime ?? a.createdTime)); + const startedHere = new Set(this.panelService.chatsStartedHere()); + const here = others.filter(chat => startedHere.has(chat.id)).slice(0, AiChatComponent.MENU_CHATS - 1); + const recent = others.filter(chat => !startedHere.has(chat.id)).slice(0, Math.max(1, AiChatComponent.MENU_CHATS - here.length)); + return [ + ...(here.length ? [{label: 'ai-assistant.on-this-page', chats: here}] : []), + ...(recent.length ? [{label: 'ai-assistant.recent-chats', chats: recent}] : []) + ]; + }); + + headNarrow = signal(false); + + shownTitle = computed(() => { + const title = this.chat()?.title; + if (title && title !== AiChatComponent.NEW_CHAT_TITLE) { + return title; + } + const first = this.messages().find(message => message.from === 'USER') as GeneralChatMessage | undefined; + return typeof first?.content === 'string' && first.content.trim() ? aiChatNameOf(first.content) : title; + }); + + fullscreen = signal(false); + + docked = computed(() => this.variant() === 'panel' && !this.fullscreen()); + + readonly markdownStyles = [ + '.tb-markdown-view p, .tb-markdown-view h2, .tb-markdown-view h3, .tb-markdown-view h4, .tb-markdown-view h5, ' + + '.tb-markdown-view h6, .tb-markdown-view div.code-wrapper {padding-left: 0 !important;} ' + + '.tb-markdown-view ol, .tb-markdown-view ul {padding-left: 24px; padding-inline-start: 24px; padding-right: 0;}' + ]; + + messages = signal([]); + + loading = signal(false); + + historyLoading = signal(false); + + completedExecutions = signal>({}); + toolDurations = signal>({}); + + chat = computed(() => { + const id = this.chatId(); + return id ? this.chats.chats().find(chat => chat.id === id) : undefined; + }); + + newChatAutoApprove = signal(false); + + private static readonly FILE_WRAP_KEY = 'tbAiFileWrap'; + + private static readonly UNLISTED_KEY = 'tbAiUnlistedFiles:'; + + shownFile = signal(null); + + fileOpen = signal(false); + + private fileChat: string | undefined; + + fileWrap = signal(AiChatComponent.storedFileWrap()); + + fileCopied = signal(false); + + fileTheme = signal<'dark' | 'light'>(AiChatComponent.stored('tbAiFileTheme') === 'light' ? 'light' : 'dark'); + + fileWhitespace = signal(AiChatComponent.stored('tbAiFileWhitespace') === 'true'); + + fileMarks = signal(null); + + composerQuote = signal(null); + + fileBody = viewChild(AiFileBodyComponent); + + private composerBox = viewChild>('composer'); + + private composerHeight = effect(onCleanup => { + const box = this.composerBox()?.nativeElement; + const body = box?.parentElement; + if (!box || !body || typeof ResizeObserver === 'undefined') { + return; + } + const observer = new ResizeObserver(() => { + const field = box.querySelector('.composer-field') ?? box; + body.style.setProperty('--k-composer-h', Math.round(box.getBoundingClientRect().bottom - field.getBoundingClientRect().top) + 'px'); + }); + observer.observe(box); + onCleanup(() => observer.disconnect()); + }); + + private chatArea = viewChild>('chatArea'); + + private chatLog = viewChild(AiChatMessagesComponent, {read: ElementRef}); + + private composer = viewChild>('composer'); + + private logSizeEffect = effect(onCleanup => { + const area = this.chatArea()?.nativeElement; + const log = this.chatLog()?.nativeElement; + const composer = this.composer()?.nativeElement; + if (!area) { + return; + } + let composerHeight = composer?.offsetHeight ?? 0; + const observer = new ResizeObserver(() => { + const height = composer?.offsetHeight ?? 0; + if (height > composerHeight && untracked(this.atEnd)) { + area.scrollTop = area.scrollHeight; + } + composerHeight = height; + this.onLogScroll(area); + }); + observer.observe(area); + if (log) { + observer.observe(log); + } + if (composer) { + observer.observe(composer); + } + onCleanup(() => observer.disconnect()); + }); + + unlisted = signal>(new Set()); + + unlisting = signal(null); + + chatFiles = computed(() => { + const files = new Map(); + this.messages().forEach(message => { + if (message.from === 'ACTION' && message.data.tool === WRITE_FILE_TOOL) { + const file = aiFileOf(message.data.executionId, message.data.arguments, !!message.data.edited); + if (file) { + files.set(file.name, {file, running: message.data.status === 'RUNNING'}); + } + } + }); + const hidden = this.unlisted(); + return [...files.values()].filter(entry => !hidden.has(entry.file.name)); + }); + + readonly fileMark = aiFileMark; + + readonly fileName = aiFileName; + + readonly fileSaver: AiFileSaver = content => this.saveFile(content); + + private static stored(key: string): string | null { + return readStored(key); + } + + private static store(key: string, value: string): void { + writeStored(key, value); + } + + fileDark(file: AiFile): boolean { + return this.fileCode(file) && this.fileTheme() === 'dark'; + } + + fileCode(file: AiFile): boolean { + return !file.previewed || !!this.fileBody()?.editing(); + } + + setFileTheme(theme: 'dark' | 'light'): void { + this.fileTheme.set(theme); + AiChatComponent.store('tbAiFileTheme', theme); + } + + toggleFileWhitespace(): void { + this.fileWhitespace.update(value => !value); + AiChatComponent.store('tbAiFileWhitespace', String(this.fileWhitespace())); + } + + markedText(file: AiFile): string { + const marks = this.fileMarks(); + return marks ? file.content.replace(/\n$/, '').split('\n').slice(marks.from - 1, marks.to).join('\n') : ''; + } + + copyMarked(file: AiFile): void { + this.clipboard.copyFromContent(this.markedText(file)); + } + + askAboutMarks(file: AiFile): void { + const marks = this.fileMarks(); + if (!marks) { + return; + } + this.composerQuote.set({name: file.name, icon: file.icon, lang: file.lang === 'text' ? '' : file.lang, from: marks.from, to: marks.to, + text: this.markedText(file)}); + this.fileMarks.set(null); + if (this.docked()) { + this.fileOpen.set(false); + } + setTimeout(() => this.promptInput?.focus()); + } + + private fileCopiedTimer: ReturnType; + + private static storedFileWrap(): boolean { + return readStored(AiChatComponent.FILE_WRAP_KEY) === 'true'; + } + + autoApprove = computed(() => this.chatId() ? !!this.chat()?.autoApprove : this.newChatAutoApprove()); + + denyReasons = signal>({}); + + stopping = signal(false); + + work = signal(undefined); + + readonly tasks = ['connect-device', 'build-dashboard', 'set-up-alarm']; + + scrolled = signal(false); + + private atEnd = signal(true); + + private newTurns = signal(0); + + notice = signal(null); + + creditsOut = signal(null); + + limitOut = signal(null); + + private freshChatId: string | null = null; + + private noticeTimer: ReturnType; + + private seenMessages = 0; + + pill = computed<{mode: 'work' | 'new' | 'card'; kind: AiSpinKind; label: string; count: number} | null>(() => { + if (this.atEnd()) { + return null; + } + const waiting = this.waitingApproval(); + if (waiting) { + return {mode: 'card', kind: 'think', label: aiReviewHead(this.translate, waiting.data), count: 0}; + } + if (this.awaitingAnswer()) { + return {mode: 'card', kind: 'think', label: this.translate.instant('ai-assistant.question.needs-answer'), count: 0}; + } + if (this.loading() && !this.waitingApproval()) { + const running = this.messages().filter((message): message is ActionChatMessage => + message.from === 'ACTION' && message.data.status === 'RUNNING'); + if (running.length) { + const words = aiActionWords(running[0].data.tool, running[0].data.arguments); + return {mode: 'work', kind: words.kind, label: aiActionText(this.translate, words, 'run'), count: 0}; + } + const work = this.work(); + return {mode: 'work', kind: 'think', label: work ? this.translate.instant('ai-assistant.work.' + work.moment) : '', count: 0}; + } + const count = this.newTurns(); + return count ? {mode: 'new', kind: 'think', label: this.translate.instant('ai-assistant.new-count', {count}), count} : null; + }); + + private answeredApprovals = signal>(new Set()); + + dockShown = signal(false); + + waitingApproval = computed(() => { + if (this.autoApprove()) { + return undefined; + } + const completed = this.completedExecutions(); + const answered = this.answeredApprovals(); + return this.messages() + .filter((message): message is ApprovalChatMessage => message.from === 'APPROVAL') + .find(message => !completed[message.data.executionId] && !answered.has(message.data.executionId) && message.data.needsApproval); + }); + + private awaitingAnswer = computed(() => { + if (this.loading()) { + return false; + } + const messages = this.messages(); + const completed = this.completedExecutions(); + const answered = this.answeredApprovals(); + for (let i = messages.length - 1; i >= 0; i--) { + const message = messages[i]; + if (message.from === 'USER') { + return false; + } + if (message.from === 'ACTION' && message.data.tool === ASK_USER_TOOL) { + return aiQuestionsOf(message.data.arguments).length > 0; + } + if (message.from === 'APPROVAL' && completed[message.data.executionId]?.approvalStatus === ToolApprovalResult.TIMEOUT + && !answered.has(message.data.executionId)) { + return true; + } + } + return false; + }); + + suggestion = computed(() => { + if (this.loading() || this.waitingApproval()) { + return null; + } + if (!this.messages().length) { + if (this.chatId()) { + return null; + } + return this.docked() ? this.startSuggestion() + : this.translate.instant(this.showGetStarted() ? 'ai-assistant.get-started.suggestion' : 'ai-assistant.start-suggestion'); + } + return aiTurnPrompts(this.messages())[0]?.text ?? null; + }); + + placeholder = computed(() => !this.waitingApproval() && !this.messages().length && this.startPlaceholder() + ? this.startPlaceholder() + : this.translate.instant(this.waitingApproval() + ? 'ai-assistant.deny-placeholder' + : this.messages().length + ? 'ai-assistant.follow-up-prompt-placeholder' + : 'ai-assistant.prompt-placeholder')); + + private aiChat = inject(AiChatService); + private chats = inject(AiChatsService); + private panelService = inject(AiAssistantPanelService); + + readonly keptEdits = this.panelService.keptEdits; + + reloadKeptEdits(): void { + this.panelService.reloadKeptEdits(); + } + + dismissKeptEdits(): void { + this.panelService.clearKeptEdits(); + } + private whiteLabelingService = inject(WhiteLabelingService); + private customMenuService = inject(CustomMenuService); + private translate = inject(TranslateService); + private clipboard = inject(ClipboardService); + private store = inject(Store); + private userService = inject(UserService); + private unitService = inject(UnitService); + private authService = inject(AuthService); + private sanitizer = inject(DomSanitizer); + private destroyRef = inject(DestroyRef); + private host = inject>(ElementRef); + private router = inject(Router); + private widgetCheck = inject(AiWidgetCheckService); + + readonly hostElement = this.host.nativeElement; + + private loadChat$ = new Subject(); + private cancelMessage$ = new Subject(); + private messageCancelled = false; + private shownChatId: string | undefined; + private replyingChatId: string | undefined; + private appliedEffects = new Set(); + private logScrollBottom: number | undefined; + + private newTurnsEffect = effect(() => { + this.messages(); + untracked(() => this.countNewTurns()); + }); + + private readonly keptDrafts = new Map(); + + private composing = false; + + private chatIdEffect = effect(() => { + const chatId = this.chatId() ?? null; + untracked(() => { + const draft = this.keptDrafts.get(chatId); + if (draft !== undefined && !(chatId === null && this.composing)) { + this.keptDrafts.delete(chatId); + setTimeout(() => this.promptInput?.setValue(draft)); + } + if (this.fileChat !== chatId) { + this.shownFile.set(null); + this.fileOpen.set(false); + } + this.unlisting.set(null); + this.newChatAutoApprove.set(false); + this.unlisted.set(new Set(AiChatComponent.storedList(chatId ? AiChatComponent.UNLISTED_KEY + chatId : null))); + this.show(chatId); + }); + }); + + level = computed(() => { + const chat = this.chat(); + return chat ? this.chats.levelOf(chat) : null; + }); + + statusTip = computed(() => { + const chat = this.chat(); + return chat ? this.chats.tipOf(chat) : ''; + }); + + private openChatEffect = effect(onCleanup => { + const chatId = this.chatId(); + untracked(() => this.chats.setOpen(chatId, true)); + onCleanup(() => untracked(() => this.chats.setOpen(chatId, false))); + }); + + private waitingEffect = effect(onCleanup => { + const chatId = this.chatId(); + const waiting = !!this.waitingApproval() || this.awaitingAnswer(); + untracked(() => this.chats.setWaiting(chatId, waiting)); + onCleanup(() => untracked(() => this.chats.setWaiting(chatId, false))); + }); + + private deletedChatEffect = effect(() => { + const chatId = this.chatId(); + if (chatId && this.chats.loaded() && !this.chats.find(chatId)) { + untracked(() => this.chatId.set(undefined)); + } + }); + + ngOnInit(): void { + if (typeof ResizeObserver !== 'undefined') { + const head = new ResizeObserver(() => { + const width = this.hostElement.querySelector('.ai-chat-head')?.clientWidth ?? 0; + this.headNarrow.set(width > 0 && width < AI_NARROW_HEAD_WIDTH); + }); + head.observe(this.hostElement); + this.destroyRef.onDestroy(() => head.disconnect()); + } + this.loadChat$.pipe( + switchMap(id => this.aiChat.getChatMessages(id, {ignoreLoading: true, ignoreErrors: true}).pipe( + catchError(err => { + this.historyLoading.set(false); + this.showErrorMessage(err); + return EMPTY; + }) + )), + takeUntilDestroyed(this.destroyRef) + ).subscribe(messages => { + this.historyLoading.set(false); + this.showHistory(messages); + this.resumeTurn(this.chatId()); + }); + } + + ngOnDestroy(): void { + this.cancelActiveMessage(); + } + + toggleFullscreen(): void { + const log = this.host.nativeElement.querySelector('.ai-chat-body'); + this.logScrollBottom = log ? log.scrollHeight - log.clientHeight - log.scrollTop : undefined; + this.fullscreen.set(!this.fullscreen()); + } + + onFullscreenChanged(fullscreen: boolean): void { + this.fullscreen.set(fullscreen); + const scrollBottom = this.logScrollBottom; + if (scrollBottom !== undefined) { + setTimeout(() => { + const log = this.host.nativeElement.querySelector('.ai-chat-body'); + if (log) { + log.scrollTop = log.scrollHeight - log.clientHeight - scrollBottom; + } + }); + } + } + + focus(): void { + this.promptInput?.focus(); + } + + levelOf(chat: ChatInfo): ChatLevel | null { + return this.chats.levelOf(chat); + } + + newChat(): void { + this.chatId.set(undefined); + setTimeout(() => this.focus()); + } + + keepDraftForCompose(): void { + const chatId = this.chatId() ?? null; + const draft = this.promptInput?.message.value ?? ''; + if (draft.trim()) { + this.keptDrafts.set(chatId, draft); + } else { + this.keptDrafts.delete(chatId); + } + this.composing = true; + } + + composeText(text: string): void { + this.composing = false; + this.promptInput?.setValue(text); + setTimeout(() => this.focus()); + } + + ask(message: string, secrets?: Record): void { + this.sendMsgFromUser(secrets ? {message, resources: [], secrets} : {message, resources: []}); + } + + showFile(file: AiFile): void { + this.shownFile.set(file); + this.fileChat = this.chatId(); + this.fileMarks.set(null); + this.fileOpen.set(true); + } + + isShownFile(file: AiFile): boolean { + return this.fileOpen() && this.shownFile()?.name === file.name; + } + + askUnlist(file: AiFile, event: Event): void { + event.preventDefault(); + event.stopPropagation(); + this.unlisting.set(file.name); + setTimeout(() => document.querySelector('.art-list-confirm .art-list-no')?.focus()); + } + + keepListed(event: Event): void { + event.stopPropagation(); + this.unlisting.set(null); + } + + unlist(file: AiFile, event: Event): void { + event.stopPropagation(); + const chatId = this.chatId(); + const next = new Set(this.unlisted()).add(file.name); + this.unlisted.set(next); + this.unlisting.set(null); + if (chatId) { + AiChatComponent.store(AiChatComponent.UNLISTED_KEY + chatId, JSON.stringify([...next])); + } + this.showToast(this.translate.instant('ai-assistant.file.unlisted', {name: escapeHtml(file.name)}), 'success'); + } + + onFileDiscarded(file: AiFile): void { + this.showToast(this.translate.instant('ai-assistant.file.discarded', {name: escapeHtml(file.name)}), 'success'); + } + + private saveFile(content: string): Promise { + const chatId = this.chatId(); + const file = this.shownFile(); + if (!chatId || !file) { + return Promise.resolve(false); + } + return new Promise(resolve => this.aiChat.updatedChat(chatId, {fileEdit: {executionId: file.executionId, content}}, {ignoreLoading: true, ignoreErrors: true}) + .subscribe({ + next: () => { + this.messages.update(messages => messages.map(message => message.from === 'ACTION' && message.data.executionId === file.executionId + ? {...message, data: {...message.data, arguments: {...(message.data.arguments as object), content}, edited: true}} : message)); + const saved = aiFileOf(file.executionId, {name: file.name, content, summary: file.summary}, true); + if (saved) { + this.shownFile.set(saved); + } + resolve(true); + }, + error: err => { + this.showErrorMessage(err); + resolve(false); + } + })); + } + + private static storedList(key: string | null): string[] { + if (!key) { + return []; + } + try { + const value = JSON.parse(localStorage.getItem(key) ?? '[]'); + return Array.isArray(value) ? value.filter(item => typeof item === 'string') : []; + } catch { + return []; + } + } + + toggleFileWrap(): void { + this.fileWrap.update(wrap => !wrap); + writeStored(AiChatComponent.FILE_WRAP_KEY, String(this.fileWrap())); + } + + copyFile(file: AiFile): void { + if (this.clipboard.copyFromContent(file.content)) { + this.fileCopied.set(true); + clearTimeout(this.fileCopiedTimer); + this.fileCopiedTimer = setTimeout(() => this.fileCopied.set(false), 1500); + } + } + + downloadFile(file: AiFile): void { + downloadAiFile(file); + } + + downloadFileAsPng(file: AiFile): void { + downloadAiFileAsPng(file).catch(() => this.store.dispatch(new ActionNotificationShow({ + message: this.translate.instant('ai-assistant.file.png-failed'), + type: 'error', + modern: true, + verticalPosition: 'bottom', + horizontalPosition: 'center' + }))); + } + + runPlan(event: {run: AiPlanRun; steps: AiPlanStep[]}): void { + if (event.run.auto && !this.autoApprove()) { + this.setAutoApprove(true); + } + const left = event.run.skipped.map(number => this.translate.instant('ai-assistant.plan.leave-out', + {number, text: event.steps[number - 1]?.text ?? ''})); + this.ask([this.translate.instant('ai-assistant.plan.run-prompt'), ...left].join('\n')); + } + + changePlan(): void { + this.ask(this.translate.instant('ai-assistant.plan.change-ask')); + } + + openAllChats(): void { + this.router.navigate(['/ai-assistant']); + this.closed.emit(); + } + + startRename(): void { + this.titleRef?.startRename(); + } + + rename(title: string): void { + const chat = this.chat(); + if (chat) { + this.chats.rename(chat.id, title).subscribe({error: err => this.showErrorMessage(err)}); + } + } + + togglePinned(): void { + const chat = this.chat(); + if (chat) { + this.chats.setPinned(chat.id, !chat.pinned).subscribe({error: err => this.showErrorMessage(err)}); + } + } + + deleteChat(): void { + const chat = this.chat(); + if (chat) { + this.chats.confirmAndDelete(chat).subscribe({error: err => this.showErrorMessage(err)}); + } + } + + setAutoApprove(enabled: boolean): void { + const chatId = this.chatId(); + if (chatId) { + this.chats.setAutoApprove(chatId, enabled).subscribe({error: err => this.showErrorMessage(err)}); + } else { + this.newChatAutoApprove.set(enabled); + } + } + + stop(): void { + const chatId = this.chatId(); + if (!chatId || !this.loading() || this.stopping()) { + return; + } + this.stopping.set(true); + this.aiChat.stopChat(chatId, {ignoreLoading: true, ignoreErrors: true}).subscribe({ + error: err => { + this.stopping.set(false); + this.showErrorMessage(err); + } + }); + } + + onApprovalAction(event: ApprovalResult): void { + const chatId = this.chatId(); + if (event.autoApprove && chatId) { + this.chats.setAutoApprove(chatId, true).subscribe({error: err => this.showErrorMessage(err)}); + } + this.answeredApprovals.update(set => new Set(set).add(event.executionId)); + this.setWork(event.approved ? 'applying-change' : event.reason ? 'reading-what-to-change' : 'going-through-results'); + if (event.reason) { + this.denyReasons.update(reasons => ({...reasons, [event.executionId]: event.reason})); + } + const result: ApprovalResult = {executionId: event.executionId, approved: event.approved}; + if (event.reason) { + result.reason = event.reason; + } + this.aiChat.resolveToolApproval(result, {ignoreLoading: true, ignoreErrors: true}).subscribe(); + } + + startExample(example: AiGetStartedExample): void { + this.promptInput?.setValue(this.translate.instant('ai-assistant.get-started.example.' + example.key + '.prompt')); + if (example.file) { + this.promptInput?.openFilePicker(); + } + } + + startTask(task: string): void { + this.promptInput?.setValue(this.translate.instant('ai-assistant.task.' + task + '.prompt')); + } + + onRate(event: AnswerRatingEvent): void { + const answer = this.answerAt(event.index); + if (answer) { + aiRateAnswer(event, answer.rating, this.answerFeedback(answer)); + } + } + + onReport(event: AnswerReportEvent): void { + const answer = this.answerAt(event.index); + if (answer) { + aiReportAnswer(event, this.answerFeedback(answer), () => this.showToast(this.translate.instant('ai-assistant.feedback.thanks'), 'success')); + } + } + + private answerFeedback(answer: GeneralChatMessage): AiAnswerFeedback { + return { + patch: patch => this.patchAnswer(answer, patch), + send: feedback => this.chats.sendFeedback(this.chatId(), {answer: answer.content, ...feedback}), + failed: () => this.showErrorToast(this.translate.instant('ai-assistant.feedback.failed')) + }; + } + + private answerAt(index: number): GeneralChatMessage | null { + const message = this.messages()[index]; + return this.chatId() && message?.from === 'AI' && message.content ? message : null; + } + + private patchAnswer(answer: GeneralChatMessage, patch: Partial): void { + this.messages.update(list => list.map(message => message === answer || (message.from === 'AI' && message.content === answer.content + && message.time === answer.time) ? {...message, ...patch} as GeneralChatMessage : message)); + } + + answerLater(event: ApprovalResult): void { + if (event.reason) { + this.denyReasons.update(reasons => ({...reasons, [event.executionId]: event.reason})); + } + this.answeredApprovals.update(set => new Set(set).add(event.executionId)); + if (!this.runAgain(event.approved ? 'approve' : 'deny', event.executionId, event.reason)) { + this.reopenCard(event.executionId); + } + } + + private reopenCard(executionId: string): void { + this.answeredApprovals.update(set => { + const next = new Set(set); + next.delete(executionId); + return next; + }); + this.denyReasons.update(({[executionId]: _, ...rest}) => rest); + this.completedExecutions.update(map => map[executionId] ? {...map, [executionId]: {...map[executionId]}} : map); + } + + sendMsgFromUser(prompt: AiPromptMessage): void { + if (prompt.quote) { + prompt = {message: aiQuoteText(prompt.quote, prompt.message), resources: prompt.resources}; + this.composerQuote.set(null); + } + const waiting = this.waitingApproval(); + if (waiting) { + if (prompt.message.trim()) { + this.onApprovalAction({executionId: waiting.data.executionId, approved: false, reason: prompt.message.trim()}); + } + return; + } + const userMessage: GeneralChatMessage = prompt.resources.length + ? {from: 'USER', content: prompt.message, resources: prompt.resources, time: Date.now()} + : {from: 'USER', content: prompt.message, time: Date.now()}; + const startedFrom = this.messages().length ? undefined : this.startingPage(); + if (startedFrom) { + userMessage.startedFrom = startedFrom; + } + this.clearPassingNotice(); + this.messages.update(list => [...list, userMessage]); + if (this.loading() && this.chatId()) { + this.sendWhileWorking(prompt, userMessage); + return; + } + const closed = this.closeWaitingCards(); + this.sendMessage(prompt, undefined, {undo: () => { + this.reopenWaitingCards(closed); + this.restoreLastPrompt(); + }}).subscribe({ + error: err => { + if (this.isConnectionLost(err) && this.chatId()) { + this.setNotice('warn', 'wifi_off', 'connection-lost'); + this.resumeTurn(this.chatId(), true); + return; + } + this.reopenWaitingCards(closed); + this.onSendFailed(err, userMessage); + } + }); + } + + private startingPage(): AiStartedFrom | undefined { + const view = this.clientContext()?.view; + if (!view?.type || this.variant() !== 'panel') { + return undefined; + } + if (view.entityId) { + return {type: view.type, entityId: view.entityId}; + } + if (isAiTitledView(view.type)) { + return view.title || view.path ? {type: view.type, title: view.title, path: view.path} : undefined; + } + return view.type.endsWith('_LIST') || view.type === 'NOTIFICATION_INBOX' ? {type: view.type} : undefined; + } + + private show(chatId: string | undefined): void { + if (chatId === this.shownChatId) { + return; + } + this.cancelActiveMessage(); + this.titleRef?.cancelRename(); + this.shownChatId = chatId; + this.resetLogPosition(0); + this.messages.set([]); + this.limitOut.set(null); + this.completedExecutions.set({}); + this.toolDurations.set({}); + this.denyReasons.set({}); + this.answeredApprovals.set(new Set()); + this.historyLoading.set(!!chatId); + if (chatId) { + this.loadChat$.next(chatId); + } else { + setTimeout(() => this.promptInput?.focus()); + } + } + + resume(): void { + this.runAgain('resume'); + } + + runAgain(again: AiRunAgain, executionId?: string, reason?: string): boolean { + if (this.loading() || !this.chatId() || this.waitingApproval()) { + return false; + } + const failed = again === 'retry' ? this.messages().filter(message => (message as GeneralChatMessage).status === 'INCOMPLETE') : []; + const marker: GeneralChatMessage | null = again === 'retry' || again === 'resume' + ? {from: 'AI', content: '', status: again === 'retry' ? 'RETRIED' : 'RESUMED', time: Date.now()} : null; + const closed = again === 'retry' || again === 'resume' ? this.closeWaitingCards() : []; + const undo = () => { + this.messages.update(list => [...list.filter(message => message !== marker), ...failed]); + this.reopenWaitingCards(closed); + if (executionId) { + this.reopenCard(executionId); + } + }; + this.clearPassingNotice(); + this.messages.update(list => [...list.filter(message => !failed.includes(message)), ...(marker ? [marker] : [])]); + this.sendMessage({message: '', resources: []}, {again, executionId, reason}, {undo, rerun: true}).subscribe({ + error: err => { + if (this.isConnectionLost(err) && this.chatId()) { + this.setNotice('warn', 'wifi_off', 'connection-lost'); + this.resumeTurn(this.chatId(), true); + return; + } + undo(); + const limitType = aiCreditsLimitOf(err); + if (limitType) { + this.creditsOut.set(limitType); + } else { + setTimeout(() => this.showErrorMessage(err), 0); + } + } + }); + return true; + } + + private sendWhileWorking(prompt: AiPromptMessage, userMessage: ChatMessage): void { + const chatId = this.chatId(); + let ownTurn = false; + this.aiChat.sendChatMessage(chatId, this.chatRequest(prompt), {ignoreLoading: true, ignoreErrors: true}).pipe( + takeUntil(this.cancelMessage$), + concatMap(event => { + if (event.event === 'messageQueued') { + return of(event); + } + if (!ownTurn && !this.loading()) { + ownTurn = true; + this.chats.clearFailure(chatId); + this.startLoading(); + } + return this.handleChatEvent(event, {undo: () => this.restoreMessage(userMessage)}); + }), + finalize(() => { + if (ownTurn) { + this.stopLoading(); + } + }) + ).subscribe({ + error: err => this.onSendFailed(err, userMessage) + }); + } + + private discardFreshChat(): void { + const chatId = this.freshChatId; + this.freshChatId = null; + if (!chatId || chatId !== this.chatId()) { + return; + } + this.chats.discard(chatId).subscribe(); + this.shownChatId = undefined; + this.chatId.set(undefined); + } + + private onSendFailed(err: any, userMessage: ChatMessage): void { + const limitType = aiCreditsLimitOf(err); + if (limitType) { + this.restoreLastPrompt(); + this.discardFreshChat(); + this.creditsOut.set(limitType); + return; + } + this.messages.update(list => list.filter(message => message !== userMessage)); + setTimeout(() => this.showErrorMessage(err), 0); + } + + private chatRequest(prompt: AiPromptMessage): SendChatMessageRequest { + const request: SendChatMessageRequest = {message: prompt.message}; + if (prompt.resources.length) { + request.resources = prompt.resources.map(resource => resource.id); + } + const context = this.clientContext(); + request.clientContext = context ? {...context, os: context.os ?? aiClientOs()} + : {timeZone: getDefaultTimezone(), os: aiClientOs()} as AiChatClientContext; + const card = [...this.messages()].reverse().find((message): message is ActionChatMessage => + message.from === 'ACTION' && message.data.tool === HAND_OVER_TOOL); + const progress = card ? aiHandOverProgress(card.data.executionId) : null; + if (progress?.ticks.length) { + request.clientContext.handOver = {title: progress.title, ticked: progress.ticked, steps: progress.steps}; + } + if (prompt.secrets) { + request.secrets = prompt.secrets; + } + const editorDraft = this.panelService.editorDraft(); + if (editorDraft) { + request.editorDraft = editorDraft; + } + return request; + } + + private sendMessage(prompt: AiPromptMessage, again?: {again: AiRunAgain; executionId?: string; reason?: string}, + refused?: AiRefusal): Observable { + this.messageCancelled = false; + const startOrContinue$ = this.chatId() + ? of(null) + : this.chats.create(AiChatComponent.NEW_CHAT_TITLE, this.newChatAutoApprove()).pipe( + tap(chat => { + if (this.variant() === 'panel') { + this.panelService.noteStartedHere(chat.id); + } + this.freshChatId = chat.id; + this.shownChatId = chat.id; + this.chatId.set(chat.id); + }) + ); + const request = this.chatRequest(prompt); + this.limitOut.set(null); + if (again) { + request.again = again.again; + if (again.executionId) { + request.executionId = again.executionId; + } + if (again.reason) { + request.reason = again.reason; + } + } + this.setWork('reading-request', true); + this.loading.set(true); + return startOrContinue$.pipe( + tap(() => { + this.chats.clearFailure(this.chatId()); + this.startLoading(); + }), + switchMap(() => this.aiChat.sendChatMessage(this.chatId(), request, {ignoreLoading: true, ignoreErrors: true})), + takeUntil(this.cancelMessage$), + concatMap(event => this.handleChatEvent(event, refused)), + finalize(() => this.stopLoading()) + ); + } + + private resumeTurn(chatId: string, afterConnectionLoss = false): void { + if (!chatId) { + return; + } + let resumed = false; + this.messageCancelled = false; + const attempt$ = timer(afterConnectionLoss ? AiChatComponent.RESUME_DELAY_MS : 0).pipe( + tap(() => { + if (afterConnectionLoss) { + this.startLoading(); + } + }), + switchMap(() => this.aiChat.resumeChat(chatId, {ignoreLoading: true, ignoreErrors: true})) + ); + attempt$.pipe( + retry({ + count: afterConnectionLoss ? AiChatComponent.RESUME_ATTEMPTS : 0, + delay: (error, attempt) => this.isConnectionLost(error) + ? timer(attempt * AiChatComponent.RESUME_DELAY_MS) + : throwError(() => error) + }), + takeUntil(this.cancelMessage$), + concatMap(event => { + if (event.event === 'turnResumed') { + resumed = true; + if (afterConnectionLoss) { + this.setNotice('info', 'wifi', 'connected-again', AiChatComponent.NOTICE_MS); + } + this.startLoading(); + this.dropRunningReply(); + return of(event); + } + return this.handleChatEvent(event); + }), + finalize(() => { + if (resumed || afterConnectionLoss) { + this.stopLoading(); + } + }) + ).subscribe({ + error: () => { + if (afterConnectionLoss) { + this.setNotice('warn', 'wifi_off', 'reconnect-failed'); + } + }, + complete: () => { + if (this.messageCancelled || this.chatId() !== chatId) { + return; + } + if (afterConnectionLoss && !resumed) { + this.setNotice('info', 'wifi', 'connected-again', AiChatComponent.NOTICE_MS); + } + if (resumed || afterConnectionLoss) { + this.aiChat.getChatMessages(chatId, {ignoreLoading: true, ignoreErrors: true}) + .pipe(takeUntil(this.cancelMessage$)) + .subscribe(messages => this.showHistory(messages)); + } + } + }); + } + + private handleChatEvent(event: ChatEvent, refused?: AiRefusal): Observable { + if (event.event && event.event !== 'error' && event.event !== 'chatTitleGenerated') { + this.freshChatId = null; + } + switch (event.event) { + case 'assistantDelta': + this.appendDelta(event.data.text); + break; + case 'thinking': { + if (event.data?.headline && !event.data.tool && this.showProgress(event.data.headline)) { + break; + } + const headline = this.thinkingHeadline(event.data); + if (headline) { + this.work.update(work => ({...(work ?? {moment: 'going-through-results' as AiWorkMoment, since: Date.now()}), headline})); + } + break; + } + case 'assistantMessage': + this.messages.update(list => [...this.withoutStreaming(list), { + from: 'AI', content: event.data.message, time: Date.now(), + ...(event.data.references?.length ? {references: event.data.references} : {}), + ...(event.data.severities?.length ? {severities: event.data.severities} : {}), + ...(event.data.readings?.length ? {readings: event.data.readings} : {}) + }]); + break; + case 'toolExecutionRequested': + this.handleToolApproval(event); + break; + case 'toolExecutionResult': { + const replayed = this.completedExecutions()[event.data.executionId]?.approvalStatus === event.data.approvalStatus; + this.completedExecutions.update(map => ({...map, [event.data.executionId]: event.data})); + if (event.data.executionStatus === 'SUCCESS' && !replayed) { + const call = this.messages().find(message => (message.from === 'APPROVAL' || message.from === 'ACTION') + && message.data.executionId === event.data.executionId); + if (call?.from === 'APPROVAL' || call?.from === 'ACTION') { + this.applySideEffects(event.data.executionId, call.data.tool, call.data.arguments); + this.openCreatedReportTemplate(call.data.tool, event.data.affectedEntities); + this.openCreatedDashboard(call.data.tool, event.data.affectedEntities); + this.openCreatedWidget(call.data.tool, event.data.affectedEntities); + this.openCreatedScadaSymbol(call.data.tool, call.data.arguments, event.data.result); + this.leaveDeletedScadaSymbol(call.data.tool, call.data.arguments); + } + } + if (event.data.affectedEntities?.length && !replayed) { + this.emitUpdated(event.data.affectedEntities); + } + break; + } + case 'toolStarted': + this.work.update(work => work?.headline ? {moment: work.moment, since: work.since} : work); + this.startAction(event.data); + this.runClientTool(event.data); + break; + case 'toolFinished': + this.finishAction(event.data); + break; + case 'limitReached': + this.limitOut.set(event.data); + break; + case 'turnStopped': + this.messages.update(list => [...this.endStreaming(list), {from: 'AI', content: this.translate.instant('ai-assistant.stopped'), status: 'STOPPED', time: Date.now()}]); + break; + case 'chatTitleGenerated': + if (this.chatId() && event.data.title) { + this.chats.setTitle(this.chatId(), event.data.title); + } + break; + default: + if (event.event === 'error' && event.data?.code === 'CREDITS_USED_UP' && this.ranSteps()) { + this.creditsOut.set('POOL'); + this.messages.update(list => [...this.endStreaming(list), {from: 'AI', content: '', status: 'INCOMPLETE', + failure: {reason: 'CREDITS_USED_UP'}, time: Date.now()}]); + } else if (event.event === 'error' && event.data?.code) { + if (refused) { + refused.undo(); + } else { + this.restoreLastPrompt(); + } + if (event.data.code === 'CREDITS_USED_UP') { + if (!refused?.rerun) { + this.discardFreshChat(); + } + this.creditsOut.set('POOL'); + } else { + this.setNotice('warn', 'hourglass_top', 'rate-limited'); + } + } else if (event.event === 'error') { + const message = event.data?.message || this.translate.instant('ai-assistant.run-failed'); + this.chats.setFailed(this.chatId(), message); + const failure = {reason: event.data?.reason}; + this.messages.update(list => [...this.endStreaming(list), {from: 'AI', content: message, status: 'INCOMPLETE', failure, time: Date.now()}]); + } + } + return of(event); + } + + onLogScroll(area: HTMLElement): void { + aiTrackLogScroll(area, {scrolled: this.scrolled, atEnd: this.atEnd, newTurns: this.newTurns}, () => this.seenMessages = this.messages().length); + } + + goToEnd(area: HTMLElement): void { + const reduce = matchMedia('(prefers-reduced-motion: reduce)').matches; + area.scrollTo({top: area.scrollHeight, behavior: reduce ? 'auto' : 'smooth'}); + } + + private countNewTurns(): void { + const total = this.messages().length; + if (this.atEnd() || total <= this.seenMessages) { + this.seenMessages = total; + return; + } + const added = total - this.seenMessages; + this.seenMessages = total; + if (added) { + this.newTurns.update(count => count + added); + } + } + + private runClientTool(started: ToolStarted): void { + if (started.tool === 'check_scada_symbol') { + const values = (typeof started.arguments === 'string' ? aiParse(started.arguments) : started.arguments) as {symbol?: string} | undefined; + if (values?.symbol) { + this.widgetCheck.checkScadaSymbol(values.symbol).subscribe(reason => + this.aiChat.resolveToolApproval({executionId: started.executionId, approved: true, reason}, {ignoreLoading: true, ignoreErrors: true}).subscribe()); + } + return; + } + if (started.tool !== 'check_widget') { + return; + } + const args = typeof started.arguments === 'string' ? this.parseArguments(started.arguments) : started.arguments as {widgetTypeId?: string}; + if (!args?.widgetTypeId) { + return; + } + this.widgetCheck.check(args.widgetTypeId).subscribe(reason => + this.aiChat.resolveToolApproval({executionId: started.executionId, approved: true, reason}, {ignoreLoading: true, ignoreErrors: true}).subscribe()); + } + + private parseArguments(text: string): {widgetTypeId?: string} { + try { + return JSON.parse(text); + } catch (e) { + return null; + } + } + + private startAction(started: ToolStarted): void { + if (isHiddenAiAction(started.tool) || this.isApprovalExecution(started.executionId) + || this.messages().some(message => message.from === 'ACTION' && message.data.executionId === started.executionId)) { + return; + } + const action: AiAction = { + executionId: started.executionId, + tool: started.tool, + arguments: started.arguments, + status: isKitCardTool(started.tool) ? 'SUCCESS' : 'RUNNING', + startedAt: started.startedAt ?? Date.now(), + ...(started.readOnly ? {readOnly: true} : {}) + }; + this.messages.update(list => [...list, {from: 'ACTION', data: action}]); + } + + private openCreatedReportTemplate(tool: string | undefined, affected: EntityId[] | undefined): void { + const chatId = this.chatId(); + const created = affected?.find(entity => entity.entityType === EntityType.REPORT_TEMPLATE); + if (tool !== 'create_report_template' || !created || !chatId + || this.panelService.clientContext()?.view?.type !== AiAssistantViewType.REPORT_TEMPLATE_LIST) { + return; + } + this.panelService.carryChat(chatId); + this.router.navigate(['/reporting/templates', created.id]); + } + + private showProgress(progress: string): boolean { + const running = [...this.messages()].reverse() + .find(message => message.from === 'ACTION' && message.data.status === 'RUNNING' && PROGRESS_TOOLS.has(message.data.tool)); + if (running?.from !== 'ACTION') { + return false; + } + const executionId = running.data.executionId; + this.messages.update(list => list.map(message => message.from === 'ACTION' && message.data.executionId === executionId + ? {from: 'ACTION', data: {...message.data, progress, stages: message.data.progress && message.data.progress !== progress + ? [...(message.data.stages ?? []), message.data.progress] : message.data.stages}} : message)); + return true; + } + + private thinkingHeadline(data: {headline?: string; tool?: string; arguments?: unknown} | undefined): string | undefined { + return data?.tool ? aiActionText(this.translate, aiActionWords(data.tool, data.arguments), 'run') : undefined; + } + + private openCreatedDashboard(tool: string | undefined, affected: EntityId[] | undefined): void { + const chatId = this.chatId(); + const created = affected?.find(entity => entity.entityType === EntityType.DASHBOARD); + const view = this.panelService.clientContext()?.view?.type ?? aiPageView((this.router.url || '/').split(/[?#]/)[0]); + if (tool !== 'create_dashboard' || !created || !chatId + || (view !== AiAssistantViewType.DASHBOARD_LIST && view !== AiAssistantViewType.DASHBOARD_GROUP_LIST)) { + return; + } + this.panelService.carryChat(chatId); + this.router.navigate(['/dashboards', created.id]); + } + + private openCreatedWidget(tool: string | undefined, affected: EntityId[] | undefined): void { + const chatId = this.chatId(); + const created = affected?.find(entity => entity.entityType === EntityType.WIDGET_TYPE); + const view = this.panelService.clientContext()?.view?.type; + if ((tool !== 'create_widget' && tool !== 'build_widget') || !created || !chatId + || (view !== AiAssistantViewType.WIDGET_TYPE_LIST && view !== AiAssistantViewType.NEW_WIDGET_TYPE)) { + return; + } + this.panelService.carryChat(chatId); + this.router.navigate(['/resources/widgets-library/widget-types', created.id]); + } + + private openCreatedScadaSymbol(tool: string | undefined, args: unknown, result: string | undefined): void { + const chatId = this.chatId(); + const view = this.panelService.clientContext()?.view?.type ?? aiPageView((this.router.url || '/').split(/[?#]/)[0]); + const values = (aiParse(args) ?? {}) as {symbol?: string}; + if ((tool !== 'build_scada_symbol' && tool !== 'create_scada_symbol') || values.symbol || !chatId || !result?.startsWith('OK: ') + || (view !== AiAssistantViewType.SCADA_SYMBOL_LIST && view !== AiAssistantViewType.SCADA_SYMBOL)) { + return; + } + const link = (aiParse(result.slice(4)) as {link?: string} | undefined)?.link; + const path = /^tb-image;\/api\/images\/((?:system|tenant)\/[^/?#]+)$/.exec(link ?? '')?.[1]; + if (!path) { + return; + } + this.panelService.carryChat(chatId); + this.router.navigate(['/resources/scada-symbols', ...path.split('/')]); + } + + private leaveDeletedScadaSymbol(tool: string | undefined, args: unknown): void { + const chatId = this.chatId(); + const values = (aiParse(args) ?? {}) as {targetType?: string; targetId?: string}; + const shown = /^\/resources\/scada-symbols\/tenant\/([^/?#]+)/.exec(this.router.url || '')?.[1]; + if (tool !== 'delete' || values.targetType !== 'IMAGE' || !chatId || !shown) { + return; + } + const deleted = (values.targetId ?? '').trim().replace(/^tb-image;/, '').split('/').pop(); + if (deleted !== decodeURIComponent(shown)) { + return; + } + this.panelService.carryChat(chatId); + this.router.navigate(['/resources/scada-symbols']); + } + + private emitUpdated(entities: EntityId[]): void { + if (entities.length) { + this.panelService.emitUpdatedData(entities); + } + } + + private applySideEffects(executionId: string, tool: string | undefined, args: unknown): void { + if (!tool || this.appliedEffects.has(executionId)) { + return; + } + const values = (aiParse(args) ?? {}) as {target?: string; locale?: string; menuId?: string; targetType?: string; targetId?: string}; + switch (tool) { + case 'save_white_labeling': { + const target = values.target === 'LOGIN' ? 'LOGIN' : 'GENERAL'; + if (target === 'GENERAL') { + this.whiteLabelingService.loadUserWhiteLabelingParams().subscribe(); + } + this.panelService.emitWhiteLabelingSaved(target); + break; + } + case 'save_mail_template': + this.panelService.emitCustomizationSaved({kind: 'MAIL_TEMPLATES'}); + break; + case 'save_custom_translation': + if (values.locale && (values.locale === this.translate.currentLang || values.locale === this.translate.getDefaultLang())) { + this.translate.currentLoader.getTranslation(values.locale).subscribe(translation => + this.translate.setTranslation(values.locale, translation, true)); + } + this.panelService.emitCustomizationSaved({kind: 'TRANSLATION', locale: values.locale}); + break; + case 'save_mobile_qr_code': + this.panelService.emitCustomizationSaved({kind: 'MOBILE_QR_CODE'}); + break; + case 'save_two_factor_settings': + this.panelService.emitCustomizationSaved({kind: 'TWO_FACTOR'}); + break; + case 'save_my_profile': + this.applyOwnProfile(); + break; + case 'save_mail_server': + this.panelService.emitCustomizationSaved({kind: 'MAIL_SERVER'}); + break; + case 'save_notification_preferences': + this.panelService.emitCustomizationSaved({kind: 'ACCOUNT_NOTIFICATIONS'}); + break; + case 'save_my_two_factor': + case 'update_api_key': + this.panelService.emitCustomizationSaved({kind: 'ACCOUNT_SECURITY'}); + break; + case 'save_custom_menu': + case 'delete': + if (tool === 'delete' && values.targetType !== 'CUSTOM_MENU') { + return; + } + this.customMenuService.loadCustomMenu(true).subscribe(); + this.panelService.emitCustomizationSaved({kind: 'MENU', menuId: values.menuId ?? values.targetId, deleted: tool === 'delete'}); + break; + default: + return; + } + this.appliedEffects.add(executionId); + } + + private applyOwnProfile(): void { + const userId = getCurrentAuthUser(this.store)?.userId; + if (!userId) { + return; + } + this.userService.getUser(userId, {ignoreLoading: true}).subscribe(user => { + this.store.dispatch(new ActionAuthUpdateUserDetails({userDetails: { + additionalInfo: {...user.additionalInfo}, + authority: user.authority, + createdTime: user.createdTime, + tenantId: user.tenantId, + customerId: user.customerId, + email: user.email, + phone: user.phone, + firstName: user.firstName, + id: user.id, + lastName: user.lastName, + customMenuId: user.customMenuId + }})); + this.store.dispatch(new ActionSettingsChangeLanguage({userLang: user.additionalInfo?.lang || env.defaultLang, reload: false, ignoredLoad: false})); + this.unitService.setUnitSystem(user.additionalInfo?.unitSystem); + this.authService.refreshJwtToken(false); + this.panelService.emitCustomizationSaved({kind: 'PROFILE'}); + }); + } + + private finishAction(finished: ToolFinished): void { + this.toolDurations.update(map => ({...map, [finished.executionId]: finished.durationMs})); + const known = this.messages().find(message => message.from === 'ACTION' && message.data.executionId === finished.executionId); + if (known?.from === 'ACTION' && known.data.status !== 'RUNNING' && (known.data.result !== undefined || !isKitCardTool(known.data.tool))) { + return; + } + if (finished.status === 'SUCCESS') { + const started = this.messages().find(message => message.from === 'ACTION' && message.data.executionId === finished.executionId); + if (started?.from === 'ACTION') { + this.applySideEffects(finished.executionId, started.data.tool, started.data.arguments); + } + } + if (finished.affectedEntities?.length) { + this.emitUpdated(finished.affectedEntities); + } + this.messages.update(list => list.map(message => message.from === 'ACTION' && message.data.executionId === finished.executionId + ? {from: 'ACTION', data: {...message.data, status: finished.status, durationMs: finished.durationMs, result: finished.result, + affectedEntities: finished.affectedEntities}} + : message)); + const prompts = this.messages().some(message => message.from === 'ACTION' && message.data.executionId === finished.executionId + && isKitCardTool(message.data.tool)); + if (!prompts && !this.messages().some(message => message.from === 'ACTION' && message.data.status === 'RUNNING')) { + this.setWork('going-through-results', true); + } + } + + private isApprovalExecution(executionId: string): boolean { + return this.messages().some(message => message.from === 'APPROVAL' && message.data.executionId === executionId); + } + + private stopRunningActions(): void { + if (this.messages().some(message => message.from === 'ACTION' && message.data.status === 'RUNNING')) { + this.messages.update(list => list.map(message => message.from === 'ACTION' && message.data.status === 'RUNNING' + ? {from: 'ACTION', data: {...message.data, status: 'STOPPED', durationMs: Date.now() - message.data.startedAt}} + : message)); + } + } + + private setWork(moment: AiWorkMoment, restart = false): void { + if (restart || this.work()?.moment !== moment) { + this.work.set({moment, since: Date.now()}); + } + } + + private closeWaitingCards(): string[] { + const map = this.completedExecutions(); + const waiting = Object.keys(map).filter(id => map[id]?.approvalStatus === ToolApprovalResult.TIMEOUT); + if (waiting.length) { + this.completedExecutions.set({...map, ...Object.fromEntries(waiting.map(id => [id, {...map[id], approvalStatus: ToolApprovalResult.DENIED}]))}); + } + return waiting; + } + + private reopenWaitingCards(ids: string[]): void { + if (!ids.length) { + return; + } + this.completedExecutions.update(map => ({...map, ...Object.fromEntries(ids.filter(id => map[id]) + .map(id => [id, {...map[id], approvalStatus: ToolApprovalResult.TIMEOUT}]))})); + } + + private handleToolApproval(event: ToolExecutionRequestedEvent): void { + if (!event.data.needsApproval) { + return; + } + const id = event.data.executionId; + if (this.messages().some(message => message.from === 'APPROVAL' && message.data.executionId === id)) { + if (this.completedExecutions()[id]?.approvalStatus !== ToolApprovalResult.TIMEOUT) { + return; + } + this.completedExecutions.update(map => { + const {[id]: _, ...rest} = map; + return rest; + }); + this.messages.update(list => list.map(message => message.from === 'APPROVAL' && message.data.executionId === id + ? {from: 'APPROVAL', data: event.data} : message)); + return; + } + this.messages.update(list => [...list, {from: 'APPROVAL', data: event.data}]); + } + + private showHistory(messages: ChatMessage[]): void { + const completed: Record = {}; + for (const message of messages) { + const result = message.from === 'APPROVAL' ? (message as ApprovalChatMessage).result : undefined; + if (result) { + completed[result.executionId] = result; + } + } + this.completedExecutions.set(completed); + this.resetLogPosition(messages.length); + this.messages.set(messages); + } + + private resetLogPosition(seen: number): void { + this.atEnd.set(true); + this.scrolled.set(false); + this.newTurns.set(0); + this.seenMessages = seen; + } + + private appendDelta(text: string): void { + const last = this.messages()[this.messages().length - 1]; + if (last?.from === 'AI' && last.streaming) { + this.messages.update(list => [...list.slice(0, -1), {...last, content: last.content + text}]); + return; + } + this.work.set(undefined); + this.messages.update(list => [...list, {from: 'AI', content: text, streaming: true, time: Date.now()}]); + } + + private withoutStreaming(list: ChatMessage[]): ChatMessage[] { + const last = list[list.length - 1]; + return last?.from === 'AI' && last.streaming ? list.slice(0, -1) : list; + } + + private endStreaming(list: ChatMessage[]): ChatMessage[] { + const last = list[list.length - 1]; + return last?.from === 'AI' && last.streaming ? [...list.slice(0, -1), {...last, streaming: false}] : list; + } + + private dropRunningReply(): void { + this.messages.update(list => { + const lastUser = list.map(message => message.from).lastIndexOf('USER'); + return lastUser >= 0 ? list.slice(0, lastUser + 1) : list; + }); + } + + private cancelActiveMessage(): void { + this.messageCancelled = true; + this.cancelMessage$.next(); + this.stopLoading(); + this.promptInput?.reset(); + } + + private startLoading(): void { + this.loading.set(true); + this.setWork('reading-request'); + this.chats.setReplying(this.replyingChatId, false); + this.replyingChatId = this.chatId(); + this.chats.setReplying(this.replyingChatId, true); + } + + private stopLoading(): void { + if (this.loading()) { + this.chats.refresh().subscribe({error: () => {}}); + } + this.loading.set(false); + this.stopping.set(false); + this.work.set(undefined); + this.stopRunningActions(); + this.chats.setReplying(this.replyingChatId, false); + this.replyingChatId = undefined; + } + + private isConnectionLost(error: any): boolean { + return error instanceof HttpErrorResponse && error.status === 0; + } + + private showErrorMessage(error: any): void { + const responseType = isNotEmptyStr(error?.error) ? 'text' : undefined; + this.showErrorToast(parseHttpErrorMessage(error, this.translate, responseType, this.sanitizer).message); + } + + private setNotice(kind: AiNotice['kind'], icon: string, key: string, hideAfter?: number): void { + clearTimeout(this.noticeTimer); + const notice: AiNotice = {kind, icon, text: this.translate.instant('ai-assistant.notice.' + key)}; + this.notice.set(notice); + if (hideAfter) { + this.noticeTimer = setTimeout(() => { + if (this.notice() === notice) { + this.notice.set(null); + } + }, hideAfter); + } + } + + private clearPassingNotice(): void { + if (this.notice()?.kind !== 'block') { + clearTimeout(this.noticeTimer); + this.notice.set(null); + } + } + + private ranSteps(): boolean { + const messages = this.messages(); + const last = messages.map(message => message.from).lastIndexOf('USER'); + return messages.slice(last + 1).some(message => message.from === 'ACTION' || message.from === 'APPROVAL'); + } + + private restoreMessage(userMessage: ChatMessage): void { + const content = (userMessage as GeneralChatMessage).content; + this.messages.update(list => list.filter(message => message !== userMessage)); + if (content) { + setTimeout(() => this.promptInput?.setValue(content)); + } + } + + private restoreLastPrompt(): void { + const messages = this.messages(); + const last = messages.map(message => message.from).lastIndexOf('USER'); + if (last < 0) { + return; + } + const content = (messages[last] as GeneralChatMessage).content; + this.messages.set(messages.slice(0, last)); + if (content) { + setTimeout(() => this.promptInput?.setValue(content)); + } + } + + private showErrorToast(message: string): void { + this.showToast(message, 'error'); + } + + private showToast(message: string, type: 'error' | 'success'): void { + this.store.dispatch(new ActionNotificationShow({ + message, + target: this.toastTarget(), + modern: true, + type, + verticalPosition: 'bottom', + horizontalPosition: 'center' + })); + } +} diff --git a/ui-ngx/src/app/modules/home/components/ai/ai-code-block.ts b/ui-ngx/src/app/modules/home/components/ai/ai-code-block.ts new file mode 100644 index 0000000000..1ba63ff0d7 --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/ai/ai-code-block.ts @@ -0,0 +1,939 @@ +// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: BUSL-1.1 +import { TranslateService } from '@ngx-translate/core'; +import { readStored, writeStored } from '@core/local-storage/stored'; +import { aiRevealOpened } from '@home/components/ai/ai-disclosure.component'; + +export interface CodeLanguage { + lang: string; + label: string; + icon: string; +} + +const FOLD_LINES = 10; +const LONG_LINE = 72; +const COPIED_MS = 1500; +const SIDEWAYS = ['python', 'js', 'c', 'json', 'yaml']; + +const LANGUAGES: Record = { + bash: {lang: 'shell', label: 'Terminal', icon: 'terminal'}, + sh: {lang: 'shell', label: 'Terminal', icon: 'terminal'}, + shell: {lang: 'shell', label: 'Terminal', icon: 'terminal'}, + zsh: {lang: 'shell', label: 'Terminal', icon: 'terminal'}, + console: {lang: 'shell', label: 'Terminal', icon: 'terminal'}, + powershell: {lang: 'powershell', label: 'PowerShell', icon: 'terminal'}, + ps1: {lang: 'powershell', label: 'PowerShell', icon: 'terminal'}, + json: {lang: 'json', label: 'JSON', icon: 'data_object'}, + yaml: {lang: 'yaml', label: 'YAML', icon: 'description'}, + yml: {lang: 'yaml', label: 'YAML', icon: 'description'}, + log: {lang: 'log', label: 'Log', icon: 'notes'}, + diff: {lang: 'diff', label: 'Diff', icon: 'difference'}, + patch: {lang: 'diff', label: 'Diff', icon: 'difference'}, + js: {lang: 'js', label: 'JavaScript', icon: 'code'}, + javascript: {lang: 'js', label: 'JavaScript', icon: 'code'}, + ts: {lang: 'js', label: 'TypeScript', icon: 'code'}, + typescript: {lang: 'js', label: 'TypeScript', icon: 'code'}, + tbel: {lang: 'js', label: 'TBEL', icon: 'code'}, + python: {lang: 'python', label: 'Python', icon: 'code'}, + py: {lang: 'python', label: 'Python', icon: 'code'}, + c: {lang: 'c', label: 'C', icon: 'code'}, + cpp: {lang: 'c', label: 'C++', icon: 'code'}, + arduino: {lang: 'c', label: 'Arduino', icon: 'code'}, + java: {lang: 'c', label: 'Java', icon: 'code'}, + sql: {lang: 'text', label: 'SQL', icon: 'code'}, + xml: {lang: 'markup', label: 'XML', icon: 'code'}, + html: {lang: 'markup', label: 'HTML', icon: 'code'}, + svg: {lang: 'markup', label: 'SVG', icon: 'image'}, + css: {lang: 'css', label: 'CSS', icon: 'code'} +}; + +const FILE_LANGUAGES: Record = { + ino: {lang: 'c', label: 'Arduino', icon: 'code'}, + h: {lang: 'c', label: 'C', icon: 'code'}, + hpp: {lang: 'c', label: 'C++', icon: 'code'}, + md: {lang: 'text', label: 'Markdown', icon: 'article'}, + markdown: {lang: 'text', label: 'Markdown', icon: 'article'}, + txt: {lang: 'text', label: 'Text', icon: 'notes'}, + csv: {lang: 'text', label: 'CSV', icon: 'table_chart'}, + toml: {lang: 'text', label: 'TOML', icon: 'description'}, + ini: {lang: 'text', label: 'INI', icon: 'description'}, + conf: {lang: 'text', label: 'Config', icon: 'description'}, + env: {lang: 'shell', label: 'Env', icon: 'description'} +}; + +const LABEL_KEYS: Record = {Terminal: 'terminal', Log: 'log', Diff: 'diff', Text: 'text', Config: 'config'}; + +function shownLabel(label: string, translate: TranslateService): string { + return LABEL_KEYS[label] ? translate.instant('ai-assistant.code.label.' + LABEL_KEYS[label]) : label; +} + +export function fileLanguage(name: string): CodeLanguage { + const ext = name.includes('.') ? name.slice(name.lastIndexOf('.') + 1).toLowerCase() : ''; + return FILE_LANGUAGES[ext] ?? LANGUAGES[ext] ?? {lang: 'text', label: ext ? ext.toUpperCase() : 'Text', icon: 'description'}; +} + +export function decorateCodeBlocks(root: HTMLElement, translate: TranslateService, copy: (text: string) => boolean): void { + readFenceMeta(root); + mergeTabs(root, translate, copy); + root.querySelectorAll('pre').forEach(pre => { + if (!pre.closest('.tb-codeblock')) { + decorate(pre, translate, copy); + } + }); +} + +const FENCE_META = '\u2063tb:'; +const OS_TABS: Record = {macos: 'macos', mac: 'macos', windows: 'windows', linux: 'linux'}; + +export function aiFenceMeta(markdown: string): string { + let open: string | null = null; + return (markdown ?? '').split('\n').map(line => { + const fence = /^(\s*)(`{3,}|~{3,})(.*)$/.exec(line); + if (!fence) { + return line; + } + if (open) { + if (fence[2].startsWith(open) && !fence[3].trim()) { + open = null; + } + return line; + } + open = fence[2]; + const info = fence[3].trim(); + const tab = /(?:^|\s)tab=(.+)$/.exec(info)?.[1]?.trim(); + const words = info.replace(/(?:^|\s)tab=.+$/, '').trim().split(/\s+/).filter(Boolean); + const fileOf = (word: string) => /^[\w.-]+\.\w+$/.test(word ?? '') ? word : null; + const file = words.length > 1 ? fileOf(words[1]) : fileOf(words[0]); + if (!file && !tab) { + return line; + } + const lang = words.length > 1 || !file ? (words[0] ?? '') : fileLanguage(file).lang; + const meta = JSON.stringify({...(file ? {file} : {}), ...(tab ? {tab} : {})}); + return fence[1] + fence[2] + lang + '\n' + FENCE_META + encodeURIComponent(meta); + }).join('\n'); +} + +function readFenceMeta(root: HTMLElement): void { + root.querySelectorAll('pre > code').forEach(code => { + const text = code.textContent ?? ''; + if (!text.startsWith(FENCE_META)) { + return; + } + const end = text.indexOf('\n'); + let meta: {file?: string; tab?: string} = {}; + try { + meta = JSON.parse(decodeURIComponent(text.slice(FENCE_META.length, end < 0 ? text.length : end))); + } catch { + meta = {}; + } + code.textContent = end < 0 ? '' : text.slice(end + 1); + if (meta.file) { + code.setAttribute('data-file', meta.file); + code.setAttribute('data-label', meta.file); + } + if (meta.tab) { + code.setAttribute('data-tab', meta.tab); + } + }); +} + +function mergeTabs(root: HTMLElement, translate: TranslateService, copy: (text: string) => boolean): void { + const unitOf = (pre: Element): Element => { + const parent = pre.parentElement; + return parent && parent !== root && parent.tagName === 'DIV' && !/tb-markdown-view/.test(parent.className) + && parent.querySelectorAll(':scope > pre').length === 1 ? parent : pre; + }; + const pres = Array.from(root.querySelectorAll('pre')).filter(pre => pre.querySelector('code[data-tab]') && !pre.closest('.tb-codeblock')); + const used = new Set(); + pres.forEach(first => { + if (used.has(first)) { + return; + } + const group = [first]; + let next = unitOf(first).nextElementSibling; + while (next) { + const pre = next.matches('pre') ? next : next.querySelector(':scope > pre'); + if (!pre || !pre.querySelector('code[data-tab]')) { + break; + } + group.push(pre as HTMLPreElement); + next = unitOf(pre).nextElementSibling; + } + group.forEach(pre => used.add(pre)); + if (group.length < 2) { + return; + } + const tabs: CodeTab[] = group.map(pre => { + const code = pre.querySelector('code'); + const label = code.getAttribute('data-tab'); + const lang = /(?:^|\s)language-([\w+#-]+)/.exec(code.className)?.[1]?.toLowerCase(); + return {id: OS_TABS[label.toLowerCase()] ?? label, label, text: (code.textContent ?? '').replace(/\n$/, ''), lang}; + }); + const os = tabs.every(tab => Object.values(OS_TABS).includes(tab.id)); + const key = os ? 'os' : 'tabs:' + tabs.map(tab => tab.id).join('|'); + const local = /Windows/i.test(navigator.userAgent) ? 'windows' : /Mac/i.test(navigator.userAgent) ? 'macos' : 'linux'; + const preferred = codeTabGroup(key) ?? (os ? local : null); + const initial = Math.max(0, tabs.findIndex(tab => tab.id === preferred)); + const block = codeTabsBlock(tabs, tabs[0].lang ?? 'shell', translate, copy, initial, undefined, {group: key}); + const anchor = unitOf(group[0]); + anchor.parentNode.insertBefore(block, anchor); + group.forEach(pre => unitOf(pre).remove()); + }); +} + +function languageOf(pre: HTMLElement): CodeLanguage | null { + const classes = [pre.className, pre.querySelector('code')?.className ?? ''].join(' '); + const name = /(?:^|\s)language-([\w+#-]+)/.exec(classes)?.[1]?.toLowerCase(); + const file = pre.querySelector('code')?.getAttribute('data-file'); + if (file && (!name || name === 'text' || name === 'plaintext' || name === 'none')) { + return {...fileLanguage(file), label: file}; + } + if (!name || name === 'text' || name === 'plaintext' || name === 'none') { + return null; + } + const language = LANGUAGES[name] ?? {lang: 'text', label: name.toUpperCase(), icon: 'code'}; + const label = pre.querySelector('code')?.getAttribute('data-label'); + return label ? {...language, label} : language; +} + +function decorate(pre: HTMLElement, translate: TranslateService, copy: (text: string) => boolean): void { + const text = (pre.textContent ?? '').replace(/\n$/, ''); + const file = pre.querySelector('code')?.getAttribute('data-file'); + const noCopy = pre.querySelector('code')?.hasAttribute('data-nocopy'); + const alwaysFolds = !!pre.querySelector('code')?.hasAttribute('data-fold'); + const language = languageOf(pre); + const lang = language?.lang ?? 'text'; + const shell = lang === 'shell' || lang === 'powershell'; + const commands = shell ? splitCommands(text) : [text]; + const code = element('code', 'lang-' + lang); + if (commands.length > 1) { + code.append(...commands.map(command => { + const row = element('div', 'tb-cmd'); + row.append(...lines(lang, command), commandCopyBtn(command, translate, copy)); + return row; + })); + } else { + code.append(...lines(lang, text)); + } + pre.className = 'tb-code'; + pre.replaceChildren(code); + const lineCount = text.split('\n').length; + const folds = (lineCount > FOLD_LINES || alwaysFolds) && lang !== 'diff'; + const block = element('div', 'tb-codeblock'); + const wrapper = pre.closest('.code-wrapper'); + if (wrapper) { + wrapper.parentNode.insertBefore(pre, wrapper); + wrapper.remove(); + } + block.dataset.lang = lang; + block.classList.toggle('shell', shell); + block.classList.toggle('labeled', !!language || folds); + block.classList.toggle('folds', folds); + block.classList.toggle('folded', folds); + pre.parentNode.insertBefore(block, pre); + const copyButton = copyBtn(text, translate, copy); + if (language || folds) { + const head = element('div', 'tb-codeblock-head'); + const label = element('span', 'tb-codeblock-label'); + label.textContent = language ? shownLabel(language.label, translate) : translate.instant('ai-assistant.code.script'); + if (folds) { + const toggle = element('button', 'tb-codefold') as HTMLButtonElement; + toggle.type = 'button'; + toggle.setAttribute('aria-expanded', 'false'); + const size = element('span', 'tb-codeblock-size'); + size.textContent = translate.instant('ai-assistant.code.lines', {count: lineCount}); + toggle.append(...[language ? icon(language.icon, 'tb-mat-16') : null, label, size, icon('expand_more', 'tb-mat-18 tb-codefold-tg')].filter(Boolean)); + toggle.addEventListener('click', () => { + const open = block.classList.toggle('folded') === false; + toggle.setAttribute('aria-expanded', String(open)); + if (open) { + aiRevealOpened(block); + } + }); + head.append(toggle); + } else { + head.append(icon(language.icon, 'tb-mat-16'), label); + } + const wrap = wrapBtn(block, text, translate); + head.append(...[wrap, noCopy ? null : copyButton, file ? downloadBtn(file, text, translate) : null].filter(Boolean)); + block.append(head, pre); + } else { + copyButton.classList.add('floating'); + block.append(...[pre, noCopy ? null : copyButton].filter(Boolean)); + } +} + +export interface CodeTab { + label: string; + text: string; + id?: string; + lang?: string; +} + +export interface CodeBlockOptions { + group?: string; + label?: string; + icon?: boolean; + check?: boolean; + labelledCopy?: boolean; + classes?: string; +} + +const GROUP_EVENT = 'tb-code-tab'; +const LABELLED_COPIED_MS = 1600; + +interface GroupPick { + group: string; + id: string; + from: HTMLElement; +} + +type PickableBlock = HTMLElement & {tbPick?: (id: string) => void}; + +let groupListening = false; + +function listenToGroups(): void { + if (groupListening) { + return; + } + groupListening = true; + document.addEventListener(GROUP_EVENT, (event: CustomEvent) => { + document.querySelectorAll('[data-code-group]').forEach(block => { + if (block !== event.detail.from && block.dataset.codeGroup === event.detail.group) { + block.tbPick?.(event.detail.id); + } + }); + }); +} + +export function codeTabGroup(group: string): string | null { + return readStored('tb-code-' + group); +} + +function storeCodeTab(group: string, id: string): void { + writeStored('tb-code-' + group, id); +} + +export function pickCodeTab(group: string, id: string, from: HTMLElement = document.body): void { + storeCodeTab(group, id); + listenToGroups(); + document.dispatchEvent(new CustomEvent(GROUP_EVENT, {detail: {group, id, from}})); +} + +export function onCodeTabGroup(group: string, picked: (id: string) => void): () => void { + const listener = (event: CustomEvent) => { + if (event.detail.group === group) { + picked(event.detail.id); + } + }; + document.addEventListener(GROUP_EVENT, listener); + return () => document.removeEventListener(GROUP_EVENT, listener); +} + +export function codeTabsBlock(tabs: CodeTab[], lang: string, translate: TranslateService, copy: (text: string) => boolean, + initial = 0, picked?: (tab: CodeTab) => void, options: CodeBlockOptions = {}): HTMLElement { + const languageOf = (tab: CodeTab) => { + const name = tab.lang ?? lang; + return LANGUAGES[name] ?? {lang: 'text', label: name.toUpperCase(), icon: 'code'}; + }; + const keyOf = (tab: CodeTab) => tab.id ?? tab.label; + let current = Math.min(Math.max(initial, 0), tabs.length - 1); + if (options.group) { + const stored = codeTabGroup(options.group); + const index = tabs.findIndex(tab => keyOf(tab) === stored); + if (index >= 0) { + current = index; + } + } + const block: PickableBlock = element('div', 'tb-codeblock labeled tabbed' + (options.classes ? ' ' + options.classes : '')); + const head = element('div', 'tb-codeblock-head'); + const list = element('div', 'tb-codetabs'); + list.setAttribute('role', 'tablist'); + if (options.label) { + list.setAttribute('aria-label', options.label); + } + const code = element('code', ''); + const pre = element('pre', 'tb-code'); + pre.append(code); + const select = (index: number, byPerson: boolean) => { + if (index === current) { + return; + } + current = index; + paint(); + if (byPerson) { + if (options.group) { + pickCodeTab(options.group, keyOf(tabs[current]), block); + } + picked?.(tabs[current]); + } + }; + const buttons = tabs.map((tab, index) => { + const button = element('button', 'tb-codetab') as HTMLButtonElement; + button.type = 'button'; + button.setAttribute('role', 'tab'); + button.textContent = tab.label; + button.addEventListener('click', () => select(index, true)); + button.addEventListener('keydown', event => { + const step = event.key === 'ArrowRight' ? 1 : event.key === 'ArrowLeft' ? -1 : 0; + if (step) { + event.preventDefault(); + select((current + step + tabs.length) % tabs.length, true); + buttons[current].focus(); + } + }); + return button; + }); + const paint = () => { + const language = languageOf(tabs[current]); + block.dataset.lang = language.lang; + block.classList.toggle('shell', language.lang === 'shell' || language.lang === 'powershell'); + code.className = 'lang-' + language.lang; + buttons.forEach((button, index) => { + button.setAttribute('aria-selected', String(index === current)); + button.tabIndex = index === current ? 0 : -1; + }); + code.replaceChildren(...lines(language.lang, tabs[current].text)); + }; + if (options.group) { + listenToGroups(); + block.dataset.codeGroup = options.group; + block.tbPick = id => { + const index = tabs.findIndex(tab => keyOf(tab) === id); + if (index >= 0) { + select(index, false); + } + }; + } + list.append(...buttons); + head.append(...[options.icon === false ? null : icon(languageOf(tabs[current]).icon, 'tb-mat-16'), list, + copyBtn(() => tabs[current].text, translate, copy, options)].filter(Boolean)); + block.append(head, pre); + paint(); + return block; +} + +export function labelledCodeBlock(text: string, label: string, lang: string, translate: TranslateService, copy: (text: string) => boolean, + options: CodeBlockOptions = {}): HTMLElement { + const language = LANGUAGES[lang]?.lang ?? 'text'; + const block = element('div', 'tb-codeblock labeled' + (options.classes ? ' ' + options.classes : '')); + block.dataset.lang = language; + block.classList.toggle('shell', language === 'shell' || language === 'powershell'); + const head = element('div', 'tb-codeblock-head'); + const name = element('span', 'tb-codeblock-label'); + name.textContent = label; + head.append(name, copyBtn(text, translate, copy, options)); + const pre = element('pre', 'tb-code'); + const code = element('code', 'lang-' + language); + code.append(...lines(language, text)); + pre.append(code); + block.append(head, pre); + return block; +} + +export function valueBlock(label: string, value: string, translate: TranslateService, copy: (text: string) => boolean, + ariaLabel?: string): HTMLElement { + const block = element('div', 'tb-codeblock value'); + block.dataset.lang = 'text'; + const name = element('span', 'tb-codeblock-label'); + name.textContent = label; + const shown = element('code', 'tb-value'); + shown.textContent = value; + shown.title = value; + const button = copyBtn(value, translate, copy, {check: true}); + if (ariaLabel) { + button.setAttribute('aria-label', ariaLabel); + } + block.append(name, shown, button); + return block; +} + +export function commandRow(text: string, windows: boolean, translate: TranslateService, copy: (text: string) => boolean): HTMLElement { + const row = element('div', 'tb-cmdrow'); + const mark = element('span', 'tb-cmd-p'); + mark.setAttribute('aria-hidden', 'true'); + mark.textContent = windows ? '>' : '$'; + const command = element('code', 'tb-cmd-t'); + command.append(...lines('shell', text).flatMap(line => Array.from(line.childNodes))); + const button = copyBtn(text, translate, copy, {check: true}); + button.classList.add('tb-cmd-copy'); + button.setAttribute('aria-label', translate.instant('ai-assistant.copy') + ': ' + text); + row.append(mark, command, button); + return row; +} + +function wrapBtn(block: HTMLElement, text: string, translate: TranslateService): HTMLButtonElement | null { + if (!SIDEWAYS.includes(block.dataset.lang) || !text.split('\n').some(line => line.length > LONG_LINE)) { + return null; + } + const button = element('button', 'tb-codecopy tb-wrap') as HTMLButtonElement; + button.type = 'button'; + const tip = (on: boolean) => translate.instant(on ? 'ai-assistant.code.one-line-each' : 'ai-assistant.code.wrap-lines'); + button.dataset.tip = tip(false); + button.setAttribute('aria-label', translate.instant('ai-assistant.code.wrap-long-lines')); + button.setAttribute('aria-pressed', 'false'); + button.append(icon('wrap_text', 'tb-mat-16')); + button.addEventListener('click', () => { + const on = block.classList.toggle('wrap'); + button.setAttribute('aria-pressed', String(on)); + button.dataset.tip = tip(on); + }); + return button; +} + +function commandCopyBtn(text: string, translate: TranslateService, copy: (text: string) => boolean): HTMLButtonElement { + const button = copyBtn(text, translate, copy); + button.classList.add('tb-cmdcopy'); + return button; +} + +function copyBtn(text: string | (() => string), translate: TranslateService, copy: (text: string) => boolean, + options: CodeBlockOptions = {}): HTMLButtonElement { + const button = element('button', 'tb-codecopy') as HTMLButtonElement; + button.type = 'button'; + button.dataset.tip = translate.instant('ai-assistant.copy'); + button.dataset.copied = translate.instant('ai-assistant.copied'); + button.setAttribute('aria-label', translate.instant('ai-assistant.copy')); + const glyph = icon('content_copy', 'tb-mat-16'); + button.append(glyph); + let timer: ReturnType; + if (options.labelledCopy) { + button.classList.add('labelled'); + const word = element('span', 'lbl'); + word.setAttribute('aria-live', 'polite'); + word.textContent = translate.instant('ai-assistant.copy'); + button.append(word); + const done = (ms: number) => { + clearTimeout(timer); + button.classList.add('done'); + word.textContent = translate.instant('ai-assistant.copied'); + glyph.textContent = 'check'; + timer = setTimeout(() => { + button.classList.remove('done'); + word.textContent = translate.instant('ai-assistant.copy'); + glyph.textContent = 'content_copy'; + }, ms); + }; + button.addEventListener('click', () => { + if (copy(typeof text === 'function' ? text() : text)) { + done(LABELLED_COPIED_MS); + } + }); + return button; + } + button.append(icon('check', 'tb-mat-16 tb-copy-ok')); + button.addEventListener('click', () => { + if (copy(typeof text === 'function' ? text() : text)) { + button.classList.add('copied'); + announceCopied(translate.instant('ai-assistant.copied')); + clearTimeout(timer); + timer = setTimeout(() => button.classList.remove('copied'), COPIED_MS); + } + }); + return button; +} + +let copiedRegion: HTMLElement | null = null; + +export function announceCopied(words: string): void { + if (!copiedRegion?.isConnected) { + copiedRegion = element('div', 'tb-ai-sr-only'); + copiedRegion.setAttribute('role', 'status'); + copiedRegion.setAttribute('aria-live', 'polite'); + document.body.append(copiedRegion); + } + const region = copiedRegion; + region.textContent = ''; + setTimeout(() => region.textContent = words, 30); +} + +function downloadBtn(file: string, text: string, translate: TranslateService): HTMLButtonElement { + const button = element('button', 'tb-codecopy labelled tb-download') as HTMLButtonElement; + button.type = 'button'; + button.setAttribute('aria-label', translate.instant('ai-assistant.code.download-file', {name: file})); + const word = element('span', 'lbl'); + word.textContent = translate.instant('ai-assistant.code.download'); + button.append(icon('download', 'tb-mat-16'), word); + button.addEventListener('click', () => { + const url = URL.createObjectURL(new Blob([text.endsWith('\n') ? text : text + '\n'], {type: 'text/plain'})); + const link = document.createElement('a'); + link.href = url; + link.download = file; + link.click(); + setTimeout(() => URL.revokeObjectURL(url)); + }); + return button; +} + +function icon(name: string, size: string): HTMLElement { + const glyph = element('span', `mat-icon material-icons notranslate ${size}`); + glyph.setAttribute('aria-hidden', 'true'); + glyph.textContent = name; + return glyph; +} + +function element(tag: string, classes: string): HTMLElement { + const created = document.createElement(tag); + created.className = classes; + return created; +} + +type Piece = string | HTMLElement | null; + +interface ShellState { + command: boolean; + quote: string | null; + comment?: boolean; +} + +const KEYWORDS: Record = { + python: /^(import|from|as|def|return|if|else|elif|for|in|while|with|try|except|True|False|None|and|or|not|print)$/, + js: /^(const|let|var|await|async|function|return|if|else|for|of|new|true|false|null|import|from|export)$/, + c: /^(constexpr|const|char|int|uint16_t|uint32_t|bool|void|return|if|else|define|include|true|false)$/ +}; + +function splitCommands(text: string): string[] { + const groups: string[][] = []; + let quote: string | null = null; + let continued = false; + text.split('\n').forEach(line => { + if (!groups.length || (!quote && !continued)) { + groups.push([]); + } + groups[groups.length - 1].push(line); + quote = openQuoteAfter(line, quote); + continued = !quote && /\\\s*$/.test(line); + }); + return groups.map(group => group.join('\n')); +} + +function openQuoteAfter(line: string, quote: string | null): string | null { + for (let i = 0; i < line.length; i++) { + const char = line[i]; + if (quote) { + if (char === '\\' && quote === '"') { + i++; + } else if (char === quote) { + quote = null; + } + } else if (char === '\\') { + i++; + } else if (char === '#' && (i === 0 || /\s/.test(line[i - 1]))) { + break; + } else if (char === '"' || char === '\'') { + quote = char; + } + } + return quote; +} + +export function highlightCode(lang: string, text: string): HTMLElement[] { + return lines(lang, text); +} + +function lines(lang: string, text: string): HTMLElement[] { + const state: ShellState = {command: true, quote: null}; + const highlight = lineHighlighter(lang, state); + return text.split('\n').map((line, i, all) => { + let classes = 'tb-line'; + if (i && /\\\s*$/.test(all[i - 1])) { + classes += ' cont'; + } + if (lang === 'diff') { + classes += /^\+(?!\+\+ )/.test(line) ? ' add' : /^-(?!-- )/.test(line) ? ' del' : ''; + } + const span = element('span', classes); + span.append(...highlight(line).filter(piece => piece !== null && piece !== '')); + return span; + }); +} + +function lineHighlighter(lang: string, state: ShellState): (line: string) => Piece[] { + switch (lang) { + case 'shell': + case 'powershell': + return line => shellLine(line, state); + case 'json': + return jsonLine; + case 'yaml': + return yamlLine; + case 'log': + return logLine; + case 'diff': + return line => /^(\+\+\+ |--- |@@)/.test(line) ? [token('com', line)] : [line]; + case 'markup': + return line => markupLine(line, state); + case 'css': + return line => cssLine(line, state); + case 'python': + case 'js': + case 'c': + return line => codeLine(lang, line); + default: + return line => [line]; + } +} + +function blockComment(line: string, state: ShellState, open: string, close: string): [Piece[], string] { + const out: Piece[] = []; + let rest = line; + while (rest) { + if (state.comment) { + const end = rest.indexOf(close); + if (end < 0) { + out.push(token('com', rest)); + return [out, '']; + } + out.push(token('com', rest.slice(0, end + close.length))); + rest = rest.slice(end + close.length); + state.comment = false; + } + const start = rest.indexOf(open); + if (start < 0) { + return [out, rest]; + } + out.push(rest.slice(0, start)); + state.comment = true; + rest = rest.slice(start); + const end = rest.indexOf(close, open.length); + if (end >= 0) { + out.push(token('com', rest.slice(0, end + close.length))); + rest = rest.slice(end + close.length); + state.comment = false; + } else { + out.push(token('com', rest)); + return [out, '']; + } + } + return [out, '']; +} + +function markupLine(line: string, state: ShellState): Piece[] { + if (state.comment || line.includes(''); + return [...pieces.flatMap(piece => typeof piece === 'string' ? markupText(piece) : [piece]), ...markupText(rest)]; + } + return markupText(line); +} + +function markupText(text: string): Piece[] { + const out: Piece[] = []; + const pattern = /(?<\/?[\w:-]+)|(?\/?>)|(?[\w:@.[\]()*#-]+)(?==)|(?=)|(?"[^"]*"?|'[^']*'?)|(?\{\{.*?\}\})|(?@(?:if|else if|else|for|empty|switch|case|default|let)\b)|(?[^<>="'{@]+|[{@>])/g; + for (const match of text.matchAll(pattern)) { + const groups = match.groups ?? {}; + if (groups.tag) { + out.push(token('op', groups.tag.startsWith(' typeof piece === 'string' ? cssText(piece) : [piece]), ...cssText(rest)]; +} + +function cssText(text: string): Piece[] { + const declaration = /^(\s*)([\w-]+)(\s*:\s*)([^;{}]*)(;?)(.*)$/.exec(text); + if (declaration && !/[{]/.test(text) && !/^\s*[.#&:@]/.test(text)) { + const [, indent, property, colon, value, semi, tail] = declaration; + return [indent, token('key', property), token('op', colon), ...cssValue(value), semi ? token('op', semi) : '', ...cssText(tail)]; + } + const out: Piece[] = []; + matches(text, /@[\w-]+|[{};]|[^{};@]+/g).forEach(part => { + if (part.startsWith('@')) { + out.push(token('kw', part)); + } else if (/^[{};]$/.test(part)) { + out.push(token('op', part)); + } else { + out.push(part.trim() ? token('fn', part) : part); + } + }); + return out; +} + +function cssValue(value: string): Piece[] { + return matches(value, /#[0-9a-fA-F]{3,8}\b|-?\d*\.?\d+(?:px|%|em|rem|vh|vw|s|ms|deg|fr)?|"[^"]*"|'[^']*'|var\([^)]*\)|[^\s#\d"'(-]+\(?|\s+|./g) + .map(part => /^["']/.test(part) ? token('str', part) : /^(#|-?\d|\.\d)/.test(part) ? token('num', part) + : /^var\(/.test(part) ? token('var', part) : /^\s+$/.test(part) ? part : token('val', part)); +} + +function token(kind: string | null, text: string): Piece { + if (!kind) { + return text; + } + const span = element('span', 'hl-' + kind); + span.textContent = text; + return span; +} + +function shellLine(line: string, state: ShellState): Piece[] { + if (state.quote) { + const close = closingQuote(line, state.quote); + if (close < 0) { + return [token('str', line)]; + } + state.quote = null; + state.command = false; + return [token('str', line.slice(0, close + 1)), ...shellLine(line.slice(close + 1), state)]; + } + if (/^\s*#/.test(line)) { + state.command = true; + return [token('com', line)]; + } + const out: Piece[] = []; + matches(line, /"(?:\\.|[^"\\])*"?|'[^']*'?|\s+|&&|\|\||[|;]|[^\s|;&]+|&/g).forEach(word => { + if (/^\s+$/.test(word)) { + out.push(word); + return; + } + if (/^(&&|\|\||\||;|&)$/.test(word)) { + state.command = true; + out.push(token('op', word)); + return; + } + if (word === '\\') { + out.push(token('op', word)); + return; + } + if (/^["']/.test(word)) { + state.command = false; + if (word.length === 1 || !word.endsWith(word[0])) { + state.quote = word[0]; + } + out.push(token('str', word)); + return; + } + if (state.command && /^[A-Za-z_]\w*=/.test(word)) { + out.push(token('var', word)); + return; + } + const kind = state.command ? 'cmd' : /^--?[A-Za-z]/.test(word) ? 'flag' : /^https?:\/\//.test(word) ? 'str' + : /^\$/.test(word) ? 'var' : /^\d+(\.\d+)?$/.test(word) ? 'num' : null; + state.command = false; + out.push(token(kind, word)); + }); + if (!state.quote && !/\\\s*$/.test(line)) { + state.command = true; + } + return out; +} + +function closingQuote(line: string, quote: string): number { + for (let i = 0; i < line.length; i++) { + if (line[i] === '\\' && quote === '"') { + i++; + } else if (line[i] === quote) { + return i; + } + } + return -1; +} + +function codeLine(lang: string, line: string): Piece[] { + const comment = lang === 'python' ? /^(\s*)(#.*)$/ : /^(\s*)(\/\/.*)$/; + const match = line.match(comment); + if (match) { + return [match[1], token('com', match[2])]; + } + const words = new RegExp('"(?:\\\\.|[^"\\\\])*"?|\'(?:\\\\.|[^\'\\\\])*\'?|`[^`]*`?|' + + (lang === 'python' ? '#.*' : '\\/\\/.*') + '|\\d+(?:\\.\\d+)?|[A-Za-z_$][\\w$]*|\\s+|.', 'g'); + return matches(line, words).map((word, i, all) => { + if (/^(#|\/\/)/.test(word)) { + return token('com', word); + } + if (/^["'`]/.test(word)) { + return token('str', word); + } + if (/^\d/.test(word)) { + return token('num', word); + } + if (/^(true|false|null|undefined|True|False|None)$/.test(word)) { + return token('bool', word); + } + if (KEYWORDS[lang]?.test(word)) { + return token('kw', word); + } + if (/^[A-Za-z_$]/.test(word) && all[i + 1] === '(') { + return token('fn', word); + } + return /^[{}()[\],.:;=]$/.test(word) ? token('op', word) : word; + }); +} + +function jsonLine(line: string): Piece[] { + return matches(line, /"(?:\\.|[^"\\])*"(\s*:)?|-?\d+(?:\.\d+)?|true|false|null|\s+|./g).flatMap(word => { + if (/^".*:$/.test(word.replace(/\s/g, ''))) { + return [token('key', word.replace(/\s*:$/, '')), token('op', word.match(/\s*:$/)[0])]; + } + if (/^"/.test(word)) { + return [token('str', word)]; + } + if (/^-?\d/.test(word)) { + return [token('num', word)]; + } + if (/^(true|false|null)$/.test(word)) { + return [token('bool', word)]; + } + return [/^[{}[\],]$/.test(word) ? token('op', word) : word]; + }); +} + +function yamlValue(value: string): Piece[] { + const match = value.match(/^(\s*)(.*?)(\s+#.*)?$/); + const text = match[2]; + const kind = !text ? null : /^["']/.test(text) ? 'str' : /^(-?\d+(\.\d+)?)$/.test(text) ? 'num' + : /^(true|false|null|yes|no)$/i.test(text) ? 'bool' : /^[|>]-?$/.test(text) ? 'op' : 'val'; + return [match[1], text ? token(kind, text) : '', match[3] ? token('com', match[3]) : null]; +} + +function yamlLine(line: string): Piece[] { + if (/^\s*#/.test(line)) { + return [token('com', line)]; + } + const pair = line.match(/^(\s*)(-\s+)?([\w.\-/]+)(:)(.*)$/); + if (pair) { + return [pair[1], pair[2] ? token('op', pair[2]) : null, token('key', pair[3]), token('op', pair[4]), ...yamlValue(pair[5])]; + } + const item = line.match(/^(\s*)(-\s+)(.*)$/); + return item ? [item[1], token('op', item[2]), ...yamlValue(item[3])] : [line]; +} + +function logLine(line: string): Piece[] { + const match = line.match(/^(.*?\|\s*|\S+\s+\d\d:\d\d:\d\d\S*\s+)?(INFO|WARN(?:ING)?|ERROR|DEBUG)?(.*)$/); + const level = match[2]; + const kind = !level ? null : level === 'INFO' ? 'lvl' : level === 'DEBUG' ? 'com' : /^WARN/.test(level) ? 'warn' : 'err'; + return [match[1] ? token('com', match[1]) : null, level ? token(kind, level) : null, match[3]]; +} + +function matches(line: string, pattern: RegExp): string[] { + return line.match(pattern) ?? []; +} + +const LONG_CELL = 32; + +export function decorateTables(root: HTMLElement): void { + root.querySelectorAll('table td, table th').forEach((cell: HTMLElement) => { + cell.classList.toggle('long', (cell.textContent ?? '').trim().length > LONG_CELL); + }); + root.querySelectorAll('table td:first-child').forEach((cell: HTMLElement) => { + if (cell.firstElementChild?.classList.contains('k-md-lead') && cell.childNodes.length === 1) { + return; + } + const lead = element('span', 'k-md-lead'); + lead.append(...Array.from(cell.childNodes)); + cell.append(lead); + }); +} diff --git a/ui-ngx/src/app/modules/home/components/ai/ai-color-field.component.html b/ui-ngx/src/app/modules/home/components/ai/ai-color-field.component.html new file mode 100644 index 0000000000..26b3ad0bd7 --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/ai/ai-color-field.component.html @@ -0,0 +1,46 @@ + +
+ @for (option of question().options; track option.label) { + + } + +
+@if (other()) { +
+ + + + + + + + +
+ @if (wrong()) { + + } +} diff --git a/ui-ngx/src/app/modules/home/components/ai/ai-color-field.component.ts b/ui-ngx/src/app/modules/home/components/ai/ai-color-field.component.ts new file mode 100644 index 0000000000..27c16f7082 --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/ai/ai-color-field.component.ts @@ -0,0 +1,87 @@ +// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: BUSL-1.1 +import { ChangeDetectionStrategy, Component, computed, ElementRef, inject, input, model, output, signal } from '@angular/core'; +import { AiQuestion } from '@shared/models/solution-creator.models'; +import { aiColorOf, aiHexOf, aiIsFree } from '@home/components/ai/ai-question.models'; + +export function aiColorReady(question: AiQuestion, value: string): boolean { + return question.options.some(option => option.label === value) || !!aiHexOf(value); +} + +export function aiColorAnswer(question: AiQuestion, value: string): string { + return question.options.some(option => option.label === value) ? value : aiHexOf(value) ?? ''; +} + +@Component({ + selector: 'tb-ai-color-field', + templateUrl: './ai-color-field.component.html', + changeDetection: ChangeDetectionStrategy.OnPush, + standalone: false +}) +export class AiColorFieldComponent { + + question = input.required(); + value = model(''); + enter = output(); + + private elementRef: ElementRef = inject(ElementRef); + + readonly colorOf = aiColorOf; + readonly wrong = signal(false); + readonly other = computed(() => aiIsFree(this.question()) || !this.question().options.some(option => option.label === this.value())); + readonly hex = computed(() => this.other() ? aiHexOf(this.value()) : null); + readonly digits = computed(() => this.value().replace(/^#/, '')); + readonly ready = computed(() => aiColorReady(this.question(), this.value())); + + pick(label: string): void { + this.wrong.set(false); + this.value.set(label); + } + + openHex(): void { + if (!this.other()) { + this.value.set('#'); + } + setTimeout(() => this.elementRef.nativeElement.querySelector('.k-hex-in')?.focus()); + } + + typeHex(field: HTMLInputElement): void { + if (field.value.startsWith('#')) { + field.value = field.value.slice(1); + } + this.value.set('#' + field.value.trim()); + if (aiHexOf(field.value)) { + this.wrong.set(false); + } + } + + checkHex(field: HTMLInputElement): void { + this.wrong.set(!!field.value.trim() && !aiHexOf(field.value)); + } + + hexEnter(event: Event, field: HTMLInputElement): void { + if ((event as KeyboardEvent).isComposing) { + return; + } + event.preventDefault(); + if (aiHexOf(field.value)) { + this.enter.emit(event); + } else { + this.wrong.set(true); + } + } + + openPicker(picker: HTMLInputElement, field: HTMLInputElement): void { + picker.value = aiHexOf(field.value) ?? '#000000'; + try { + picker.showPicker(); + } catch { + picker.click(); + } + } + + pickColor(picker: HTMLInputElement, field: HTMLInputElement): void { + field.value = picker.value.slice(1).toUpperCase(); + this.typeHex(field); + } +} diff --git a/ui-ngx/src/app/modules/home/components/ai/ai-composer.module.ts b/ui-ngx/src/app/modules/home/components/ai/ai-composer.module.ts new file mode 100644 index 0000000000..6fb56345c0 --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/ai/ai-composer.module.ts @@ -0,0 +1,33 @@ +// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: BUSL-1.1 +import { NgModule } from '@angular/core'; +import { CommonModule } from '@angular/common'; +import { SharedModule } from '@shared/shared.module'; +import { AiCoreModule } from '@home/components/ai/ai-core.module'; +import { AiPromptInputComponent } from '@home/components/ai/ai-prompt-input.component'; +import { AiCreditsComponent } from '@home/components/ai/ai-credits.component'; +import { AiAttachmentsComponent } from '@home/components/ai/ai-attachments.component'; +import { AiAttachmentPreviewDialogComponent } from '@home/components/ai/ai-attachment-preview-dialog.component'; +import { AiShortcutsDialogComponent } from '@home/components/ai/ai-shortcuts-dialog.component'; + +@NgModule({ + declarations: [ + AiPromptInputComponent, + AiCreditsComponent, + AiAttachmentsComponent, + AiAttachmentPreviewDialogComponent, + AiShortcutsDialogComponent + ], + imports: [ + CommonModule, + SharedModule, + AiCoreModule + ], + exports: [ + AiCoreModule, + AiPromptInputComponent, + AiCreditsComponent, + AiAttachmentsComponent + ] +}) +export class AiComposerModule {} diff --git a/ui-ngx/src/app/modules/home/components/ai/ai-core.module.ts b/ui-ngx/src/app/modules/home/components/ai/ai-core.module.ts new file mode 100644 index 0000000000..3c15a3f45d --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/ai/ai-core.module.ts @@ -0,0 +1,46 @@ +// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: BUSL-1.1 +import { NgModule } from '@angular/core'; +import { CommonModule } from '@angular/common'; +import { SharedModule } from '@shared/shared.module'; +import { AiAssistantButtonComponent } from '@home/components/ai/ai-assistant-button.component'; +import { AiMarkComponent } from '@home/components/ai/ai-mark.component'; +import { AiSparkComponent } from '@home/components/ai/ai-spark.component'; +import { AiTipDirective } from '@home/components/ai/ai-tip.directive'; +import { AiFadeInImageDirective } from '@home/components/ai/ai-fade-in-image.directive'; +import { AiSpinComponent } from '@home/components/ai/ai-spin.component'; +import { AiSevMarkComponent } from '@home/components/ai/ai-sev-mark.component'; +import { AiNoTelemetryModalComponent } from '@home/components/ai/ai-no-telemetry-modal.component'; +import { AiTipIfCutDirective, AiTooltipChainDirective } from '@home/components/ai/ai-tooltip'; + +@NgModule({ + declarations: [ + AiAssistantButtonComponent, + AiMarkComponent, + AiSparkComponent, + AiTipDirective, + AiFadeInImageDirective, + AiSpinComponent, + AiSevMarkComponent, + AiNoTelemetryModalComponent, + AiTooltipChainDirective, + AiTipIfCutDirective + ], + imports: [ + CommonModule, + SharedModule + ], + exports: [ + AiAssistantButtonComponent, + AiMarkComponent, + AiSparkComponent, + AiTipDirective, + AiFadeInImageDirective, + AiSpinComponent, + AiSevMarkComponent, + AiNoTelemetryModalComponent, + AiTooltipChainDirective, + AiTipIfCutDirective + ] +}) +export class AiCoreModule {} diff --git a/ui-ngx/src/app/modules/home/components/ai/ai-credits-out.component.html b/ui-ngx/src/app/modules/home/components/ai/ai-credits-out.component.html new file mode 100644 index 0000000000..0e0709c24c --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/ai/ai-credits-out.component.html @@ -0,0 +1,49 @@ + + diff --git a/ui-ngx/src/app/modules/home/components/ai/ai-credits-out.component.scss b/ui-ngx/src/app/modules/home/components/ai/ai-credits-out.component.scss new file mode 100644 index 0000000000..178025672c --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/ai/ai-credits-out.component.scss @@ -0,0 +1,155 @@ +// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: BUSL-1.1 +:host { + display: block; + max-width: 760px; + margin: 0 auto 8px; +} + +.k-credits-out { + display: flex; + flex-direction: column; + gap: 12px; + padding: 14px 14px 14px 16px; + border: 1px solid color-mix(in srgb, var(--tb-crit) 18%, transparent); + border-radius: 12px; + background: + linear-gradient(180deg, color-mix(in srgb, var(--tb-crit) 5%, var(--tb-surface, #fff)) 0%, var(--tb-surface, #fff) 100%); + box-shadow: 0 1px 2px rgba(16, 24, 40, 0.06); + font: 400 14px/20px var(--tb-font, Roboto, sans-serif); + color: var(--tb-ink, rgba(0, 0, 0, 0.87)); +} + +.k-credits-out-head { + display: flex; + align-items: flex-start; + gap: 12px; +} + +.k-credits-out-mark { + display: inline-flex; + flex: none; + align-items: center; + justify-content: center; + width: 36px; + height: 36px; + border-radius: 10px; + background: color-mix(in srgb, var(--tb-crit) 10%, transparent); + color: var(--tb-crit); + + .mat-icon { + width: 20px; + height: 20px; + font-size: 20px; + } +} + +.k-credits-out-text { + display: flex; + flex: 1; + flex-direction: column; + gap: 2px; + min-width: 0; + + b { + font-weight: 500; + font-size: 15px; + line-height: 20px; + } + + span { + font-size: 13.5px; + line-height: 19px; + color: var(--tb-ink-76, rgba(0, 0, 0, 0.76)); + } +} + +.k-credits-out-close.mat-mdc-icon-button.mat-mdc-button-base { + --mdc-icon-button-state-layer-size: 32px; + --mat-icon-button-state-layer-size: 32px; + flex: none; + display: inline-flex; + align-items: center; + justify-content: center; + width: 32px; + height: 32px; + margin: -4px -4px 0 0; + padding: 0; + color: var(--tb-ink-54, rgba(0, 0, 0, 0.54)); + + .mat-icon { + width: 20px; + height: 20px; + font-size: 20px; + } +} + +.k-credits-out-meter { + display: flex; + align-items: center; + gap: 12px; + padding-left: 48px; +} + +.k-credits-out-bar { + flex: 1; + height: 6px; + overflow: hidden; + border-radius: 3px; + background: color-mix(in srgb, var(--tb-crit) 10%, transparent); + + > i { + display: block; + height: 100%; + border-radius: 3px; + background: var(--tb-crit); + } +} + +.k-credits-out-count { + flex: none; + font-size: 13px; + line-height: 18px; + font-variant-numeric: tabular-nums; + color: var(--tb-ink-76, rgba(0, 0, 0, 0.76)); +} + +.k-credits-out-actions { + display: flex; + flex-wrap: wrap; + align-items: center; + gap: 8px 12px; + padding-left: 48px; + + .mdc-button { + height: 32px; + } +} + +.k-credits-out-sent { + display: inline-flex; + align-items: center; + gap: 6px; + font-size: 13.5px; + line-height: 19px; + color: var(--tb-ink-76, rgba(0, 0, 0, 0.76)); + + .mat-icon { + width: 18px; + height: 18px; + font-size: 18px; + color: var(--tb-primary-500); + } +} + +.k-credits-out-failed { + font-size: 13px; + line-height: 18px; + color: var(--tb-crit); +} + +@media (max-width: 599px) { + .k-credits-out-meter, .k-credits-out-actions { + padding-left: 0; + } +} diff --git a/ui-ngx/src/app/modules/home/components/ai/ai-credits-out.component.ts b/ui-ngx/src/app/modules/home/components/ai/ai-credits-out.component.ts new file mode 100644 index 0000000000..f7327d5df8 --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/ai/ai-credits-out.component.ts @@ -0,0 +1,94 @@ +// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: BUSL-1.1 +import { ChangeDetectionStrategy, Component, computed, DestroyRef, inject, input, NgZone, OnInit, output, signal } from '@angular/core'; +import { Store } from '@ngrx/store'; +import { AppState } from '@core/core.state'; +import { getCurrentAuthUser } from '@core/auth/auth.selectors'; +import { TelemetryWebsocketService } from '@core/ws/telemetry-websocket.service'; +import { NotificationService } from '@core/http/notification.service'; +import { ShortNumberPipe } from '@shared/pipe/short-number.pipe'; +import { readStored, writeStored } from '@core/local-storage/stored'; +import { AiCreditsLimitType, aiCreditsResetDate, watchAiCredits } from '@home/components/ai/ai-credits.models'; + +type RequestState = 'idle' | 'sending' | 'sent' | 'failed'; + +@Component({ + selector: 'tb-ai-credits-out', + templateUrl: './ai-credits-out.component.html', + styleUrls: ['./ai-credits-out.component.scss'], + changeDetection: ChangeDetectionStrategy.OnPush, + standalone: false +}) +export class AiCreditsOutComponent implements OnInit { + + limitType = input('TENANT'); + + dismissed = output(); + + private notificationService = inject(NotificationService); + private shortNumber = inject(ShortNumberPipe); + private readonly tenantId = getCurrentAuthUser(inject(Store))?.tenantId; + + readonly used = signal(null); + readonly limit = signal(null); + readonly resetDate = aiCreditsResetDate(); + readonly state = signal('idle'); + + readonly tenantLimit = computed(() => this.limitType() === 'TENANT'); + readonly hasUsage = computed(() => this.tenantLimit() && !!this.limit()); + readonly usedLabel = computed(() => this.shortNumber.transform(this.used() ?? 0, {roundDown: true})); + readonly limitLabel = computed(() => this.shortNumber.transform(this.limit() ?? 0)); + readonly percent = computed(() => { + const limit = this.limit(); + return limit ? Math.min(100, Math.round((this.used() ?? 0) / limit * 100)) : 100; + }); + + constructor() { + const subscriber = watchAiCredits(inject(TelemetryWebsocketService), inject(NgZone), update => { + if (update.count !== undefined) { + this.used.set(update.count); + } + if (update.limit !== undefined) { + this.limit.set(update.limit); + } + }); + inject(DestroyRef).onDestroy(() => subscriber.unsubscribe()); + } + + ngOnInit(): void { + if (this.wasRequested()) { + this.state.set('sent'); + } + } + + request(): void { + if (this.state() === 'sending' || this.state() === 'sent') { + return; + } + this.state.set('sending'); + this.notificationService.sendAiCreditsLimitIncreaseRequest(this.limitType(), {ignoreLoading: true, ignoreErrors: true}).subscribe({ + next: () => { + this.rememberRequested(); + this.state.set('sent'); + }, + error: () => this.state.set('failed') + }); + } + + private requestKey(): string { + return `tb-ai-credits-request:${this.tenantId}:${this.limitType()}`; + } + + private wasRequested(): boolean { + return readStored(this.requestKey()) === String(this.periodStart()); + } + + private rememberRequested(): void { + writeStored(this.requestKey(), String(this.periodStart())); + } + + private periodStart(): number { + const now = new Date(); + return Date.UTC(now.getUTCFullYear(), now.getUTCMonth(), 1); + } +} diff --git a/ui-ngx/src/app/modules/home/components/ai/ai-credits-popup.component.html b/ui-ngx/src/app/modules/home/components/ai/ai-credits-popup.component.html deleted file mode 100644 index 7f6baee9a2..0000000000 --- a/ui-ngx/src/app/modules/home/components/ai/ai-credits-popup.component.html +++ /dev/null @@ -1,21 +0,0 @@ - -
-
- solution-creator.ai-credits - -
-
- -
-
diff --git a/ui-ngx/src/app/modules/home/components/ai/ai-credits-popup.component.scss b/ui-ngx/src/app/modules/home/components/ai/ai-credits-popup.component.scss deleted file mode 100644 index 371f0a9ebd..0000000000 --- a/ui-ngx/src/app/modules/home/components/ai/ai-credits-popup.component.scss +++ /dev/null @@ -1,30 +0,0 @@ -// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. -// SPDX-License-Identifier: BUSL-1.1 -:host { - display: block; - - .ai-credits-popup-content { - width: 268px; - } - - .popup-title { - font-size: 16px; - font-weight: 500; - line-height: 24px; - letter-spacing: 0.25px; - color: rgba(0, 0, 0, 0.87); - } - - .popup-description { - font-size: 14px; - line-height: 20px; - letter-spacing: 0.2px; - color: rgba(0, 0, 0, 0.76); - margin: 0; - - strong { - font-weight: 500; - letter-spacing: 0.25px; - } - } -} diff --git a/ui-ngx/src/app/modules/home/components/ai/ai-credits-popup.component.ts b/ui-ngx/src/app/modules/home/components/ai/ai-credits-popup.component.ts deleted file mode 100644 index 7795ee295c..0000000000 --- a/ui-ngx/src/app/modules/home/components/ai/ai-credits-popup.component.ts +++ /dev/null @@ -1,26 +0,0 @@ -// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. -// SPDX-License-Identifier: BUSL-1.1 -import { ChangeDetectionStrategy, Component, inject, output } from '@angular/core'; -import { TbPopoverComponent } from '@shared/components/popover.component'; - -@Component({ - selector: 'tb-ai-credits-popup', - templateUrl: './ai-credits-popup.component.html', - styleUrls: ['./ai-credits-popup.component.scss'], - changeDetection: ChangeDetectionStrategy.OnPush, - standalone: false -}) -export class AiCreditsPopupComponent { - - usedLabel: string; - maxLabel: string; - resetDate: Date; - - updatePlan = output(); - - private popover = inject>(TbPopoverComponent); - - cancel(): void { - this.popover.hide(); - } -} diff --git a/ui-ngx/src/app/modules/home/components/ai/ai-credits.component.html b/ui-ngx/src/app/modules/home/components/ai/ai-credits.component.html index 3dfde64edb..b5bd700a3c 100644 --- a/ui-ngx/src/app/modules/home/components/ai/ai-credits.component.html +++ b/ui-ngx/src/app/modules/home/components/ai/ai-credits.component.html @@ -5,58 +5,26 @@ --> @if (hasData()) { - @if (asButton()) { - - } @else { -
-
- - + + @if (near() || over()) { + {{ over() ? ('ai-assistant.credits.none-left' | translate) : ('ai-assistant.credits.left' | translate: {left: leftLabel(), count: left()}) }} + } + + + + + +
+
+ {{ 'ai-assistant.credits.title' | translate }} + {{ usagePercent() | number: '1.0-0' }}%
- @if (expanded()) { -
- {{ 'solution-creator.ai-credits' | translate }} - {{ usedLabel() }} / {{ maxLabel() }} -
- - } +

{{ 'ai-assistant.credits.used' | translate: {used: usedLabel(), max: maxLabel()} }}

+

{{ 'ai-assistant.credits.resets' | translate: {date: (resetDate() | date: 'MMMM d')} }}

- } +
} diff --git a/ui-ngx/src/app/modules/home/components/ai/ai-credits.component.scss b/ui-ngx/src/app/modules/home/components/ai/ai-credits.component.scss index 14313bb7c9..3c772e1f21 100644 --- a/ui-ngx/src/app/modules/home/components/ai/ai-credits.component.scss +++ b/ui-ngx/src/app/modules/home/components/ai/ai-credits.component.scss @@ -1,70 +1,94 @@ // SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. // SPDX-License-Identifier: BUSL-1.1 :host { - .ai-credits-donut, - .mat-mdc-icon-button { - --_donut-color: #198038; - --_donut-track: rgba(0, 0, 0, 0.12); - - &.WARNING { - --_donut-color: var(--tb-warning); - --_donut-track: color-mix(in srgb, var(--tb-warning) 20%, transparent); - } - - &.DISABLED { - --_donut-color: var(--tb-crit); - --_donut-track: color-mix(in srgb, var(--tb-crit) 20%, transparent); - } + display: inline-flex; + min-width: 0; +} + +.cred { + display: inline-flex; + align-items: center; + gap: 8px; + min-width: 0; + + > :not(.cred-line) { + flex-shrink: 0; } +} - .ai-credits-donut { - &:hover { - background-color: rgba(0, 0, 0, 0.04); - } - - &:focus-visible { - outline: 2px solid var(--tb-primary-500, #00695c); - outline-offset: 2px; - } - - .donut-spinner { - width: 30px; - } - - .donut-title { - font-size: 14px; - font-weight: 500; - line-height: 20px; - letter-spacing: 0.25px; - color: rgba(0, 0, 0, 0.76); - } - - .donut-usage { - font-size: 13px; - line-height: 16px; - color: rgba(0, 0, 0, 0.54); - } +.cred-line { + min-width: 0; + overflow: hidden; + text-overflow: ellipsis; + font: 400 var(--chat-meta)/var(--chat-meta-lh) var(--tb-font); + color: var(--tb-ink-76); + white-space: nowrap; +} + +.cred.near .cred-line { + color: var(--tb-caution-text); +} + +.cred-ring { + display: inline-flex; + align-items: center; + justify-content: center; + width: 32px; + height: 32px; + border-radius: 8px; + cursor: default; + transition: background-color .12s ease; + + &:hover, &[aria-describedby] { + background: rgba(0, 0, 0, 0.05); } - .update-btn { - --mat-button-outlined-outline-color: rgba(0, 0, 0, 0.12); - --mat-button-outlined-horizontal-padding: 12px; + &:focus-visible { + outline: 2px solid var(--ai-focus); + outline-offset: 2px; } -} -:host ::ng-deep .mat-mdc-progress-spinner { - --mat-progress-spinner-active-indicator-color: var(--_donut-color); + svg { + display: block; + width: 20px; + height: 20px; + } + + circle { + fill: none; + stroke-width: 2.5; + } - .mdc-circular-progress__determinate-circle { + .track { + stroke: rgba(0, 0, 0, 0.1); + } + + .arc { + stroke: var(--ai-teal-500); stroke-linecap: round; } +} + +.cred.near .arc { + stroke: var(--tb-caution); +} + +.cred.over .arc { + stroke: var(--tb-crit); +} + +:host-context(.tb-ai-composer.docked) .cred-ring { + width: 28px; + height: 28px; +} + +.tb-ai-tip-body .tip-value { + &.warn { + color: #f2c98a; + } - .mdc-circular-progress__determinate-container::before { - content: ''; - position: absolute; - inset: 0; - border-radius: 50%; - border: 4px solid var(--_donut-track); - box-sizing: border-box; + &.crit { + color: #ff9d92; } } + diff --git a/ui-ngx/src/app/modules/home/components/ai/ai-credits.component.ts b/ui-ngx/src/app/modules/home/components/ai/ai-credits.component.ts index cebcf7bdb6..ec6d4ee89c 100644 --- a/ui-ngx/src/app/modules/home/components/ai/ai-credits.component.ts +++ b/ui-ngx/src/app/modules/home/components/ai/ai-credits.component.ts @@ -1,28 +1,10 @@ // SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. // SPDX-License-Identifier: BUSL-1.1 -import { - ChangeDetectionStrategy, - Component, - computed, - effect, - inject, - input, - NgZone, - OnDestroy, - Renderer2, - signal, - ViewContainerRef -} from '@angular/core'; -import { Subject } from 'rxjs'; -import { takeUntil } from 'rxjs/operators'; +import { ChangeDetectionStrategy, Component, computed, effect, inject, input, NgZone, OnDestroy, signal } from '@angular/core'; import { TelemetryWebsocketService } from '@core/ws/telemetry-websocket.service'; import { TelemetrySubscriber } from '@shared/models/telemetry/telemetry.models'; -import { AliasFilterType } from '@shared/models/alias.models'; -import { EntityKeyType } from '@shared/models/query/query.models'; +import { aiCreditsResetDate, watchAiCredits } from '@home/components/ai/ai-credits.models'; import { ApiUsageStateValue } from '@shared/models/api-usage.models'; -import { TbPopoverService } from '@shared/components/popover.service'; -import { PopoverPreferredPlacement } from '@shared/components/popover.models'; -import { AiCreditsPopupComponent } from './ai-credits-popup.component'; import { ShortNumberPipe } from '@shared/pipe/short-number.pipe'; @Component({ @@ -34,19 +16,7 @@ import { ShortNumberPipe } from '@shared/pipe/short-number.pipe'; }) export class AiCreditsComponent implements OnDestroy { - expanded = input(false); - asButton = input(false); active = input(true); - popoverPlacement = input(null); - tooltipPosition = input<'above' | 'below' | 'before' | 'after'>(null); - - resolvedTooltipPosition = computed(() => { - return this.tooltipPosition() ?? (this.asButton() ? 'above' : 'after'); - }); - - resolvedPopoverPlacement = computed(() => { - return this.popoverPlacement() ?? (this.asButton() ? 'bottom' : (this.expanded() ? 'top' : 'right')); - }); aiCreditsCount = signal(0); aiCreditsLimit = signal(0); @@ -61,24 +31,29 @@ export class AiCreditsComponent implements OnDestroy { status = computed(() => this.aiApiState() ?? ApiUsageStateValue.ENABLED); + over = computed(() => this.status() === ApiUsageStateValue.DISABLED || this.usagePercent() >= 100); + + near = computed(() => !this.over() && (this.status() === ApiUsageStateValue.WARNING || this.usagePercent() >= 80)); + + arcDash = computed(() => { + const circumference = 2 * Math.PI * 8; + const share = Math.max(this.usagePercent() / 100, this.aiCreditsCount() > 0 ? 0.02 : 0); + return `${(share * circumference).toFixed(2)} ${circumference.toFixed(2)}`; + }); + private shortNumber = inject(ShortNumberPipe); usedLabel = computed(() => this.shortNumber.transform(this.aiCreditsCount(), {roundDown: true})); maxLabel = computed(() => this.shortNumber.transform(this.aiCreditsLimit())); + left = computed(() => Math.max(0, this.aiCreditsLimit() - this.aiCreditsCount())); + leftLabel = computed(() => this.shortNumber.transform(this.left(), {roundDown: true})); - resetDate = computed(() => { - const now = new Date(); - return new Date(now.getFullYear(), now.getMonth() + 1, 2); - }); + resetDate = computed(() => aiCreditsResetDate()); private telemetryWsService = inject(TelemetryWebsocketService); private zone = inject(NgZone); - private popoverService = inject(TbPopoverService); - private renderer = inject(Renderer2); - private viewContainerRef = inject(ViewContainerRef); private telemetrySubscriber: TelemetrySubscriber; - private cancelSubscription$ = new Subject(); private activeEffect = effect(() => { if (this.active()) { @@ -90,83 +65,28 @@ export class AiCreditsComponent implements OnDestroy { ngOnDestroy(): void { this.unsubscribeFromCredits(); - this.cancelSubscription$.complete(); } private unsubscribeFromCredits(): void { - this.cancelSubscription$.next(); if (this.telemetrySubscriber) { this.telemetrySubscriber.unsubscribe(); this.telemetrySubscriber = null; } } - togglePopup(event: Event, trigger: Element): void { - event.stopPropagation(); - if (this.popoverService.hasPopover(trigger)) { - this.popoverService.hidePopover(trigger); - } else { - const popover = this.popoverService.displayPopover({ - trigger, - renderer: this.renderer, - componentType: AiCreditsPopupComponent, - hostView: this.viewContainerRef, - preferredPlacement: this.resolvedPopoverPlacement(), - hideOnClickOutside: true, - showCloseButton: true, - context: { - usedLabel: this.usedLabel(), - maxLabel: this.maxLabel(), - resetDate: this.resetDate() - } - }); - popover.tbComponentRef.instance.updatePlan.subscribe(() => { - this.onUpdatePlan(); - }); - } - } - - onUpdatePlan($event?: Event): void { - $event?.stopPropagation(); - alert('Update plan'); - } - private subscribeToCredits(): void { if (this.telemetrySubscriber) { return; } - const latestKeys = [ - { key: 'aiApiState', type: EntityKeyType.TIME_SERIES }, - { key: 'aiCreditsLimit', type: EntityKeyType.TIME_SERIES }, - { key: 'aiCreditsCount', type: EntityKeyType.TIME_SERIES } - ]; - - this.telemetrySubscriber = TelemetrySubscriber.createEntityFilterLatestSubscription( - this.telemetryWsService, - { type: AliasFilterType.apiUsageState }, - this.zone, - latestKeys - ); - - this.telemetrySubscriber.subscribe(); - this.telemetrySubscriber.entityData$.pipe( - takeUntil(this.cancelSubscription$) - ).subscribe(update => { - const entityData = update.data?.data ?? update.update; - if (entityData?.length) { - const latest = entityData[0].latest; - if (latest?.[EntityKeyType.TIME_SERIES]) { - const ts = latest[EntityKeyType.TIME_SERIES]; - if (ts.aiCreditsCount) { - this.aiCreditsCount.set(Number(ts.aiCreditsCount.value) || 0); - } - if (ts.aiCreditsLimit) { - this.aiCreditsLimit.set(Number(ts.aiCreditsLimit.value) || 0); - } - if (ts.aiApiState) { - this.aiApiState.set(ts.aiApiState.value); - } - } + this.telemetrySubscriber = watchAiCredits(this.telemetryWsService, this.zone, update => { + if (update.count !== undefined) { + this.aiCreditsCount.set(update.count); + } + if (update.limit !== undefined) { + this.aiCreditsLimit.set(update.limit); + } + if (update.state) { + this.aiApiState.set(update.state); } }); } diff --git a/ui-ngx/src/app/modules/home/components/ai/ai-credits.models.ts b/ui-ngx/src/app/modules/home/components/ai/ai-credits.models.ts new file mode 100644 index 0000000000..60498f56d3 --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/ai/ai-credits.models.ts @@ -0,0 +1,62 @@ +// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: BUSL-1.1 +import { NgZone } from '@angular/core'; +import { TelemetryWebsocketService } from '@core/ws/telemetry-websocket.service'; +import { TelemetrySubscriber } from '@shared/models/telemetry/telemetry.models'; +import { AliasFilterType } from '@shared/models/alias.models'; +import { EntityKeyType } from '@shared/models/query/query.models'; + +export type AiCreditsLimitType = 'TENANT' | 'POOL'; + +export interface AiCreditsUpdate { + count?: number; + limit?: number; + state?: string; +} + +export const watchAiCredits = (telemetryWsService: TelemetryWebsocketService, zone: NgZone, + onUpdate: (update: AiCreditsUpdate) => void): TelemetrySubscriber => { + const subscriber = TelemetrySubscriber.createEntityFilterLatestSubscription( + telemetryWsService, + {type: AliasFilterType.apiUsageState}, + zone, + [ + {key: 'aiApiState', type: EntityKeyType.TIME_SERIES}, + {key: 'aiCreditsLimit', type: EntityKeyType.TIME_SERIES}, + {key: 'aiCreditsCount', type: EntityKeyType.TIME_SERIES} + ] + ); + subscriber.entityData$.subscribe(update => { + const entityData = update.data?.data ?? update.update; + const ts = entityData?.[0]?.latest?.[EntityKeyType.TIME_SERIES]; + if (ts) { + onUpdate({ + count: ts.aiCreditsCount ? Number(ts.aiCreditsCount.value) || 0 : undefined, + limit: ts.aiCreditsLimit ? Number(ts.aiCreditsLimit.value) || 0 : undefined, + state: ts.aiApiState?.value + }); + } + }); + subscriber.subscribe(); + return subscriber; +}; + +export const aiCreditsResetDate = (): Date => { + const now = new Date(); + return new Date(Date.UTC(now.getUTCFullYear(), now.getUTCMonth() + 1, 1)); +}; + +export const aiCreditsLimitOf = (error: any): AiCreditsLimitType | null => { + if (error?.status !== 429) { + return null; + } + let body = error.error; + if (typeof body === 'string') { + try { + body = JSON.parse(body); + } catch { + return null; + } + } + return body?.aiCreditsLimit === 'TENANT' ? 'TENANT' : null; +}; diff --git a/ui-ngx/src/app/modules/home/components/ai/ai-dashboard-generation.service.ts b/ui-ngx/src/app/modules/home/components/ai/ai-dashboard-generation.service.ts index d1e86c90ae..96eb0771b6 100644 --- a/ui-ngx/src/app/modules/home/components/ai/ai-dashboard-generation.service.ts +++ b/ui-ngx/src/app/modules/home/components/ai/ai-dashboard-generation.service.ts @@ -1,37 +1,30 @@ // SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. // SPDX-License-Identifier: BUSL-1.1 -import { DestroyRef, Injectable } from '@angular/core'; +import { Injectable } from '@angular/core'; import { createDefaultEntityDataPageLink, singleEntityFilterFromDeviceId } from '@shared/models/query/query.models'; -import { AiLoadingModalComponent, AiLoadingModalData } from '@home/components/ai/ai-loading-modal.component'; -import { dashboardGenerateImage, generateDashboardSteps } from '@home/components/ai/ai.models'; -import { finalize } from 'rxjs/operators'; -import { takeUntilDestroyed } from '@angular/core/rxjs-interop'; -import { isNotEmptyStr, parseHttpErrorMessage } from '@core/utils'; -import { ActionNotificationShow } from '@core/notification/notification.actions'; +import { map } from 'rxjs/operators'; +import { forkJoin, of } from 'rxjs'; import { AiNoTelemetryModalComponent, AiNoTelemetryModalData } from '@home/components/ai/ai-no-telemetry-modal.component'; -import { getCurrentAuthState, getCurrentAuthUser } from '@core/auth/auth.selectors'; -import { Authority } from '@shared/models/authority.enum'; -import { Operation, Resource } from '@shared/models/security.models'; +import { Operation } from '@shared/models/security.models'; import { EntityType } from '@shared/models/entity-type.models'; import { EntityService } from '@core/http/entity.service'; +import { DeviceService } from '@core/http/device.service'; +import { AiAssistantPanelService } from '@core/services/ai-assistant-panel.service'; import { MatDialog } from '@angular/material/dialog'; -import { AiChatService } from '@core/http/ai-chat.service'; -import { Router } from '@angular/router'; import { TranslateService } from '@ngx-translate/core'; -import { DomSanitizer } from '@angular/platform-browser'; -import { Store } from '@ngrx/store'; -import { AppState } from '@core/core.state'; import { UserPermissionsService } from '@core/http/user-permissions.service'; import { EntityGroupInfo } from '@shared/models/entity-group.models'; interface GenerateDashboardOptions { deviceId: string; - destroyRef?: DestroyRef; - noTelemetry: AiNoTelemetryModalData; - beforeOpen?: () => void; + deviceName?: string; + keys?: string[]; + checkTelemetry?: boolean; + noTelemetry?: AiNoTelemetryModalData; + beforeCompose?: () => void; } interface AllowDashboardGenerateOptions { @@ -45,48 +38,29 @@ interface AllowDashboardGenerateOptions { export class AiDashboardGenerationService { constructor(private entityService: EntityService, + private deviceService: DeviceService, private dialog: MatDialog, - private aiChatService: AiChatService, - private router: Router, + private panelService: AiAssistantPanelService, private translate: TranslateService, - private sanitizer: DomSanitizer, - private store: Store, private userPermissionsService: UserPermissionsService) { } - generateWithTelemetryCheck(opts: GenerateDashboardOptions): void { - this.entityService.findEntityKeysByQueryV2({ + askInChat(opts: GenerateDashboardOptions): void { + const telemetry$ = opts.checkTelemetry === false ? of(true) : this.entityService.findEntityKeysByQueryV2({ entityFilter: singleEntityFilterFromDeviceId(opts.deviceId), pageLink: createDefaultEntityDataPageLink(1), - }, true, false).subscribe((res) => { - opts.beforeOpen?.(); - if (res.timeseries.length) { - this.generate(opts.deviceId, opts.destroyRef); - } else { - this.openNoTelemetryModal(opts.noTelemetry); + }, true, false).pipe(map(res => res.timeseries.length > 0)); + const name$ = opts.deviceName ? of(opts.deviceName) : this.deviceService.getDevice(opts.deviceId, {ignoreLoading: true}).pipe(map(device => device.name)); + forkJoin([telemetry$, name$]).subscribe(([hasTelemetry, name]) => { + if (!hasTelemetry) { + this.openNoTelemetryModal(opts.noTelemetry ?? {}); + return; } - }); - } - - - generate(deviceId: string, destroyRef?: DestroyRef, timeseriesKeys: string[] = []): void { - const dialogRef = this.dialog.open(AiLoadingModalComponent, { - disableClose: true, - panelClass: ['tb-dialog', 'tb-fullscreen-dialog'], - data: { - messages: generateDashboardSteps, - estimateWaitTime: 60000, - image: dashboardGenerateImage - } as AiLoadingModalData - }); - let request$ = this.aiChatService.generateDashboard(deviceId, timeseriesKeys).pipe( - finalize(() => dialogRef.close()) - ); - if (destroyRef) { - request$ = request$.pipe(takeUntilDestroyed(destroyRef)); - } - request$.subscribe({ - next: (response) => this.router.navigate(['/dashboards', response]) + opts.beforeCompose?.(); + const keys = (opts.keys ?? []).filter(Boolean); + this.panelService.compose(keys.length + ? this.translate.instant('ai-assistant.ask.device-dashboard-keys', {name, keys: keys.join(', ')}) + : this.translate.instant('ai-assistant.ask.device-dashboard', {name})); }); } @@ -98,9 +72,7 @@ export class AiDashboardGenerationService { } isAllowedDashboardGenerate(opts: AllowDashboardGenerateOptions = {}): boolean { - const allowed = getCurrentAuthState(this.store).aiEnabled - && getCurrentAuthUser(this.store).authority === Authority.TENANT_ADMIN - && this.userPermissionsService.hasGenericPermission(Resource.AI, Operation.WRITE) + const allowed = this.userPermissionsService.isAiAvailable(Operation.WRITE) && this.userPermissionsService.hasEntityTypeOperationPermission(EntityType.DASHBOARD, Operation.WRITE) && this.userPermissionsService.hasEntityTypeOperationPermission(EntityType.DEVICE, Operation.READ_ATTRIBUTES, opts.entityGroup); if (!opts.requireTelemetry) { diff --git a/ui-ngx/src/app/modules/home/components/ai/ai-date-panel.component.html b/ui-ngx/src/app/modules/home/components/ai/ai-date-panel.component.html new file mode 100644 index 0000000000..7b65d79e94 --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/ai/ai-date-panel.component.html @@ -0,0 +1,23 @@ + + diff --git a/ui-ngx/src/app/modules/home/components/ai/ai-date-panel.component.ts b/ui-ngx/src/app/modules/home/components/ai/ai-date-panel.component.ts new file mode 100644 index 0000000000..11f0c2001e --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/ai/ai-date-panel.component.ts @@ -0,0 +1,85 @@ +// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: BUSL-1.1 +import { AfterViewInit, ChangeDetectionStrategy, ChangeDetectorRef, Component, ElementRef, EventEmitter, inject, ViewChild } from '@angular/core'; +import { MatCalendar } from '@angular/material/datepicker'; +import { TbPopoverComponent } from '@shared/components/popover.component'; +import { aiReadTime } from '@home/components/ai/ai-question.models'; + +export interface AiPickedDay { + date: Date; + time: string; +} + +@Component({ + selector: 'tb-ai-date-panel', + templateUrl: './ai-date-panel.component.html', + changeDetection: ChangeDetectionStrategy.OnPush, + standalone: false +}) +export class AiDatePanelComponent implements AfterViewInit { + + @ViewChild(MatCalendar) calendar: MatCalendar; + + selected: Date; + time = '9:00'; + popover: TbPopoverComponent; + + readonly minDate = startOfDay(new Date()); + readonly applied = new EventEmitter(); + timeWrong = false; + + private cd = inject(ChangeDetectorRef); + private host: ElementRef = inject(ElementRef); + + ngAfterViewInit(): void { + setTimeout(() => this.calendar?.focusActiveCell()); + } + + hasFocus(): boolean { + return this.host.nativeElement.contains(document.activeElement); + } + + select(date: Date): void { + this.selected = date; + this.cd.markForCheck(); + } + + typeTime(field: HTMLInputElement): void { + this.time = field.value; + this.timeWrong = false; + } + + settleTime(field: HTMLInputElement): void { + const time = aiReadTime(field.value); + if (time) { + field.value = time; + this.time = time; + } + } + + stepTime(field: HTMLInputElement, minutes: number): void { + const time = aiReadTime(field.value); + if (!time) { + return; + } + const [hours, mins] = time.split(':').map(Number); + const total = (((hours * 60 + mins + minutes) % 1440) + 1440) % 1440; + field.value = `${Math.floor(total / 60)}:${String(total % 60).padStart(2, '0')}`; + this.time = field.value; + } + + apply(field: HTMLInputElement): void { + const time = aiReadTime(field.value); + if (!time || !this.selected) { + this.timeWrong = !time; + this.cd.markForCheck(); + field.focus(); + return; + } + this.applied.emit({date: this.selected, time}); + } +} + +function startOfDay(date: Date): Date { + return new Date(date.getFullYear(), date.getMonth(), date.getDate()); +} diff --git a/ui-ngx/src/app/modules/home/components/ai/ai-disclosure.component.ts b/ui-ngx/src/app/modules/home/components/ai/ai-disclosure.component.ts new file mode 100644 index 0000000000..11e2c8b819 --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/ai/ai-disclosure.component.ts @@ -0,0 +1,132 @@ +// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: BUSL-1.1 +import { ChangeDetectionStrategy, Component, computed, ElementRef, inject, input, linkedSignal, WritableSignal } from '@angular/core'; + +const STORE = 'tb-ai-disclosure'; + +export function aiDisclosureRemembered(key: string): boolean { + try { + return !!key && JSON.parse(sessionStorage.getItem(STORE) ?? '[]').includes(key); + } catch { + return false; + } +} + +export function aiDisclosureRemember(key: string, open: boolean): void { + if (!key) { + return; + } + try { + const keys: string[] = JSON.parse(sessionStorage.getItem(STORE) ?? '[]').filter((item: string) => item !== key); + if (open) { + keys.push(key); + } + sessionStorage.setItem(STORE, JSON.stringify(keys.slice(-200))); + } catch { + return; + } +} + +export interface AiFold { + readonly open: WritableSignal; + toggle(): boolean; +} + +export function aiFold(key?: () => string): AiFold { + const open = linkedSignal(() => key ? aiDisclosureRemembered(key()) : false); + return { + open, + toggle: () => { + const next = !open(); + open.set(next); + if (key) { + aiDisclosureRemember(key(), next); + } + return next; + } + }; +} + +const REVEAL_GAP = 12; + +function scrollerOf(element: HTMLElement): HTMLElement | null { + for (let node = element.parentElement; node; node = node.parentElement) { + const overflow = getComputedStyle(node).overflowY; + if ((overflow === 'auto' || overflow === 'scroll') && node.scrollHeight > node.clientHeight) { + return node; + } + } + return null; +} + +export function aiRevealOpened(element: HTMLElement): void { + requestAnimationFrame(() => requestAnimationFrame(() => { + const scroller = scrollerOf(element); + if (!scroller) { + return; + } + const box = element.getBoundingClientRect(); + const view = scroller.getBoundingClientRect(); + const composer = scroller.querySelector('.ai-chat-composer') ?? element.closest('.ai-chat')?.querySelector('.ai-chat-composer'); + const composerTop = composer?.getBoundingClientRect().top ?? view.bottom; + const bottom = Math.min(view.bottom, composerTop) - REVEAL_GAP; + const overflow = box.bottom - bottom; + if (overflow <= 0) { + return; + } + const room = box.top - view.top - REVEAL_GAP; + scroller.scrollBy({top: Math.min(overflow, Math.max(room, 0)), behavior: 'smooth'}); + })); +} + +@Component({ + selector: 'tb-ai-disclosure', + template: ` +
+ {{ summary() }} + @if (open()) { + + } +
+ `, + standalone: false, + changeDetection: ChangeDetectionStrategy.OnPush, + host: { + 'class': 'tb-ai-disclosure' + } +}) +export class AiDisclosureComponent { + + summary = input.required(); + + variant = input<'section' | 'divided'>('section'); + + private host = inject(ElementRef); + + private fold = aiFold(); + + open = this.fold.open; + + classes = computed(() => 'tb-disc tb-disc-section' + (this.variant() === 'divided' ? ' tb-disc-divided' : '')); + + toggled(open: boolean): void { + if (open !== this.open() && this.fold.toggle()) { + aiRevealOpened(this.host.nativeElement); + } + } +} + +export function decorateSections(root: HTMLElement, scope: string): void { + root.querySelectorAll('details:not(.tb-disc)').forEach((section, index) => { + const summary = section.querySelector(':scope > summary'); + if (!summary) { + section.insertBefore(Object.assign(document.createElement('summary'), {textContent: '…'}), section.firstChild); + } + section.classList.add('tb-disc', 'tb-disc-section'); + const key = `${scope}:${index}:${section.querySelector(':scope > summary')?.textContent?.trim() ?? ''}`; + if (aiDisclosureRemembered(key)) { + section.open = true; + } + section.addEventListener('toggle', () => aiDisclosureRemember(key, section.open)); + }); +} diff --git a/ui-ngx/src/app/modules/home/components/ai/ai-fade-in-image.directive.ts b/ui-ngx/src/app/modules/home/components/ai/ai-fade-in-image.directive.ts new file mode 100644 index 0000000000..ebb2e86d0a --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/ai/ai-fade-in-image.directive.ts @@ -0,0 +1,19 @@ +// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: BUSL-1.1 +import { Directive } from '@angular/core'; + +@Directive({ + selector: 'img[tbAiFadeIn]', + standalone: false, + host: { + class: 'tb-ai-fade-in', + '[class.loaded]': 'loaded', + '(load)': 'loaded = true', + '(error)': 'loaded = true' + } +}) +export class AiFadeInImageDirective { + + loaded = false; + +} diff --git a/ui-ngx/src/app/modules/home/components/ai/ai-file-body.component.ts b/ui-ngx/src/app/modules/home/components/ai/ai-file-body.component.ts new file mode 100644 index 0000000000..d184adf89b --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/ai/ai-file-body.component.ts @@ -0,0 +1,551 @@ +// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: BUSL-1.1 +import { AfterViewInit, Component, computed, DestroyRef, effect, inject, ElementRef, EventEmitter, input, Output, signal, untracked, ViewChild } from '@angular/core'; +import { MatDialog } from '@angular/material/dialog'; +import { AiFile, aiFileDraftKey, aiImageSrc, downloadAiFile, downloadAiFileAsPng } from '@home/components/ai/ai-file.models'; +import { + AiAttachmentPreviewDialogComponent, + AiAttachmentPreviewDialogData +} from '@home/components/ai/ai-attachment-preview-dialog.component'; +import { readStored, writeStored } from '@core/local-storage/stored'; +import { highlightCode } from '@home/components/ai/ai-code-block'; + +export interface AiFileMarks { + from: number; + to: number; +} + +export interface AiFileCaret { + line: number; + col: number; + selected: number; +} + +export type AiFileSaver = (content: string) => Promise; + +const DRAFT_DELAY_MS = 400; +const SAVED_MS = 1600; + +@Component({ + selector: 'tb-ai-file-body', + template: ` + @if (editing()) { +
+ +
+ + +
+
+ } @else if (file().markdown) { +
+ +
+ } @else if (file().image) { +
+ @if (imageBroken()) { +

{{ 'ai-assistant.file.svg-broken' | translate }}

+ } @else { + + } +
+ } @else { + @if (finding()) { + + } +
+ } + `, + standalone: false, + host: {class: 'file-body', '(keydown)': 'onKey($event)'} +}) +export class AiFileBodyComponent implements AfterViewInit { + + file = input.required(); + wrap = input(false); + whitespace = input(false); + marks = input(null); + saver = input(null); + + @Output() marksChange = new EventEmitter(); + @Output() discarded = new EventEmitter(); + + @ViewChild('code') code: ElementRef; + @ViewChild('findInput') findInput: ElementRef; + @ViewChild('area') area: ElementRef; + @ViewChild('layer') layer: ElementRef; + @ViewChild('gutter') gutter: ElementRef; + + private dialog = inject(MatDialog); + private destroyRef = inject(DestroyRef); + + imageSrc = computed(() => aiImageSrc(this.file())); + + imageBroken = signal(false); + + editing = signal(false); + draft = signal(''); + caret = signal({line: 1, col: 1, selected: 0}); + saving = signal(false); + saved = signal(false); + + dirty = computed(() => this.editing() && this.draft() !== this.file().content); + + private shownId: string | null = null; + private draftTimer: ReturnType; + private savedTimer: ReturnType; + + finding = signal(false); + query = signal(''); + matches = signal(0); + current = signal(0); + + private anchor = 0; + + readonly markdownStyles = [ + '.tb-markdown-view {font-size: var(--chat-text); line-height: var(--chat-text-lh); color: var(--tb-ink);} ' + + '.tb-markdown-view > :first-child {margin-top: 0 !important;} ' + + '.tb-markdown-view h1, .tb-markdown-view h2, .tb-markdown-view h3, .tb-markdown-view h4, .tb-markdown-view h5 ' + + '{margin: 28px 0 8px !important; padding: 0 !important; border: 0 !important; font-weight: 500 !important; letter-spacing: -0.1px; color: var(--tb-ink);} ' + + '.tb-markdown-view h1, .tb-markdown-view h2 {font-size: var(--chat-title) !important; line-height: var(--chat-title-lh) !important; letter-spacing: -0.3px;} ' + + '.tb-markdown-view h3 {font-size: var(--chat-head) !important; line-height: var(--chat-head-lh) !important;} ' + + '.tb-markdown-view h4, .tb-markdown-view h5 {font-size: var(--chat-line) !important; line-height: var(--chat-line-lh) !important;} ' + + '.tb-markdown-view p {margin: 0 0 12px !important; padding: 0 !important; font-size: inherit; line-height: inherit;} ' + + '.tb-markdown-view ol, .tb-markdown-view ul {margin: 0 0 12px !important; padding-left: 24px !important; padding-inline-start: 24px;} ' + + '.tb-markdown-view li {font-size: inherit; line-height: inherit;} .tb-markdown-view li + li {margin-top: 4px;} ' + + '.tb-markdown-view div.code-wrapper {padding-left: 0 !important; margin: 0 0 16px !important;} ' + + '.tb-markdown-view pre {border-radius: 10px !important;} ' + + '.tb-markdown-view table, .tb-markdown-view div.code-wrapper {margin-left: 0 !important; margin-right: 0 !important;} ' + + '.tb-markdown-view :not(pre) > code {padding: 1px 5px; border-radius: 4px; background: color-mix(in srgb, var(--tb-ink) 6%, transparent) !important; ' + + 'color: var(--tb-ink) !important; font-family: var(--tb-mono); font-size: var(--chat-code);}' + ]; + + private redraw = effect(() => { + this.file(); + this.whitespace(); + this.editing(); + setTimeout(() => this.drawCode()); + }); + + private follow = effect(() => { + const file = this.file(); + untracked(() => { + if (file.executionId === this.shownId) { + return; + } + this.shownId = file.executionId; + this.imageBroken.set(false); + this.saved.set(false); + const stored = AiFileBodyComponent.storedDraft(file.executionId); + this.editing.set(stored !== null && stored !== file.content); + this.draft.set(stored ?? file.content); + if (this.editing()) { + setTimeout(() => this.drawEditor()); + } + }); + }); + + private relayout = effect(() => { + this.wrap(); + if (untracked(() => this.editing())) { + setTimeout(() => this.drawEditor()); + } + }); + + private remark = effect(() => { + const marks = this.marks(); + setTimeout(() => this.paintMarks(marks)); + }); + + ngAfterViewInit(): void { + this.drawCode(); + this.destroyRef.onDestroy(() => { + clearTimeout(this.draftTimer); + clearTimeout(this.savedTimer); + }); + } + + startEdit(): void { + const file = this.file(); + this.draft.set(AiFileBodyComponent.storedDraft(file.executionId) ?? file.content); + this.editing.set(true); + this.saved.set(false); + this.closeFind(); + setTimeout(() => { + this.drawEditor(); + const area = this.area?.nativeElement; + area?.focus({preventScroll: true}); + area?.setSelectionRange(0, 0); + this.updateCaret(); + }); + } + + done(): void { + this.leaveEditor(); + } + + discard(): void { + const file = this.file(); + this.leaveEditor(); + this.discarded.emit(file); + } + + async save(stay = false): Promise { + const saver = this.saver(); + if (!this.dirty()) { + if (!stay) { + this.leaveEditor(); + } + return; + } + if (!saver || this.saving()) { + return; + } + this.saving.set(true); + const ok = await saver(this.draft()); + this.saving.set(false); + if (!ok) { + return; + } + AiFileBodyComponent.storeDraft(this.file().executionId, null); + if (!stay) { + this.editing.set(false); + } + this.saved.set(true); + clearTimeout(this.savedTimer); + this.savedTimer = setTimeout(() => this.saved.set(false), SAVED_MS); + } + + onEditInput(value: string): void { + this.draft.set(value); + this.drawEditor(); + this.updateCaret(); + clearTimeout(this.draftTimer); + const id = this.file().executionId; + const content = this.file().content; + this.draftTimer = setTimeout(() => AiFileBodyComponent.storeDraft(id, value === content ? null : value), DRAFT_DELAY_MS); + } + + onEditKey(event: KeyboardEvent): void { + const area = event.target as HTMLTextAreaElement; + if ((event.metaKey || event.ctrlKey) && event.key.toLowerCase() === 's') { + event.preventDefault(); + this.save(true); + } else if (event.key === 'Escape') { + event.preventDefault(); + event.stopPropagation(); + if (!this.dirty()) { + this.leaveEditor(); + } + } else if (event.key === 'Tab' && !event.shiftKey && !event.metaKey && !event.ctrlKey && !event.altKey) { + event.preventDefault(); + area.setRangeText(' '.repeat(this.file().lang === 'python' ? 4 : 2), area.selectionStart, area.selectionEnd, 'end'); + this.onEditInput(area.value); + } + } + + focusEditor(event: MouseEvent): void { + if (event.target === event.currentTarget || (event.target as HTMLElement).closest('.file-edit-ln')) { + this.area?.nativeElement.focus(); + } + } + + updateCaret(): void { + const area = this.area?.nativeElement; + if (!area) { + return; + } + const before = area.value.slice(0, area.selectionStart); + const line = before.split('\n').length; + const col = area.selectionStart - before.lastIndexOf('\n'); + this.caret.set({line, col, selected: Math.abs(area.selectionEnd - area.selectionStart)}); + this.gutter?.nativeElement.querySelectorAll('li').forEach((item, index) => item.classList.toggle('now', index + 1 === line)); + } + + private leaveEditor(): void { + clearTimeout(this.draftTimer); + AiFileBodyComponent.storeDraft(this.file().executionId, null); + this.draft.set(this.file().content); + this.editing.set(false); + } + + private drawEditor(): void { + const layer = this.layer?.nativeElement; + const gutter = this.gutter?.nativeElement; + const area = this.area?.nativeElement; + if (!layer || !gutter || !area) { + return; + } + const text = this.draft(); + const rows = highlightCode(this.file().lang, text).map(line => { + const row = document.createElement('div'); + row.className = 'file-edit-row'; + row.append(line, '\n'); + return row; + }); + layer.replaceChildren(...rows); + const numbers = rows.map((row, index) => { + const item = document.createElement('li'); + item.textContent = String(index + 1); + return item; + }); + gutter.replaceChildren(...numbers); + if (this.wrap() || this.file().previewed) { + rows.forEach((row, index) => numbers[index].style.height = row.offsetHeight + 'px'); + } + area.style.height = '0px'; + area.style.height = Math.max(area.scrollHeight, layer.offsetHeight) + 'px'; + this.updateCaret(); + } + + private static storedDraft(executionId: string): string | null { + return readStored(aiFileDraftKey(executionId)); + } + + private static storeDraft(executionId: string, value: string | null): void { + writeStored(aiFileDraftKey(executionId), value); + } + + expandImage(): void { + const file = this.file(); + this.dialog.open(AiAttachmentPreviewDialogComponent, { + panelClass: ['tb-dialog', 'tb-ai-attachment-preview-dialog'], + maxWidth: '92vw', + data: {name: file.name, url: this.imageSrc(), vector: true, download: () => downloadAiFile(file), downloadPng: () => downloadAiFileAsPng(file)} + }); + } + + openFind(): void { + this.finding.set(true); + setTimeout(() => { + this.findInput?.nativeElement.focus(); + this.findInput?.nativeElement.select(); + }); + } + + closeFind(): void { + this.finding.set(false); + this.query.set(''); + this.paintFind(); + } + + setQuery(value: string): void { + this.query.set(value); + this.current.set(0); + this.paintFind(); + } + + step(by: number): void { + const count = this.matches(); + if (!count) { + return; + } + this.current.set((this.current() + by + count) % count); + this.focusMatch(); + } + + onFindKey(event: KeyboardEvent): void { + if (event.key === 'Enter') { + event.preventDefault(); + this.step(event.shiftKey ? -1 : 1); + } else if (event.key === 'Escape') { + event.preventDefault(); + event.stopPropagation(); + this.closeFind(); + } + } + + onKey(event: KeyboardEvent): void { + if ((event.metaKey || event.ctrlKey) && event.key.toLowerCase() === 'f' && !this.file().previewed && !this.editing()) { + event.preventDefault(); + this.openFind(); + } + } + + onCodeClick(event: MouseEvent): void { + const number = (event.target as HTMLElement).closest('.ln') as HTMLElement | null; + if (!number) { + return; + } + const line = Number(number.dataset.line); + const marks = this.marks(); + if (event.shiftKey && marks) { + this.marksChange.emit({from: Math.min(this.anchor, line), to: Math.max(this.anchor, line)}); + return; + } + if (marks && marks.from === line && marks.to === line) { + this.marksChange.emit(null); + return; + } + this.anchor = line; + this.marksChange.emit({from: line, to: line}); + } + + private drawCode(): void { + const container = this.code?.nativeElement; + if (!container) { + return; + } + const file = this.file(); + const list = document.createElement('ol'); + list.className = 'file-lines'; + highlightCode(file.lang, file.content.replace(/\n$/, '')).forEach((line, index) => { + const item = document.createElement('li'); + const number = document.createElement('button'); + number.type = 'button'; + number.className = 'ln'; + number.tabIndex = -1; + number.dataset.line = String(index + 1); + number.textContent = String(index + 1); + const code = document.createElement('code'); + const indent = /^\s*/.exec(line.textContent ?? '')?.[0].length ?? 0; + code.style.setProperty('--ind', indent + 'ch'); + if (this.whitespace()) { + AiFileBodyComponent.markWhitespace(line); + } + code.append(line); + item.append(number, code); + list.append(item); + }); + container.replaceChildren(list); + this.paintMarks(this.marks()); + this.paintFind(); + } + + private paintMarks(marks: AiFileMarks | null): void { + this.code?.nativeElement.querySelectorAll('.file-lines li').forEach((item, index) => { + item.classList.toggle('marked', !!marks && index + 1 >= marks.from && index + 1 <= marks.to); + }); + } + + private paintFind(): void { + const container = this.code?.nativeElement; + if (!container) { + return; + } + container.querySelectorAll('mark.fm').forEach(mark => mark.replaceWith(...Array.from(mark.childNodes))); + container.normalize(); + const query = this.query(); + let count = 0; + if (query) { + container.querySelectorAll('.file-lines li > code').forEach(code => { + count += AiFileBodyComponent.wrapMatches(code, query.toLowerCase()); + }); + } + this.matches.set(count); + if (this.current() >= count) { + this.current.set(0); + } + this.focusMatch(); + } + + private focusMatch(): void { + const marks = this.code?.nativeElement.querySelectorAll('mark.fm') ?? []; + marks.forEach((mark, index) => mark.classList.toggle('now', index === this.current())); + marks[this.current()]?.scrollIntoView({block: 'nearest', inline: 'nearest'}); + } + + private static wrapMatches(root: HTMLElement, query: string): number { + const text = (root.textContent ?? '').toLowerCase(); + const starts: number[] = []; + for (let at = text.indexOf(query); at >= 0; at = text.indexOf(query, at + query.length)) { + starts.push(at); + } + for (let i = starts.length - 1; i >= 0; i--) { + AiFileBodyComponent.wrapRange(root, starts[i], starts[i] + query.length); + } + return starts.length; + } + + private static wrapRange(root: HTMLElement, from: number, to: number): void { + const walker = document.createTreeWalker(root, NodeFilter.SHOW_TEXT); + const pieces: {node: Text; start: number; end: number}[] = []; + let offset = 0; + for (let node = walker.nextNode() as Text | null; node; node = walker.nextNode() as Text | null) { + const length = node.data.length; + const start = Math.max(from, offset); + const end = Math.min(to, offset + length); + if (start < end) { + pieces.push({node, start: start - offset, end: end - offset}); + } + offset += length; + } + pieces.forEach(({node, start, end}) => { + const middle = node.splitText(start); + middle.splitText(end - start); + const mark = document.createElement('mark'); + mark.className = 'fm'; + middle.replaceWith(mark); + mark.append(middle); + }); + } + + private static markWhitespace(line: HTMLElement): void { + const full = line.textContent ?? ''; + const trailFrom = full.replace(/[ \t]+$/, '').length; + const walker = document.createTreeWalker(line, NodeFilter.SHOW_TEXT); + const nodes: Text[] = []; + for (let node = walker.nextNode() as Text | null; node; node = walker.nextNode() as Text | null) { + nodes.push(node); + } + let offset = 0; + nodes.forEach(node => { + const data = node.data; + const fragment = document.createDocumentFragment(); + let plain = ''; + for (let i = 0; i < data.length; i++) { + const char = data[i]; + const at = offset + i; + if (char !== ' ' && char !== '\t') { + plain += char; + continue; + } + if (plain) { + fragment.append(plain); + plain = ''; + } + const span = document.createElement('span'); + span.textContent = char; + const run = (full[at - 1] === ' ' || full[at + 1] === ' ') && char === ' '; + span.className = char === '\t' ? 'ws tab' : at >= trailFrom ? 'ws trail' : run || at < (/^\s*/.exec(full)?.[0].length ?? 0) ? 'ws' : 'ws quiet'; + fragment.append(span); + } + if (plain) { + fragment.append(plain); + } + offset += data.length; + node.replaceWith(fragment); + }); + } + +} diff --git a/ui-ngx/src/app/modules/home/components/ai/ai-file.models.ts b/ui-ngx/src/app/modules/home/components/ai/ai-file.models.ts new file mode 100644 index 0000000000..b5cda81c83 --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/ai/ai-file.models.ts @@ -0,0 +1,192 @@ +// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: BUSL-1.1 +import { fileLanguage } from '@home/components/ai/ai-code-block'; +import { AiResourceInfo } from '@shared/models/ai-chat.models'; + +export const WRITE_FILE_TOOL = 'write_file'; +export const CREATE_FILE_TOOL = 'create_file'; +export const FILE_MAKING_TOOLS = new Set([CREATE_FILE_TOOL, 'test_report_template', 'generate_report', 'read_reports']); + +export interface AiMadeFile { + executionId: string; + resource: AiResourceInfo; + label: string; + icon: string; + size: string; + preview: 'image' | null; + download: boolean; +} + +const MADE_KINDS: Record = { + 'image/png': {label: 'PNG', icon: 'image', preview: 'image'}, + 'application/pdf': {label: 'PDF', icon: 'picture_as_pdf', preview: null}, + 'text/csv': {label: 'CSV', icon: 'table_chart', preview: null}, + 'application/vnd.openxmlformats-officedocument.wordprocessingml.document': {label: 'Word', icon: 'description', preview: null}, + 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet': {label: 'Excel', icon: 'table_chart', preview: null} +}; + +export function aiMadeFileOf(executionId: string, result: unknown): AiMadeFile | null { + let parsed: unknown = result; + if (typeof result === 'string') { + const text = /^OK: [^\n]*\n/.test(result) ? result.slice(result.indexOf('\n') + 1) : result; + try { + parsed = JSON.parse(text); + } catch { + return null; + } + } + const file = (parsed as {file?: Partial})?.file; + const download = (parsed as {download?: unknown})?.download === true; + if (!file || typeof file.id !== 'string' || typeof file.name !== 'string' || typeof file.mediaType !== 'string') { + return null; + } + const kind = MADE_KINDS[file.mediaType] ?? {label: file.name.split('.').pop()?.toUpperCase() ?? 'File', icon: 'draft', preview: null}; + const bytes = typeof file.size === 'number' ? file.size : 0; + return { + executionId, + resource: {id: file.id, name: file.name, mediaType: file.mediaType, size: bytes}, + label: kind.label, + icon: kind.icon, + size: formatSize(bytes), + preview: kind.preview, + download + }; +} + +function formatSize(bytes: number): string { + return bytes < 1024 ? `${bytes} B` : bytes < 1024 * 1024 ? `${(bytes / 1024).toFixed(1)} KB` : `${(bytes / 1024 / 1024).toFixed(1)} MB`; +} + +export interface AiFile { + executionId: string; + name: string; + content: string; + summary?: string; + lang: string; + label: string; + icon: string; + lines: number; + size: string; + markdown: boolean; + image: boolean; + previewed: boolean; + edited: boolean; +} + +export interface AiFileName { + base: string; + ext: string; +} + +const MARKS: Record = {JSON: 'data_object', YAML: 'data_object', TOML: 'data_object', XML: 'data_object', Markdown: 'article', SVG: 'image', Text: 'description', CSV: 'table_chart'}; + +export function aiFileName(name: string): AiFileName { + const found = /^(.+?)(\.[A-Za-z0-9]{1,8})$/.exec(name); + return found ? {base: found[1], ext: found[2]} : {base: name, ext: ''}; +} + +export function aiFileMark(file: AiFile): string { + return MARKS[file.label] ?? (file.lang === 'text' ? 'description' : 'code'); +} + +export function aiFileDraftKey(executionId: string): string { + return 'tbAiFileDraft:' + executionId; +} + +const PNG_SCALE = 2; +const PNG_MAX_SIDE = 4096; + +const XML_ENTITIES = new Set(['amp', 'lt', 'gt', 'quot', 'apos']); + +export function aiImageSrc(file: AiFile): string { + return 'data:image/svg+xml;charset=utf-8,' + encodeURIComponent(xmlEntities(file.content)); +} + +function xmlEntities(svg: string): string { + const decoder = document.createElement('textarea'); + return svg.replace(/&([a-zA-Z][a-zA-Z0-9]*);/g, (entity, name: string) => { + if (XML_ENTITIES.has(name)) { + return entity; + } + decoder.innerHTML = entity; + const text = decoder.value; + return text === entity ? '&' + name + ';' : Array.from(text).map(char => `&#${char.codePointAt(0)};`).join(''); + }); +} + +export function downloadAiFile(file: AiFile): void { + save(new Blob([file.content], {type: file.image ? 'image/svg+xml' : 'text/plain;charset=utf-8'}), file.name); +} + +export function downloadAiFileAsPng(file: AiFile): Promise { + return new Promise((resolve, reject) => { + const image = new Image(); + image.onload = () => { + const size = svgSize(file.content) ?? {width: image.naturalWidth || 800, height: image.naturalHeight || 400}; + const scale = Math.min(PNG_SCALE, PNG_MAX_SIDE / Math.max(size.width, size.height)); + const canvas = document.createElement('canvas'); + canvas.width = Math.max(1, Math.round(size.width * scale)); + canvas.height = Math.max(1, Math.round(size.height * scale)); + canvas.getContext('2d').drawImage(image, 0, 0, canvas.width, canvas.height); + canvas.toBlob(blob => { + if (blob) { + save(blob, file.name.replace(/\.svg$/i, '') + '.png'); + resolve(); + } else { + reject(new Error('PNG export failed')); + } + }, 'image/png'); + }; + image.onerror = () => reject(new Error('The image could not be drawn')); + image.src = aiImageSrc(file); + }); +} + +function svgSize(svg: string): {width: number; height: number} | null { + const root = new DOMParser().parseFromString(svg, 'image/svg+xml').documentElement; + if (root?.nodeName.toLowerCase() !== 'svg') { + return null; + } + const width = parseFloat(root.getAttribute('width') ?? ''); + const height = parseFloat(root.getAttribute('height') ?? ''); + if (width > 0 && height > 0 && !/%/.test(root.getAttribute('width') + root.getAttribute('height'))) { + return {width, height}; + } + const box = (root.getAttribute('viewBox') ?? '').trim().split(/[\s,]+/).map(Number); + return box.length === 4 && box[2] > 0 && box[3] > 0 ? {width: box[2], height: box[3]} : null; +} + +function save(blob: Blob, name: string): void { + const url = URL.createObjectURL(blob); + const link = document.createElement('a'); + link.href = url; + link.download = name; + link.click(); + setTimeout(() => URL.revokeObjectURL(url)); +} + +export function aiFileOf(executionId: string, args: unknown, edited = false): AiFile | null { + const values = (args ?? {}) as {name?: unknown; content?: unknown; summary?: unknown}; + if (typeof values.name !== 'string' || !values.name.trim() || typeof values.content !== 'string') { + return null; + } + const name = values.name.trim(); + const language = fileLanguage(name); + const content = values.content; + const bytes = new TextEncoder().encode(content).length; + return { + executionId, + name, + content, + summary: typeof values.summary === 'string' ? values.summary : undefined, + lang: language.lang, + label: language.label, + icon: language.icon, + lines: content.replace(/\n$/, '').split('\n').length, + size: bytes < 1024 ? `${bytes} B` : bytes < 1024 * 1024 ? `${(bytes / 1024).toFixed(1)} KB` : `${(bytes / 1024 / 1024).toFixed(1)} MB`, + markdown: language.label === 'Markdown', + image: language.label === 'SVG', + previewed: language.label === 'Markdown' || language.label === 'SVG', + edited + }; +} diff --git a/ui-ngx/src/app/modules/home/components/ai/ai-hand-over.component.html b/ui-ngx/src/app/modules/home/components/ai/ai-hand-over.component.html new file mode 100644 index 0000000000..31aebbd8c5 --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/ai/ai-hand-over.component.html @@ -0,0 +1,197 @@ + +
+ @if (folded()) { + +

{{ arrivedLine() }}

+ } @else { +
+ {{ 'ai-assistant.hand-over.needs-you' | translate }} + {{ handOver().title }} +
+ @if (arrived()) { + + } @else if (time()) { + + } +
+ @if (handOver().text) { + + } + @if (handOver().choice; as choice) { +
+
+ + {{ choice.question }} + + @for (option of choice.options; track option.id) { + + } + +
+ @if (choiceText()) { +
+ } +
+ } + @if (steps().length) { +
    + @for (step of steps(); track step; let i = $index) { +
  1. + + @if (step.file && files().get(step.file); as file) { + + } + @if (step.values.length || step.markdown) { +
    +
    + @for (value of step.values; track $index; let v = $index) { +
    + + {{ value.label }} + {{ value.secret && !shown().has(i + '-' + v) ? masked(value.value) : value.value }} + @if (value.secret) { + + } + +
    + } +
    + @if (step.markdown) { + + } +
    + } +
  2. + } +
+ } + @if (!handOver().waitFor && handOver().test; as test) { + + @if (test.hint) { +

{{ test.hint }}

+ } +
+
+ } + @if (stopped()) { +
+
+ + {{ (undecoded() ? 'ai-assistant.hand-over.not-decoded' : 'ai-assistant.hand-over.stopped-at') | translate: {time: stoppedAt()} }} + @if (canListenAgain()) { + + + + } +
+
+ } @else if (quiet()) { +
+
+ + {{ (undecoded() ? 'ai-assistant.hand-over.not-decoded' : 'ai-assistant.hand-over.nothing-heard') | translate: {minutes: quietMinutes()} }} + {{ clock() }} + + + +
+
+ @if (canSendTest()) { + + } + + @if (handOver().paste; as paste) { + + } @else { + + } +
+ @if (handOver().test; as test) { + + @if (test.hint) { +

{{ test.hint }}

+ } +
+
+ } +
+ } @else if (waiting()) { +
+
+ + {{ waitLabel() }} + {{ clock() }} + + + +
+ @if (canSendTest()) { +
+ +
+ } +
+ } + @if (testNote(); as note) { +
+ + {{ note }} +
+ } +
+ } +
diff --git a/ui-ngx/src/app/modules/home/components/ai/ai-hand-over.component.ts b/ui-ngx/src/app/modules/home/components/ai/ai-hand-over.component.ts new file mode 100644 index 0000000000..1b6dd6f36d --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/ai/ai-hand-over.component.ts @@ -0,0 +1,330 @@ +// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: BUSL-1.1 +import { readStored, writeStored } from '@core/local-storage/stored'; +import { AfterViewChecked, Component, computed, DestroyRef, effect, ElementRef, EventEmitter, inject, input, NgZone, Output, signal, untracked } from '@angular/core'; +import { AiFile, aiFileMark, aiFileName } from '@home/components/ai/ai-file.models'; +import { aiFold, aiRevealOpened } from '@home/components/ai/ai-disclosure.component'; +import { Clipboard } from '@angular/cdk/clipboard'; +import { TranslateService } from '@ngx-translate/core'; +import { AiConnectionCheck, AiHandOver } from '@home/components/ai/ai-action.models'; +import { aiFenceMeta, announceCopied, codeTabGroup, codeTabsBlock, decorateCodeBlocks } from '@home/components/ai/ai-code-block'; + +export interface AiHandOverWait { + running: boolean; + startedAt: number; + progress?: string; + endedAt?: number; + check?: AiConnectionCheck | null; +} + +const MIN_SILENCE_MS = 120000; +const MAX_SILENCE_MS = 300000; +const TEST_MARKER = 'aiTestValue'; +const OS_LABELS: Record = {macos: 'macOS', windows: 'Windows', linux: 'Linux'}; + +function localOs(): string { + const platform = navigator.userAgent; + return /Windows/i.test(platform) ? 'windows' : /Mac/i.test(platform) ? 'macos' : 'linux'; +} +const COPIED_MS = 1500; +const PROGRESS_KEY = 'tb.ai.handOver.'; +const PROGRESS_INDEX = 'tb.ai.handOvers'; +const MAX_SAVED_PROGRESS = 50; + +export interface AiHandOverProgress { + title: string; + choice?: string; + ticks: number[]; + ticked: string[]; + steps: number; +} + +export function aiHandOverProgress(cardId: string): AiHandOverProgress | null { + if (!cardId) { + return null; + } + try { + const saved = readStored(PROGRESS_KEY + cardId); + return saved ? JSON.parse(saved) as AiHandOverProgress : null; + } catch { + return null; + } +} + +function aiSaveHandOverProgress(cardId: string, progress: AiHandOverProgress): void { + if (!cardId) { + return; + } + writeStored(PROGRESS_KEY + cardId, JSON.stringify(progress)); + let saved: string[] = []; + try { + saved = JSON.parse(readStored(PROGRESS_INDEX) ?? '[]'); + } catch { + saved = []; + } + const kept = [...saved.filter(id => id !== cardId), cardId]; + kept.slice(0, Math.max(0, kept.length - MAX_SAVED_PROGRESS)).forEach(id => writeStored(PROGRESS_KEY + id, null)); + writeStored(PROGRESS_INDEX, JSON.stringify(kept.slice(-MAX_SAVED_PROGRESS))); +} + +@Component({ + selector: 'tb-ai-hand-over', + templateUrl: './ai-hand-over.component.html', + standalone: false +}) +export class AiHandOverComponent implements AfterViewChecked { + + handOver = input.required(); + wait = input(null); + time = input(0); + files = input>(new Map()); + cardId = input(''); + testRequest = input(0); + + private handledTest = 0; + + private testRequested = effect(() => { + const request = this.testRequest(); + if (request > this.handledTest) { + this.handledTest = request; + untracked(() => this.sendTest()); + } + }); + canListenAgain = input(false); + + @Output() prompt = new EventEmitter(); + + @Output() stop = new EventEmitter(); + @Output() compose = new EventEmitter(); + @Output() openFile = new EventEmitter(); + @Output() listenAgain = new EventEmitter(); + + readonly fileMark = aiFileMark; + readonly fileName = aiFileName; + + private host = inject(ElementRef); + private translate = inject(TranslateService); + private clipboard = inject(Clipboard); + + readonly picked = signal(null); + readonly ticked = signal>(new Set()); + readonly shown = signal>(new Set()); + readonly copied = signal(null); + readonly now = signal(Date.now()); + private readonly fold = aiFold(); + + readonly open = this.fold.open; + readonly testState = signal<'idle' | 'sending' | 'sent' | 'failed'>('idle'); + readonly testAt = signal(0); + readonly testError = signal(''); + readonly lastTickAt = signal(0); + + readonly choiceValue = computed(() => this.picked() ?? this.handOver().choice?.value ?? null); + readonly steps = computed(() => { + const picked = this.handOver().choice?.options.find(option => option.id === this.choiceValue()); + return picked?.steps?.length ? picked.steps : this.handOver().steps; + }); + readonly choiceText = computed(() => this.handOver().choice?.options.find(option => option.id === this.choiceValue())?.text ?? ''); + + readonly arrived = computed(() => this.wait()?.check?.dataArriving === true); + readonly folded = computed(() => this.arrived() && !this.open()); + readonly arrivedLine = computed(() => { + const wait = this.wait(); + const at = wait?.endedAt ? new Date(wait.endedAt).toLocaleTimeString([], {hour: '2-digit', minute: '2-digit', hourCycle: 'h23'}) : ''; + return this.translate.instant('ai-assistant.hand-over.arrived-' + (this.handOver().waitFor ?? 'message'), {time: at}); + }); + + readonly waiting = computed(() => !!this.wait()?.running); + readonly canSendTest = computed(() => !!this.handOver().test?.sample && this.handOver().waitFor === 'message'); + readonly testNote = computed(() => { + const time = new Date(this.testAt()).toLocaleTimeString([], {hour: '2-digit', minute: '2-digit', hourCycle: 'h23'}); + switch (this.testState()) { + case 'sent': + return this.translate.instant('ai-assistant.hand-over.test-sent', {time}); + case 'failed': + return this.translate.instant('ai-assistant.hand-over.test-failed', {error: this.testError()}); + default: + return ''; + } + }); + readonly elapsed = computed(() => Math.max(0, this.now() - (this.wait()?.startedAt ?? this.now()))); + readonly clock = computed(() => { + const seconds = Math.floor(this.elapsed() / 1000); + return `${Math.floor(seconds / 60)}:${String(seconds % 60).padStart(2, '0')}`; + }); + readonly silenceMs = computed(() => Math.min(MAX_SILENCE_MS, + Math.max(MIN_SILENCE_MS, 2 * 1000 * (this.handOver().waitFor === 'gateway' ? 0 : this.handOver().intervalSeconds ?? 0)))); + readonly silent = computed(() => Math.max(0, this.now() - Math.max(this.wait()?.startedAt ?? this.now(), this.lastTickAt()))); + readonly quiet = computed(() => this.waiting() && this.silent() >= this.silenceMs()); + readonly quietMinutes = computed(() => Math.max(2, Math.floor(this.silent() / 60000))); + readonly undecoded = computed(() => this.wait()?.check?.failedStep === 'decoded'); + readonly stopped = computed(() => { + const wait = this.wait(); + return !!wait && !wait.running && !!wait.check && !wait.check.dataArriving; + }); + readonly stoppedAt = computed(() => { + const at = this.wait()?.endedAt; + return at ? new Date(at).toLocaleTimeString([], {hour: '2-digit', minute: '2-digit', hourCycle: 'h23'}) : ''; + }); + + constructor() { + const zone = inject(NgZone); + let timer: ReturnType | null = null; + const stopTimer = () => { + if (timer) { + clearInterval(timer); + timer = null; + } + }; + effect(() => { + if (this.waiting()) { + untracked(() => this.now.set(Date.now())); + if (!timer) { + timer = zone.runOutsideAngular(() => setInterval(() => this.now.set(Date.now()), 1000)); + } + } else { + stopTimer(); + } + }); + inject(DestroyRef).onDestroy(stopTimer); + effect(() => { + const saved = aiHandOverProgress(this.cardId()); + untracked(() => { + if (saved?.choice) { + this.picked.set(saved.choice); + } + this.ticked.set(new Set(saved?.ticks ?? [])); + }); + }); + effect(() => { + this.choiceText(); + this.steps(); + this.handOver(); + this.folded(); + setTimeout(() => this.decorate()); + }); + } + + md(text: string): string { + return aiFenceMeta(text); + } + + ngAfterViewChecked(): void { + if ((this.host.nativeElement as HTMLElement).querySelector('.k-test-slot:empty')) { + this.decorate(); + } + } + + decorate(): void { + const root = this.host.nativeElement as HTMLElement; + const test = this.handOver().test; + root.querySelectorAll('.k-test-slot:empty').forEach(slot => { + if (!test) { + return; + } + const order = ['macos', 'windows', 'linux']; + const tabs = [...test.commands].sort((a, b) => order.indexOf(a.os) - order.indexOf(b.os)).map(command => ({id: command.os, label: OS_LABELS[command.os], text: command.command, + lang: command.os === 'windows' ? 'powershell' : 'shell'})); + const preferred = codeTabGroup('os') ?? localOs(); + const initial = Math.max(0, tabs.findIndex(tab => tab.id === preferred)); + slot.append(codeTabsBlock(tabs, 'shell', this.translate, text => this.clipboard.copy(text), initial, undefined, {group: 'os'})); + }); + decorateCodeBlocks(root, this.translate, text => this.clipboard.copy(text)); + } + + waitLabel(): string { + return this.translate.instant('ai-assistant.hand-over.wait-' + (this.handOver().waitFor ?? 'message')); + } + + pick(id: string): void { + this.picked.set(id); + this.ticked.set(new Set()); + this.saveProgress(); + } + + tick(index: number): void { + const next = new Set(this.ticked()); + if (next.has(index)) { + next.delete(index); + } else { + next.add(index); + } + this.ticked.set(next); + this.lastTickAt.set(Date.now()); + this.saveProgress(); + } + + private saveProgress(): void { + const steps = this.steps(); + aiSaveHandOverProgress(this.cardId(), { + title: this.handOver().title, + choice: this.picked() ?? undefined, + ticks: [...this.ticked()], + ticked: steps.filter((_, index) => this.done(index)).map(step => step.title), + steps: steps.length + }); + } + + done(index: number): boolean { + return this.ticked().has(index) !== (this.steps()[index]?.done === true); + } + + reveal(key: string): void { + const next = new Set(this.shown()); + if (next.has(key)) { + next.delete(key); + } else { + next.add(key); + } + this.shown.set(next); + } + + masked(value: string): string { + return value.length > 8 ? value.slice(0, 4) + '••••••••' + value.slice(-4) : '••••••••'; + } + + copy(key: string, value: string): void { + if (this.clipboard.copy(value)) { + this.copied.set(key); + announceCopied(this.translate.instant('ai-assistant.copied')); + setTimeout(() => this.copied.set(null), COPIED_MS); + } + } + + async sendTest(): Promise { + const test = this.handOver().test; + if (!test?.sample || !test.accessToken || this.testState() === 'sending') { + return; + } + this.testState.set('sending'); + const ts = Date.now(); + try { + const response = await fetch(`/api/v1/${encodeURIComponent(test.accessToken)}/telemetry`, { + method: 'POST', + headers: {'Content-Type': 'application/json'}, + body: JSON.stringify({ts, values: {...test.sample, [TEST_MARKER]: true}}) + }); + if (!response.ok) { + throw new Error(`HTTP ${response.status}`); + } + this.testAt.set(ts); + this.testState.set('sent'); + } catch (error) { + this.testError.set(error instanceof Error ? error.message : String(error)); + this.testState.set('failed'); + } + } + + unfold(): void { + this.open.set(true); + aiRevealOpened(this.host.nativeElement); + } + + startPaste(intro: string): void { + this.compose.emit(intro + '\n'); + } + + say(key: string): void { + this.prompt.emit(this.translate.instant(key)); + } +} diff --git a/ui-ngx/src/app/modules/home/components/ai/ai-limit-out.component.html b/ui-ngx/src/app/modules/home/components/ai/ai-limit-out.component.html new file mode 100644 index 0000000000..0ea48ad67d --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/ai/ai-limit-out.component.html @@ -0,0 +1,31 @@ + +@let current = view(); +
+ + {{ noticeText() }} + @switch (current.action) { + @case ('request') { + @if (state() === 'sent') { + {{ 'ai-assistant.limit-out.sent' | translate }} + } @else { + + } + } + @case ('license') { + {{ 'ai-assistant.limit-out.manage-license' | translate }} + } + @case ('pricing') { + {{ 'subscription.upgrade-plan' | translate }} + } + } + +
+@if (state() === 'failed') { +

{{ 'ai-assistant.limit-out.failed' | translate }}

+} diff --git a/ui-ngx/src/app/modules/home/components/ai/ai-limit-out.component.ts b/ui-ngx/src/app/modules/home/components/ai/ai-limit-out.component.ts new file mode 100644 index 0000000000..b6878ea0f0 --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/ai/ai-limit-out.component.ts @@ -0,0 +1,170 @@ +// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: BUSL-1.1 +import { aiLocale } from '@home/components/ai/ai-text'; +import { ChangeDetectionStrategy, Component, computed, effect, inject, input, output, signal } from '@angular/core'; +import { Store } from '@ngrx/store'; +import { TranslateService } from '@ngx-translate/core'; +import { Observable } from 'rxjs'; +import { AppState } from '@core/core.state'; +import { getCurrentAuthState, getCurrentAuthUser } from '@core/auth/auth.selectors'; +import { NotificationService } from '@core/http/notification.service'; +import { Authority } from '@shared/models/authority.enum'; +import { EntityType, entityTypeTranslations } from '@shared/models/entity-type.models'; +import { AddonType, SubscriptionEntry, subscriptionEntryToEntityType } from '@shared/models/subscription.models'; +import { writeStored } from '@core/local-storage/stored'; +import { AiPlatformLimit } from '@shared/models/ai-chat.models'; + +type RequestState = 'idle' | 'sending' | 'sent' | 'failed'; + +type LimitAction = 'request' | 'license' | 'pricing' | 'none'; + +interface LimitView { + icon: string; + title: string; + action: LimitAction; + requestLabel?: string; + storageKey: string; + send?: () => Observable; +} + +const PRICING_URL = 'https://thingsboard.io/pricing/'; +const WL_REQUESTED_STORAGE_KEY = 'wlRequested'; +const PE_PACK_REQUESTED_STORAGE_KEY = 'pePackRequested'; +const FEATURE_KEYS: Record = { + [SubscriptionEntry.WHITE_LABELING]: 'white-labeling', + INTEGRATIONS: 'integrations', + SCHEDULER: 'scheduler', + REPORTING: 'reporting' +}; + +@Component({ + selector: 'tb-ai-limit-out', + templateUrl: './ai-limit-out.component.html', + styleUrls: ['./ai-credits-out.component.scss'], + changeDetection: ChangeDetectionStrategy.OnPush, + standalone: false +}) +export class AiLimitOutComponent { + + platformLimit = input.required(); + + dismissed = output(); + + private notificationService = inject(NotificationService); + private translate = inject(TranslateService); + private readonly store = inject(Store); + private readonly user = getCurrentAuthUser(this.store); + private readonly authState = getCurrentAuthState(this.store); + + readonly pricingUrl = PRICING_URL; + readonly state = signal('idle'); + readonly view = computed(() => this.viewOf(this.platformLimit())); + readonly noticeText = computed(() => { + const limit = this.platformLimit(); + const title = this.view().title; + return limit.limit ? this.say('notice-count', {title, limit: this.count(limit.limit)}) : this.say('notice', {title}); + }); + + constructor() { + effect(() => this.state.set(this.wasRequested(this.view().storageKey) ? 'sent' : 'idle')); + } + + request(): void { + const send = this.view().send; + if (!send || this.state() === 'sending' || this.state() === 'sent') { + return; + } + this.state.set('sending'); + send().subscribe({ + next: () => { + this.rememberRequested(this.view().storageKey); + this.state.set('sent'); + }, + error: () => this.state.set('failed') + }); + } + + private count(value: number): string { + return value.toLocaleString(aiLocale(this.translate.currentLang)); + } + + private viewOf(limit: AiPlatformLimit): LimitView { + const sysAdmin = this.user?.authority === Authority.SYS_ADMIN; + const oldLicense = !(this.authState?.licenseVersion > 1); + const config = {ignoreLoading: true, ignoreErrors: true}; + if (limit.errorCode === 41 && limit.entityType) { + const entityType = limit.entityType; + return { + icon: 'data_usage', + title: this.say('entity-title', {entities: this.entities(entityType)}), + action: 'request', + requestLabel: 'ai-assistant.limit-out.request', + storageKey: `tb-entity-limit-request:${this.user?.tenantId}:${entityType}:${limit.limit}`, + send: () => this.notificationService.sendEntitiesLimitIncreaseRequest(entityType, false, config) + }; + } + const entry = limit.subscriptionEntry as SubscriptionEntry; + const licensedType = subscriptionEntryToEntityType.get(entry); + if (limit.subscriptionErrorCode === 'LIMIT_REACHED' && licensedType) { + return { + icon: 'data_usage', + title: this.say('entity-title', {entities: this.entities(licensedType)}), + action: oldLicense ? 'pricing' : (sysAdmin ? 'license' : 'request'), + requestLabel: 'ai-assistant.limit-out.request', + storageKey: `tb-entity-limit-request:${this.user?.tenantId}:${licensedType}:license`, + send: () => this.notificationService.sendEntitiesLimitIncreaseRequest(licensedType, true, config) + }; + } + const featureKey = FEATURE_KEYS[limit.subscriptionEntry ?? '']; + if (limit.subscriptionErrorCode === 'FEATURE_DISABLED' && featureKey) { + const whiteLabeling = entry === SubscriptionEntry.WHITE_LABELING; + const grant = !!this.authState?.communityGrantLicense; + const addon = whiteLabeling && !grant ? AddonType.WHITE_LABELING : AddonType.PROFESSIONAL_UPGRADE; + return { + icon: whiteLabeling ? 'palette' : 'lock', + title: grant + ? this.translate.instant(`platform-feature.${featureKey}.not-in-ce-grant`) + : (whiteLabeling ? this.translate.instant('platform-feature.white-labeling.not-in-plan') + : this.say('feature-title', {feature: this.say(`feature.${featureKey}`)})), + action: sysAdmin ? 'license' : (oldLicense && !grant ? 'pricing' : 'request'), + requestLabel: 'subscription.request-access', + storageKey: addon === AddonType.WHITE_LABELING ? WL_REQUESTED_STORAGE_KEY : PE_PACK_REQUESTED_STORAGE_KEY, + send: () => this.notificationService.sendAddonAccessRequest(addon, config) + }; + } + return { + icon: 'lock', + title: this.say('license-required'), + action: sysAdmin ? 'license' : 'none', + storageKey: '' + }; + } + + private entities(entityType: EntityType): string { + const translations = entityTypeTranslations.get(entityType); + return translations ? this.translate.instant(translations.typePlural) as string : entityType; + } + + private say(key: string, params?: object): string { + return this.translate.instant('ai-assistant.limit-out.' + key, params); + } + + private wasRequested(key: string): boolean { + if (!key) { + return false; + } + try { + const stored = localStorage.getItem(key); + return stored === 'sent' || stored === 'true'; + } catch { + return false; + } + } + + private rememberRequested(key: string): void { + if (!key) { + return; + } + writeStored(key, key === WL_REQUESTED_STORAGE_KEY || key === PE_PACK_REQUESTED_STORAGE_KEY ? JSON.stringify(true) : 'sent'); + } +} diff --git a/ui-ngx/src/app/modules/home/components/ai/ai-load-lines.component.ts b/ui-ngx/src/app/modules/home/components/ai/ai-load-lines.component.ts new file mode 100644 index 0000000000..79fc471864 --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/ai/ai-load-lines.component.ts @@ -0,0 +1,61 @@ +// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: BUSL-1.1 +import { ChangeDetectionStrategy, Component, DestroyRef, effect, inject, input, signal, untracked } from '@angular/core'; + +const ROLL_MS = 720; + +@Component({ + selector: 'tb-ai-load-lines', + template: ` + {{ current() }} + + `, + standalone: false, + changeDetection: ChangeDetectionStrategy.OnPush, + host: { + 'class': 'art-load-lines' + } +}) +export class AiLoadLinesComponent { + + line = input(''); + lines = input([]); + + current = signal(''); + previous = signal(null); + + private timer: ReturnType; + + constructor() { + effect(() => { + const text = this.line() ?? ''; + untracked(() => this.show(text)); + }); + inject(DestroyRef).onDestroy(() => clearTimeout(this.timer)); + } + + private show(text: string): void { + const now = this.current(); + if (text === now) { + return; + } + clearTimeout(this.timer); + this.previous.set(now || null); + this.current.set(text); + if (now) { + this.timer = setTimeout(() => this.previous.set(null), ROLL_MS); + } + } +} diff --git a/ui-ngx/src/app/modules/home/components/ai/ai-loading-modal.component.html b/ui-ngx/src/app/modules/home/components/ai/ai-loading-modal.component.html deleted file mode 100644 index 59a00e96d0..0000000000 --- a/ui-ngx/src/app/modules/home/components/ai/ai-loading-modal.component.html +++ /dev/null @@ -1,15 +0,0 @@ - -
-
- Loading -
- {{ statusMessage | translate }} - {{ 'solution-creator.estimate-wait-time' | translate: {time: (data.estimateWaitTime | milliSecondsToTimeString:true : true)} }} -
-
-
diff --git a/ui-ngx/src/app/modules/home/components/ai/ai-loading-modal.component.scss b/ui-ngx/src/app/modules/home/components/ai/ai-loading-modal.component.scss deleted file mode 100644 index 7af33d5f19..0000000000 --- a/ui-ngx/src/app/modules/home/components/ai/ai-loading-modal.component.scss +++ /dev/null @@ -1,39 +0,0 @@ -// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. -// SPDX-License-Identifier: BUSL-1.1 -.ai-backdrop-filter { - background: rgba(255, 255, 255, .01); - backdrop-filter: blur(8px); -} - -.tb-generated { - z-index: 3; - .panel { - box-shadow: 0 6px 12px 0 rgba(0, 0, 0, 0.04), 0 12px 32px 0 rgba(0, 0, 0, 0.08); - background-color: #fff; - width: 500px; - } - img { - width: 200px; - } - .info { - white-space: pre-line; - text-align: center; - line-height: 1.5; - letter-spacing: 0.15px; - } - - .msg.text-changed { - animation: fadeInSlideUp 0.5s ease-out forwards; - } - - @keyframes fadeInSlideUp { - 0% { - opacity: 0; - transform: translateY(15px); - } - 100% { - opacity: 1; - transform: translateY(0); - } - } -} diff --git a/ui-ngx/src/app/modules/home/components/ai/ai-loading-modal.component.ts b/ui-ngx/src/app/modules/home/components/ai/ai-loading-modal.component.ts deleted file mode 100644 index 3ab1c957eb..0000000000 --- a/ui-ngx/src/app/modules/home/components/ai/ai-loading-modal.component.ts +++ /dev/null @@ -1,61 +0,0 @@ -// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. -// SPDX-License-Identifier: BUSL-1.1 -import { Component, DestroyRef, Inject, OnInit, ViewEncapsulation } from '@angular/core'; -import { DialogComponent } from '@shared/components/dialog.component'; -import { Store } from '@ngrx/store'; -import { AppState } from '@core/core.state'; -import { Router } from '@angular/router'; -import { MAT_DIALOG_DATA, MatDialogRef } from '@angular/material/dialog'; -import { from, of } from 'rxjs'; -import { concatMap, delay } from 'rxjs/operators'; -import { takeUntilDestroyed } from '@angular/core/rxjs-interop'; -import { generatedStateImages } from '@home/components/ai/ai.models'; - -export interface AiLoadingModalData { - messages: Array<{text: string; delay: number}>; - estimateWaitTime: number; - image?: string; -} - -@Component({ - selector: 'tb-ai-loading-modal', - templateUrl: './ai-loading-modal.component.html', - styleUrl: './ai-loading-modal.component.scss', - encapsulation: ViewEncapsulation.None, - standalone: false, - host: { - style: 'width: 100%; height: 100%; min-height: 100%; display: flex; overflow: hidden;' - } -}) -export class AiLoadingModalComponent extends DialogComponent implements OnInit { - - generateImage: string = generatedStateImages[Math.floor(Math.random() * generatedStateImages.length)]; - statusMessage: string = ''; - statusMessageChanged = false; - - constructor(protected store: Store, - protected router: Router, - @Inject(MAT_DIALOG_DATA) public data: AiLoadingModalData, - public dialogRef: MatDialogRef, - private destroyRef: DestroyRef) { - super(store, router, dialogRef); - } - - ngOnInit() { - this.initGenerateState(); - } - - private initGenerateState(): void { - from(this.data.messages).pipe( - concatMap(message => of(message).pipe(delay(message.delay))), - takeUntilDestroyed(this.destroyRef) - ).subscribe((msg) => { - this.statusMessageChanged = true; - this.statusMessage = msg.text; - setTimeout(() => { - this.statusMessageChanged = false; - }, 500); - }); - } - -} diff --git a/ui-ngx/src/app/modules/home/components/ai/ai-mark.component.ts b/ui-ngx/src/app/modules/home/components/ai/ai-mark.component.ts new file mode 100644 index 0000000000..6a24e78074 --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/ai/ai-mark.component.ts @@ -0,0 +1,71 @@ +// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: BUSL-1.1 +import { ChangeDetectionStrategy, Component, ElementRef, inject, input, numberAttribute, booleanAttribute } from '@angular/core'; + +export type AiMarkCue = 'needs' | 'error'; + +const MARK_CYCLE_MS = 16000; +const LARGE_MARK = 44; + +@Component({ + selector: 'tb-ai-mark, button[tb-ai-mark]', + template: ` + + @if (icon()) { + {{ icon() }} + } @else if (large()) { + + } @else { + auto_awesome + } + + @if (button) { + + @if (cue()) { + + } + } @else { + + } + `, + standalone: false, + changeDetection: ChangeDetectionStrategy.OnPush, + host: { + '[class.tb-ai-mark]': '!button', + '[class.lg]': '!button && large()', + '[style.--m]': 'button ? null : sizePx()', + '[style.animation-delay]': 'button ? null : phase', + '[attr.aria-hidden]': 'button ? null : "true"', + '[class.tb-ai-mark-button]': 'button', + '[attr.type]': 'button ? "button" : null', + '[class.working]': 'button && working()', + '[class.glow]': 'button && glow()' + } +}) +export class AiMarkComponent { + + readonly button = inject>(ElementRef).nativeElement.tagName === 'BUTTON'; + + readonly phase = `-${Date.now() % MARK_CYCLE_MS}ms`; + + size = input(undefined, {transform: (value: unknown) => value == null || value === '' ? undefined : numberAttribute(value)}); + + icon = input(); + + working = input(false, {transform: booleanAttribute}); + + glow = input(false, {transform: booleanAttribute}); + + cue = input(null); + + large(): boolean { + return (this.size() ?? 0) >= LARGE_MARK; + } + + sizePx(): string | null { + const size = this.size() ?? (this.button ? 36 : undefined); + return size ? `${size}px` : null; + } +} diff --git a/ui-ngx/src/app/modules/home/components/ai/ai-number-field.component.html b/ui-ngx/src/app/modules/home/components/ai/ai-number-field.component.html new file mode 100644 index 0000000000..b2f16d33d2 --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/ai/ai-number-field.component.html @@ -0,0 +1,22 @@ + +
+ + + @if (question().number?.unit) { + {{ question().number.unit }} + } + +
+@if (wrong()) { + +} diff --git a/ui-ngx/src/app/modules/home/components/ai/ai-number-field.component.ts b/ui-ngx/src/app/modules/home/components/ai/ai-number-field.component.ts new file mode 100644 index 0000000000..b7eae1fd27 --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/ai/ai-number-field.component.ts @@ -0,0 +1,61 @@ +// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: BUSL-1.1 +import { ChangeDetectionStrategy, Component, computed, inject, input, model, output, signal } from '@angular/core'; +import { TranslateService } from '@ngx-translate/core'; +import { AiQuestion } from '@shared/models/solution-creator.models'; +import { aiLocale, aiNumberReady, aiReadNumber, aiSayNumber, aiStepDecimals } from '@home/components/ai/ai-question.models'; + +@Component({ + selector: 'tb-ai-number-field', + templateUrl: './ai-number-field.component.html', + changeDetection: ChangeDetectionStrategy.OnPush, + standalone: false +}) +export class AiNumberFieldComponent { + + question = input.required(); + value = model(''); + enter = output(); + + private translate = inject(TranslateService); + private touched = signal(false); + + readonly ready = computed(() => aiNumberReady(this.value(), this.locale())); + readonly wrong = computed(() => this.touched() && !!this.value().trim() && !this.ready()); + readonly size = computed(() => this.question().number?.size === 'short' ? 's' : this.question().number?.size === 'medium' ? 'm' : 'l'); + readonly step = computed(() => this.question().number?.step > 0 ? this.question().number.step : 1); + + typed(field: HTMLInputElement): void { + this.value.set(field.value); + } + + stepBy(field: HTMLInputElement, direction: number): void { + const current = aiReadNumber(field.value, this.locale()); + const base = isNaN(current) ? (this.question().number?.suggested ?? 0) : current; + const decimals = Math.max(aiStepDecimals(this.step()), isNaN(current) ? 0 : aiStepDecimals(current)); + field.value = aiSayNumber(+(base + direction * this.step()).toFixed(decimals), this.locale()); + this.touched.set(false); + this.value.set(field.value); + field.focus(); + } + + settle(): void { + this.touched.set(true); + } + + onEnter(event: Event): void { + if ((event as KeyboardEvent).isComposing) { + return; + } + if (!this.ready()) { + event.preventDefault(); + this.touched.set(true); + return; + } + this.enter.emit(event); + } + + private locale(): string { + return aiLocale(this.translate.currentLang); + } +} diff --git a/ui-ngx/src/app/modules/home/components/ai/ai-plan.component.html b/ui-ngx/src/app/modules/home/components/ai/ai-plan.component.html new file mode 100644 index 0000000000..e750917182 --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/ai/ai-plan.component.html @@ -0,0 +1,64 @@ + +@if (folded()) { + +} +@if (!folded() || open()) { +
+
+ {{ 'ai-assistant.plan.title' | translate }} + {{ gate() || !progress() ? ('ai-assistant.plan.steps' | translate: {count: counted()}) : ('ai-assistant.plan.done-of' | translate: {done: done(), count: counted()}) }} + + @if (gate()) { + + } +
+
    + @for (step of steps(); track $index) { +
  1. + @if (gate() && step.optional) { + + } @else { + + } + @if (step.by === 'user') {{{ 'ai-assistant.plan.you' | translate }}}@for (part of parts(step.text); track $index) {@if (part.code) {{{ part.text }}} @else {{{ part.text }}}}@if (step.by === 'user' && step.needs) { {{ 'ai-assistant.plan.needs.' + step.needs | translate }}} +
  2. + } +
+ @if (gate()) { +
+ @if (autoApprove()) { + + + } @else { + + + } +
+ } +
+} diff --git a/ui-ngx/src/app/modules/home/components/ai/ai-plan.component.ts b/ui-ngx/src/app/modules/home/components/ai/ai-plan.component.ts new file mode 100644 index 0000000000..282a52dd5a --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/ai/ai-plan.component.ts @@ -0,0 +1,104 @@ +// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: BUSL-1.1 +import { Component, computed, effect, ElementRef, EventEmitter, inject, input, Output, signal } from '@angular/core'; +import { TranslateService } from '@ngx-translate/core'; +import { decorateReferences } from '@home/components/ai/ai-references'; +import { AiPlanProgress, AiPlanStep, aiPlanStatus } from '@home/components/ai/ai-action.models'; +import { aiFold } from '@home/components/ai/ai-disclosure.component'; + +export interface AiPlanRun { + auto: boolean; + skipped: number[]; +} + + +@Component({ + selector: 'tb-ai-plan', + templateUrl: './ai-plan.component.html', + standalone: false +}) +export class AiPlanComponent { + + steps = input.required(); + progress = input(null); + gate = input(false); + autoApprove = input(false); + replacedAfter = input(null); + + private fold = aiFold(); + + open = this.fold.open; + + @Output() run = new EventEmitter(); + @Output() changeRequested = new EventEmitter(); + + private cleared = signal>(new Set()); + + private host = inject(ElementRef); + private translate = inject(TranslateService); + + private chips = effect(() => { + const steps = this.steps(); + this.open(); + this.folded(); + setTimeout(() => { + const whats = (this.host.nativeElement as HTMLElement).querySelectorAll('.k-plan li .k-what'); + steps.forEach((step, index) => { + if (step.makes?.length && whats[index]) { + decorateReferences(whats[index], step.makes.map(made => ({name: made.name, entityType: made.type, id: ''}))); + } + }); + }); + }); + + status = computed(() => aiPlanStatus(this.steps(), this.progress())); + + marks = computed(() => this.status().marks); + + counted = computed(() => this.gate() + ? this.steps().filter((step, index) => !step.optional || !this.cleared().has(index)).length + : this.status().counted); + + done = computed(() => this.status().done); + + finished = computed(() => !this.gate() && this.status().finished); + + folded = computed(() => this.replacedAfter() !== null || this.finished()); + + foldText = computed(() => { + const translate = this.translate; + return this.replacedAfter() !== null + ? translate.instant('ai-assistant.plan.replaced', {done: this.replacedAfter(), count: this.counted()}) + : translate.instant('ai-assistant.plan.folded', {done: this.done(), count: this.counted()}); + }); + + toggleFold(): void { + this.fold.toggle(); + } + + parts(text: string): {text: string; code: boolean}[] { + return text.split('`').map((part, index) => ({text: part, code: index % 2 === 1})).filter(part => part.text); + } + + checked(index: number): boolean { + return !this.cleared().has(index); + } + + toggle(index: number): void { + this.cleared.update(set => { + const next = new Set(set); + if (next.has(index)) { + next.delete(index); + } else { + next.add(index); + } + return next; + }); + } + + start(auto: boolean): void { + const skipped = this.steps().map((step, index) => step.optional && this.cleared().has(index) ? index + 1 : 0).filter(Boolean); + this.run.emit({auto, skipped}); + } + +} diff --git a/ui-ngx/src/app/modules/home/components/ai/ai-prompt-input.component.html b/ui-ngx/src/app/modules/home/components/ai/ai-prompt-input.component.html index 082f2708b0..b01eee5cf8 100644 --- a/ui-ngx/src/app/modules/home/components/ai/ai-prompt-input.component.html +++ b/ui-ngx/src/app/modules/home/components/ai/ai-prompt-input.component.html @@ -4,13 +4,27 @@ SPDX-License-Identifier: BUSL-1.1 --> -
+
@if (attachEnabled()) { }
- @if (attachments().length) { + @if (attachments().length || quote) {
+ @if (quote) { + + {{ quote.icon }} + + {{ fileName(quote.name).base }}{{ fileName(quote.name).ext }} + {{ (quote.from === quote.to ? 'ai-assistant.file.line' : 'ai-assistant.file.lines-range') | translate: {from: quote.from, to: quote.to} }} + + + + } @for (attachment of attachments(); track attachment.key) { {{ attachment.status === 'error' ? 'error_outline' : attachment.icon }} } - {{ attachment.name }} + {{ fileName(attachment.name).base }}{{ fileName(attachment.name).ext }} {{ meta(attachment) }} @if (attachment.status === 'uploading') { @@ -38,26 +52,44 @@ }
+ @if (suggestion && !hasText()) { + + {{ 'ai-assistant.suggestion-sr' | translate: {text: suggestion} }} + } + @if (slim) { + + } - + @if (canStop) { + + } @else { + + }
@@ -69,17 +101,34 @@ attach_file } + @if (showAutoApprove) { + + } -
+ +
+
+ {{ 'ai-assistant.stop' | translate }} + Esc +
+
+
+
@@ -97,6 +146,16 @@
+ +
+
+ {{ 'ai-assistant.auto-approve' | translate }} + {{ (autoApprove ? 'ai-assistant.auto-approve-on' : 'ai-assistant.auto-approve-off') | translate }} +
+

{{ (autoApproveInChat ? 'ai-assistant.auto-approve-text' : 'ai-assistant.auto-approve-new-chat-text') | translate }}

+
+
+
{{ 'ai-assistant.shortcuts' | translate }}
@@ -108,6 +167,12 @@ {{ 'ai-assistant.new-line' | translate }} ShiftEnter
+ @if (suggestion && !hasText()) { +
+ {{ 'ai-assistant.accept-suggestion' | translate }} + Tab +
+ }
{{ 'ai-assistant.focus-composer' | translate }} / diff --git a/ui-ngx/src/app/modules/home/components/ai/ai-prompt-input.component.scss b/ui-ngx/src/app/modules/home/components/ai/ai-prompt-input.component.scss index 088c205465..72fbccb13c 100644 --- a/ui-ngx/src/app/modules/home/components/ai/ai-prompt-input.component.scss +++ b/ui-ngx/src/app/modules/home/components/ai/ai-prompt-input.component.scss @@ -1,19 +1,5 @@ // SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. // SPDX-License-Identifier: BUSL-1.1 -$ai-teal-300: #4db6ac; -$ai-teal-400: #26a69a; -$ai-action: #00695c; -$ai-action-hover: #004d40; -$ai-focus: #00695c; -$ai-teal-700: #00796b; -$ink: rgba(0, 0, 0, 0.87); -$ink-54: rgba(0, 0, 0, 0.54); -$ink-38: rgba(0, 0, 0, 0.38); -$faint: rgba(0, 0, 0, 0.56); -$line: rgba(0, 0, 0, 0.12); -$line-soft: rgba(0, 0, 0, 0.05); -$crit: #d12730; -$font: Roboto, "Helvetica Neue", Helvetica, Arial, sans-serif; $chevron: "data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24' fill='none' stroke='black' stroke-width='2.75' stroke-linecap='round' stroke-linejoin='round'%3E%3Cpath d='M9 5l7 7-7 7'/%3E%3C/svg%3E"; :host { @@ -23,32 +9,32 @@ $chevron: "data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox= .tb-ai-composer { width: 100%; - font-family: $font; - letter-spacing: 0.25px; + font-family: var(--tb-font); + letter-spacing: var(--chat-text-ls); text-align: left; .composer-field { position: relative; display: flow-root; - background: #fff; + background: var(--tb-surface); border: 1px solid transparent; border-radius: 14px; box-shadow: 0 0 0 1px rgba(16, 24, 40, 0.04), 0 1px 2px rgba(16, 24, 40, 0.06), 0 8px 24px rgba(16, 24, 40, 0.08); transition: border-color .18s ease, box-shadow .18s ease; &:focus-within { - border-color: $ai-focus; - box-shadow: 0 0 0 1px $ai-focus, 0 8px 24px rgba(0, 105, 92, 0.12); + border-color: var(--ai-focus); + box-shadow: 0 0 0 1px var(--ai-focus), 0 8px 24px var(--ai-focus-shadow); .composer-chevron { - color: $ai-focus; + color: var(--ai-focus); } } } &.drop .composer-field { - box-shadow: inset 0 0 0 2px $ai-teal-300; - background: color-mix(in srgb, $ai-action 4%, #fff); + box-shadow: inset 0 0 0 2px var(--ai-teal-300); + background: color-mix(in srgb, var(--ai-action) 4%, var(--tb-surface)); } .composer-files { @@ -66,16 +52,16 @@ $chevron: "data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox= max-width: 100%; overflow: hidden; padding: 6px 10px 6px 8px; - border: 1px solid $line; + border: 1px solid var(--tb-line); border-radius: 8px; - background: #fff; + background: var(--tb-surface); font-size: 13.5px; line-height: 20px; animation: composer-file-in .12s ease-out; .mat-icon { flex: none; - color: $ink-54; + color: var(--tb-ink-54); } .file-pic { @@ -99,15 +85,15 @@ $chevron: "data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox= font-size: 13.5px; font-weight: 500; line-height: 18px; - color: $ink; + color: var(--tb-ink); text-overflow: ellipsis; white-space: nowrap; } small { - font-size: 12px; - line-height: 16px; - color: $faint; + font-size: var(--chat-meta); + line-height: var(--chat-meta-lh); + color: var(--k-faint); } } @@ -116,7 +102,7 @@ $chevron: "data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox= left: 0; bottom: 0; height: 2px; - background: $ai-action; + background: var(--ai-teal-500); transition: width .15s linear; } @@ -132,25 +118,25 @@ $chevron: "data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox= border: 0; border-radius: 50%; background: none; - color: $ink-54; + color: var(--tb-ink-54); cursor: pointer; &:hover { background: rgba(0, 0, 0, 0.06); - color: $ink; + color: var(--tb-ink); } } &.up small { - color: $ai-teal-700; + color: var(--ai-teal-700); } &.bad { - border-color: color-mix(in srgb, $crit 40%, transparent); - background: color-mix(in srgb, $crit 4%, #fff); + border-color: color-mix(in srgb, var(--tb-crit) 40%, transparent); + background: color-mix(in srgb, var(--tb-crit) 4%, var(--tb-surface)); .mat-icon, small { - color: $crit; + color: var(--tb-crit); } } } @@ -170,7 +156,7 @@ $chevron: "data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox= align-items: center; height: 24px; margin: 4px 0 0 -2px; - color: $ai-action; + color: var(--ai-teal-500); transition: color .18s ease; &::before { @@ -193,17 +179,17 @@ $chevron: "data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox= outline: 0; resize: none; background: transparent; - font-family: $font; - font-size: 16px; - line-height: 24px; - letter-spacing: normal; - color: $ink; - caret-color: $ai-action; + font-family: var(--tb-font); + font-size: var(--chat-text); + line-height: var(--chat-text-lh); + letter-spacing: inherit; + color: var(--tb-ink); + caret-color: var(--ai-action); tab-size: 2; transition: height .12s ease; &::placeholder { - color: $faint; + color: var(--k-faint); } } @@ -214,6 +200,67 @@ $chevron: "data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox= display: inline-flex; } + .composer-stop.composer-stop { + background: none; + isolation: isolate; + + &::before { + content: ''; + position: absolute; + inset: 0; + z-index: -1; + border-radius: inherit; + background: var(--ai-action); + transition: background-color .2s ease; + } + + &::after { + content: ''; + position: absolute; + inset: -9px; + z-index: -2; + border-radius: 50%; + background: var(--ai-glow); + filter: blur(9px); + pointer-events: none; + --ai-glow-peak: .85; + opacity: .55; + animation: composer-glow-breathe 2.4s ease-in-out infinite, composer-glow-turn 6s linear infinite; + transition: opacity .2s ease; + } + + &:hover:not(:disabled) { + background: none; + + &::before { + background: var(--tb-crit); + } + + &::after { + opacity: 0; + animation: none; + } + } + + &:disabled { + opacity: .6; + cursor: default; + } + + .mat-icon { + width: 24px; + height: 24px; + font-size: 24px; + animation: composer-pop .28s cubic-bezier(.2, 0, 0, 1.4); + } + + @media (prefers-reduced-motion: reduce) { + &::after, .mat-icon { + animation: none; + } + } + } + .composer-send { position: relative; display: inline-flex; @@ -225,13 +272,13 @@ $chevron: "data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox= padding: 0; border: 0; border-radius: 10px; - background: $ai-action; - color: #fff; + background: var(--ai-action); + color: var(--ai-on-action); cursor: pointer; transition: background-color .2s ease, color .2s ease, box-shadow .2s ease, transform .16s cubic-bezier(.2, 0, 0, 1); &:hover:not(:disabled) { - background: $ai-action-hover; + background: var(--ai-action-hover); .return-glyph polyline { transform: scale(1.12); @@ -243,13 +290,13 @@ $chevron: "data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox= } &:focus-visible { - outline: 2px solid $ai-focus; + outline: 2px solid var(--ai-focus); outline-offset: 2px; } &:disabled { background: rgba(0, 0, 0, 0.06); - color: $ink-38; + color: var(--tb-ink-38); cursor: default; } @@ -287,11 +334,11 @@ $chevron: "data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox= align-items: center; gap: 2px; padding: 2px 8px 6px 16px; - border-top: 1px solid $line-soft; + border-top: 1px solid var(--tb-line-soft); border-radius: 0 0 14px 14px; font-size: 13px; line-height: 18px; - color: rgba(0, 0, 0, 0.6); + color: var(--tb-text-secondary); } .composer-spacer { @@ -309,19 +356,117 @@ $chevron: "data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox= border: 0; border-radius: 8px; background: none; - color: $ink-54; + color: var(--tb-ink-54); cursor: pointer; transition: background-color .12s ease, color .12s ease; &:hover, &[aria-describedby] { - background: $line-soft; - color: $ink; + background: var(--tb-line-soft); + color: var(--tb-ink); } &:focus-visible { - outline: 2px solid $ai-focus; + outline: 2px solid var(--ai-focus); outline-offset: 1px; - color: $ink; + color: var(--tb-ink); + } + } + + .composer-auto { + position: relative; + display: inline-flex; + align-items: center; + gap: 8px; + height: 32px; + padding: 0 10px 0 8px; + border-radius: 8px; + font-size: 12.5px; + line-height: 18px; + color: var(--tb-text-secondary); + cursor: pointer; + user-select: none; + transition: background-color .12s ease, color .12s ease; + + &:hover, &[aria-describedby], &:has(input:focus-visible) { + background: rgba(0, 0, 0, 0.05); + color: var(--tb-ink); + } + + input { + position: absolute; + width: 0; + height: 0; + opacity: 0; + } + + .track { + position: relative; + flex: none; + width: 34px; + height: 14px; + border-radius: 7px; + background: rgba(0, 0, 0, 0.26); + transition: background-color .32s cubic-bezier(.4, 0, .2, 1); + } + + .knob { + position: absolute; + top: -3px; + left: 0; + display: inline-flex; + align-items: center; + justify-content: center; + width: 20px; + height: 20px; + border-radius: 50%; + background: #fafafa; + box-shadow: 0 1px 3px rgba(0, 0, 0, 0.4); + transition: transform .32s cubic-bezier(.4, 0, .2, 1), background-color .32s cubic-bezier(.4, 0, .2, 1), box-shadow .2s ease; + + .mat-icon { + font-size: 13px; + width: 13px; + height: 13px; + line-height: 13px; + color: var(--tb-ink-54); + transition: color .32s cubic-bezier(.4, 0, .2, 1); + } + } + + .label { + white-space: nowrap; + color: var(--tb-ink-76); + } + + &:active .knob { + box-shadow: 0 0 0 5px rgba(0, 0, 0, 0.04), 0 1px 3px rgba(0, 0, 0, 0.3); + } + + &.on { + color: var(--tb-ink-76); + + .track { + background: color-mix(in srgb, var(--ai-selected) 35%, transparent); + } + + .knob { + transform: translateX(14px); + background: var(--ai-selected); + + .mat-icon { + color: var(--ai-on-action); + } + } + + &:active .knob { + box-shadow: 0 0 0 5px color-mix(in srgb, var(--ai-selected) 10%, transparent), 0 1px 3px rgba(0, 0, 0, 0.3); + } + } + + @media (prefers-reduced-motion: reduce) { + .track, .knob, .knob .mat-icon { + transition: none; + } } } @@ -330,14 +475,14 @@ $chevron: "data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox= } &.docked { - border-top: 1px solid $line; - background: #fff; - font-size: 14px; - line-height: 20px; + border-top: 1px solid var(--tb-line); + background: var(--tb-surface); + font-size: var(--chat-line); + line-height: var(--chat-line-lh); transition: border-top-color .18s ease; &:focus-within { - border-top-color: $ai-focus; + border-top-color: var(--ai-focus); } .composer-field { @@ -347,12 +492,12 @@ $chevron: "data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox= transition: box-shadow .18s ease; &:focus-within { - box-shadow: inset 0 1px 0 $ai-focus; + box-shadow: inset 0 1px 0 var(--ai-focus); } } &.drop .composer-field { - box-shadow: inset 0 0 0 2px $ai-teal-300; + box-shadow: inset 0 0 0 2px var(--ai-teal-300); } .composer-files { @@ -366,15 +511,19 @@ $chevron: "data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox= .composer-chevron { --chevron: 17px; - height: 22px; + height: var(--chat-line-lh, 20px); + } + + .composer-foot .composer-auto { + height: 28px; } textarea { min-height: 44px; max-height: 160px; padding-right: 44px; - font-size: 14px; - line-height: 20px; + font-size: var(--chat-line); + line-height: var(--chat-line-lh); } .composer-send-slot { @@ -402,7 +551,7 @@ $chevron: "data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox= gap: 6px 8px; padding: 2px 8px 6px 12px; border-radius: 0; - font-size: 12px; + font-size: var(--chat-meta); } .composer-tool { @@ -413,6 +562,27 @@ $chevron: "data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox= .composer-foot > .composer-add:first-child { margin-left: -7.5px; } + + @container k-col (min-width: 481px) { + border-top: 0; + background: none; + + .composer-field, .composer-field:not(:focus-within) { + border: 1px solid var(--tb-line); + border-radius: 14px; + background: var(--tb-surface); + box-shadow: 0 1px 2px rgba(16, 24, 40, 0.06), 0 10px 28px rgba(16, 24, 40, 0.10); + + &:focus-within { + border-color: var(--ai-focus); + box-shadow: 0 0 0 3px var(--ai-focus-shadow), 0 10px 28px rgba(16, 24, 40, 0.10); + } + } + + .composer-foot { + border-radius: 0 0 14px 14px; + } + } } } @@ -452,3 +622,129 @@ $chevron: "data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox= } } } + +@keyframes composer-glow-breathe { + 0%, 100% { + opacity: calc(var(--ai-glow-peak, .85) * .35); + scale: .94; + } + 50% { + opacity: var(--ai-glow-peak, .85); + scale: 1.06; + } +} + +@keyframes composer-glow-turn { + to { + rotate: 1turn; + } +} + +@keyframes composer-pop { + from { + transform: scale(.4) rotate(-20deg); + opacity: 0; + } + to { + transform: none; + opacity: 1; + } +} + +.tb-ai-composer.slim { + .composer-field { + border-radius: 12px; + + &:not(:focus-within) { + border-color: transparent; + box-shadow: var(--tb-home-card-shadow, 0 1px 1px rgba(20, 52, 58, 0.06), 0 2px 6px -1px rgba(20, 52, 58, 0.08)); + } + } + + .composer-row { + padding-bottom: 12px; + transition: padding .24s ease; + } + + textarea { + min-height: 24px; + transition: min-height .24s cubic-bezier(.2, .7, .2, 1); + } + + .composer-foot { + max-height: 0; + padding-top: 0; + padding-bottom: 0; + border-top-width: 0; + opacity: 0; + overflow: clip; + transition: max-height .24s cubic-bezier(.2, .7, .2, 1), padding .24s cubic-bezier(.2, .7, .2, 1), opacity .18s ease; + } + + .composer-slash { + display: inline-flex; + align-items: center; + justify-content: center; + box-sizing: border-box; + min-width: 20px; + height: 20px; + padding: 0 5px; + border: 1px solid var(--tb-line); + border-bottom-width: 2px; + border-radius: 5px; + background: var(--chat-key); + color: var(--tb-ink-76); + font: 500 11px/1 var(--tb-font); + letter-spacing: .2px; + white-space: nowrap; + position: absolute; + top: 50%; + right: 19px; + pointer-events: none; + transform: translateY(-50%); + } + + &:not(:focus-within):not(.has-text) .composer-send-slot { + visibility: hidden; + } + + &:is(:focus-within, .has-text) { + .composer-row { + padding-bottom: 8px; + } + + textarea { + min-height: 72px; + } + + .composer-foot { + max-height: 56px; + padding-top: 2px; + padding-bottom: 6px; + border-top-width: 1px; + opacity: 1; + overflow: visible; + } + + .composer-slash { + display: none; + } + } + + @media (hover: none), (max-width: 599px) { + .composer-slash { + display: none; + } + + &:not(:focus-within):not(.has-text) .composer-send-slot { + visibility: visible; + } + } + + @media (prefers-reduced-motion: reduce) { + textarea, .composer-foot, .composer-row { + transition: none; + } + } +} + diff --git a/ui-ngx/src/app/modules/home/components/ai/ai-prompt-input.component.ts b/ui-ngx/src/app/modules/home/components/ai/ai-prompt-input.component.ts index 5297f99045..dc85e60070 100644 --- a/ui-ngx/src/app/modules/home/components/ai/ai-prompt-input.component.ts +++ b/ui-ngx/src/app/modules/home/components/ai/ai-prompt-input.component.ts @@ -1,32 +1,37 @@ // SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. // SPDX-License-Identifier: BUSL-1.1 +import { aiFileName } from '@home/components/ai/ai-file.models'; import { AfterViewInit, + ChangeDetectionStrategy, Component, computed, ElementRef, EventEmitter, - HostListener, inject, Input, OnChanges, OnDestroy, Output, Renderer2, + SecurityContext, signal, SimpleChanges, untracked, - ViewChild, - SecurityContext + ViewChild } from '@angular/core'; import { FormControl } from '@angular/forms'; import { toSignal } from '@angular/core/rxjs-interop'; import { Subscription } from 'rxjs'; +import { take } from 'rxjs/operators'; import { TranslateService } from '@ngx-translate/core'; +import { MatDialog } from '@angular/material/dialog'; +import { AiShortcutsDialogComponent } from '@home/components/ai/ai-shortcuts-dialog.component'; import { DomSanitizer } from '@angular/platform-browser'; import { guid } from '@core/utils'; +import { AiSlashService } from '@core/services/ai-slash.service'; import { AiResourceService } from '@core/http/ai-resource.service'; -import { AI_IMAGE_MEDIA_TYPES, AiPromptMessage, AiResourceConfig, AiResourceInfo } from '@shared/models/ai-chat.models'; +import { AI_IMAGE_MEDIA_TYPES, AiLinesQuote, AiPromptMessage, AiResourceConfig, AiResourceInfo } from '@shared/models/ai-chat.models'; import { AI_SVG_EXTENSION, aiAttachmentKind, @@ -36,8 +41,7 @@ import { isAiSvg, namePastedImage, svgToAiImage, - aiServerMessage -} from '@home/components/ai/ai-attachment.models'; + aiServerMessage, aiResourceFact } from '@home/components/ai/ai-attachment.models'; interface PendingAttachment { key: string; @@ -56,6 +60,7 @@ interface PendingAttachment { const FLY_DURATION = 520; @Component({ + changeDetection: ChangeDetectionStrategy.OnPush, selector: 'tb-ai-prompt-input', templateUrl: './ai-prompt-input.component.html', styleUrls: ['./ai-prompt-input.component.scss'], @@ -63,24 +68,74 @@ const FLY_DURATION = 520; }) export class AiPromptInputComponent implements OnChanges, AfterViewInit, OnDestroy { + readonly fileName = aiFileName; + private aiResourceService = inject(AiResourceService); private translate = inject(TranslateService); private sanitizer = inject(DomSanitizer); private renderer = inject(Renderer2); + private dialog = inject(MatDialog); private host = inject>(ElementRef); @Input() placeholder = ''; + @Input() suggestion: string | null = null; + + ghostTight = signal(false); + + @Input() quote: AiLinesQuote | null = null; + + @Output() quoteRemoved = new EventEmitter(); + @Input() loading: boolean; @Input() docked = false; + @Input() slim = false; + + @Input() pinned = false; + @Input() dropZone: HTMLElement; + @Input() showAutoApprove = false; + + @Input() autoApprove = false; + + @Input() autoApproveInChat = true; + @Output() messageSent = new EventEmitter(); + @Output() autoApproveChange = new EventEmitter(); + + @Input() stoppable = false; + + @Input() stopping = false; + + @Input() sendWhileWorking = false; + + @Input() blocked = false; + + @Output() stopped = new EventEmitter(); + + get working(): boolean { + return this.loading && this.stoppable; + } + + get canStop(): boolean { + return this.working && !(this.sendWhileWorking && this.hasContent()); + } + + stop(): void { + if (this.working && !this.stopping) { + this.stopped.emit(); + } + } + @ViewChild('textarea') textarea!: ElementRef; + private slash = inject(AiSlashService); + private removeSlash: () => void; + @ViewChild('fileInput') fileInput!: ElementRef; message = new FormControl(''); @@ -113,16 +168,31 @@ export class AiPromptInputComponent implements OnChanges, AfterViewInit, OnDestr get canSend(): boolean { const ready = this.attachments().some(attachment => attachment.status === 'ready'); - return !this.loading && !this.uploading() && (!!this.message.value?.trim() || ready); + return !this.blocked && (!this.loading || this.sendWhileWorking) && !this.uploading() && (!!this.message.value?.trim() || ready || !!this.quote); + } + + private hasContent(): boolean { + return this.hasText() || this.attachments().some(attachment => attachment.status === 'ready'); } ngOnChanges(changes: SimpleChanges): void { if (changes.dropZone) { this.listenForDrops(this.dropZone ?? this.host.nativeElement); } + if (changes.suggestion) { + setTimeout(() => this.fitGhost()); + } } ngAfterViewInit(): void { + this.removeSlash = this.slash.addComposer({ + field: () => this.textarea?.nativeElement, + focusEnd: () => { + const field = this.textarea?.nativeElement; + field.focus(); + field.selectionStart = field.selectionEnd = field.value.length; + } + }); if (!this.dropTarget) { this.listenForDrops(this.host.nativeElement); } @@ -130,32 +200,38 @@ export class AiPromptInputComponent implements OnChanges, AfterViewInit, OnDestr } ngOnDestroy(): void { + this.removeSlash?.(); this.destroyed = true; clearTimeout(this.flyTimer); this.stopListening(); this.clearAttachments(true); } - @HostListener('document:keydown', ['$event']) - onDocumentKeydown(event: KeyboardEvent): void { - if (event.key !== '/' || event.metaKey || event.ctrlKey || event.altKey) { + openShortcuts(event: MouseEvent): void { + const from = event.currentTarget as HTMLElement; + if (this.dialog.openDialogs.some(open => open.componentInstance instanceof AiShortcutsDialogComponent)) { return; } - const target = event.target as HTMLElement; - if (target?.closest?.('input, textarea, select, [contenteditable]')) { + this.dialog.open(AiShortcutsDialogComponent, {panelClass: ['tb-dialog', 'tb-ai-keys-dialog'], autoFocus: 'dialog', restoreFocus: true}) + .afterClosed().subscribe(() => from?.focus({preventScroll: true})); + } + + onKeydown(event: KeyboardEvent): void { + if (event.key === 'Tab' && !event.shiftKey && this.suggestion && !this.message.value) { + event.preventDefault(); + this.setValue(this.suggestion); return; } - const visible = Array.from(document.querySelectorAll('.tb-ai-composer textarea')) - .filter(textarea => textarea.offsetParent); - const field = this.textarea?.nativeElement; - if (field && visible[visible.length - 1] === field) { + if (event.key === 'Escape' && this.working) { event.preventDefault(); - field.focus(); - field.selectionStart = field.selectionEnd = field.value.length; + this.stop(); + return; + } + if (event.key === 'Escape' && this.slim) { + event.preventDefault(); + this.textarea?.nativeElement.blur(); + return; } - } - - onKeydown(event: KeyboardEvent): void { if (event.key === 'Enter' && (!event.shiftKey || event.metaKey || event.ctrlKey)) { event.preventDefault(); this.send(); @@ -170,13 +246,17 @@ export class AiPromptInputComponent implements OnChanges, AfterViewInit, OnDestr send(): void { const msg = this.message.value?.trim() ?? ''; const ready = this.attachments().filter(attachment => attachment.status === 'ready'); - if (this.loading || this.uploading() || (!msg && !ready.length)) { + if ((this.loading && !this.sendWhileWorking) || this.uploading() || (!msg && !ready.length && !this.quote)) { return; } this.fly(); this.clearText(); this.clearAttachments(false); - this.messageSent.emit({message: msg, resources: ready.map(attachment => attachment.resource)}); + const sent: AiPromptMessage = {message: msg, resources: ready.map(attachment => attachment.resource)}; + if (this.quote) { + sent.quote = this.quote; + } + this.messageSent.emit(sent); } reset(): void { @@ -184,19 +264,47 @@ export class AiPromptInputComponent implements OnChanges, AfterViewInit, OnDestr this.clearAttachments(true); } + restoreAttachments(resources: AiResourceInfo[]): void { + const kept = untracked(() => this.attachments()); + const missing = (resources ?? []).filter(resource => !kept.some(attachment => attachment.resource?.id === resource.id)); + for (const resource of missing) { + const kind = aiAttachmentKind(resource.mediaType, resource.name); + const key = guid(); + this.attachments.update(list => [...list, { + key, name: resource.name, size: resource.size, icon: kind.icon, kind: kind.label, status: 'ready', progress: 100, resource + }]); + if (resource.mediaType?.startsWith('image/')) { + this.aiResourceService.getUrl(resource.id).pipe(take(1)).subscribe({ + next: previewUrl => this.patch(key, {previewUrl}), + error: () => {} + }); + } + } + } + focus(): void { this.textarea?.nativeElement.focus(); } - setValue(value: string): void { + setValue(value: string, showStart = false): void { this.message.setValue(value); this.hasText.set(!!value); setTimeout(() => { - this.textarea?.nativeElement.focus(); + const field = this.textarea?.nativeElement; + field?.focus({preventScroll: showStart}); + field?.setSelectionRange(field.value.length, field.value.length); this.resize(); + if (field && showStart) { + field.scrollTop = 0; + } }); } + toggleAutoApprove(event: Event): void { + this.autoApprove = (event.target as HTMLInputElement).checked; + this.autoApproveChange.emit(this.autoApprove); + } + openFilePicker(): void { this.fileInput?.nativeElement.click(); } @@ -228,7 +336,8 @@ export class AiPromptInputComponent implements OnChanges, AfterViewInit, OnDestr if (attachment.status === 'uploading') { return this.translate.instant('ai-assistant.attachment-uploading', {progress: attachment.progress}); } - return `${this.translate.instant(attachment.kind)} · ${formatAiFileSize(attachment.size)}`; + const fact = aiResourceFact(attachment.resource?.facts, this.translate); + return `${this.translate.instant(attachment.kind)} · ${fact ?? formatAiFileSize(attachment.size)}`; } addFiles(files: File[]): void { @@ -338,9 +447,40 @@ export class AiPromptInputComponent implements OnChanges, AfterViewInit, OnDestr if (!field) { return; } - const cap = this.docked ? Math.min(160, Math.round(innerHeight * 0.3)) : Math.min(220, Math.round(innerHeight * 0.4)); + const cap = this.docked ? Math.min(160, Math.round(innerHeight * 0.3)) : Math.min(this.pinned ? 240 : 220, Math.round(innerHeight * 0.4)); field.style.height = 'auto'; field.style.height = Math.min(field.scrollHeight, cap) + 'px'; + this.fitGhost(); + } + + ghostHead(): string { + const text = this.suggestion ?? ''; + const space = text.lastIndexOf(' '); + return space < 0 ? '' : text.slice(0, space + 1); + } + + ghostLast(): string { + const text = this.suggestion ?? ''; + return text.slice(text.lastIndexOf(' ') + 1); + } + + private fitGhost(): void { + const ghost = this.host.nativeElement.querySelector('.composer-ghost'); + const words = ghost?.firstElementChild as HTMLElement | null; + const key = ghost?.querySelector('kbd'); + if (!ghost || !words || !key) { + this.ghostTight.set(false); + return; + } + ghost.classList.remove('tight'); + const wrap = ghost.style.whiteSpace; + ghost.style.whiteSpace = 'nowrap'; + const keyWidth = key.getBoundingClientRect().width + parseFloat(getComputedStyle(key).marginLeft || '0'); + const wordsWidth = words.getBoundingClientRect().width - (words.contains(key) ? keyWidth : 0); + ghost.style.whiteSpace = wrap; + const tight = wordsWidth <= ghost.clientWidth && wordsWidth + keyWidth > ghost.clientWidth; + ghost.classList.toggle('tight', tight); + this.ghostTight.set(tight); } private clearText(): void { diff --git a/ui-ngx/src/app/modules/home/components/ai/ai-question.component.html b/ui-ngx/src/app/modules/home/components/ai/ai-question.component.html new file mode 100644 index 0000000000..3fe0631674 --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/ai/ai-question.component.html @@ -0,0 +1,187 @@ + +@if (answered(); as answers) { +
+
+ {{ 'ai-assistant.question.you-said' | translate }} +
+ @if (time()) { + + } + @for (item of answers; track item.question.id) { +
+ {{ item.question.question }} + +
+ } +
+} @else if (sheet()) { +
+
+ {{ 'ai-assistant.question.needs-answer' | translate }} +
+ @for (step of questions(); track step.id; let index = $index) { +
+ +
+ } +
+ + + +
+
+} @else if (current(); as question) { +
+
+ {{ 'ai-assistant.question.needs-answer' | translate }} + @if (questions().length > 1) { + {{ 'ai-assistant.question.count' | translate: {at: at() + 1, of: questions().length} }} + } +
+ @for (step of [question]; track step.id) { +
+ +
+ } +
+ @if (at() > 0) { + + } + + + +
+
+} + + +
+ @if (numbered) { + + } + @if (step.parts) {@for (part of step.parts; track $index) {@if (part.severity) {{{ ('alarm.severity-' + part.severity.toLowerCase()) | translate }}} @else {{{ part.text }}}}} @else {{{ step.question }}} + @if (step.why) { + {{ step.why }} + } +
+
+ @switch (kind(step)) { + @case ('color') { + + } + @case ('secret') { + + } + @case ('number') { + + } + @case ('text') { +
+
+ + {{ otherLabel(step) }} + + +
+
+ } + @case ('multi') { +
+ @for (option of step.options; track option.label) { + + } + +
+ } + @case ('date') { +
+ @for (option of step.options; track option.label) { + + } + +
+ } + @case ('chips') { +
+ @for (option of step.options; track option.label) { + + } + +
+ @if (isOther(step) && step.number) { + + } @else if (isOther(step)) { + + } @else if (chosenHint(step); as hint) { +

{{ hint }}

+ } + } + @default { +
+ @for (option of step.options; track option.label) { + + } + +
+ } + } +
+
diff --git a/ui-ngx/src/app/modules/home/components/ai/ai-question.component.ts b/ui-ngx/src/app/modules/home/components/ai/ai-question.component.ts new file mode 100644 index 0000000000..bc13df9505 --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/ai/ai-question.component.ts @@ -0,0 +1,337 @@ +// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: BUSL-1.1 +import { ChangeDetectionStrategy, Component, computed, EventEmitter, inject, input, Output, Renderer2, signal, ViewContainerRef } from '@angular/core'; +import { TranslateService } from '@ngx-translate/core'; +import { AiQuestion, AiQuestionAnswer, AiQuestionKind } from '@shared/models/solution-creator.models'; +import { TbPopoverService } from '@shared/components/popover.service'; +import { + aiColorOf, + aiIsFree, + aiIsNumber, + aiKindOf, + aiLocale, + aiNumberReady, + aiSayNumber +} from '@home/components/ai/ai-question.models'; +import { aiColorAnswer, aiColorReady } from '@home/components/ai/ai-color-field.component'; +import { AiDatePanelComponent, AiPickedDay } from '@home/components/ai/ai-date-panel.component'; + +const MULTI_SEPARATOR = ', '; + +export function aiAnswersText(answers: AiQuestionAnswer[]): string { + return answers.map(item => item.question.question.trim() + ' ' + item.answer.trim()).join('\n'); +} + +export function aiAnswersPrompt(answers: AiQuestionAnswer[]): {message: string; secrets?: Record} { + const secrets: Record = {}; + const lines = answers.map((item, index) => { + if (!item.secret || !item.answer) { + return item.question.question.trim() + ' ' + item.answer.trim(); + } + const name = (item.question.id || '').replace(/[^A-Za-z0-9_.-]/g, '_').slice(0, 64) || 'answer_' + (index + 1); + secrets[name] = item.answer; + return item.question.question.trim() + ' {{secret:' + name + '}}'; + }); + return Object.keys(secrets).length ? {message: lines.join('\n'), secrets} : {message: lines.join('\n')}; +} + +export function aiAnswersOf(content: string | undefined, questions: AiQuestion[] | undefined): AiQuestionAnswer[] | null { + if (!content || !questions?.length) { + return null; + } + const lines = content.split('\n').map(line => line.trim()).filter(Boolean); + const answers: AiQuestionAnswer[] = []; + for (const line of lines) { + const found = questions.map(question => ({question, asked: askedPrefix(question).exec(line)})).find(item => !!item.asked); + if (!found) { + return null; + } + answers.push({question: found.question, answer: line.slice(found.asked[0].length).trim()}); + } + return answers.length ? answers : null; +} + +function askedPrefix(question: AiQuestion): RegExp { + const escape = (text: string) => text.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); + const asked = question.parts?.length + ? question.parts.map(part => part.severity ? '.+?' : escape(part.text ?? '')).join('') + : escape(question.question.trim()); + return new RegExp('^' + asked.trim() + ' '); +} + +function recommendedOf(question: AiQuestion): string[] { + const recommended = Array.isArray(question.recommended) ? question.recommended : question.recommended ? [question.recommended] : []; + return recommended.filter(label => question.options.some(option => option.label === label)); +} + +@Component({ + selector: 'tb-ai-question', + templateUrl: './ai-question.component.html', + changeDetection: ChangeDetectionStrategy.OnPush, + standalone: false +}) +export class AiQuestionComponent { + + questions = input.required(); + answered = input(null); + time = input(undefined); + + @Output() done = new EventEmitter(); + @Output() skip = new EventEmitter(); + + private translate = inject(TranslateService); + private popoverService = inject(TbPopoverService); + private renderer = inject(Renderer2); + private viewContainerRef = inject(ViewContainerRef); + + colorOf = aiColorOf; + isFree = aiIsFree; + + at = signal(0); + move = signal<'next' | 'back' | null>(null); + dayOpen = signal(null); + private picked = signal>({}); + private days: Record = {}; + private chosen = signal>({}); + private typed = signal>({}); + + current = computed(() => this.questions()[Math.min(this.at(), this.questions().length - 1)]); + last = computed(() => this.at() >= this.questions().length - 1); + + valueOf(question: AiQuestion): string { + const picked = this.picked()[question.id]; + if (picked !== undefined) { + return picked; + } + return this.isFree(question) || question.date ? '' : this.defaultOf(question); + } + + kind(question: AiQuestion): AiQuestionKind { + return aiKindOf(question); + } + + isChosen(question: AiQuestion, label: string): boolean { + return (this.chosen()[question.id] ?? recommendedOf(question)).includes(label); + } + + toggle(question: AiQuestion, label: string): void { + const current = this.chosen()[question.id] ?? recommendedOf(question); + this.chosen.update(values => ({...values, [question.id]: current.includes(label) ? current.filter(item => item !== label) : [...current, label]})); + } + + isOther(question: AiQuestion): boolean { + if (this.isFree(question)) { + return true; + } + if (question.multiple) { + return !!this.otherText(question).trim(); + } + return this.picked()[question.id] === null; + } + + otherText(question: AiQuestion): string { + const typed = this.typed()[question.id]; + if (typed !== undefined) { + return typed; + } + const suggested = aiIsNumber(question) ? question.number?.suggested : undefined; + return suggested !== undefined && suggested !== null ? aiSayNumber(suggested, this.locale()) : ''; + } + + otherLabel(question: AiQuestion): string { + return question.other?.label || this.translate.instant(this.isFree(question) ? 'ai-assistant.question.your-answer' + : question.date ? 'ai-assistant.question.another-day' : 'ai-assistant.question.other'); + } + + colorValue(question: AiQuestion): string { + const picked = this.picked()[question.id]; + return picked === null || aiIsFree(question) ? this.typed()[question.id] ?? '' : picked ?? this.defaultOf(question); + } + + setColor(question: AiQuestion, value: string): void { + if (question.options.some(option => option.label === value)) { + this.pick(question, value); + } else { + this.picked.update(values => ({...values, [question.id]: null})); + this.typed.update(values => ({...values, [question.id]: value})); + } + } + + setTyped(question: AiQuestion, value: string): void { + this.pickOther(question); + this.typed.update(values => ({...values, [question.id]: value})); + } + + openDay(question: AiQuestion, chip: HTMLElement): void { + if (this.popoverService.hasPopover(chip)) { + this.popoverService.hidePopover(chip); + return; + } + const today = new Date(); + const chosen = this.days[question.id]; + const popover = this.popoverService.displayPopover({ + trigger: chip, + renderer: this.renderer, + hostView: this.viewContainerRef, + componentType: AiDatePanelComponent, + preferredPlacement: ['bottomLeft', 'bottom', 'topLeft', 'top'], + context: { + selected: chosen?.date ?? new Date(today.getFullYear(), today.getMonth(), today.getDate() + 1), + time: chosen?.time ?? '9:00' + }, + showCloseButton: false, + popoverContentStyle: {padding: '8px 12px 12px'}, + isModal: true + }); + this.dayOpen.set(question.id); + popover.tbHideStart.subscribe(() => { + this.dayOpen.set(null); + if (popover.tbComponentRef?.instance.hasFocus() || document.activeElement === document.body) { + chip.focus(); + } + }); + popover.tbComponentRef.instance.popover = popover; + popover.tbComponentRef.instance.applied.subscribe((day: AiPickedDay) => { + this.days[question.id] = day; + this.picked.update(values => ({...values, [question.id]: null})); + this.typed.update(values => ({...values, [question.id]: + `${day.date.toLocaleDateString(this.locale(), {weekday: 'long', day: 'numeric', month: 'short'})}, ${day.time}`})); + popover.hide(); + }); + } + + private locale(): string { + return aiLocale(this.translate.currentLang); + } + + ready(question: AiQuestion): boolean { + if (question.multiple && !this.isFree(question)) { + return true; + } + if (aiKindOf(question) === 'color') { + return aiColorReady(question, this.colorValue(question)); + } + if (this.isOther(question) && aiIsNumber(question)) { + return aiNumberReady(this.otherText(question), this.locale()); + } + return this.isOther(question) ? !!this.otherText(question).trim() : !!this.valueOf(question); + } + + sheet = computed(() => this.questions().length > 1 && this.questions().every(question => + !question.multiple && !aiIsFree(question) && (aiKindOf(question) === 'chips' || aiKindOf(question) === 'color' || question.options.length <= 3))); + + allReady = computed(() => this.questions().every(question => this.ready(question))); + + finish(): void { + if (this.questions().every(question => this.ready(question))) { + this.done.emit(this.answers()); + } + } + + chosenHint(question: AiQuestion): string | undefined { + const value = this.valueOf(question); + return question.options.find(option => option.label === value)?.hint; + } + + pick(question: AiQuestion, label: string): void { + this.picked.update(values => ({...values, [question.id]: label})); + } + + pickOther(question: AiQuestion): void { + if (question.multiple || this.isFree(question)) { + return; + } + if (!this.isOther(question)) { + this.picked.update(values => ({...values, [question.id]: null})); + } + } + + type(question: AiQuestion, area: HTMLTextAreaElement | HTMLInputElement): void { + this.pickOther(question); + this.typed.update(values => ({...values, [question.id]: area.value})); + if (area instanceof HTMLTextAreaElement) { + area.style.height = 'auto'; + area.style.height = area.scrollHeight + 'px'; + } + } + + shown(item: {question: AiQuestion; answer: string}): string { + return item.question.secret && item.answer && item.answer !== this.translate.instant('ai-assistant.question.no-answer') ? '••••••••' : item.answer; + } + + next(): void { + const question = this.current(); + if (!question || !this.ready(question)) { + return; + } + if (this.last()) { + this.done.emit(this.answers()); + } else { + this.move.set('next'); + this.at.update(index => index + 1); + } + } + + back(): void { + this.move.set('back'); + this.at.update(index => Math.max(0, index - 1)); + } + + skipAll(): void { + this.skip.emit(this.questions().map(question => this.given(question) + ? {question, answer: this.answerOf(question), secret: !!question.secret && !question.options?.length} + : {question, answer: this.defaultOf(question)})); + } + + onEnter(event: Event): void { + const keyboard = event as KeyboardEvent; + if (!keyboard.shiftKey && !keyboard.isComposing) { + event.preventDefault(); + if (this.sheet()) { + this.finish(); + } else { + this.next(); + } + } + } + + private given(question: AiQuestion): boolean { + return question.multiple && !this.isFree(question) + ? this.answerOf(question) !== this.translate.instant('ai-assistant.question.none') + : this.ready(question); + } + + private answers(): AiQuestionAnswer[] { + return this.questions().map(question => ({question, answer: this.answerOf(question), secret: !!question.secret && !question.options?.length})); + } + + private answerOf(question: AiQuestion): string { + if (question.multiple && !this.isFree(question)) { + const values = [...question.options.map(option => option.label).filter(label => this.isChosen(question, label))]; + const typed = this.otherText(question).trim(); + if (typed) { + values.push(typed); + } + return values.length ? values.join(MULTI_SEPARATOR) : this.translate.instant('ai-assistant.question.none'); + } + if (aiKindOf(question) === 'color') { + return aiColorAnswer(question, this.colorValue(question)); + } + if (this.isOther(question) && aiIsNumber(question)) { + const value = this.otherText(question).trim(); + return value && question.number?.unit ? `${value} ${question.number.unit}` : value; + } + return this.isOther(question) ? this.otherText(question).trim() : this.valueOf(question); + } + + private defaultOf(question: AiQuestion): string { + if (this.isFree(question)) { + return this.translate.instant('ai-assistant.question.no-answer'); + } + if (question.multiple) { + const recommended = recommendedOf(question); + return recommended.length ? recommended.join(MULTI_SEPARATOR) : this.translate.instant('ai-assistant.question.none'); + } + return recommendedOf(question)[0] ?? question.options?.[0]?.label ?? ''; + } +} diff --git a/ui-ngx/src/app/modules/home/components/ai/ai-question.models.ts b/ui-ngx/src/app/modules/home/components/ai/ai-question.models.ts new file mode 100644 index 0000000000..ae0493c09d --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/ai/ai-question.models.ts @@ -0,0 +1,102 @@ +// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: BUSL-1.1 +import { AiQuestion, AiQuestionKind } from '@shared/models/solution-creator.models'; +import { MINUS } from '@home/components/ai/ai-text'; + +export { aiLocale } from '@home/components/ai/ai-text'; + +const HEX_COLOR = /#[0-9a-f]{6}(?![0-9a-z])|#[0-9a-f]{3}(?![0-9a-z])/i; + + +export function aiColorOf(text: string | undefined): string | null { + return text?.match(HEX_COLOR)?.[0] ?? null; +} + +export function aiIsFree(question: AiQuestion): boolean { + return !question.options?.length; +} + +export function aiIsColor(question: AiQuestion): boolean { + return !question.multiple && !question.secret + && (!!question.color || (!!question.options?.length && question.options.every(option => !!aiColorOf(option.label)))); +} + +export function aiIsNumber(question: AiQuestion): boolean { + return !!question.number && !question.multiple && !question.secret && !question.date && !aiIsColor(question); +} + +export function aiIsChipRow(question: AiQuestion): boolean { + return !question.multiple && question.options.length >= 2 && question.options.length <= (aiIsColor(question) ? 6 : 4) + && question.options.every(option => option.label.length <= 24); +} + +export function aiQuestionKind(question: AiQuestion): AiQuestionKind { + const free = aiIsFree(question); + if (aiIsColor(question)) { + return 'color'; + } + if (free) { + return question.secret ? 'secret' : aiIsNumber(question) ? 'number' : 'text'; + } + if (question.multiple) { + return 'multi'; + } + if (question.date) { + return 'date'; + } + return aiIsChipRow(question) ? 'chips' : 'cards'; +} + +export function aiKindOf(question: AiQuestion): AiQuestionKind { + return question.kind ?? aiQuestionKind(question); +} + +function commaDecimal(locale?: string): boolean { + return (1.5).toLocaleString(locale).charAt(1) === ','; +} + +export function aiSayNumber(value: number, locale?: string): string { + const text = String(value).replace('-', MINUS); + return commaDecimal(locale) ? text.replace('.', ',') : text; +} + +export function aiReadNumber(text: string, locale?: string): number { + let normalized = String(text ?? '').trim().replace(/[\s\u00a0\u202f']/g, '').replace(MINUS, '-'); + if (commaDecimal(locale)) { + const grouped = normalized.includes(',') || /^-?\d{1,3}(\.\d{3})+$/.test(normalized); + normalized = (grouped ? normalized.replace(/\./g, '') : normalized).replace(',', '.'); + } else { + const thousands = /^-?\d{1,3}(,\d{3})+(\.\d+)?$/.test(normalized); + normalized = normalized.includes(',') && !normalized.includes('.') && !thousands ? normalized.replace(',', '.') : normalized.replace(/,/g, ''); + } + return /^[-+]?(\d+\.?\d*|\.\d+)$/.test(normalized) ? parseFloat(normalized) : NaN; +} + +export function aiNumberReady(text: string, locale?: string): boolean { + return !isNaN(aiReadNumber(text, locale)); +} + +export function aiStepDecimals(step: number): number { + const text = String(step); + return text.includes('e-') ? +text.split('e-')[1] : (text.split('.')[1]?.length ?? 0); +} + +export function aiHexOf(text: string | undefined): string | null { + const digits = (text ?? '').trim().replace(/^#/, ''); + if (!/^([0-9a-f]{3}|[0-9a-f]{6})$/i.test(digits)) { + return null; + } + const full = digits.length === 3 ? digits.split('').map(digit => digit + digit).join('') : digits; + return '#' + full.toUpperCase(); +} + +export function aiReadTime(text: string): string | null { + const match = String(text).trim().match(/^(\d{1,2})(?:[:.h]?(\d{2}))?$/); + if (!match) { + return null; + } + const hours = +match[1]; + const minutes = match[2] ? +match[2] : 0; + return hours < 24 && minutes < 60 ? `${hours}:${String(minutes).padStart(2, '0')}` : null; +} + diff --git a/ui-ngx/src/app/modules/home/components/ai/ai-record-card.component.ts b/ui-ngx/src/app/modules/home/components/ai/ai-record-card.component.ts new file mode 100644 index 0000000000..e79673afdf --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/ai/ai-record-card.component.ts @@ -0,0 +1,243 @@ +// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: BUSL-1.1 +import { ChangeDetectionStrategy, Component, computed, DestroyRef, effect, ElementRef, inject, input, output, signal, viewChild } from '@angular/core'; +import { DomSanitizer } from '@angular/platform-browser'; +import { takeUntilDestroyed } from '@angular/core/rxjs-interop'; +import { TranslateService } from '@ngx-translate/core'; +import { aiEntityKind, aiThingWord } from '@home/components/ai/ai-action.models'; +import { aiFactParts, AiRecordFact, AiRecordView } from '@home/components/ai/ai-record.models'; +import { AiCardAction } from '@home/components/ai/ai-card-actions.component'; +import { IotHubActionsService } from '@home/components/iot-hub/iot-hub-actions.service'; +import { EntityType } from '@shared/models/entity-type.models'; + +const TIGHT_WIDTH = 400; + +export type AiRecordPrimary = 'open' | 'install' | null; + +export function aiDashboardThumb(cards: number): string { + const n = Math.max(1, Math.min(cards, 6)); + const w = (112 - (n - 1) * 3) / n; + const tiles = Array.from({length: n}, (_, i) => `` + + `` + + ``).join(''); + const rows = [40, 48, 56, 64].map(y => `` + + ``).join(''); + return `` + + `${tiles}` + + `` + + `` + + `${rows}`; +} + +export function aiWidgetThumb(): string { + return `` + + `` + + `` + + `` + + `` + + ``; +} + +@Component({ + selector: 'tb-ai-record-card', + template: ` + @let rec = view(); +
+
+ @if (picture()) { + + } @else { + + } +
+ @if (rec.url) { + {{ rec.name }} + } @else { + {{ rec.name }} + } + @if (rec.badge) { + {{ rec.badge }} + } + + @if (rec.hub; as listing) { + + {{ listing.type }}@if (listing.creator) {{{ listing.type ? ' · ' : '' }}{{ listing.creator }}}@if (listing.verified) {}@if (listing.installs) { · {{ listing.installs }}} + } @else { + {{ meta() || rec.meta }} + } + +
+ + @if (rec.hub) { + + IoT Hub + + } @else if (rec.alarm; as current) { + + {{ (current.cleared ? 'ai-assistant.record.cleared' : 'alarm.severity-' + current.severity.toLowerCase()) | translate }} + @if (current.acknowledged) { + + } + + } @else if (rec.state; as current) { + {{ current.label }} + } + @switch (primaryAction()) { + @case ('install') { + + } + @case ('open') { + + + + } + @default { + @if (rec.url) { + + + + } + } + } + +
+ @if (hasFoot()) { +
+ @if (note()) { +

{{ note() }}

+ } + @if (shownFacts().length) { +
+ @for (fact of shownFacts(); track $index) { +
{{ fact.label }}
+
@for (part of parts(fact); track $index) {@if (part.code) {{{ part.text }}} @else {{{ part.text }}}}
+ } +
+ } + @if (actions().length) { + + } +
+ } +
+ `, + standalone: false, + changeDetection: ChangeDetectionStrategy.OnPush +}) +export class AiRecordCardComponent { + + view = input.required(); + + primary = input(null); + + meta = input(null); + + facts = input([]); + + note = input(undefined); + + actions = input([]); + + act = output(); + + compose = output(); + + tight = signal(false); + + installing = signal(false); + + kind = computed(() => aiEntityKind(this.view().entityType, this.view().alarmRule, this.view().groupType)); + + picture = computed(() => { + const view = this.view(); + return !!(view.image || view.imageUrl || view.entityType === EntityType.DASHBOARD || view.entityType === EntityType.WIDGET_TYPE); + }); + + primaryAction = computed(() => { + const primary = this.primary(); + if (primary === 'install') { + return this.view().hubItem ? 'install' : null; + } + return primary === 'open' && this.view().url ? 'open' : null; + }); + + shownFacts = computed(() => { + const view = this.view(); + const said = [view.badge, this.meta() || view.meta].filter(Boolean).map(text => text.toLowerCase()); + const sameWords = (value: string) => said.some(text => text === value || text.split(' · ').includes(value)); + return this.facts().filter(fact => !sameWords(fact.value.trim().toLowerCase())); + }); + + hasFoot = computed(() => !!this.note() || this.shownFacts().length > 0 || this.actions().length > 0); + + thumb = computed(() => this.sanitizer.bypassSecurityTrustHtml(this.view().entityType === EntityType.WIDGET_TYPE + ? aiWidgetThumb() : aiDashboardThumb(this.view().widgets ?? 4))); + + openLabel = computed(() => this.translate.instant('ai-assistant.record.open-type', {type: this.typeWord()})); + + openTip = computed(() => this.view().hub ? this.translate.instant('ai-assistant.record.open-on-iot-hub') + : this.translate.instant('ai-assistant.record.open-new-tab', {type: this.typeWord()})); + + private card = viewChild>('card'); + + private sanitizer = inject(DomSanitizer); + private translate = inject(TranslateService); + private iotHubActions = inject(IotHubActionsService); + private destroyRef = inject(DestroyRef); + + constructor() { + effect(onCleanup => { + const card = this.card()?.nativeElement; + if (!card || !this.picture() || typeof ResizeObserver === 'undefined') { + return; + } + const observer = new ResizeObserver(() => this.tight.set(card.clientWidth > 0 && card.clientWidth < TIGHT_WIDTH)); + observer.observe(card); + onCleanup(() => observer.disconnect()); + }); + } + + parts(fact: AiRecordFact) { + return aiFactParts(fact.value); + } + + install(): void { + const item = this.view().hubItem; + if (!item || this.installing()) { + return; + } + this.installing.set(true); + this.iotHubActions.installItem(item).pipe(takeUntilDestroyed(this.destroyRef)).subscribe({ + complete: () => this.installing.set(false), + error: () => this.installing.set(false) + }); + } + + private typeWord(): string { + const view = this.view(); + if (view.alarmRule) { + return this.translate.instant('ai-assistant.detail.thing.alarm-rule'); + } + if (view.entityType === 'SCADA_SYMBOL') { + return this.translate.instant('ai-assistant.review.type.SCADA_SYMBOL'); + } + return aiThingWord(this.translate, view.entityType, 'ai-assistant.record.entity'); + } +} diff --git a/ui-ngx/src/app/modules/home/components/ai/ai-record-loader.service.ts b/ui-ngx/src/app/modules/home/components/ai/ai-record-loader.service.ts new file mode 100644 index 0000000000..3fc7f6fda4 --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/ai/ai-record-loader.service.ts @@ -0,0 +1,330 @@ +// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: BUSL-1.1 +import { aiLocale } from '@home/components/ai/ai-text'; +import { TB_IMAGE_PREFIX } from '@shared/models/resource.models'; +import { ReportTemplateService } from '@core/http/report-template.service'; +import { widgetType, widgetTypesData } from '@shared/models/widget.models'; +import { ReportTemplateType } from '@shared/models/report.models'; +import { inject, Injectable } from '@angular/core'; +import { TranslateService } from '@ngx-translate/core'; +import { forkJoin, Observable, of } from 'rxjs'; +import { catchError, map, switchMap } from 'rxjs/operators'; +import { EntityId } from '@shared/models/id/entity-id'; +import { baseDetailsPageByEntityType, EntityType, entityTypeTranslations } from '@shared/models/entity-type.models'; +import { EntityService } from '@core/http/entity.service'; +import { CalculatedFieldsService } from '@core/http/calculated-fields.service'; +import { NotificationService } from '@core/http/notification.service'; +import { DeviceService } from '@core/http/device.service'; +import { DeviceProfileService } from '@core/http/device-profile.service'; +import { DashboardService } from '@core/http/dashboard.service'; +import { AlarmService } from '@core/http/alarm.service'; +import { AttributeService } from '@core/http/attribute.service'; +import { UserService } from '@core/http/user.service'; +import { IotHubApiService } from '@core/http/iot-hub-api.service'; +import { CalculatedFieldType } from '@shared/models/calculated-field.models'; +import { AttributeScope } from '@shared/models/telemetry/telemetry.models'; +import { AlarmInfo, AlarmSeverity, alarmSeverityTranslations } from '@shared/models/alarm.models'; +import { ItemType, itemTypeTranslations } from '@shared/models/iot-hub/iot-hub-item.models'; +import { MpItemVersionView } from '@shared/models/iot-hub/iot-hub-version.models'; +import { DeviceInfo } from '@shared/models/device.models'; +import { getEntityDetailsPageURL } from '@core/utils'; +import { aiDateText } from '@home/components/ai/ai-action-detail.models'; +import { defaultHttpOptionsFromConfig, RequestConfig } from '@core/http/http-utils'; +import { HttpClient } from '@angular/common/http'; +import { AiRecordRef, AiRecordState, AiRecordView } from '@home/components/ai/ai-record.models'; + +const CONFIG: RequestConfig = {ignoreLoading: true, ignoreErrors: true}; + +const NOTIFICATION_PAGES: Partial> = { + [EntityType.NOTIFICATION_RULE]: '/notification/rules', + [EntityType.NOTIFICATION_TEMPLATE]: '/notification/templates', + [EntityType.NOTIFICATION_TARGET]: '/notification/recipients' +}; + +const PROFILE_TYPES = new Set([EntityType.DEVICE_PROFILE, EntityType.ASSET_PROFILE]); + +const HUB_KINDS: Record = { + [ItemType.DEVICE]: EntityType.DEVICE, + [ItemType.WIDGET]: EntityType.WIDGET_TYPE, + [ItemType.CALCULATED_FIELD]: EntityType.CALCULATED_FIELD, + [ItemType.ALARM_RULE]: 'ALARM_RULE', + [ItemType.RULE_CHAIN]: EntityType.RULE_CHAIN, + [ItemType.SOLUTION_TEMPLATE]: 'SOLUTION_TEMPLATE' +}; + +export interface AiRecordLoadOptions { + image?: boolean; +} + +@Injectable({providedIn: 'root'}) +export class AiRecordLoaderService { + + private entityService = inject(EntityService); + private calculatedFieldsService = inject(CalculatedFieldsService); + private notificationService = inject(NotificationService); + private deviceService = inject(DeviceService); + private deviceProfileService = inject(DeviceProfileService); + private dashboardService = inject(DashboardService); + private alarmService = inject(AlarmService); + private attributeService = inject(AttributeService); + private userService = inject(UserService); + private iotHubApi = inject(IotHubApiService); + private translate = inject(TranslateService); + private http = inject(HttpClient); + private reportTemplateService = inject(ReportTemplateService); + + loadAll(refs: AiRecordRef[], options: AiRecordLoadOptions = {}): Observable { + if (!refs.length) { + return of([]); + } + return forkJoin(refs.map(ref => this.load(ref, options).pipe(catchError(() => of(null))))) + .pipe(map(views => views.filter(view => !!view))); + } + + load(ref: AiRecordRef, options: AiRecordLoadOptions = {}): Observable { + return 'versionId' in ref ? this.hub(ref.versionId) : this.entity({entityType: ref.entityType, id: ref.id} as EntityId, options); + } + + hub(versionId: string): Observable { + if (!this.iotHubApi.baseUrl) { + return of(null); + } + return this.iotHubApi.getVersionInfo(versionId, CONFIG).pipe(map(item => item ? this.hubView(item) : null)); + } + + hubView(item: MpItemVersionView): AiRecordView { + const typeKey = itemTypeTranslations.get(item.type); + const installs = item.totalInstallCount ?? item.installCount; + return { + key: `HUB:${item.id}`, + entityType: HUB_KINDS[item.type] ?? 'SOLUTION_TEMPLATE', + alarmRule: item.type === ItemType.ALARM_RULE, + name: item.name, + meta: '', + url: `/iot-hub/version/${item.id}`, + hub: { + type: typeKey ? this.translate.instant(typeKey) : item.type, + creator: item.creatorDisplayName || undefined, + verified: !!item.creatorVerified, + installs: installs ? this.translate.instant('ai-assistant.record.installs', {count: installs, shown: installs.toLocaleString(this.locale())}) : undefined + }, + hubItem: item, + description: item.description || undefined, + imageUrl: this.hubImage(item), + square: item.type === ItemType.DEVICE, + wide: item.type === ItemType.SOLUTION_TEMPLATE + }; + } + + entity(entity: EntityId, options: AiRecordLoadOptions = {}): Observable { + const entityType = entity.entityType as EntityType; + const key = `${entityType}:${entity.id}`; + const url = getEntityDetailsPageURL(entity.id, entityType) || undefined; + switch (entityType) { + case EntityType.DEVICE: + return this.deviceService.getDeviceInfo(entity.id, CONFIG).pipe(switchMap(device => this.device(key, url, device, options))); + case EntityType.DASHBOARD: + return this.dashboardService.getDashboard(entity.id, CONFIG).pipe(map(dashboard => { + const widgets = Object.keys(dashboard.configuration?.widgets ?? {}).length; + return { + key, entityType, alarmRule: false, name: dashboard.title, url, widgets, image: dashboard.image || undefined, + meta: this.meta(this.typeLabel(entityType), widgets ? this.translate.instant('ai-assistant.record.widgets', {count: widgets}) : null) + }; + })); + case EntityType.CALCULATED_FIELD: + return this.calculatedFieldsService.getCalculatedFieldById(entity.id, CONFIG).pipe(switchMap(field => { + const alarmRule = field.type === CalculatedFieldType.ALARM; + const type = this.translate.instant(alarmRule ? 'ai-assistant.review.type.ALARM_RULE' : 'entity.type-calculated-field'); + const view = (target?: string): AiRecordView => ({ + key, entityType, alarmRule, name: field.name, meta: this.meta(type, target), + url: alarmRule ? `/alarms/alarm-rules/${entity.id}` : `/calculatedFields/${entity.id}` + }); + const owner = field.entityId; + if (!owner?.id) { + return of(view()); + } + return this.entityService.getEntity(owner.entityType as EntityType, owner.id, CONFIG).pipe( + map(found => view(found?.name ? this.onTarget(owner.entityType, found.name) : undefined)), + catchError(() => of(view())) + ); + })); + case EntityType.ALARM: + return this.alarmService.getAlarmInfo(entity.id, CONFIG).pipe(map(alarm => this.alarm(key, alarm))); + case EntityType.USER: + return this.userService.getUser(entity.id, CONFIG).pipe(map(user => { + const name = [user.firstName, user.lastName].filter(Boolean).join(' ') || user.email; + const invited = user.additionalInfo?.userActivated === false; + return { + key, entityType, alarmRule: false, name, url, + meta: this.meta(this.typeLabel(entityType), name !== user.email ? user.email : null), + state: invited ? {tone: 'wait', label: this.translate.instant('ai-assistant.record.invited')} : undefined + }; + })); + case EntityType.ENTITY_GROUP: + return this.entityService.getEntity(entityType, entity.id, CONFIG).pipe(map(found => { + const group = found as {name?: string; type?: EntityType}; + if (!group?.name) { + return null; + } + const base = group.type ? baseDetailsPageByEntityType.get(group.type) : undefined; + const typeKey = group.type ? entityTypeTranslations.get(group.type)?.type : undefined; + return { + key, entityType, alarmRule: false, name: group.name, groupType: group.type, + url: base ? `${base.replace(/\/all$/, '/groups')}/${entity.id}` : undefined, + meta: typeKey ? this.translate.instant('ai-assistant.record.group-of', {type: this.translate.instant(typeKey)}) + : this.typeLabel(entityType) + }; + })); + case EntityType.NOTIFICATION_RULE: + return this.notificationService.getNotificationRuleById(entity.id, CONFIG) + .pipe(map(rule => this.simple(key, entityType, rule.name, NOTIFICATION_PAGES[entityType]))); + case EntityType.NOTIFICATION_TEMPLATE: + return this.notificationService.getNotificationTemplateById(entity.id, CONFIG) + .pipe(map(template => this.simple(key, entityType, template.name, NOTIFICATION_PAGES[entityType]))); + case EntityType.REPORT_TEMPLATE: + return this.reportTemplateService.getReportTemplateInfo(entity.id, CONFIG).pipe(map(template => ({ + key, entityType, alarmRule: false, name: template.name, url: `/reporting/templates/${entity.id}`, + badge: template.format, + meta: this.translate.instant(template.type === ReportTemplateType.SUB_REPORT ? 'ai-assistant.record.sub-report' : 'ai-assistant.record.report') + }))); + case EntityType.WIDGET_TYPE: + return this.http.get<{name: string; widgetType?: string; image?: string; description?: string}>(`/api/widgetTypeInfo/${entity.id}`, + defaultHttpOptionsFromConfig(CONFIG)) + .pipe(map(info => ({ + key, entityType, alarmRule: false, name: info.name, url: `/resources/widgets-library/widget-types/${entity.id}`, + image: info.image || undefined, description: info.description || undefined, + meta: info.widgetType && widgetTypesData.get(info.widgetType as widgetType) + ? this.translate.instant(widgetTypesData.get(info.widgetType as widgetType).name) : undefined + }))); + case EntityType.TB_RESOURCE: + return this.http.get<{title: string; resourceType?: string; resourceSubType?: string; link?: string}>(`/api/resource/info/${entity.id}`, + defaultHttpOptionsFromConfig(CONFIG)) + .pipe(map(info => { + if (info.resourceType !== 'IMAGE' || !info.link) { + return this.simple(key, entityType, info.title, undefined); + } + const symbol = info.resourceSubType === 'SCADA_SYMBOL'; + const path = info.link.replace(/^\/api\/images\//, ''); + return { + key, entityType: symbol ? 'SCADA_SYMBOL' : entityType, alarmRule: false, name: info.title, + url: symbol ? `/resources/scada-symbols/${path}` : '/resources/images', + image: TB_IMAGE_PREFIX + info.link, + meta: this.translate.instant(symbol ? 'ai-assistant.review.type.SCADA_SYMBOL' : 'ai-assistant.review.type.IMAGE') + }; + })); + case EntityType.WIDGETS_BUNDLE: + return this.http.get<{title: string}>(`/api/widgetsBundle/${entity.id}`, defaultHttpOptionsFromConfig(CONFIG)) + .pipe(map(bundle => ({ + key, entityType, alarmRule: false, name: bundle.title, url: `/resources/widgets-library/widgets-bundles/${entity.id}`, meta: undefined + }))); + case EntityType.REPORT: + return this.http.get<{name: string; format?: string; templateInfo?: {name?: string}}>(`/api/v2/report/${entity.id}`, defaultHttpOptionsFromConfig(CONFIG)) + .pipe(map(report => ({ + key, entityType, alarmRule: false, name: report.name, url: '/reporting/reports', badge: report.format, + meta: report.templateInfo?.name + }))); + case EntityType.SCHEDULER_EVENT: + return this.http.get<{name: string; type?: string}>(`/api/schedulerEvent/${entity.id}`, defaultHttpOptionsFromConfig(CONFIG)) + .pipe(map(event => { + const report = event.type === 'generateReport' || event.type === 'generateDashboardReport'; + return { + key, entityType, alarmRule: false, name: event.name, url: report ? '/reporting/scheduling' : url, + meta: report ? this.translate.instant('ai-assistant.record.scheduled-report') : undefined + }; + })); + default: + return this.entityService.getEntity(entityType, entity.id, CONFIG).pipe(map(found => { + const view = this.simple(key, entityType, found?.name ?? (found as {title?: string})?.title, NOTIFICATION_PAGES[entityType] ?? url); + const subtype = (found as {type?: string})?.type; + if (view && subtype && (entityType === EntityType.ASSET || entityType === EntityType.ENTITY_VIEW)) { + view.meta = this.meta(view.meta, subtype); + } + return view; + })); + } + } + + private device(key: string, url: string, device: DeviceInfo, options: AiRecordLoadOptions): Observable { + const gateway = !!device.additionalInfo?.gateway; + const view: AiRecordView = { + key, entityType: gateway ? 'GATEWAY' : EntityType.DEVICE, alarmRule: false, name: device.name, url, + meta: this.meta(this.translate.instant(gateway ? 'ai-assistant.record.gateway' : 'entity.type-device'), device.type), + square: true + }; + const activity = device.active ? of(true) : this.attributeService.getEntityAttributes(device.id, AttributeScope.SERVER_SCOPE, ['lastActivityTime'], CONFIG) + .pipe( + map(attributes => Number(attributes?.find(attribute => attribute.key === 'lastActivityTime')?.value) > 0), + switchMap(seen => seen ? of(true) : this.http.get(`/api/plugins/telemetry/DEVICE/${device.id.id}/keys/timeseries`, + defaultHttpOptionsFromConfig(CONFIG)).pipe(map(keys => !!keys?.length))), + catchError(() => of(true)) + ); + const image = options.image && device.deviceProfileId?.id + ? this.deviceProfileService.getDeviceProfileInfo(device.deviceProfileId.id, CONFIG).pipe(map(profile => profile?.image || undefined), catchError(() => of(undefined))) + : of(undefined); + return forkJoin([activity, image]).pipe(map(([seen, picture]) => ({ + ...view, + image: picture, + state: this.deviceState(device.active, seen, gateway) + }))); + } + + private deviceState(active: boolean, seen: boolean, gateway: boolean): AiRecordState { + if (active) { + return {tone: 'ok', label: this.translate.instant('ai-assistant.record.active')}; + } + if (!seen) { + return {tone: 'wait', label: this.translate.instant(gateway ? 'ai-assistant.record.waiting-connect' : 'ai-assistant.record.waiting-data')}; + } + return {tone: 'off', label: this.translate.instant('ai-assistant.record.inactive')}; + } + + private alarm(key: string, alarm: AlarmInfo): AiRecordView { + const severity = alarm.severity ?? AlarmSeverity.INDETERMINATE; + const word = this.translate.instant(alarmSeverityTranslations.get(severity) ?? severity); + const tip = [word, this.translate.instant(alarm.cleared ? 'ai-assistant.record.cleared' : 'ai-assistant.record.alarm-active').toLowerCase(), + this.translate.instant(alarm.acknowledged ? 'ai-assistant.record.acknowledged' : 'ai-assistant.record.not-acknowledged').toLowerCase()].join(', '); + const when = alarm.cleared && alarm.clearTs + ? this.translate.instant('ai-assistant.record.cleared-at', {time: this.time(alarm.clearTs)}) + : alarm.startTs ? this.translate.instant('ai-assistant.record.since', {time: this.time(alarm.startTs)}) : null; + return { + key, entityType: EntityType.ALARM, alarmRule: false, name: alarm.type, + meta: this.meta(alarm.originatorName, when), + url: '/alarms', + alarm: {severity, cleared: !!alarm.cleared, acknowledged: !!alarm.acknowledged, tip} + }; + } + + private hubImage(item: MpItemVersionView): string | undefined { + if (!item.image) { + return undefined; + } + const [path, query] = item.image.split('?'); + const preview = path.endsWith('/preview') ? path : `${path}/preview`; + return this.iotHubApi.resolveResourceUrl(query ? `${preview}?${query}` : preview); + } + + private simple(key: string, entityType: EntityType, name: string, url?: string): AiRecordView | null { + return name ? {key, entityType, alarmRule: false, name, meta: this.typeLabel(entityType), url} : null; + } + + private onTarget(entityType: string, name: string): string { + return this.translate.instant(PROFILE_TYPES.has(entityType) ? 'ai-assistant.record.on-profile' : 'ai-assistant.record.on', {name}); + } + + private meta(...parts: Array): string { + return parts.filter(part => !!part).join(' · '); + } + + private typeLabel(entityType: EntityType): string { + const translation = entityTypeTranslations.get(entityType)?.type; + return translation ? this.translate.instant(translation) : entityType; + } + + private locale(): string | undefined { + return aiLocale(this.translate.currentLang); + } + + private time(ts: number): string { + return aiDateText(new Date(ts), this.locale()); + } +} diff --git a/ui-ngx/src/app/modules/home/components/ai/ai-record.component.ts b/ui-ngx/src/app/modules/home/components/ai/ai-record.component.ts new file mode 100644 index 0000000000..48c327ed29 --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/ai/ai-record.component.ts @@ -0,0 +1,70 @@ +// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: BUSL-1.1 +import { ChangeDetectionStrategy, Component, computed, input } from '@angular/core'; +import { aiEntityKind } from '@home/components/ai/ai-action.models'; +import { AiAlarmState, AiHubMeta, AiRecordState } from '@home/components/ai/ai-record.models'; + +export { AiRecordState } from '@home/components/ai/ai-record.models'; + +@Component({ + selector: 'tb-ai-record', + template: ` + + @if (url()) { + {{ name() }} + } @else { + {{ name() }} + } + @if (badge(); as label) { + {{ label }} + } + @if (hub(); as listing) { + + + {{ listing.type }}@if (listing.creator) {{{ listing.type ? ' · ' : '' }}{{ listing.creator }}}@if (listing.verified) {}@if (listing.installs) { · {{ listing.installs }}} + + } @else if (meta()) { + {{ meta() }} + } + @if (alarm(); as current) { + + {{ (current.cleared ? 'ai-assistant.record.cleared' : 'alarm.severity-' + current.severity.toLowerCase()) | translate }} + @if (current.acknowledged) { + + } + + } @else if (state(); as current) { + {{ current.label }} + } + `, + standalone: false, + changeDetection: ChangeDetectionStrategy.OnPush, + host: { + 'class': 'tb-rec line', + '[attr.data-pal]': 'kind().palette' + } +}) +export class AiRecordComponent { + + entityType = input.required(); + + alarmRule = input(false); + groupType = input(undefined); + + name = input.required(); + + meta = input(); + + badge = input(); + + url = input(); + + state = input(); + + alarm = input(); + + hub = input(); + + kind = computed(() => aiEntityKind(this.entityType(), this.alarmRule(), this.groupType())); +} diff --git a/ui-ngx/src/app/modules/home/components/ai/ai-record.models.ts b/ui-ngx/src/app/modules/home/components/ai/ai-record.models.ts new file mode 100644 index 0000000000..d8d7308ec2 --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/ai/ai-record.models.ts @@ -0,0 +1,106 @@ +// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: BUSL-1.1 +import { aiTrueMinus } from '@home/components/ai/ai-text'; +import { MpItemVersionView } from '@shared/models/iot-hub/iot-hub-version.models'; + +export const SHOW_RECORDS_TOOL = 'show_records'; + +export const MAX_SHOWN_RECORDS = 20; + +export interface AiRecordState { + tone: 'ok' | 'off' | 'warn' | 'wait'; + label: string; +} + +export interface AiAlarmState { + severity: string; + cleared: boolean; + acknowledged: boolean; + tip: string; +} + +export interface AiHubMeta { + type: string; + creator?: string; + verified?: boolean; + installs?: string; +} + +export interface AiRecordFact { + label: string; + value: string; +} + +export interface AiRecordView { + key: string; + entityType: string; + alarmRule: boolean; + groupType?: string; + name: string; + meta: string; + badge?: string; + url?: string; + state?: AiRecordState; + alarm?: AiAlarmState; + hub?: AiHubMeta; + hubItem?: MpItemVersionView; + description?: string; + image?: string; + imageUrl?: string; + widgets?: number; + square?: boolean; + wide?: boolean; +} + +export type AiRecordRef = {versionId: string} | {entityType: string; id: string}; + +export interface AiShownRecords { + refs: AiRecordRef[]; + facts: AiRecordFact[]; + note?: string; +} + +const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i; + +const text = (value: unknown): string | null => typeof value === 'string' && value.trim() ? value.trim() : null; + +export function aiRecordKey(ref: AiRecordRef): string { + return 'versionId' in ref ? `HUB:${ref.versionId}` : `${ref.entityType}:${ref.id}`; +} + +export function aiShownRecordsOf(args: unknown): AiShownRecords | null { + const given = (args as {records?: unknown})?.records; + if (!Array.isArray(given)) { + return null; + } + const seen = new Set(); + const refs: AiRecordRef[] = []; + given.forEach(item => { + const versionId = text(item?.iotHubVersionId); + const id = text(item?.id); + const entityType = text(item?.entityType)?.toUpperCase(); + const ref: AiRecordRef | null = versionId && UUID.test(versionId) ? {versionId} + : id && entityType && UUID.test(id) ? {entityType: entityType === 'ALARM_RULE' ? 'CALCULATED_FIELD' : entityType, id} : null; + if (ref && !seen.has(aiRecordKey(ref))) { + seen.add(aiRecordKey(ref)); + refs.push(ref); + } + }); + if (!refs.length) { + return null; + } + const single = refs.length === 1; + const rawFacts = (args as {facts?: unknown})?.facts; + const facts = single && Array.isArray(rawFacts) + ? rawFacts.map(fact => ({label: text(fact?.label), value: text(fact?.value)})) + .filter(fact => fact.label && fact.value).slice(0, 4) as AiRecordFact[] + : []; + const note = single ? text((args as {note?: unknown})?.note) ?? undefined : undefined; + return {refs: refs.slice(0, MAX_SHOWN_RECORDS), facts, note}; +} + +export function aiFactParts(value: string): Array<{text: string; code: boolean}> { + return value.split(/(`[^`]+`)/).filter(part => part.length) + .map(part => part.length > 2 && part.startsWith('`') && part.endsWith('`') ? {text: part.slice(1, -1), code: true} + : {text: aiTrueMinus(part), code: false}); +} diff --git a/ui-ngx/src/app/modules/home/components/ai/ai-records.component.ts b/ui-ngx/src/app/modules/home/components/ai/ai-records.component.ts new file mode 100644 index 0000000000..ac27ede19d --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/ai/ai-records.component.ts @@ -0,0 +1,152 @@ +// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: BUSL-1.1 +import { ChangeDetectionStrategy, Component, computed, DestroyRef, effect, inject, input, output, signal, untracked } from '@angular/core'; +import { takeUntilDestroyed } from '@angular/core/rxjs-interop'; +import { TranslateService } from '@ngx-translate/core'; +import { Subscription, timer } from 'rxjs'; +import { concatMap, take, takeWhile } from 'rxjs/operators'; +import { aiEntityKind } from '@home/components/ai/ai-action.models'; +import { aiRecordKey, AiRecordView, AiShownRecords } from '@home/components/ai/ai-record.models'; +import { AiRecordLoaderService } from '@home/components/ai/ai-record-loader.service'; +import { AiCardAction } from '@home/components/ai/ai-card-actions.component'; +import { AiRecordPrimary } from '@home/components/ai/ai-record-card.component'; +import { EntityType, entityTypeTranslations } from '@shared/models/entity-type.models'; +import { ItemType } from '@shared/models/iot-hub/iot-hub-item.models'; + +const LIST_SHOWN = 8; + +const TARGETED_HUB_TYPES = new Set([ItemType.CALCULATED_FIELD, ItemType.ALARM_RULE]); + +const WAIT_RECHECK_MS = 10000; +const WAIT_RECHECKS = 90; + +@Component({ + selector: 'tb-ai-records', + template: ` + @if (views().length === 1 && single(); as rec) { + + } @else if (views().length > 1) { +
+ + @if (listOpen()) { +
+ @for (rec of shownViews(); track rec.key) { + + } + @if (views().length > LIST_SHOWN) { + + } +
+ } +
+ } + `, + standalone: false, + changeDetection: ChangeDetectionStrategy.OnPush +}) +export class AiRecordsComponent { + + shown = input.required(); + + compose = output(); + + made = input([]); + + views = signal([]); + + allShown = signal(false); + + private listToggled = signal(null); + + listOpen = computed(() => this.listToggled() ?? true); + + toggleList(): void { + this.listToggled.set(!this.listOpen()); + } + + readonly LIST_SHOWN = LIST_SHOWN; + + single = computed(() => this.views()[0] ?? null); + + primary = computed(() => { + const single = this.single(); + if (single?.hubItem) { + return 'install'; + } + return single && this.made().includes(single.key) ? 'open' : null; + }); + + cardActions = computed(() => { + const item = this.single()?.hubItem; + if (!item || !TARGETED_HUB_TYPES.has(item.type)) { + return []; + } + return [{ + id: 'install-on', icon: 'edit', label: this.translate.instant('ai-assistant.record.install-on'), + compose: this.translate.instant('ai-assistant.record.install-on-prompt', {name: item.name}) + }]; + }); + + shownViews = computed(() => this.allShown() ? this.views() : this.views().slice(0, LIST_SHOWN)); + + sameKind = computed(() => new Set(this.views().map(view => this.kindKey(view))).size === 1); + + listKind = computed(() => this.sameKind() && this.views().length ? aiEntityKind(this.views()[0].entityType, this.views()[0].alarmRule, this.views()[0].groupType) : null); + + listLabel = computed(() => { + const views = this.views(); + if (views.every(view => !!view.hub)) { + return this.translate.instant('ai-assistant.record.hub-items', {count: views.length}); + } + if (!this.sameKind()) { + return this.translate.instant('ai-assistant.summary.entities', {count: views.length}); + } + const view = views[0]; + const plural = view.alarmRule ? 'ai-assistant.summary.alarm-rules' + : view.entityType === 'GATEWAY' ? 'ai-assistant.record.gateways' : entityTypeTranslations.get(view.entityType as EntityType)?.typePlural; + return plural ? `${views.length} ${this.translate.instant(plural).toLowerCase()}` : this.translate.instant('ai-assistant.summary.entities', {count: views.length}); + }); + + private loader = inject(AiRecordLoaderService); + private translate = inject(TranslateService); + private destroyRef = inject(DestroyRef); + private loading: Subscription; + + private key = computed(() => this.shown().refs.map(aiRecordKey).join(',')); + + constructor() { + effect(() => { + this.key(); + const shown = untracked(() => this.shown()); + this.loading?.unsubscribe(); + this.loading = timer(0, WAIT_RECHECK_MS).pipe( + take(WAIT_RECHECKS), + concatMap(() => this.loader.loadAll(shown.refs, {image: shown.refs.length === 1})), + takeWhile(views => views.some(view => view.state?.tone === 'wait'), true), + takeUntilDestroyed(this.destroyRef) + ).subscribe(views => this.views.set(views)); + }); + } + + lineMeta(view: AiRecordView): string { + if (view.hub) { + return view.meta; + } + const parts = view.meta.split(' · '); + return parts.length > 1 ? parts.slice(1).join(' · ') : ''; + } + + private kindKey(view: AiRecordView): string { + return view.hub ? 'HUB:' + view.entityType + view.alarmRule : view.alarmRule ? 'ALARM_RULE' : view.entityType; + } +} diff --git a/ui-ngx/src/app/modules/home/components/ai/ai-references.ts b/ui-ngx/src/app/modules/home/components/ai/ai-references.ts new file mode 100644 index 0000000000..39379705b6 --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/ai/ai-references.ts @@ -0,0 +1,401 @@ +// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: BUSL-1.1 +import { SEVERITY_MARK } from '@home/components/ai/ai-text'; +import { AiFile, aiFileMark, aiFileName } from '@home/components/ai/ai-file.models'; +import { baseDetailsPageByEntityType, EntityType } from '@shared/models/entity-type.models'; +import { aiEntityKind } from '@home/components/ai/ai-action.models'; +import { aiSevMarkElement } from '@home/components/ai/ai-sev-mark.component'; + +export interface AiReference { + name: string; + entityType: string; + id: string; +} + +const SKIP = 'code, pre, a, .tb-chiplink, .k-ent'; + +export function decorateReferences(root: HTMLElement, references: AiReference[] | undefined): void { + if (!references?.length) { + return; + } + const linkable = references + .filter(reference => reference.name?.trim().length >= 3) + .sort((a, b) => b.name.length - a.name.length); + if (!linkable.length) { + return; + } + const pattern = new RegExp(`(? escape(reference.name)).join('|')})(?![\\p{L}\\p{N}_])`, 'u'); + const walker = document.createTreeWalker(root, NodeFilter.SHOW_TEXT, { + acceptNode: node => node.parentElement?.closest(SKIP) || !node.textContent?.trim() ? NodeFilter.FILTER_REJECT : NodeFilter.FILTER_ACCEPT + }); + const nodes: Text[] = []; + while (walker.nextNode()) { + nodes.push(walker.currentNode as Text); + } + nodes.forEach(node => replaceIn(node, pattern, linkable)); +} + +const PLAIN_WORD = /^\p{Ll}+$/u; +const QUOTE_OPEN = /["'“‘«]$/u; +const QUOTE_CLOSE = /^["'”’»]/u; + +function replaceIn(node: Text, pattern: RegExp, references: AiReference[]): void { + let rest = node.textContent ?? ''; + let match = pattern.exec(rest); + if (!match) { + return; + } + const fragment = document.createDocumentFragment(); + while (match) { + if (match.index > 0) { + fragment.append(rest.slice(0, match.index)); + } + const reference = references.find(item => item.name === match[1]); + const before = rest.slice(0, match.index); + const after = rest.slice(match.index + match[1].length); + const standsAsName = !reference || !PLAIN_WORD.test(reference.name) + || (node.textContent ?? '').trim() === reference.name || (QUOTE_OPEN.test(before) && QUOTE_CLOSE.test(after)); + fragment.append(reference && standsAsName ? chip(reference) : match[1]); + rest = after; + match = pattern.exec(rest); + } + if (rest) { + fragment.append(rest); + } + node.replaceWith(fragment); +} + +const SVG_ICONS = new Map>(); + +function svgIcon(name: string): Promise { + let icon = SVG_ICONS.get(name); + if (!icon) { + const [namespace, file] = name.split(':'); + icon = namespace !== 'mdi' || !/^[a-z0-9-]+$/.test(file) ? Promise.resolve(null) + : fetch(`./assets/mdi/${file}.svg`).then(response => response.ok ? response.text() : '').then(text => { + const svg = new DOMParser().parseFromString(text, 'image/svg+xml').documentElement; + return svg?.nodeName === 'svg' ? svg as unknown as SVGElement : null; + }).catch(() => null); + SVG_ICONS.set(name, icon); + } + return icon; +} + +function aiIconElement(name: string, className: string): HTMLElement { + const icon = document.createElement('span'); + icon.setAttribute('aria-hidden', 'true'); + if (!name.includes(':')) { + icon.className = 'mat-icon notranslate material-icons mat-ligature-font ' + className; + icon.textContent = name; + return icon; + } + icon.className = 'mat-icon notranslate ' + className; + svgIcon(name).then(svg => { + if (svg) { + const copy = svg.cloneNode(true) as SVGElement; + copy.setAttribute('width', '100%'); + copy.setAttribute('height', '100%'); + copy.setAttribute('fill', 'currentColor'); + copy.setAttribute('focusable', 'false'); + icon.replaceChildren(copy); + } + }); + return icon; +} + +const REFERENCE_PAGES: Record = { + ALARM_RULE: '/alarms/alarm-rules', + EDGE_RULE_CHAIN: '/edgeManagement/templates/ruleChains' +}; + +function chip(reference: AiReference): HTMLElement { + const kind = aiEntityKind(reference.entityType); + const code = document.createElement('code'); + code.className = 'k-ent'; + code.dataset.pal = kind.palette; + code.append(aiIconElement(kind.icon, 'k-ent-ic'), reference.name); + const base = REFERENCE_PAGES[reference.entityType] ?? baseDetailsPageByEntityType.get(reference.entityType as EntityType); + if (!base || !reference.id) { + return code; + } + const link = document.createElement('a'); + link.className = 'tb-chiplink'; + link.href = `${base}/${reference.id}`; + code.append(chipChevron()); + link.append(code); + return link; +} + +export function chipChevron(): HTMLElement { + const chevron = document.createElement('span'); + chevron.className = 'mat-icon notranslate material-icons mat-ligature-font tb-chip-go'; + chevron.setAttribute('aria-hidden', 'true'); + chevron.textContent = 'chevron_right'; + return chevron; +} + +function escape(text: string): string { + return text.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); +} + +export function decorateLinks(root: HTMLElement, newTab: string): void { + root.querySelectorAll('a[href]:not(.tb-chiplink)').forEach(link => { + if (link.closest('pre, code') || link.origin === location.origin || !/^https?:$/.test(link.protocol)) { + return; + } + link.target = '_blank'; + link.rel = 'noopener noreferrer'; + if (link.querySelector('.k-ext')) { + return; + } + const last = lastText(link); + const tail = document.createElement('span'); + tail.className = 'k-ext-tail'; + if (last) { + const text = last.textContent ?? ''; + const cut = text.trimEnd().lastIndexOf(' ') + 1; + tail.append(text.slice(cut)); + last.textContent = text.slice(0, cut); + last.after(tail); + } else { + link.append(tail); + } + const icon = document.createElement('span'); + icon.className = 'mat-icon notranslate material-icons mat-ligature-font k-ext'; + icon.setAttribute('aria-hidden', 'true'); + icon.textContent = 'north_east'; + tail.append(icon); + const hidden = document.createElement('span'); + hidden.className = 'tb-ai-sr-only'; + hidden.textContent = ' ' + newTab; + link.append(hidden); + }); +} + +function lastText(root: Node): Text | null { + for (let node = root.lastChild; node; node = node.previousSibling) { + if (node.nodeType === Node.TEXT_NODE) { + if (node.textContent?.trim()) { + return node as Text; + } + } else { + const found = lastText(node); + if (found) { + return found; + } + } + } + return null; +} + +const SEVERITY_SKIP = 'code, pre, a, table, .k-sev, .tb-chiplink, .tb-rec, tb-ai-record, tb-ai-records'; +const MARK_SKIP = 'code, pre, a, .k-sev, .tb-chiplink'; + +function aiHasSeverityMarks(text: string | undefined): boolean { + return !!text && SEVERITY_MARK.test(text); +} + +function severityChip(severity: string, label: (severity: string) => string): HTMLElement { + const chip = document.createElement('span'); + chip.className = 'k-sev ' + severity.toLowerCase(); + chip.append(aiSevMarkElement(severity), label(severity)); + return chip; +} + +function textNodes(root: HTMLElement, skip: string): Text[] { + const walker = document.createTreeWalker(root, NodeFilter.SHOW_TEXT, { + acceptNode: node => node.parentElement?.closest(skip) || !node.textContent?.trim() ? NodeFilter.FILTER_REJECT : NodeFilter.FILTER_ACCEPT + }); + const nodes: Text[] = []; + while (walker.nextNode()) { + nodes.push(walker.currentNode as Text); + } + return nodes; +} + +function replaceMatches(node: Text, pattern: RegExp, chip: (match: RegExpExecArray) => Node | null): void { + let rest = node.textContent ?? ''; + let match = pattern.exec(rest); + if (!match) { + return; + } + const fragment = document.createDocumentFragment(); + while (match) { + if (match.index > 0) { + fragment.append(rest.slice(0, match.index)); + } + fragment.append(chip(match) ?? match[0]); + rest = rest.slice(match.index + match[0].length); + match = pattern.exec(rest); + } + if (rest) { + fragment.append(rest); + } + node.replaceWith(fragment); +} + +export function decorateSeverities(root: HTMLElement, severities: string[] | undefined, label: (severity: string) => string): void { + if (aiHasSeverityMarks(root.textContent ?? '')) { + const lone = new RegExp('^\\s*' + SEVERITY_MARK.source + '\\s*$'); + root.querySelectorAll('code').forEach(code => { + const match = !code.closest('pre') ? lone.exec(code.textContent ?? '') : null; + if (match) { + code.replaceWith(severityChip(match[1], label)); + } + }); + textNodes(root, MARK_SKIP).forEach(node => replaceMatches(node, SEVERITY_MARK, match => severityChip(match[1], label))); + decorateAlarmTables(root); + return; + } + if (!severities?.length) { + return; + } + const pattern = new RegExp(`(? severity.toLowerCase()).join('|')})(?![\\p{L}\\p{N}_])`, 'iu'); + const chipped = new Set(); + textNodes(root, SEVERITY_SKIP).forEach(node => replaceMatches(node, pattern, match => { + const severity = match[1].toUpperCase(); + if (chipped.has(severity)) { + return null; + } + chipped.add(severity); + return severityChip(severity, label); + })); +} + +function decorateAlarmTables(root: HTMLElement): void { + root.querySelectorAll('table').forEach(table => { + const rows = Array.from(table.querySelectorAll('tbody tr')); + const columns = table.querySelectorAll('thead th').length; + if (columns < 4 || !rows.length || !rows.every(row => row.children[2]?.querySelector('.k-sev'))) { + return; + } + table.classList.add('k-alarms'); + rows.forEach(row => { + const [alarm, device] = [row.children[0] as HTMLElement, row.children[1] as HTMLElement]; + if (!alarm.querySelector('.k-cell-meta') && device?.textContent?.trim()) { + const meta = document.createElement('span'); + meta.className = 'k-cell-meta'; + meta.append(...Array.from(device.childNodes).map(node => node.cloneNode(true))); + alarm.append(meta); + } + }); + }); +} + +const HINT_KINDS: Record = { + note: {kind: 'note', icon: 'info_outline'}, + tip: {kind: 'tip', icon: 'lightbulb_outline'}, + 'heads-up': {kind: 'heads-up', icon: 'outlined_flag'} +}; + +export function decorateHints(root: HTMLElement): void { + root.querySelectorAll('blockquote').forEach(quote => { + const paragraph = quote.querySelector('p') ?? quote; + const first = paragraph.firstChild; + const match = first?.nodeType === Node.TEXT_NODE ? /^\s*(note|tip|heads-up)\s*:\s*/i.exec(first.textContent ?? '') : null; + if (!match) { + return; + } + const hint = HINT_KINDS[match[1].toLowerCase()]; + first.textContent = (first.textContent ?? '').slice(match[0].length); + const box = document.createElement('div'); + box.className = 'k-hint agent-hint ' + hint.kind; + const icon = document.createElement('mat-icon'); + icon.className = 'mat-icon material-icons mat-icon-no-color'; + icon.setAttribute('aria-hidden', 'true'); + icon.textContent = hint.icon; + const text = document.createElement('span'); + paragraph.querySelectorAll('strong').forEach(strong => { + const lead = document.createElement('b'); + lead.append(...Array.from(strong.childNodes)); + strong.replaceWith(lead); + }); + text.append(...Array.from(paragraph.childNodes)); + box.append(icon, text); + quote.replaceWith(box); + }); +} + +const VALUE_CODE = /^([^:\n]{1,60}):\s+(.+)$/; +const NUMBER = /^([-−]?\d+(?:\.\d+)?)(.*)$/; + +export function decorateValues(root: HTMLElement, readings: Array<{key: string; values: string[]}> | undefined): void { + if (!readings?.length) { + return; + } + root.querySelectorAll('code').forEach(code => { + if (code.closest('pre, a, .k-ent, .k-tel') || code.children.length) { + return; + } + const match = VALUE_CODE.exec(code.textContent?.trim() ?? ''); + const reading = match ? readings.find(item => item.key === match[1].trim()) : undefined; + if (!match || !reading) { + return; + } + const written = match[2].trim(); + const number = NUMBER.exec(written); + let value: string; + let unit = ''; + if (number && reading.values.some(item => Number(item) === Number(number[1].replace('−', '-')))) { + value = number[1].replace('-', '−'); + unit = number[2].trim(); + } else if (reading.values.includes(written)) { + value = written; + } else { + return; + } + const chip = document.createElement('span'); + chip.className = 'k-tel'; + const key = document.createElement('code'); + key.className = 'k-tel-key'; + key.textContent = reading.key; + const shown = document.createElement('span'); + shown.className = 'k-tel-val'; + shown.append(value); + if (unit) { + const unitEl = document.createElement('span'); + unitEl.className = 'k-tel-unit'; + unitEl.textContent = unit; + shown.append(unitEl); + } + chip.append(key, shown); + code.replaceWith(chip); + }); +} + +export function decorateFileChips(root: HTMLElement, files: ReadonlyMap, shown: string | null): void { + if (!files.size) { + return; + } + root.querySelectorAll('code').forEach(code => { + if (code.closest('pre, a, .k-ent, .k-tel, .art-chip') || code.children.length) { + return; + } + const file = files.get(code.textContent?.trim() ?? ''); + if (!file) { + return; + } + const chip = document.createElement('button'); + chip.type = 'button'; + chip.className = 'art-chip' + (file.name === shown ? ' on' : ''); + chip.dataset.file = file.name; + chip.setAttribute('aria-pressed', String(file.name === shown)); + chip.setAttribute('aria-label', `${file.name}, ${file.lines} · ${file.size}`); + const icon = document.createElement('span'); + icon.className = 'mat-icon notranslate material-icons-round mat-ligature-font'; + icon.setAttribute('aria-hidden', 'true'); + icon.textContent = aiFileMark(file); + const parts = aiFileName(file.name); + const name = document.createElement('span'); + name.className = 'art-name'; + name.textContent = parts.base; + if (parts.ext) { + const ext = document.createElement('span'); + ext.className = 'art-ext'; + ext.textContent = parts.ext; + name.append(ext); + } + chip.append(icon, name); + code.replaceWith(chip); + }); +} diff --git a/ui-ngx/src/app/modules/home/components/ai/ai-rename-dialog.component.html b/ui-ngx/src/app/modules/home/components/ai/ai-rename-dialog.component.html deleted file mode 100644 index 641c9b706a..0000000000 --- a/ui-ngx/src/app/modules/home/components/ai/ai-rename-dialog.component.html +++ /dev/null @@ -1,33 +0,0 @@ - - -

{{ data.title }}

- - -
-
- - - -
-
- - -
diff --git a/ui-ngx/src/app/modules/home/components/ai/ai-rename-dialog.component.ts b/ui-ngx/src/app/modules/home/components/ai/ai-rename-dialog.component.ts deleted file mode 100644 index 304fa2d4e2..0000000000 --- a/ui-ngx/src/app/modules/home/components/ai/ai-rename-dialog.component.ts +++ /dev/null @@ -1,42 +0,0 @@ -// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. -// SPDX-License-Identifier: BUSL-1.1 -import { Component, Inject } from '@angular/core'; -import { MAT_DIALOG_DATA, MatDialogRef } from '@angular/material/dialog'; -import { DialogComponent } from '@shared/components/dialog.component'; -import { AppState } from '@core/core.state'; -import { Router } from '@angular/router'; -import { Store } from '@ngrx/store'; -import { FormBuilder, Validators } from '@angular/forms'; - -export interface AiRenameDialogData { - title: string; - value: string; -} - -@Component({ - selector: 'tb-input-dialog', - templateUrl: './ai-rename-dialog.component.html', - styles: ':host{min-width: 100%;max-width: 100%;width: 420px;display: grid;grid-template-rows: min-content minmax(auto, 1fr) min-content;height: 100%}', - standalone: false -}) -export class AiRenameDialogComponent extends DialogComponent { - - valueControl = this.fb.control('', [Validators.required]); - - constructor(protected store: Store, - protected router: Router, - public dialogRef: MatDialogRef, - @Inject(MAT_DIALOG_DATA) public data: AiRenameDialogData, - private fb: FormBuilder) { - super(store, router, dialogRef); - this.valueControl.patchValue(data.value || ''); - } - - cancel(): void { - this.dialogRef.close(null); - } - - confirm(): void { - this.dialogRef.close(this.valueControl.value.trim()); - } -} diff --git a/ui-ngx/src/app/modules/home/components/ai/ai-run-summary.component.ts b/ui-ngx/src/app/modules/home/components/ai/ai-run-summary.component.ts new file mode 100644 index 0000000000..3d512d4cf3 --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/ai/ai-run-summary.component.ts @@ -0,0 +1,114 @@ +// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: BUSL-1.1 +import { aiEntityKind } from '@home/components/ai/ai-action.models'; +import { ChangeDetectionStrategy, Component, computed, DestroyRef, effect, inject, input, signal, untracked } from '@angular/core'; +import { takeUntilDestroyed } from '@angular/core/rxjs-interop'; +import { TranslateService } from '@ngx-translate/core'; +import { Subscription } from 'rxjs'; +import { EntityId } from '@shared/models/id/entity-id'; +import { EntityType, entityTypeTranslations } from '@shared/models/entity-type.models'; +import { AiRecordView } from '@home/components/ai/ai-record.models'; +import { AiRecordLoaderService } from '@home/components/ai/ai-record-loader.service'; + +const LEAD_TYPES = new Set([EntityType.DASHBOARD, EntityType.WIDGET_TYPE, 'SCADA_SYMBOL']); + +@Component({ + selector: 'tb-ai-run-summary', + template: ` + @if (lead(); as card) { + + } + @if (rest().length > 1) { +
+ + @if (listOpen()) { +
+ @for (row of shownRows(); track row.key) { + + } + @if (rest().length > LIST_SHOWN) { + + } +
+ } +
+ } @else if (rest().length) { +
+ @for (row of rest(); track row.key) { + + } +
+ } + `, + standalone: false, + changeDetection: ChangeDetectionStrategy.OnPush +}) +export class AiRunSummaryComponent { + + entities = input.required(); + leadMeta = input(null); + + rows = signal([]); + + lead = computed(() => this.rows().find(row => LEAD_TYPES.has(row.entityType) && !!row.url) ?? null); + + rest = computed(() => this.rows().filter(row => row !== this.lead())); + + readonly LIST_SHOWN = 8; + + private listToggled = signal(null); + + allShown = signal(false); + + listOpen = computed(() => this.listToggled() ?? this.rest().length <= 3); + + shownRows = computed(() => this.allShown() ? this.rest() : this.rest().slice(0, this.LIST_SHOWN)); + + listKind = computed(() => { + const kinds = new Set(this.rest().map(row => row.alarmRule ? 'ALARM_RULE' : row.entityType)); + return kinds.size === 1 ? aiEntityKind([...kinds][0]) : null; + }); + + listLabel = computed(() => { + const rows = this.rest(); + const kinds = new Set(rows.map(row => row.alarmRule ? 'ALARM_RULE' : row.entityType)); + if (kinds.size !== 1) { + return this.translate.instant('ai-assistant.summary.entities', {count: rows.length}); + } + const kind = [...kinds][0]; + const plural = kind === 'ALARM_RULE' ? 'ai-assistant.summary.alarm-rules' : entityTypeTranslations.get(kind as EntityType)?.typePlural; + return plural ? `${rows.length} ${this.translate.instant(plural).toLowerCase()}` : this.translate.instant('ai-assistant.summary.entities', {count: rows.length}); + }); + + toggleList(): void { + this.listToggled.set(!this.listOpen()); + } + + private key = computed(() => this.entities().map(entity => `${entity.entityType}:${entity.id}`).join(',')); + + private loader = inject(AiRecordLoaderService); + private translate = inject(TranslateService); + private destroyRef = inject(DestroyRef); + + private loading: Subscription; + + constructor() { + effect(() => { + this.key(); + const entities = untracked(() => this.entities()); + this.loading?.unsubscribe(); + this.loading = this.loader.loadAll(entities.map(entity => ({entityType: entity.entityType, id: entity.id}))) + .pipe(takeUntilDestroyed(this.destroyRef)) + .subscribe(rows => this.rows.set(rows)); + }); + } +} diff --git a/ui-ngx/src/app/modules/home/components/ai/ai-secret-field.component.html b/ui-ngx/src/app/modules/home/components/ai/ai-secret-field.component.html new file mode 100644 index 0000000000..cf6c0da3dd --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/ai/ai-secret-field.component.html @@ -0,0 +1,19 @@ + +
+ + + + +
diff --git a/ui-ngx/src/app/modules/home/components/ai/ai-secret-field.component.ts b/ui-ngx/src/app/modules/home/components/ai/ai-secret-field.component.ts new file mode 100644 index 0000000000..e7198963f6 --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/ai/ai-secret-field.component.ts @@ -0,0 +1,25 @@ +// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: BUSL-1.1 +import { ChangeDetectionStrategy, Component, computed, input, model, output, signal } from '@angular/core'; +import { AiQuestion } from '@shared/models/solution-creator.models'; + +@Component({ + selector: 'tb-ai-secret-field', + templateUrl: './ai-secret-field.component.html', + changeDetection: ChangeDetectionStrategy.OnPush, + standalone: false +}) +export class AiSecretFieldComponent { + + question = input.required(); + value = model(''); + enter = output(); + + readonly shown = signal(false); + readonly ready = computed(() => !!this.value()); + + toggle(field: HTMLInputElement): void { + this.shown.update(shown => !shown); + field.focus(); + } +} diff --git a/ui-ngx/src/app/modules/home/components/ai/ai-sev-mark.component.ts b/ui-ngx/src/app/modules/home/components/ai/ai-sev-mark.component.ts new file mode 100644 index 0000000000..2e01d13b07 --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/ai/ai-sev-mark.component.ts @@ -0,0 +1,61 @@ +// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: BUSL-1.1 +import { ChangeDetectionStrategy, Component, input } from '@angular/core'; +import { AlarmSeverity } from '@shared/models/alarm.models'; + +const TRIANGLE = 'M6 1.3c.33 0 .64.18.8.47l4.75 8.4c.33.58-.09 1.3-.76 1.3H1.21c-.67 0-1.09-.72-.76-1.3l4.75-8.4c.16-.29.47-.47.8-.47z'; + +const MARKS: Record = { + CRITICAL: ``, + MAJOR: ``, + MINOR: '', + WARNING: '', + INDETERMINATE: '' +}; + +export function aiSevMarkElement(severity: string): HTMLElement { + const mark = document.createElement('span'); + mark.className = 'tb-sev-mark ' + severity.toLowerCase(); + mark.setAttribute('aria-hidden', 'true'); + mark.innerHTML = ``; + return mark; +} + +@Component({ + selector: 'tb-ai-sev-mark', + template: ` + + `, + standalone: false, + changeDetection: ChangeDetectionStrategy.OnPush, + host: { + '[class]': '"tb-sev-mark " + (severity() ?? "").toLowerCase()', + 'aria-hidden': 'true' + } +}) +export class AiSevMarkComponent { + + severity = input(); + + readonly triangle = 'M6 1.3c.33 0 .64.18.8.47l4.75 8.4c.33.58-.09 1.3-.76 1.3H1.21c-.67 0-1.09-.72-.76-1.3l4.75-8.4c.16-.29.47-.47.8-.47z'; +} diff --git a/ui-ngx/src/app/modules/home/components/ai/ai-shortcuts-dialog.component.ts b/ui-ngx/src/app/modules/home/components/ai/ai-shortcuts-dialog.component.ts new file mode 100644 index 0000000000..ece7cfd02b --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/ai/ai-shortcuts-dialog.component.ts @@ -0,0 +1,73 @@ +// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: BUSL-1.1 +import { ChangeDetectionStrategy, Component } from '@angular/core'; + +interface ShortcutRow { + label: string; + keys: string[][]; +} + +const MOD = typeof navigator !== 'undefined' && /Mac|iPhone|iPad/.test(navigator.platform) ? '⌘' : 'Ctrl'; + +@Component({ + selector: 'tb-ai-shortcuts-dialog', + template: ` +
+

{{ 'ai-assistant.keys.title' | translate }}

+ +
+
+ @for (group of groups; track group.title) { +
+

{{ group.title | translate }}

+ @for (row of group.rows; track row.label) { +
+ {{ row.label | translate }} + + @for (keys of row.keys; track $index) { + + @for (key of keys; track $index) { + {{ key }} + } + + } + +
+ } +
+ } +
+ `, + standalone: false, + changeDetection: ChangeDetectionStrategy.OnPush, + host: { + 'class': 'k-keys-dialog', + 'data-ai': '' + } +}) +export class AiShortcutsDialogComponent { + + readonly groups: Array<{title: string; rows: ShortcutRow[]}> = [ + { + title: 'ai-assistant.keys.composer', + rows: [ + {label: 'ai-assistant.send', keys: [['Enter'], [MOD, 'Enter']]}, + {label: 'ai-assistant.new-line', keys: [['Shift', 'Enter']]}, + {label: 'ai-assistant.accept-suggestion', keys: [['Tab']]}, + {label: 'ai-assistant.keys.stop', keys: [['Esc']]}, + {label: 'ai-assistant.keys.slash', keys: [['/']]} + ] + }, + { + title: 'ai-assistant.keys.chat', + rows: [ + {label: 'ai-assistant.keys.search-chats', keys: [[MOD, 'K']]}, + {label: 'ai-assistant.keys.find', keys: [[MOD, 'F']]}, + {label: 'ai-assistant.keys.close-panel', keys: [['Esc']]} + ] + } + ]; +} diff --git a/ui-ngx/src/app/modules/home/components/ai/ai-spark.component.ts b/ui-ngx/src/app/modules/home/components/ai/ai-spark.component.ts new file mode 100644 index 0000000000..b3aa186e5f --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/ai/ai-spark.component.ts @@ -0,0 +1,119 @@ +// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: BUSL-1.1 +import { ChangeDetectionStrategy, Component } from '@angular/core'; + +type Point = [number, number]; + +interface SparkPart { + d: string; + values: string; + keyTimes: string; + keySplines: string; + begin: string; +} + +const SPARK_WAIST = 0.55; +const CYCLE_MS = 8000; +const LOW_DELAY_MS = 2000; +const STARS: Record<'big' | 'top' | 'low', [number, number, number]> = { + big: [9.1, 11.85, 6.8], + top: [17.8, 5.95, 3.6], + low: [17.8, 17.75, 3.6] +}; + +let sparkCount = 0; + +function sparkPath(cx: number, cy: number, radius: number, waist = SPARK_WAIST, tip = 0.1): string { + const format = (p: Point) => `${p[0].toFixed(2)} ${p[1].toFixed(2)}`; + const inner = radius * waist; + const tips: Point[] = [0, 1, 2, 3].map(i => { + const angle = i * 90 * Math.PI / 180; + return [cx + radius * Math.sin(angle), cy - radius * Math.cos(angle)]; + }); + const controls: Point[] = [0, 1, 2, 3].map(i => { + const angle = (i * 90 + 45) * Math.PI / 180; + const distance = 2 * inner - radius / Math.SQRT2; + return [cx + distance * Math.sin(angle), cy - distance * Math.cos(angle)]; + }); + const along = (p0: Point, c: Point, p2: Point, t: number): Point => [ + (1 - t) ** 2 * p0[0] + 2 * (1 - t) * t * c[0] + t * t * p2[0], + (1 - t) ** 2 * p0[1] + 2 * (1 - t) * t * c[1] + t * t * p2[1] + ]; + const after: Point[] = []; + const before: Point[] = []; + for (let i = 0; i < 4; i++) { + const next = (i + 1) % 4; + after[i] = along(tips[i], controls[i], tips[next], tip); + before[next] = along(tips[i], controls[i], tips[next], 1 - tip); + } + let d = 'M' + format(after[0]); + for (let i = 0; i < 4; i++) { + const next = (i + 1) % 4; + d += 'Q' + format(controls[i]) + ' ' + format(before[next]) + 'Q' + format(tips[next]) + ' ' + format(after[next]); + } + return d + 'Z'; +} + +function star(kind: keyof typeof STARS, waist?: number, tip?: number): string { + const [cx, cy, radius] = STARS[kind]; + return sparkPath(cx, cy, radius, waist, tip); +} + +function part(frames: string[], begin: number): SparkPart { + return { + d: frames[0], + values: frames.join(';'), + keyTimes: frames.map((_, i) => (i / (frames.length - 1)).toFixed(3)).join(';'), + keySplines: frames.slice(1).map(() => '0.42 0 0.58 1').join(';'), + begin: begin + 'ms' + }; +} + +@Component({ + selector: 'tb-ai-spark', + template: ` + + `, + standalone: false, + changeDetection: ChangeDetectionStrategy.OnPush, + host: { + 'class': 'ai-spark-svg', + 'aria-hidden': 'true' + } +}) +export class AiSparkComponent { + + readonly id = 'tb-ai-spark-ink-' + (++sparkCount); + + readonly fill = `url(#${this.id})`; + + readonly still = typeof matchMedia === 'function' && matchMedia('(prefers-reduced-motion: reduce)').matches; + + readonly parts: SparkPart[]; + + constructor() { + const phase = -(Date.now() % CYCLE_MS); + const pinch = (kind: 'top' | 'low') => [star(kind), star(kind, 0.51), star(kind), star(kind, 0.51), star(kind)]; + this.parts = [ + part([star('big'), star('big', 0.61, 0.14), star('big')], phase), + part(pinch('top'), phase), + part(pinch('low'), phase + LOW_DELAY_MS) + ]; + } +} diff --git a/ui-ngx/src/app/modules/home/components/ai/ai-spin.component.scss b/ui-ngx/src/app/modules/home/components/ai/ai-spin.component.scss new file mode 100644 index 0000000000..faa2ed69ab --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/ai/ai-spin.component.scss @@ -0,0 +1,43 @@ +// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: BUSL-1.1 +:host { + --spin: 22px; + flex: none; + display: inline-flex; + align-items: center; + justify-content: center; + width: var(--spin); + height: var(--spin); + line-height: 0; + vertical-align: middle; + color: var(--spin-color, var(--ai-teal-500)); + + &[data-kind="wait"], + &[data-kind="listen"] { + color: var(--spin-color, var(--tb-caution)); + } + + &[data-kind="stop"] { + color: var(--spin-color, var(--tb-ink-38)); + } +} + +.cell { + display: inline-grid; + font-size: calc(var(--spin) * 1.5); + grid-template-columns: repeat(2, 0.115em); + grid-auto-rows: 0.115em; + gap: 0.075em 0.08em; + line-height: 0; + vertical-align: middle; + + i { + border-radius: 50%; + background: currentColor; + visibility: hidden; + + &.on { + visibility: visible; + } + } +} diff --git a/ui-ngx/src/app/modules/home/components/ai/ai-spin.component.ts b/ui-ngx/src/app/modules/home/components/ai/ai-spin.component.ts new file mode 100644 index 0000000000..1d72167969 --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/ai/ai-spin.component.ts @@ -0,0 +1,81 @@ +// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: BUSL-1.1 +import { ChangeDetectionStrategy, Component, ElementRef, inject, Input, NgZone, OnDestroy, OnInit } from '@angular/core'; +import { AiSpinKind } from '@home/components/ai/ai-action.models'; + +const FRAME_MS = 80; +const DOT_BITS = [0x01, 0x08, 0x02, 0x10, 0x04, 0x20]; + +const FRAMES: Record = { + think: [...'⠋⠙⠹⠸⠼⠴⠦⠧⠇⠏'].map(glyph => glyph.charCodeAt(0) - 0x2800), + listen: [0x01, 0x03, 0x07, 0x0f, 0x1f, 0x3f, 0x3f, 0x3e, 0x3c, 0x38, 0x30, 0x20, 0x00], + gen: [0x01, 0x08, 0x10, 0x20, 0x04, 0x02].map(bit => 0x3f & ~bit), + install: [0x09, 0x12, 0x24, 0x2d, 0x36, 0x3f, 0x3f, 0x3f, 0x00], + stop: [0x12] +}; + +const spinners = new Set(); +let tick = 0; +let timer: ReturnType | undefined; + +function startTimer(zone: NgZone): void { + if (timer || matchMedia('(prefers-reduced-motion: reduce)').matches) { + return; + } + zone.runOutsideAngular(() => { + timer = setInterval(() => { + tick++; + spinners.forEach(spinner => spinner.draw()); + }, FRAME_MS); + }); +} + +@Component({ + selector: 'tb-ai-spin', + template: '', + styleUrls: ['./ai-spin.component.scss'], + standalone: false, + changeDetection: ChangeDetectionStrategy.OnPush, + host: { + 'aria-hidden': 'true', + '[attr.data-kind]': 'kind' + } +}) +export class AiSpinComponent implements OnInit, OnDestroy { + + private kindValue: AiSpinKind = 'think'; + + @Input() + set kind(kind: AiSpinKind) { + this.kindValue = kind ?? 'think'; + this.draw(); + } + + get kind(): AiSpinKind { + return this.kindValue; + } + + private host = inject>(ElementRef); + private zone = inject(NgZone); + + ngOnInit(): void { + spinners.add(this); + this.draw(); + startTimer(this.zone); + } + + ngOnDestroy(): void { + spinners.delete(this); + if (!spinners.size && timer) { + clearInterval(timer); + timer = undefined; + } + } + + draw(): void { + const frames = FRAMES[this.kindValue]; + const bits = frames[tick % frames.length]; + const dots = this.host.nativeElement.querySelectorAll('i'); + dots.forEach((dot, index) => dot.classList.toggle('on', !!(bits & DOT_BITS[index]))); + } +} diff --git a/ui-ngx/src/app/modules/home/components/ai/ai-started-from.component.ts b/ui-ngx/src/app/modules/home/components/ai/ai-started-from.component.ts new file mode 100644 index 0000000000..d16c5e4c0d --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/ai/ai-started-from.component.ts @@ -0,0 +1,133 @@ +// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: BUSL-1.1 +import { ChangeDetectionStrategy, Component, computed, DestroyRef, effect, inject, input, signal, untracked } from '@angular/core'; +import { TranslateService } from '@ngx-translate/core'; +import { takeUntilDestroyed } from '@angular/core/rxjs-interop'; +import { Observable, of, Subscription } from 'rxjs'; +import { catchError, map } from 'rxjs/operators'; +import { EntityService } from '@core/http/entity.service'; +import { CalculatedFieldsService } from '@core/http/calculated-fields.service'; +import { EntityType } from '@shared/models/entity-type.models'; +import { getEntityDetailsPageURL } from '@core/utils'; +import { RequestConfig } from '@core/http/http-utils'; +import { AiStartedFrom } from '@shared/models/solution-creator.models'; +import { isAiTitledView } from '@shared/models/ai-chat.models'; +import { aiEntityKind } from '@home/components/ai/ai-action.models'; + +interface AiPage { + name: string; + url?: string; +} + +const CONFIG: RequestConfig = {ignoreLoading: true, ignoreErrors: true}; + +const LIST_PAGES: Record = { + DEVICE_LIST: {entityType: EntityType.DEVICE, url: '/entities/devices'}, + DEVICE_GROUP_LIST: {entityType: EntityType.DEVICE, url: '/entities/devices/groups'}, + DASHBOARD_LIST: {entityType: EntityType.DASHBOARD, url: '/dashboards'}, + DASHBOARD_GROUP_LIST: {entityType: EntityType.DASHBOARD, url: '/dashboards/groups'}, + ALARM_LIST: {entityType: 'ALARM', url: '/alarms/alarms'}, + ALARM_RULE_LIST: {entityType: 'ALARM_RULE', url: '/alarms/alarm-rules'}, + CALCULATED_FIELD_LIST: {entityType: EntityType.CALCULATED_FIELD, url: '/calculatedFields'}, + ASSET_LIST: {entityType: EntityType.ASSET, url: '/entities/assets/all'}, + ASSET_GROUP_LIST: {entityType: EntityType.ASSET, url: '/entities/assets/groups'}, + ENTITY_VIEW_LIST: {entityType: EntityType.ENTITY_VIEW, url: '/entities/entityViews/all'}, + ENTITY_VIEW_GROUP_LIST: {entityType: EntityType.ENTITY_VIEW, url: '/entities/entityViews/groups'}, + DEVICE_PROFILE_LIST: {entityType: EntityType.DEVICE_PROFILE, url: '/profiles/deviceProfiles'}, + ASSET_PROFILE_LIST: {entityType: EntityType.ASSET_PROFILE, url: '/profiles/assetProfiles'}, + CUSTOMER_LIST: {entityType: EntityType.CUSTOMER, url: '/customers/all'}, + CUSTOMER_GROUP_LIST: {entityType: EntityType.CUSTOMER, url: '/customers/groups'}, + USER_LIST: {entityType: EntityType.USER, url: '/users/all'}, + USER_GROUP_LIST: {entityType: EntityType.USER, url: '/users/groups'}, + ROLE_LIST: {entityType: EntityType.ROLE, url: '/roles'}, + RULE_CHAIN_LIST: {entityType: EntityType.RULE_CHAIN, url: '/ruleChains'}, + INTEGRATION_LIST: {entityType: EntityType.INTEGRATION, url: '/integrationsCenter/integrations'}, + CONVERTER_LIST: {entityType: EntityType.CONVERTER, url: '/integrationsCenter/converters'}, + NOTIFICATION_TEMPLATE_LIST: {entityType: EntityType.NOTIFICATION_TEMPLATE, url: '/notification/templates'}, + NOTIFICATION_RULE_LIST: {entityType: EntityType.NOTIFICATION_RULE, url: '/notification/rules'}, + NOTIFICATION_RECIPIENT_LIST: {entityType: EntityType.NOTIFICATION_TARGET, url: '/notification/recipients'}, + SENT_NOTIFICATION_LIST: {entityType: EntityType.NOTIFICATION_RULE, url: '/notification/sent'}, + NOTIFICATION_INBOX: {entityType: EntityType.NOTIFICATION_RULE, url: '/notification/inbox'} +}; + +@Component({ + selector: 'tb-ai-started-from', + template: ` + @if (page(); as current) { + {{ 'ai-assistant.started-from' | translate }} + @if (current.url) { + + {{ current.name }} + + } @else { + {{ current.name }} + } + } + `, + standalone: false, + changeDetection: ChangeDetectionStrategy.OnPush, + host: { + 'class': 'k-start', + 'role': 'note', + '[hidden]': '!page()' + } +}) +export class AiStartedFromComponent { + + from = input.required(); + + page = signal(null); + + kind = computed(() => { + const from = this.from(); + const entityType = from.entityId?.entityType ?? LIST_PAGES[from.type]?.entityType ?? from.type; + return aiEntityKind(entityType, from.type === 'ALARM_RULE' || from.type === 'ALARM_RULE_LIST'); + }); + + private entityService = inject(EntityService); + private calculatedFieldsService = inject(CalculatedFieldsService); + private translate = inject(TranslateService); + private destroyRef = inject(DestroyRef); + + private loading: Subscription; + + constructor() { + effect(() => { + const from = this.from(); + untracked(() => { + this.loading?.unsubscribe(); + this.loading = this.resolve(from).pipe( + catchError(() => of(null)), + takeUntilDestroyed(this.destroyRef) + ).subscribe(page => this.page.set(page)); + }); + }); + } + + private resolve(from: AiStartedFrom): Observable { + if (isAiTitledView(from.type)) { + return of(from.title || from.path ? {name: from.title || from.path, url: from.path} : null); + } + const list = LIST_PAGES[from.type]; + if (list && !from.entityId?.id) { + return of({name: this.translate.instant('ai-assistant.page.' + from.type), url: list.url}); + } + const entityId = from.entityId; + if (!entityId?.id) { + return of(null); + } + if (entityId.entityType === EntityType.CALCULATED_FIELD) { + const alarmRule = from.type === 'ALARM_RULE'; + return this.calculatedFieldsService.getCalculatedFieldById(entityId.id, CONFIG).pipe(map(field => ({ + name: field.name, + url: alarmRule ? `/alarms/alarm-rules/${entityId.id}` : `/calculatedFields/${entityId.id}` + }))); + } + const entityType = entityId.entityType as EntityType; + return this.entityService.getEntity(entityType, entityId.id, CONFIG).pipe(map(entity => { + const named = entity as {name?: string; title?: string}; + const name = named?.title || named?.name; + return name ? {name, url: getEntityDetailsPageURL(entityId.id, entityType) || undefined} : null; + })); + } +} diff --git a/ui-ngx/src/app/modules/home/components/ai/ai-step-mark.component.ts b/ui-ngx/src/app/modules/home/components/ai/ai-step-mark.component.ts new file mode 100644 index 0000000000..ee9b4b60e0 --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/ai/ai-step-mark.component.ts @@ -0,0 +1,41 @@ +// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: BUSL-1.1 +import { ChangeDetectionStrategy, Component, input } from '@angular/core'; +import { AiPlanMark } from '@home/components/ai/ai-action.models'; + +export type AiStepMark = AiPlanMark | 'listen' | 'run' | 'stopped'; + +@Component({ + selector: 'tb-ai-step-mark', + template: ` + @switch (mark()) { + @case ('stopped') { + + } + @case ('listen') { + + } + @case ('run') { + + } + @default { + + } + } + `, + changeDetection: ChangeDetectionStrategy.OnPush, + standalone: false, + host: { + 'class': 'tb-ai-step-mark' + } +}) +export class AiStepMarkComponent { + + mark = input.required(); +} diff --git a/ui-ngx/src/app/modules/home/components/ai/ai-text.ts b/ui-ngx/src/app/modules/home/components/ai/ai-text.ts new file mode 100644 index 0000000000..fadd7049b7 --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/ai/ai-text.ts @@ -0,0 +1,30 @@ +// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: BUSL-1.1 + +export const MINUS = '\u2212'; + +export const SEVERITY_MARK = /\{(CRITICAL|MAJOR|MINOR|WARNING|INDETERMINATE)\}/; + +export function aiTrueMinus(text: string): string { + return text.replace(/(^|[\s(=:])-(?=\d)/g, '$1' + MINUS); +} + +export function aiLocale(lang: string | undefined): string | undefined { + return lang ? lang.replace('_', '-') : undefined; +} + +export function aiClockText(time: number | undefined, lang: string | undefined): string { + return new Date(time ?? Date.now()).toLocaleTimeString(aiLocale(lang), {hour: '2-digit', minute: '2-digit', hourCycle: 'h23'}); +} + +const CHAT_NAME_MAX = 44; +const CHAT_NAME_MIN_CUT = 20; + +export function aiChatNameOf(prompt: string): string { + const first = prompt.replace(/[*`#>]|(? CHAT_NAME_MIN_CUT ? space : CHAT_NAME_MAX).replace(/[,;·\s]+$/, '') + '…'; +} diff --git a/ui-ngx/src/app/modules/home/components/ai/ai-tip.directive.ts b/ui-ngx/src/app/modules/home/components/ai/ai-tip.directive.ts index 4c20bb7dfc..a591cb2432 100644 --- a/ui-ngx/src/app/modules/home/components/ai/ai-tip.directive.ts +++ b/ui-ngx/src/app/modules/home/components/ai/ai-tip.directive.ts @@ -22,8 +22,6 @@ export class AiTipDirective implements OnInit, OnDestroy { @Input('tbAiTip') template: TemplateRef; - @Input() tipToggle = false; - private pointerType: string; private visibleSubscription: Subscription; private unlistenKeydown: () => void; @@ -75,14 +73,9 @@ export class AiTipDirective implements OnInit, OnDestroy { this.popover.hide(); } - @HostListener('click', ['$event']) - onClick(event: MouseEvent): void { - if (!this.tipToggle || this.popover.component?.visible) { - this.popover.hide(); - return; - } - event.preventDefault(); - this.popover.show(); + @HostListener('click') + onClick(): void { + this.popover.hide(); } private onShown(): void { diff --git a/ui-ngx/src/app/modules/home/components/ai/ai-tooltip.ts b/ui-ngx/src/app/modules/home/components/ai/ai-tooltip.ts new file mode 100644 index 0000000000..dbdd3d4eec --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/ai/ai-tooltip.ts @@ -0,0 +1,82 @@ +// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: BUSL-1.1 +import { Directive, ElementRef, inject, Provider } from '@angular/core'; +import { MAT_TOOLTIP_DEFAULT_OPTIONS, MatTooltip, MatTooltipDefaultOptions } from '@angular/material/tooltip'; + +export const AI_TOOLTIP_OPTIONS: MatTooltipDefaultOptions = { + showDelay: 500, + hideDelay: 0, + touchendHideDelay: 1500, + disableTooltipInteractivity: true, + tooltipClass: 'tb-ai-tip' +}; + +export const AI_TOOLTIP_PROVIDERS: Provider[] = [{provide: MAT_TOOLTIP_DEFAULT_OPTIONS, useValue: AI_TOOLTIP_OPTIONS}]; + +const NEXT_AT_ONCE_MS = 400; + +let lastTipAt = 0; + +function focusedByKeyboard(element: HTMLElement): boolean { + return element.matches(':focus-visible'); +} + +@Directive({ + selector: '[matTooltip]', + standalone: false, + host: { + '(mouseenter)': 'onEnter()', + '(mouseleave)': 'onLeave()', + '(focus)': 'onFocus()' + } +}) +export class AiTooltipChainDirective { + + private tooltip = inject(MatTooltip, {self: true}); + private host = inject>(ElementRef); + private inChat = inject(MAT_TOOLTIP_DEFAULT_OPTIONS, {optional: true}) === AI_TOOLTIP_OPTIONS; + + onEnter(): void { + if (this.inChat) { + this.tooltip.showDelay = Date.now() - lastTipAt < NEXT_AT_ONCE_MS ? 0 : AI_TOOLTIP_OPTIONS.showDelay; + } + } + + onLeave(): void { + if (this.inChat && this.tooltip._isTooltipVisible()) { + lastTipAt = Date.now(); + } + } + + onFocus(): void { + if (this.inChat && !this.tooltip.disabled && focusedByKeyboard(this.host.nativeElement)) { + this.tooltip.show(0); + } + } +} + +@Directive({ + selector: '[aiTipIfCut]', + standalone: false, + host: { + '(mouseenter)': 'check()', + '(focus)': 'onFocus()' + } +}) +export class AiTipIfCutDirective { + + private tooltip = inject(MatTooltip, {self: true}); + private host = inject>(ElementRef); + + check(): void { + const element = this.host.nativeElement.querySelector('.tb-ai-cut') ?? this.host.nativeElement; + this.tooltip.disabled = element.scrollWidth <= element.clientWidth + 1; + } + + onFocus(): void { + this.check(); + if (!this.tooltip.disabled && focusedByKeyboard(this.host.nativeElement)) { + this.tooltip.show(0); + } + } +} diff --git a/ui-ngx/src/app/modules/home/components/ai/ai-welcome.models.ts b/ui-ngx/src/app/modules/home/components/ai/ai-welcome.models.ts new file mode 100644 index 0000000000..ca918ccec0 --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/ai/ai-welcome.models.ts @@ -0,0 +1,178 @@ +// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: BUSL-1.1 +import { TranslateService } from '@ngx-translate/core'; +import { EntityType } from '@shared/models/entity-type.models'; +import { AiAssistantPanelConfig, AiAssistantPromptExample, AiAssistantViewType, AiChatView } from '@shared/models/ai-chat.models'; + +export type AiWelcomePlace = 'dashboard' | 'list' | 'page'; + +export interface AiWelcome { + place: AiWelcomePlace; + title?: string; + line?: string; + examples: AiAssistantPromptExample[]; + suggestion: string | null; +} + +interface AiWelcomeKind { + key: string; + entity?: boolean; + owned?: boolean; + examples?: string[]; +} + +const WELCOMES: Partial> = { + [AiAssistantViewType.DASHBOARD_LIST]: {key: 'dashboards', examples: ['build', 'find']}, + [AiAssistantViewType.DASHBOARD]: {key: 'dashboard', entity: true}, + [AiAssistantViewType.REPORT_TEMPLATE_LIST]: {key: 'report-templates', examples: ['fleet', 'export']}, + [AiAssistantViewType.REPORT_TEMPLATE]: {key: 'report-template', entity: true}, + [AiAssistantViewType.SCHEDULED_REPORTS]: {key: 'scheduled-reports', examples: ['weekly', 'next']}, + [AiAssistantViewType.REPORTS]: {key: 'reports', examples: ['latest', 'now']}, + [AiAssistantViewType.WIDGET_TYPE_LIST]: {key: 'widget-types', examples: ['tank', 'heatmap']}, + [AiAssistantViewType.WIDGET_TYPE]: {key: 'widget-type', entity: true}, + [AiAssistantViewType.NEW_WIDGET_TYPE]: {key: 'widget-type-new'}, + [AiAssistantViewType.WIDGETS_BUNDLE_LIST]: {key: 'widgets-bundles', examples: ['custom']}, + [AiAssistantViewType.WIDGETS_BUNDLE]: {key: 'widgets-bundle', entity: true, examples: ['add', 'order']}, + [AiAssistantViewType.DEVICE_LIST]: {key: 'devices', examples: ['inactive']}, + [AiAssistantViewType.DEVICE]: {key: 'device', entity: true, examples: ['telemetry', 'alarm', 'dashboard']}, + [AiAssistantViewType.DEVICE_GROUP_LIST]: {key: 'device-groups', owned: true}, + [AiAssistantViewType.DEVICE_GROUP]: {key: 'device-group', entity: true, examples: ['status']}, + [AiAssistantViewType.ALARM_RULE_LIST]: {key: 'alarm-rules'}, + [AiAssistantViewType.ALARM_RULE]: {key: 'alarm-rule', entity: true, examples: ['explain']}, + [AiAssistantViewType.ALARM_LIST]: {key: 'alarms', examples: ['attention', 'triage']}, + [AiAssistantViewType.ALARM]: {key: 'alarm', entity: true, examples: ['explain', 'acknowledge']}, + [AiAssistantViewType.CALCULATED_FIELD_LIST]: {key: 'calculated-fields'}, + [AiAssistantViewType.CALCULATED_FIELD]: {key: 'calculated-field', entity: true, examples: ['explain']}, + [AiAssistantViewType.ASSET_LIST]: {key: 'assets', examples: ['find', 'hierarchy']}, + [AiAssistantViewType.ASSET]: {key: 'asset', entity: true, examples: ['telemetry', 'metric', 'dashboard']}, + [AiAssistantViewType.ASSET_GROUP_LIST]: {key: 'asset-groups', owned: true, examples: ['find']}, + [AiAssistantViewType.ASSET_GROUP]: {key: 'asset-group', entity: true, examples: ['status']}, + [AiAssistantViewType.ENTITY_VIEW_LIST]: {key: 'entity-views', examples: ['find', 'create']}, + [AiAssistantViewType.ENTITY_VIEW]: {key: 'entity-view', entity: true, examples: ['telemetry', 'source']}, + [AiAssistantViewType.DEVICE_PROFILE_LIST]: {key: 'device-profiles', examples: ['find']}, + [AiAssistantViewType.DEVICE_PROFILE]: {key: 'device-profile', entity: true, examples: ['devices', 'alarm', 'metric']}, + [AiAssistantViewType.ASSET_PROFILE_LIST]: {key: 'asset-profiles', examples: ['find', 'create']}, + [AiAssistantViewType.ASSET_PROFILE]: {key: 'asset-profile', entity: true, examples: ['assets', 'alarm']}, + [AiAssistantViewType.CUSTOMER_LIST]: {key: 'customers', examples: ['create', 'find']}, + [AiAssistantViewType.CUSTOMER]: {key: 'customer', entity: true, examples: ['user', 'share', 'devices']}, + [AiAssistantViewType.CUSTOMER_GROUP_LIST]: {key: 'customer-groups', owned: true, examples: ['create']}, + [AiAssistantViewType.CUSTOMER_GROUP]: {key: 'customer-group', entity: true, examples: ['list']}, + [AiAssistantViewType.USER_LIST]: {key: 'users', examples: ['invite', 'find']}, + [AiAssistantViewType.USER]: {key: 'user', entity: true, examples: ['access', 'notifications']}, + [AiAssistantViewType.USER_GROUP_LIST]: {key: 'user-groups', owned: true, examples: ['create']}, + [AiAssistantViewType.USER_GROUP]: {key: 'user-group', entity: true, examples: ['access', 'add']}, + [AiAssistantViewType.ROLE_LIST]: {key: 'roles', examples: ['create', 'explain']}, + [AiAssistantViewType.ROLE]: {key: 'role', entity: true, examples: ['explain']}, + [AiAssistantViewType.RULE_CHAIN_LIST]: {key: 'rule-chains', examples: ['alarm', 'notify']}, + [AiAssistantViewType.RULE_CHAIN]: {key: 'rule-chains', examples: ['alarm', 'notify']}, + [AiAssistantViewType.INTEGRATION_LIST]: {key: 'integrations', examples: ['connect']}, + [AiAssistantViewType.INTEGRATION]: {key: 'integration', entity: true, examples: ['connect']}, + [AiAssistantViewType.CONVERTER_LIST]: {key: 'converters', examples: ['connect']}, + [AiAssistantViewType.CONVERTER]: {key: 'converter', entity: true, examples: ['connect']}, + [AiAssistantViewType.EDGE_LIST]: {key: 'edges', examples: ['offline', 'create']}, + [AiAssistantViewType.EDGE]: {key: 'edge', entity: true, examples: ['status', 'assign', 'install']}, + [AiAssistantViewType.EDGE_GROUP_LIST]: {key: 'edge-groups', owned: true, examples: ['find']}, + [AiAssistantViewType.EDGE_GROUP]: {key: 'edge-group', entity: true, examples: ['status']}, + [AiAssistantViewType.EDGE_SCHEDULER]: {key: 'edge-scheduler', examples: ['assign']}, + [AiAssistantViewType.RULE_CHAIN_TEMPLATE_LIST]: {key: 'rule-chain-templates', examples: ['root', 'hub']}, + [AiAssistantViewType.RULE_CHAIN_TEMPLATE]: {key: 'rule-chain-template', entity: true, examples: ['edges', 'auto']}, + [AiAssistantViewType.INTEGRATION_TEMPLATE_LIST]: {key: 'integration-templates', examples: ['edges']}, + [AiAssistantViewType.INTEGRATION_TEMPLATE]: {key: 'integration-template', entity: true, examples: ['edges']}, + [AiAssistantViewType.CONVERTER_TEMPLATE_LIST]: {key: 'converter-templates', examples: ['explain']}, + [AiAssistantViewType.CONVERTER_TEMPLATE]: {key: 'converter-template', entity: true, examples: ['explain']}, + [AiAssistantViewType.AGENT_LIST]: {key: 'agents', examples: ['status', 'deploy']}, + [AiAssistantViewType.AGENT]: {key: 'agent', entity: true, examples: ['apps', 'edge', 'upgrade']}, + [AiAssistantViewType.AGENT_GROUP_LIST]: {key: 'agent-groups', owned: true, examples: ['find']}, + [AiAssistantViewType.AGENT_GROUP]: {key: 'agent-group', entity: true, examples: ['status']}, + [AiAssistantViewType.AGENT_APPLICATION_LIST]: {key: 'agent-applications', examples: ['status', 'install']}, + [AiAssistantViewType.AGENT_APPLICATION]: {key: 'agent-application', entity: true, examples: ['logs', 'restart']}, + [AiAssistantViewType.AGENT_EVENTS]: {key: 'agent-events', examples: ['failed']}, + [AiAssistantViewType.AGENT_PROFILE_LIST]: {key: 'agent-profiles', examples: ['create', 'default']}, + [AiAssistantViewType.AGENT_PROFILE]: {key: 'agent-profile', entity: true, examples: ['apps', 'bulk']}, + [AiAssistantViewType.AGENT_APP_PROFILE_LIST]: {key: 'agent-app-profiles', examples: ['edge', 'gateway']}, + [AiAssistantViewType.AGENT_APP_PROFILE]: {key: 'agent-app-profile', entity: true, examples: ['explain']}, + [AiAssistantViewType.AGENT_BULK_ACTION]: {key: 'agent-bulk-action', examples: ['progress']}, + [AiAssistantViewType.NOTIFICATION_TEMPLATE_LIST]: {key: 'notifications'}, + [AiAssistantViewType.NOTIFICATION_RULE_LIST]: {key: 'notifications'}, + [AiAssistantViewType.NOTIFICATION_RECIPIENT_LIST]: {key: 'notifications'}, + [AiAssistantViewType.SENT_NOTIFICATION_LIST]: {key: 'notifications'}, + [AiAssistantViewType.NOTIFICATION_INBOX]: {key: 'notifications'}, + [AiAssistantViewType.NOTIFICATION_TEMPLATE]: {key: 'notification-template', entity: true, examples: ['explain', 'slack']}, + [AiAssistantViewType.NOTIFICATION_RULE]: {key: 'notification-rule', entity: true, examples: ['explain', 'escalate']}, + [AiAssistantViewType.NOTIFICATION_RECIPIENT]: {key: 'notification-recipient', entity: true, examples: ['rules']}, + [AiAssistantViewType.IOT_HUB]: {key: 'iot-hub', examples: ['popular', 'alarm', 'installed']}, + [AiAssistantViewType.DASHBOARD_GROUP_LIST]: {key: 'dashboard-groups', owned: true, examples: ['share']}, + [AiAssistantViewType.DASHBOARD_GROUP]: {key: 'dashboard-group', entity: true, examples: ['access']}, + [AiAssistantViewType.ENTITY_VIEW_GROUP_LIST]: {key: 'entity-view-groups', owned: true}, + [AiAssistantViewType.ENTITY_VIEW_GROUP]: {key: 'entity-view-group', entity: true, examples: ['list']}, + [AiAssistantViewType.CUSTOMER_HIERARCHY]: {key: 'customer-hierarchy', examples: ['move']}, + [AiAssistantViewType.GATEWAYS]: {key: 'gateways', examples: ['modbus', 'status']}, + [AiAssistantViewType.OTA_UPDATES]: {key: 'ota-updates', examples: ['rollout', 'add']}, + [AiAssistantViewType.WHITE_LABELING]: {key: 'white-labeling', examples: ['brand']}, + [AiAssistantViewType.LOGIN_WHITE_LABELING]: {key: 'login-white-labeling', examples: ['match']}, + [AiAssistantViewType.MAIL_TEMPLATES]: {key: 'mail-templates', examples: ['name', 'activation']}, + [AiAssistantViewType.CUSTOM_TRANSLATION]: {key: 'custom-translation', examples: ['rename', 'find']}, + [AiAssistantViewType.CUSTOM_MENU]: {key: 'custom-menu', examples: ['simple', 'link']}, + [AiAssistantViewType.IMAGES]: {key: 'images', examples: ['icon']}, + [AiAssistantViewType.SCADA_SYMBOL_LIST]: {key: 'scada-symbols', examples: ['find', 'connectors']}, + [AiAssistantViewType.SCADA_SYMBOL]: {key: 'scada-symbol', entity: true, examples: ['explain', 'values']}, + [AiAssistantViewType.JAVASCRIPT_LIBRARY]: {key: 'javascript-library', examples: ['module']}, + [AiAssistantViewType.RESOURCES_LIBRARY]: {key: 'resources-library'}, + [AiAssistantViewType.TWO_FACTOR_AUTH]: {key: 'two-factor-auth', examples: ['review', 'methods', 'enforce']}, + [AiAssistantViewType.OAUTH2_DOMAINS]: {key: 'oauth2-domains', examples: ['missing', 'hide']}, + [AiAssistantViewType.OAUTH2_CLIENTS]: {key: 'oauth2-clients', examples: ['review']}, + [AiAssistantViewType.SELF_REGISTRATION]: {key: 'self-registration', examples: ['review']}, + [AiAssistantViewType.SECRETS]: {key: 'secrets', examples: ['create']}, + [AiAssistantViewType.AUDIT_LOGS]: {key: 'audit-logs', examples: ['changes', 'logins']}, + [AiAssistantViewType.VERSION_CONTROL]: {key: 'version-control', examples: ['save', 'history']}, + [AiAssistantViewType.TASK_MANAGER]: {key: 'task-manager', examples: ['failed']}, + [AiAssistantViewType.SCHEDULER]: {key: 'scheduler', examples: ['night', 'week']}, + [AiAssistantViewType.HOME_SETTINGS]: {key: 'home-settings', examples: ['set']}, + [AiAssistantViewType.MAIL_SERVER_SETTINGS]: {key: 'mail-server-settings', examples: ['setup', 'check']}, + [AiAssistantViewType.NOTIFICATION_SETTINGS]: {key: 'notification-settings', examples: ['slack', 'sms']}, + [AiAssistantViewType.REPOSITORY_SETTINGS]: {key: 'repository-settings', examples: ['connect']}, + [AiAssistantViewType.AUTO_COMMIT_SETTINGS]: {key: 'auto-commit-settings', examples: ['devices']}, + [AiAssistantViewType.AI_MODELS]: {key: 'ai-models', examples: ['add']}, + [AiAssistantViewType.API_USAGE]: {key: 'api-usage', examples: ['limits']}, + [AiAssistantViewType.MOBILE_BUNDLES]: {key: 'mobile-bundles', examples: ['dashboard', 'review']}, + [AiAssistantViewType.MOBILE_APPS]: {key: 'mobile-apps', examples: ['release', 'register']}, + [AiAssistantViewType.MOBILE_QR_CODE]: {key: 'mobile-qr-code', examples: ['home']}, + [AiAssistantViewType.ACCOUNT_PROFILE]: {key: 'account-profile', examples: ['home', 'units']}, + [AiAssistantViewType.ACCOUNT_SECURITY]: {key: 'account-security', examples: ['review', 'keys']}, + [AiAssistantViewType.ACCOUNT_NOTIFICATIONS]: {key: 'account-notifications', examples: ['quiet', 'review']}, + [AiAssistantViewType.TRENDZ]: {key: 'trendz'} +}; + +export function aiWelcome(view: AiChatView | undefined, name: string | null, config: AiAssistantPanelConfig | null, + translate: TranslateService): AiWelcome { + const configExamples = config?.promptExamples ?? []; + const kind = view ? WELCOMES[view.type] : undefined; + if (!kind) { + return {place: 'page', title: config?.title, line: config?.subTitle, examples: configExamples, suggestion: config?.suggestion ?? shortExample(configExamples)}; + } + const base = 'ai-assistant.welcome.' + (config?.welcomeKey ?? kind.key); + const own = (kind.examples ?? []).map(example => ({ + label: translate.instant(`${base}.example.${example}.label`), + message: translate.instant(`${base}.example.${example}.message`) + })); + const examples = kind.entity && own.length ? own : [...own, ...configExamples.filter(item => !own.some(mine => mine.message === item.message))]; + return { + place: view.type === AiAssistantViewType.DASHBOARD ? 'dashboard' : kind.entity ? 'page' : 'list', + title: translate.instant(`${base}.${titleKey(kind, view, name)}`, {name}), + line: translate.instant(`${base}.line`), + examples, + suggestion: translate.instant(`${base}.suggestion`) + }; +} + +function titleKey(kind: AiWelcomeKind, view: AiChatView, name: string | null): string { + if (kind.entity) { + return name ? 'title' : 'title-unnamed'; + } + return kind.owned && view.entityId?.entityType === EntityType.CUSTOMER ? 'title-customer' : 'title'; +} + +function shortExample(examples: AiAssistantPromptExample[]): string | null { + const example = examples[0]?.message?.trim(); + return example && example.length <= 80 && !example.includes('...') ? example : null; +} diff --git a/ui-ngx/src/app/modules/home/components/ai/ai-widget-check.service.ts b/ui-ngx/src/app/modules/home/components/ai/ai-widget-check.service.ts new file mode 100644 index 0000000000..852110daf2 --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/ai/ai-widget-check.service.ts @@ -0,0 +1,372 @@ +// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: BUSL-1.1 +import { Injectable } from '@angular/core'; +import { firstValueFrom, forkJoin, from, Observable, of } from 'rxjs'; +import { catchError, filter, map, switchMap, take, timeout } from 'rxjs/operators'; +import { WidgetService } from '@core/http/widget.service'; +import { AiResourceService } from '@core/http/ai-resource.service'; +import { migrateWidgetTypeToDynamicForms, WidgetTypeDetails } from '@shared/models/widget.models'; +import { ImageService } from '@core/http/image.service'; +import { parseScadaSymbolMetadataFromContent, ScadaSymbolMetadata } from '@home/components/widget/lib/scada/scada-symbol.models'; +import { detailsToWidgetInfo, WidgetInfo } from '@home/models/widget-component.models'; + +const SETTLE_MS = 2500; +const RUN_TIMEOUT_MS = 30000; +const MAX_REASON_LENGTH = 1900; +const MAX_LINE_LENGTH = 300; +const PREVIEW_WIDTH = 1280; +const PREVIEW_HEIGHT = 800; +const STYLE_CHUNK = 8; +const ICON_FONT = /material (icons|symbols)/i; + +interface WidgetCheckReport { + initialised: boolean; + errors: string[]; + console: string[]; + noData?: boolean; + width?: number; + height?: number; + screenshot?: string; + rendered?: boolean; + activeValues?: Record; +} + +type CapturedReport = WidgetCheckReport & {canvas?: HTMLCanvasElement}; + +@Injectable({ + providedIn: 'root' +}) +export class AiWidgetCheckService { + + constructor(private widgetService: WidgetService, + private imageService: ImageService, + private aiResources: AiResourceService) { + } + + checkScadaSymbol(link: string): Observable { + const url = link.replace(/^tb-image;/, ''); + return forkJoin({ + widgetType: this.widgetService.getWidgetType('system.scada_symbol', {ignoreLoading: true, ignoreErrors: true}), + content: this.imageService.getImageString(url) + }).pipe( + switchMap(({widgetType, content}) => { + const widget = detailsToWidgetInfo(migrateWidgetTypeToDynamicForms(widgetType as WidgetTypeDetails)); + const active = this.activeValues(parseScadaSymbolMetadataFromContent(content)); + return from(this.runSymbol(widget, link, {}).then(normal => + this.runSymbol(widget, link, active.behavior).then(activeRun => ({normal, activeRun, values: active.values})))); + }), + switchMap(({normal, activeRun, values}) => { + const report: CapturedReport = { + initialised: normal.initialised && activeRun.initialised, + rendered: !!normal.rendered && !!activeRun.rendered, + errors: [...new Set([...normal.errors, ...activeRun.errors])], + console: [...new Set([...normal.console, ...activeRun.console])], + activeValues: values, + canvas: this.sideBySide(normal.canvas, activeRun.canvas) + }; + return this.attachScreenshot(report); + }), + map(report => this.toReason(report)), + timeout(2 * RUN_TIMEOUT_MS + 15000), + catchError(error => of(this.toReason({ + initialised: false, + errors: ['The symbol could not be loaded: ' + (error?.message || error?.statusText || error)], + console: [] + }))) + ); + } + + private runSymbol(widget: WidgetInfo, link: string, behavior: Record): Promise { + const config = JSON.parse(widget.defaultConfig || '{}'); + config.showTitle = false; + config.settings = {...(config.settings || {}), scadaSymbolUrl: link, simulated: true, + scadaSymbolObjectSettings: {behavior, properties: {}}}; + return this.run({...widget, defaultConfig: JSON.stringify(config)}); + } + + private activeValues(metadata: ScadaSymbolMetadata): {behavior: Record; values: Record} { + const behavior: Record = {}; + const values: Record = {}; + for (const item of metadata?.behavior || []) { + if (item.type !== 'value') { + continue; + } + const type = String(item.valueType); + const value = type === 'BOOLEAN' ? !/animation/i.test(item.id) + : type === 'DOUBLE' || type === 'INTEGER' ? (/capacity|max/i.test(item.id) ? 100 : 60) + : type === 'STRING' ? 'Test' : null; + behavior[item.id] = {...(item.defaultGetValueSettings || {}), action: 'DO_NOTHING', defaultValue: value}; + values[item.id] = value; + } + return {behavior, values}; + } + + private sideBySide(left?: HTMLCanvasElement, right?: HTMLCanvasElement): HTMLCanvasElement | undefined { + if (!left || !right) { + return left || right; + } + const gap = 16; + const canvas = document.createElement('canvas'); + canvas.width = left.width + gap + right.width; + canvas.height = Math.max(left.height, right.height); + const context = canvas.getContext('2d'); + context.fillStyle = '#ffffff'; + context.fillRect(0, 0, canvas.width, canvas.height); + context.drawImage(left, 0, 0); + context.drawImage(right, left.width + gap, 0); + return canvas; + } + + check(widgetTypeId: string): Observable { + return this.widgetService.getWidgetTypeById(widgetTypeId, {ignoreLoading: true, ignoreErrors: true}).pipe( + map(details => detailsToWidgetInfo(migrateWidgetTypeToDynamicForms(details))), + switchMap(widget => from(this.run(widget))), + switchMap(report => this.attachScreenshot(report)), + map(report => this.toReason(report)), + timeout(RUN_TIMEOUT_MS + 15000), + catchError(error => of(this.toReason({ + initialised: false, + errors: ['The widget could not be loaded: ' + (error?.message || error?.statusText || error)], + console: [] + }))) + ); + } + + private run(widget: WidgetInfo): Promise { + return new Promise(resolve => { + const report: CapturedReport = {initialised: false, errors: [], console: []}; + const config = JSON.parse(widget.defaultConfig || '{}'); + config.title = config.title || widget.widgetName; + const frame = document.createElement('iframe'); + frame.setAttribute('aria-hidden', 'true'); + frame.style.cssText = `position:fixed;left:-${PREVIEW_WIDTH + 200}px;top:0;width:${PREVIEW_WIDTH}px;height:${PREVIEW_HEIGHT}px;border:0;visibility:visible;`; + frame.setAttribute('data-widget', JSON.stringify({...widget, defaultConfig: JSON.stringify(config)})); + let settled = false; + let settleTimer: ReturnType; + const finish = async () => { + if (settled) { + return; + } + settled = true; + clearTimeout(settleTimer); + clearTimeout(overall); + window.removeEventListener('message', onMessage); + try { + this.inspect(frame, report); + report.canvas = await this.capture(frame); + } catch (e) { + report.console.push('Inspecting the preview failed: ' + (e as Error)?.message); + } + frame.remove(); + resolve(report); + }; + const onMessage = (event: MessageEvent) => { + if (event.source !== frame.contentWindow || typeof event.data !== 'string') { + return; + } + let message: {type: string; data?: any}; + try { + message = JSON.parse(event.data); + } catch (e) { + return; + } + if (message.type === 'widgetException') { + const data = message.data || {}; + const line = data.lineNumber ? ` (line ${data.lineNumber})` : ''; + report.errors.push(this.clip(this.plain(data.message || data.name || 'Widget error') + line)); + } else if (message.type === 'widgetEditModeInited') { + report.initialised = true; + settleTimer = setTimeout(finish, SETTLE_MS); + } + }; + const overall = setTimeout(finish, RUN_TIMEOUT_MS); + window.addEventListener('message', onMessage); + frame.addEventListener('load', () => this.watchConsole(frame, report)); + frame.setAttribute('src', '/widget-editor'); + document.body.appendChild(frame); + }); + } + + private watchConsole(frame: HTMLIFrameElement, report: WidgetCheckReport) { + try { + const win = frame.contentWindow as any; + const original = win.console.error.bind(win.console); + win.console.error = (...args: any[]) => { + report.console.push(this.clip(args.map(arg => arg?.message || (typeof arg === 'string' ? arg : this.safeJson(arg))).join(' '))); + original(...args); + }; + win.addEventListener('error', (event: ErrorEvent) => report.console.push(this.clip(event.message))); + win.addEventListener('unhandledrejection', (event: PromiseRejectionEvent) => + report.console.push(this.clip('Unhandled promise rejection: ' + (event.reason?.message || event.reason)))); + } catch (e) { + report.console.push('The preview console could not be watched'); + } + } + + private inspect(frame: HTMLIFrameElement, report: WidgetCheckReport) { + const doc = frame.contentDocument; + if (!doc) { + return; + } + const errorPanel = doc.querySelector('.tb-widget-error'); + if (errorPanel?.textContent?.trim()) { + const text = this.clip(errorPanel.textContent.trim().replace(/^Widget Error:\s*/, '')); + if (!report.errors.includes(text)) { + report.errors.push(text); + } + } + report.noData = !!doc.querySelector('.tb-widget-no-data'); + report.rendered = !!doc.querySelector('tb-scada-symbol-widget svg'); + const widget = doc.querySelector('tb-widget') as HTMLElement; + if (widget) { + const rect = widget.getBoundingClientRect(); + report.width = Math.round(rect.width); + report.height = Math.round(rect.height); + } + } + + private async capture(frame: HTMLIFrameElement): Promise { + const doc = frame.contentDocument; + const win = frame.contentWindow; + const target = (doc?.querySelector('tb-widget-container') || doc?.querySelector('tb-widget')) as HTMLElement; + if (!target || !win) { + return undefined; + } + const rect = target.getBoundingClientRect(); + const width = Math.ceil(rect.width); + const height = Math.ceil(rect.height); + if (!width || !height) { + return undefined; + } + const clone = target.cloneNode(true) as HTMLElement; + const sources = [target, ...Array.from(target.querySelectorAll('*'))]; + const copies = [clone, ...Array.from(clone.querySelectorAll('*'))]; + for (let i = 0; i < sources.length; i++) { + if (i % STYLE_CHUNK === STYLE_CHUNK - 1) { + await new Promise(resolve => setTimeout(resolve)); + } + this.copyElement(win, sources[i], copies[i]); + } + const markup = new XMLSerializer().serializeToString(clone); + const svg = `` + + `${markup}`; + const image = new Image(); + image.src = 'data:image/svg+xml;charset=utf-8,' + encodeURIComponent(svg); + await image.decode(); + const canvas = document.createElement('canvas'); + canvas.width = width; + canvas.height = height; + canvas.getContext('2d').drawImage(image, 0, 0); + return canvas; + } + + private copyElement(win: Window, source: Element, copy: Element) { + const style = win.getComputedStyle(source); + let text = ''; + for (const property of Array.from(style)) { + if (!property.startsWith('--')) { + text += `${property}:${style.getPropertyValue(property)};`; + } + } + copy.setAttribute('style', text); + const glyph = source.tagName !== 'CANVAS' && ICON_FONT.test(style.fontFamily) && source.childElementCount === 0; + const image = source.tagName === 'CANVAS' ? this.canvasImage(source as HTMLCanvasElement) + : glyph ? this.glyphImage(win, source, style) : undefined; + if (glyph && !image) { + copy.setAttribute('style', text + 'visibility:hidden;'); + return; + } + if (image) { + const img = copy.ownerDocument.createElement('img'); + img.setAttribute('src', image); + img.setAttribute('style', text); + copy.replaceWith(img); + } + } + + private canvasImage(canvas: HTMLCanvasElement): string | undefined { + try { + return canvas.toDataURL(); + } catch (e) { + return undefined; + } + } + + private glyphImage(win: Window, source: Element, style: CSSStyleDeclaration): string | undefined { + const rect = source.getBoundingClientRect(); + const glyph = source.textContent?.trim(); + if (!glyph || !rect.width || !rect.height) { + return undefined; + } + const canvas = win.document.createElement('canvas'); + canvas.width = Math.ceil(rect.width); + canvas.height = Math.ceil(rect.height); + const context = canvas.getContext('2d'); + context.font = `${style.fontStyle} ${style.fontWeight} ${style.fontSize} ${style.fontFamily}`; + context.fillStyle = style.color; + context.textAlign = 'center'; + context.textBaseline = 'middle'; + context.fillText(glyph, canvas.width / 2, canvas.height / 2); + return this.canvasImage(canvas); + } + + private attachScreenshot(report: CapturedReport): Observable { + const canvas = report.canvas; + delete report.canvas; + return from(this.upload(canvas, 'widget-check.png')).pipe( + map(screenshot => { + if (screenshot) { + report.screenshot = screenshot; + } + return report; + }), + catchError(() => of(report)) + ); + } + + private upload(canvas: HTMLCanvasElement | undefined, name: string): Promise { + if (!canvas) { + return Promise.resolve(undefined); + } + return new Promise(resolve => canvas.toBlob(blob => resolve(blob), 'image/png')).then(blob => !blob ? undefined : + firstValueFrom(this.aiResources.upload(new File([blob], name, {type: 'image/png'})).pipe( + filter(event => event.type === 'done'), + take(1), + map(event => event.type === 'done' ? event.resource?.id : undefined), + catchError(() => of(undefined)) + ), {defaultValue: undefined})); + } + + private toReason(report: WidgetCheckReport): string { + const trimmed: WidgetCheckReport = {...report, errors: report.errors.slice(0, 6), console: [...new Set(report.console)].slice(0, 5)}; + let reason = JSON.stringify(trimmed); + while (reason.length > MAX_REASON_LENGTH && (trimmed.console.length || trimmed.errors.length > 1)) { + if (trimmed.console.length) { + trimmed.console.pop(); + } else { + trimmed.errors.pop(); + } + reason = JSON.stringify(trimmed); + } + return reason.length > MAX_REASON_LENGTH ? JSON.stringify({...trimmed, errors: [trimmed.errors[0]?.slice(0, 600)], console: []}) : reason; + } + + private plain(html: string): string { + const body = new DOMParser().parseFromString(html, 'text/html').body; + return (body.textContent || '').replace(/\s+/g, ' ').trim(); + } + + private clip(text: string): string { + const single = (text || '').replace(/\s+/g, ' ').trim(); + return single.length > MAX_LINE_LENGTH ? single.substring(0, MAX_LINE_LENGTH) + '…' : single; + } + + private safeJson(value: any): string { + try { + return JSON.stringify(value); + } catch (e) { + return String(value); + } + } + +} diff --git a/ui-ngx/src/app/modules/home/components/ai/ai-work-line.component.scss b/ui-ngx/src/app/modules/home/components/ai/ai-work-line.component.scss new file mode 100644 index 0000000000..fe1e9efea1 --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/ai/ai-work-line.component.scss @@ -0,0 +1,72 @@ +// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: BUSL-1.1 +:host { + display: flex; + align-items: flex-start; + gap: 8px; + font-family: var(--tb-mono); + font-size: 15px; + line-height: var(--chat-line-lh); + color: var(--tb-ink); + + tb-ai-spin { + margin-block: calc((var(--chat-line-lh) - var(--spin)) / 2); + } +} + +.say { + display: inline-block; + min-width: 0; + font-family: var(--tb-font); + font-size: var(--chat-line); + background: linear-gradient(90deg, var(--tb-ink-76) 0%, var(--tb-ink) 42%, var(--tb-ink-76) 58%, var(--tb-ink-76) 100%); + background-size: 260% 100%; + -webkit-background-clip: text; + background-clip: text; + color: transparent; + animation: k-shimmer 5s linear infinite, k-swap .2s ease-out; + + &.still { + animation: none; + background: none; + color: var(--k-faint); + } +} + +.clock { + flex: none; + white-space: nowrap; + font-family: var(--tb-mono); + font-variant-numeric: tabular-nums; + font-size: var(--chat-meta); + line-height: var(--chat-line-lh); + color: var(--k-faint); +} + +@keyframes k-shimmer { + from { + background-position: 130% 0; + } + to { + background-position: -130% 0; + } +} + +@keyframes k-swap { + from { + transform: translateY(6px); + opacity: .25; + } + to { + transform: none; + opacity: 1; + } +} + +@media (prefers-reduced-motion: reduce) { + .say { + animation: none; + background: none; + color: var(--tb-ink); + } +} diff --git a/ui-ngx/src/app/modules/home/components/ai/ai-work-line.component.ts b/ui-ngx/src/app/modules/home/components/ai/ai-work-line.component.ts new file mode 100644 index 0000000000..d5f567a735 --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/ai/ai-work-line.component.ts @@ -0,0 +1,84 @@ +// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: BUSL-1.1 +import { ChangeDetectionStrategy, Component, computed, DestroyRef, inject, input, linkedSignal, NgZone, OnInit, signal } from '@angular/core'; +import { TranslateService } from '@ngx-translate/core'; +import { AiSpinKind, aiWorkClock } from '@home/components/ai/ai-action.models'; + +const CLOCK_AFTER_MS = 10_000; +const STILL_AFTER_MS = 30_000; +const LONGER_AFTER_MS = 90_000; + +@Component({ + selector: 'tb-ai-work-line', + template: ` + + @for (words of [say()]; track words) { + {{ words }} + } + @if (tail(); as text) { + + } + `, + styleUrls: ['./ai-work-line.component.scss'], + standalone: false, + changeDetection: ChangeDetectionStrategy.OnPush, + host: { + 'role': 'status', + '[attr.aria-label]': 'say()' + } +}) +export class AiWorkLineComponent implements OnInit { + + words = input.required(); + + kind = input('think'); + + since = input(Date.now()); + + held = input(false); + + private now = signal(Date.now()); + + private elapsed = computed(() => Math.max(0, this.now() - this.since())); + + private shown = computed(() => ({words: this.words(), since: this.since()}), { + equal: (a, b) => a.words === b.words && a.since === b.since + }); + + private wordsSince = linkedSignal<{words: string; since: number}, number>({ + source: this.shown, + computation: (shown, previous) => !previous || previous.source.since !== shown.since ? shown.since : Date.now() + }); + + say = computed(() => { + const words = this.words(); + if (this.held() || this.now() - this.wordsSince() < STILL_AFTER_MS || !words) { + return words; + } + return this.translate.instant('ai-assistant.work.still', {words: words.charAt(0).toLocaleLowerCase() + words.slice(1)}); + }); + + tail = computed(() => { + if (this.held()) { + return undefined; + } + const elapsed = this.elapsed(); + const parts: string[] = []; + if (this.kind() === 'gen') { + parts.push(this.translate.instant(elapsed < LONGER_AFTER_MS ? 'ai-assistant.work.estimate-minute' : 'ai-assistant.work.taking-longer')); + } + if (elapsed >= CLOCK_AFTER_MS) { + parts.push(aiWorkClock(elapsed)); + } + return parts.join(' · ') || undefined; + }); + + private translate = inject(TranslateService); + private zone = inject(NgZone); + private destroyRef = inject(DestroyRef); + + ngOnInit(): void { + const timer = this.zone.runOutsideAngular(() => setInterval(() => this.zone.run(() => this.now.set(Date.now())), 1000)); + this.destroyRef.onDestroy(() => clearInterval(timer)); + } +} diff --git a/ui-ngx/src/app/modules/home/components/ai/ai.models.ts b/ui-ngx/src/app/modules/home/components/ai/ai.models.ts deleted file mode 100644 index 06298efabd..0000000000 --- a/ui-ngx/src/app/modules/home/components/ai/ai.models.ts +++ /dev/null @@ -1,22 +0,0 @@ -// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. -// SPDX-License-Identifier: BUSL-1.1 -export const generatedStateImages: string[] = [ - '/assets/solution-creator/building-animated.webp', - '/assets/solution-creator/catch-animated.webp', - '/assets/solution-creator/dashboard-animated.webp', - '/assets/solution-creator/forest-animated.webp', - '/assets/solution-creator/parachute-animated.webp', - '/assets/solution-creator/rocket-animated.webp' -]; - -export const dashboardGenerateImage = '/assets/solution-creator/dashboard-animated.webp'; - -export const generateDashboardSteps = [ - { text: 'solution-creator.step-reading-device-data', delay: 0 }, - { text: 'solution-creator.step-analyzing-telemetry-attributes', delay: 2000 }, - { text: 'solution-creator.step-selecting-widgets', delay: 10000 }, - { text: 'solution-creator.step-configuring-titles-units-ranges', delay: 15000 }, - { text: 'solution-creator.step-designing-layout', delay: 25000 }, - { text: 'solution-creator.step-arranging-widgets', delay: 35000 }, - { text: 'solution-creator.step-loading-adding-finishing-touches', delay: 45000 }, -] diff --git a/ui-ngx/src/app/modules/home/components/ai/ai.module.ts b/ui-ngx/src/app/modules/home/components/ai/ai.module.ts index d837940241..a85d2bcc33 100644 --- a/ui-ngx/src/app/modules/home/components/ai/ai.module.ts +++ b/ui-ngx/src/app/modules/home/components/ai/ai.module.ts @@ -3,48 +3,94 @@ import { NgModule } from '@angular/core'; import { CommonModule } from '@angular/common'; import { SharedModule } from '@shared/shared.module'; -import { AiPromptInputComponent } from '@home/components/ai/ai-prompt-input.component'; +import { AiComposerModule } from '@home/components/ai/ai-composer.module'; import { AiAssistantPanelComponent } from '@home/components/ai/ai-assistant-panel.component'; import { AiChatMessagesComponent } from '@home/components/ai/ai-chat-messages.component'; +import { AiChatComponent } from '@home/components/ai/ai-chat.component'; import { AiApprovalCardComponent } from '@home/components/ai/ai-approval-card.component'; -import { AiRenameDialogComponent } from '@home/components/ai/ai-rename-dialog.component'; -import { AiCreditsComponent } from '@home/components/ai/ai-credits.component'; -import { AiCreditsPopupComponent } from '@home/components/ai/ai-credits-popup.component'; -import { AiLoadingModalComponent } from '@home/components/ai/ai-loading-modal.component'; -import { AiNoTelemetryModalComponent } from '@home/components/ai/ai-no-telemetry-modal.component'; -import { AiAttachmentsComponent } from '@home/components/ai/ai-attachments.component'; -import { AiAttachmentPreviewDialogComponent } from '@home/components/ai/ai-attachment-preview-dialog.component'; -import { AiTipDirective } from '@home/components/ai/ai-tip.directive'; +import { AiCreditsOutComponent } from '@home/components/ai/ai-credits-out.component'; +import { AiLimitOutComponent } from '@home/components/ai/ai-limit-out.component'; +import { AiLoadLinesComponent } from '@home/components/ai/ai-load-lines.component'; +import { AiChatTitleComponent } from '@home/components/ai/ai-chat-title.component'; +import { AiWorkLineComponent } from '@home/components/ai/ai-work-line.component'; +import { AiActionLineComponent } from '@home/components/ai/ai-action-line.component'; +import { AiActionDetailComponent } from '@home/components/ai/ai-action-detail.component'; +import { AiRunSummaryComponent } from '@home/components/ai/ai-run-summary.component'; +import { AiStartedFromComponent } from '@home/components/ai/ai-started-from.component'; +import { AiRecordComponent } from '@home/components/ai/ai-record.component'; +import { AiRecordCardComponent } from '@home/components/ai/ai-record-card.component'; +import { AiRecordsComponent } from '@home/components/ai/ai-records.component'; +import { AiCardActionsComponent } from '@home/components/ai/ai-card-actions.component'; +import { AiDisclosureComponent } from '@home/components/ai/ai-disclosure.component'; +import { AiQuestionComponent } from '@home/components/ai/ai-question.component'; +import { AiNumberFieldComponent } from '@home/components/ai/ai-number-field.component'; +import { AiSecretFieldComponent } from '@home/components/ai/ai-secret-field.component'; +import { AiColorFieldComponent } from '@home/components/ai/ai-color-field.component'; +import { AiDatePanelComponent } from '@home/components/ai/ai-date-panel.component'; +import { AiStepMarkComponent } from '@home/components/ai/ai-step-mark.component'; +import { AiPlanComponent } from '@home/components/ai/ai-plan.component'; +import { AiHandOverComponent } from '@home/components/ai/ai-hand-over.component'; +import { AiArtifactPaneComponent } from '@home/components/ai/ai-artifact-pane.component'; +import { AiFileBodyComponent } from '@home/components/ai/ai-file-body.component'; @NgModule({ declarations: [ - AiPromptInputComponent, AiAssistantPanelComponent, + AiChatComponent, AiChatMessagesComponent, AiApprovalCardComponent, - AiRenameDialogComponent, - AiCreditsComponent, - AiCreditsPopupComponent, - AiLoadingModalComponent, - AiNoTelemetryModalComponent, - AiAttachmentsComponent, - AiAttachmentPreviewDialogComponent, - AiTipDirective + AiCreditsOutComponent, + AiLimitOutComponent, + AiWorkLineComponent, + AiActionLineComponent, + AiActionDetailComponent, + AiRunSummaryComponent, + AiStartedFromComponent, + AiRecordComponent, + AiRecordCardComponent, + AiRecordsComponent, + AiCardActionsComponent, + AiDisclosureComponent, + AiQuestionComponent, + AiNumberFieldComponent, + AiSecretFieldComponent, + AiColorFieldComponent, + AiDatePanelComponent, + AiStepMarkComponent, + AiPlanComponent, + AiHandOverComponent, + AiArtifactPaneComponent, + AiFileBodyComponent, + AiLoadLinesComponent, + AiChatTitleComponent ], imports: [ CommonModule, - SharedModule + SharedModule, + AiComposerModule ], exports: [ - AiPromptInputComponent, + AiComposerModule, + AiLoadLinesComponent, + AiChatTitleComponent, + AiWorkLineComponent, + AiRunSummaryComponent, AiAssistantPanelComponent, + AiChatComponent, AiChatMessagesComponent, AiApprovalCardComponent, - AiRenameDialogComponent, - AiCreditsComponent, - AiLoadingModalComponent, - AiNoTelemetryModalComponent, - AiAttachmentsComponent + AiCreditsOutComponent, + AiLimitOutComponent, + AiQuestionComponent, + AiPlanComponent, + AiHandOverComponent, + AiArtifactPaneComponent, + AiFileBodyComponent, + AiRecordComponent, + AiRecordCardComponent, + AiRecordsComponent, + AiCardActionsComponent, + AiDisclosureComponent ] }) export class AiModule {} diff --git a/ui-ngx/src/app/modules/home/components/ai/solution/pane/solution-dashboards.component.html b/ui-ngx/src/app/modules/home/components/ai/solution/pane/solution-dashboards.component.html new file mode 100644 index 0000000000..4a24e86361 --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/ai/solution/pane/solution-dashboards.component.html @@ -0,0 +1,34 @@ + +
+ @if (dashboards.length > 1) { +
+ @for (dashboard of dashboards; track dashboard.name; let index = $index) { + + } +
+ } +
+ @for (dashboard of dashboards; track dashboard.name; let index = $index) { +
+
+ +
+

{{ dashboard.name }}

+ {{ dashboard.assignedTo }} +
+
+ @if (dashboard.overview) { +

{{ dashboard.overview }}

+ } + +
+ } @empty { +

{{ 'solution-creator.pane.no-dashboards' | translate }}

+ } +
+
diff --git a/ui-ngx/src/app/modules/home/components/ai/solution/pane/solution-dashboards.component.scss b/ui-ngx/src/app/modules/home/components/ai/solution/pane/solution-dashboards.component.scss new file mode 100644 index 0000000000..ac9767e0fe --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/ai/solution/pane/solution-dashboards.component.scss @@ -0,0 +1,46 @@ +// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: BUSL-1.1 +.sol-dash { + padding: 16px var(--art-x) 8px; + + & + .sol-dash { + border-top: 1px solid var(--tb-line); + } +} + +.sol-dash-head { + display: flex; + align-items: flex-start; + gap: 10px; + + > .mat-icon { + flex: none; + margin-top: 2px; + color: var(--entity-view-fg); + } + + h3 { + margin: 0; + font: 500 var(--chat-head)/var(--chat-head-lh) var(--tb-font); + color: var(--tb-ink); + } + + small { + display: block; + font-size: var(--chat-meta); + line-height: var(--chat-meta-lh); + color: var(--tb-ink-60); + } +} + +.sol-dash-lead { + margin: 10px 0 0; + font-size: var(--chat-line); + line-height: var(--chat-line-lh); + color: var(--tb-ink-76); +} + +.sol-dash-doc { + display: block; + margin-top: 4px; +} diff --git a/ui-ngx/src/app/modules/home/components/ai/solution/pane/solution-dashboards.component.ts b/ui-ngx/src/app/modules/home/components/ai/solution/pane/solution-dashboards.component.ts new file mode 100644 index 0000000000..d520c1f995 --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/ai/solution/pane/solution-dashboards.component.ts @@ -0,0 +1,83 @@ +// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: BUSL-1.1 +import { AfterViewInit, ChangeDetectionStrategy, Component, ElementRef, inject, Input, OnDestroy, signal } from '@angular/core'; +import { DashboardsOverview } from '@shared/models/solution-creator.models'; + +@Component({ + changeDetection: ChangeDetectionStrategy.OnPush, + selector: 'tb-solution-dashboards', + templateUrl: './solution-dashboards.component.html', + styleUrls: ['./solution-pane.scss', './solution-dashboards.component.scss'], + standalone: false +}) +export class SolutionDashboardsComponent implements AfterViewInit, OnDestroy { + + @Input({required: true}) dashboards: DashboardsOverview[] = []; + + readonly markdownStyles = [ + '.tb-markdown-view h1, .tb-markdown-view h2, .tb-markdown-view h3 { display: none; }', + '.tb-markdown-view h4, .tb-markdown-view h5 { font-size: 14px; line-height: 20px; font-weight: 500; margin: 16px 0 6px; padding: 0; }', + '.tb-markdown-view p, .tb-markdown-view li { font-size: 14px; line-height: 20px; padding: 0; }', + '.tb-markdown-view ul, .tb-markdown-view ol { padding-left: 20px; margin: 0; }' + ]; + + active = signal(0); + + wide = signal(false); + + private host = inject>(ElementRef); + private resize: ResizeObserver; + private scroller: HTMLElement | null = null; + private scrollListener = () => this.onScroll(); + + ngAfterViewInit(): void { + this.resize = new ResizeObserver(() => this.wide.set(this.host.nativeElement.clientWidth >= 660 && this.dashboards?.length > 1)); + this.resize.observe(this.host.nativeElement); + this.scroller = this.host.nativeElement.closest('.art-pane-body') as HTMLElement; + this.scroller?.addEventListener('scroll', this.scrollListener, {passive: true}); + } + + ngOnDestroy(): void { + this.resize?.disconnect(); + this.scroller?.removeEventListener('scroll', this.scrollListener); + } + + details(dashboard: DashboardsOverview): string { + const description = dashboard.description ?? ''; + if (!dashboard.overview) { + return description; + } + const lines = description.split('\n'); + const start = lines.findIndex(line => /^\s*(#{4,}\s|[-*+]\s|\d+[.)]\s|\*\*[^*]+\*\*:?\s*$)/.test(line)); + return start > 0 ? lines.slice(start).join('\n') : description; + } + + goTo(index: number): void { + this.active.set(index); + const target = this.host.nativeElement.querySelector(`[data-dash="${index}"]`) as HTMLElement; + if (target && this.scroller) { + const tabs = this.wide() ? 0 : (this.host.nativeElement.querySelector('.sol-tabs') as HTMLElement)?.offsetHeight ?? 0; + this.scroller.scrollTo({ + top: this.scroller.scrollTop + target.getBoundingClientRect().top - this.scroller.getBoundingClientRect().top - tabs, + behavior: 'smooth' + }); + } + } + + private onScroll(): void { + if (!this.scroller) { + return; + } + const top = this.scroller.getBoundingClientRect().top + (this.wide() ? 8 : 60); + let current = 0; + this.dashboards.forEach((_, index) => { + const el = this.host.nativeElement.querySelector(`[data-dash="${index}"]`) as HTMLElement; + if (el && el.getBoundingClientRect().top <= top) { + current = index; + } + }); + if (current !== this.active()) { + this.active.set(current); + } + } +} diff --git a/ui-ngx/src/app/modules/home/components/ai/solution/pane/solution-installed.component.html b/ui-ngx/src/app/modules/home/components/ai/solution/pane/solution-installed.component.html new file mode 100644 index 0000000000..3289cdf830 --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/ai/solution/pane/solution-installed.component.html @@ -0,0 +1,134 @@ + +@if (creating()) { +} @else if (installed() && !bannerClosed()) { +
+ +
+ {{ 'solution-creator.pane.installed' | translate }} + {{ 'solution-creator.pane.installed-line' | translate: {entities: entityCount(), dashboards: dashboardCount()} }} +
+ @if (hasMain()) { + + } + +
+} @else if (!installed()) { +

{{ 'solution-creator.pane.not-installed' | translate }}

+} +
+ @for (section of sections(); track section.id) { +
+

+ @if (section.link) { + + {{ section.title | translate }} + + } @else { + {{ section.title | translate }} + } +

+
+ + + @for (row of section.rows; track row.key) { + + + @switch (section.id) { + @case ('dashboards') { + + + } + @case ('users') { + + + } + @case ('profiles') { + + } + @case ('roles') { + + } + @case ('alarms') { + + } + @case ('cfs') { + } + @default { + + } + } + + + } + +
+ @if (link(row.type, row); as url) { + + {{ row.primary.additionalData?.name }} + + } @else { + + {{ row.primary.additionalData?.name }} + + } + {{ row.details.role }} + + @if (link(row.type, row); as url) { + + open_in_new{{ 'solution-creator.pane.open' | translate }} + + } + @if (canViewAs(row)) { + + } + + {{ row.details.role }}{{ row.details.where }}{{ row.details.kindLabel }} +
+ @for (op of row.details.ops ?? []; track op) { + {{ op }} + } +
+
+
+ @for (severity of row.details.severities ?? []; track severity) { + + {{ severityLabel(severity) | translate }} + + } +
+
+ @if (row.details.chip; as chip) { + {{ chip.label }} + } + + @if (row.progress === 'wait') { + + } @else if (row.progress === 'now') { + + + + } @else { + + {{ statusIcon(row) }} + + } +
+ } @empty { +

{{ 'solution-creator.pane.nothing-created' | translate }}

+ } +
diff --git a/ui-ngx/src/app/modules/home/components/ai/solution/pane/solution-installed.component.scss b/ui-ngx/src/app/modules/home/components/ai/solution/pane/solution-installed.component.scss new file mode 100644 index 0000000000..5a47c2b3ef --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/ai/solution/pane/solution-installed.component.scss @@ -0,0 +1,198 @@ +// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: BUSL-1.1 +.sol-done { + position: sticky; + top: 0; + z-index: 2; + display: flex; + align-items: center; + gap: 16px; + padding: 22px calc(var(--art-x) + 36px) 22px var(--art-x); + background: linear-gradient(90deg in oklab, + color-mix(in oklab, var(--ai-light-teal) 42%, var(--tb-surface)) 0%, + color-mix(in oklab, var(--ai-light-aqua) 26%, var(--tb-surface)) 48%, + var(--tb-surface) 100%); +} + +.sol-done-mark { + --ai-mark-fill: linear-gradient(var(--tb-surface), var(--tb-surface)); + --ai-mark-edge: inset 0 0 0 1px color-mix(in srgb, var(--tb-ink) 10%, transparent), 0 1px 2px rgb(16 24 40 / 0.06); + --ai-mark-ink: var(--tb-ok); + --ai-mark-ink-fill: linear-gradient(var(--tb-ok), var(--tb-ok)); + animation: none; +} + +.sol-done-t { + flex: 1; + display: grid; + gap: 2px; + min-width: 0; + + b { + font: 500 var(--chat-head)/var(--chat-head-lh) var(--tb-font); + color: var(--tb-ink); + } + + span { + font-size: var(--chat-line); + line-height: var(--chat-line-lh); + color: var(--tb-ink-76); + } +} + +.sol-done-go { + flex: none; + --mat-button-filled-container-color: var(--ai-action); + --mat-button-filled-label-text-color: var(--ai-on-action); +} + +.sol-done-x { + position: absolute; + top: 8px; + right: 8px; + width: 32px; + height: 32px; + padding: 0; + border: 0; + border-radius: 8px; + background: none; + color: var(--tb-ink-54); + display: inline-flex; + align-items: center; + justify-content: center; + cursor: pointer; + + &:hover { + background: rgba(0, 0, 0, 0.06); + color: var(--tb-ink); + } +} + +.sol-not-installed { + margin: 0; + padding: 16px var(--art-x) 0; + font-size: var(--chat-line); + line-height: var(--chat-line-lh); + color: var(--tb-ink-76); +} + +.sol-installed-table { + table-layout: fixed; + + td.sol-installed-name { + width: 44%; + } + + td.act { + width: 170px; + } + + td.stc { + width: 44px; + } + + td code.k-ent, td .k-sev, td .sol-op { + vertical-align: baseline; + } + +} + +.sol-acts { + display: inline-flex; + gap: 2px; +} + +.sol-act.mat-mdc-button { + height: 36px; + margin: -8px 0 -6px; + padding: 0 8px; + gap: 8px; + border: 1px solid transparent; + line-height: 36px; + --mat-button-text-label-text-color: var(--tb-ink-76); + + .mat-icon { + font-size: 18px; + width: 18px; + height: 18px; + margin: 0 0 0 -4px; + } +} + +:host.narrow .sol-acts { + flex-direction: column; + align-items: flex-start; + gap: 8px; +} + +:host.narrow .sol-installed-table { + table-layout: auto; + + td.sol-installed-name { + width: auto; + } + + td.act { + width: 1px; + } +} + +.sol-st { + display: inline-flex; + align-items: center; + justify-content: center; + box-sizing: border-box; + width: 18px; + height: 18px; + margin-top: 1px; + border-radius: 50%; + color: var(--tb-surface); + cursor: default; + + .mat-icon { + font-size: 13px; + width: 13px; + height: 13px; + line-height: 13px; + font-weight: 500; + } + + &.wait { border: 1.5px solid var(--tb-ink-38); } + &.now { color: var(--ai-teal-500); } + &.ok { background: var(--tb-ok); } + &.warn { background: var(--tb-caution); } + &.error { background: var(--tb-crit); } + + &:focus-visible { + outline: 2px solid var(--ai-focus); + outline-offset: 1px; + } +} + +.sol-infos.creating tbody tr { + animation: sol-row-in .2s cubic-bezier(.2, 0, 0, 1); +} + +@keyframes sol-row-in { + from { + opacity: 0; + } + + to { + opacity: 1; + } +} + +@media (prefers-reduced-motion: reduce) { + .sol-infos.creating tbody tr { + animation: none; + } +} + +.sol-st.now tb-ai-spin { + --spin: 18px; +} + +tr.waiting > td:not(.stc) { + opacity: .42; +} diff --git a/ui-ngx/src/app/modules/home/components/ai/solution/pane/solution-installed.component.ts b/ui-ngx/src/app/modules/home/components/ai/solution/pane/solution-installed.component.ts new file mode 100644 index 0000000000..fc419a23f8 --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/ai/solution/pane/solution-installed.component.ts @@ -0,0 +1,322 @@ +// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: BUSL-1.1 +import { roleOperations } from './solution-overview.component'; +import { ChangeDetectionStrategy, Component, computed, DestroyRef, ElementRef, EventEmitter, inject, input, Output, signal } from '@angular/core'; +import { TranslateService } from '@ngx-translate/core'; +import { AuthService } from '@core/auth/auth.service'; +import { EntityResult, SolutionCreatorInfo, SolutionInstallProgress, SolutionProgressItem } from '@shared/models/solution-creator.models'; +import { + baseDetailsPageByEntityType, + EntityType, + entityTypeTranslations, + groupUrlPrefixByEntityType +} from '@shared/models/entity-type.models'; +import { AlarmSeverity, alarmSeverityColors, alarmSeverityTranslations } from '@shared/models/alarm.models'; +import { aiEntityKind } from '@home/components/ai/ai-action.models'; +import { + AggregatedEntityResult, + aggregateByName, + IssueStatus +} from '@home/components/ai/solution/solution-info/issues-aggregation'; + +interface InstalledSection { + id: string; + title: string; + link: string | null; + rows: InstalledRow[]; +} + +interface RowChip { + label: string; + icon: string; + palette: string; +} + +interface RowDetails { + role?: string; + where?: string; + chip?: RowChip; + kindLabel?: string; + ops?: string[]; + severities?: AlarmSeverity[]; +} + +type InstalledRow = AggregatedEntityResult & { + type: EntityType; + icon: string; + palette: string; + details: RowDetails; + progress?: 'wait' | 'now'; +}; + +interface SectionSpec { + id: string; + types: EntityType[]; + title: string; + link: string | null; +} + +const GROUPS: SectionSpec[] = [ + {id: 'dashboards', types: [EntityType.DASHBOARD], title: 'entity.type-dashboards', link: '/dashboards/all'}, + {id: 'devices', types: [EntityType.DEVICE], title: 'entity.type-devices', link: '/entities/devices/all'}, + {id: 'assets', types: [EntityType.ASSET], title: 'entity.type-assets', link: '/entities/assets/all'}, + {id: 'customers', types: [EntityType.CUSTOMER], title: 'entity.type-customers', link: '/customers/all'}, + {id: 'users', types: [EntityType.USER], title: 'entity.type-users', link: '/users/all'}, + {id: 'profiles', types: [EntityType.DEVICE_PROFILE, EntityType.ASSET_PROFILE], title: 'solution-creator.pane.profiles', link: '/profiles/deviceProfiles'}, + {id: 'roles', types: [EntityType.ROLE], title: 'entity.type-roles', link: '/security-settings/roles'}, + {id: 'groups', types: [EntityType.ENTITY_GROUP], title: 'entity.type-entity-groups', link: null}, + {id: 'cfs', types: [EntityType.CALCULATED_FIELD], title: 'entity.type-calculated-fields', link: '/calculatedFields'}, + {id: 'alarms', types: [EntityType.ALARM], title: 'solution-creator.pane.alarm-rules', link: '/alarms/alarm-rules'}, + {id: 'chains', types: [EntityType.RULE_CHAIN], title: 'entity.type-rulechains', link: null} +]; + + +const SECTIONS: EntityType[] = GROUPS.flatMap(group => group.types); + +const SUPPORTING: EntityType[] = [EntityType.ENTITY_GROUP, EntityType.RULE_CHAIN]; + +const GENERATED: EntityType[] = [EntityType.DEVICE, EntityType.ASSET, EntityType.CUSTOMER, EntityType.USER]; + +const STEP_MS = 160; + +@Component({ + changeDetection: ChangeDetectionStrategy.OnPush, + selector: 'tb-solution-installed', + templateUrl: './solution-installed.component.html', + styleUrls: ['./solution-pane.scss', './solution-installed.component.scss'], + standalone: false, + host: { + '[class.narrow]': 'narrow()' + } +}) +export class SolutionInstalledComponent { + + solution = input.required(); + creating = input(false); + items = input(null); + stage = input(null); + createShare = input(0.85); + seconds = input(90); + startedAt = input(0); + + @Output() openMain = new EventEmitter(); + + private translate = inject(TranslateService); + private authService = inject(AuthService); + + bannerClosed = signal(false); + + narrow = signal(false); + + private shown = signal(-1); + private elapsed = signal(0); + + private planned = computed(() => { + const items = this.items() ?? []; + return SECTIONS.flatMap(type => items.filter(item => item.type === type)); + }); + + private target = computed(() => { + const planned = this.planned(); + if (!planned.length) { + return 0; + } + const share = this.createShare(); + const install = this.stage() === 'INSTALL'; + const ready = planned.filter(item => install ? item.state === 'DONE' : item.state !== 'WORKING').length / planned.length; + let count = Math.floor(planned.length * (install ? share + (1 - share) * ready : share * ready)); + const pending = planned.findIndex(item => !item.name); + if (!install && pending >= 0) { + count = Math.min(count, pending); + } else if (!install && !planned.some(item => GENERATED.includes(item.type))) { + count = Math.min(count, Math.max(0, planned.filter(item => item.type === EntityType.DASHBOARD).length - 1)); + } + const paced = Math.floor(planned.length * this.elapsed() / Math.max(1, this.seconds())); + return Math.min(count, paced, planned.length - 1); + }); + + constructor() { + const created = Date.now(); + const timer = setInterval(() => { + this.elapsed.set((Date.now() - (this.startedAt() || created)) / 1000); + const target = this.target(); + if (this.shown() < 0) { + this.shown.set(target); + } else if (this.shown() < target) { + this.shown.update(count => count + 1); + } + }, STEP_MS); + const host = inject>(ElementRef).nativeElement; + const resize = new ResizeObserver(() => this.narrow.set(host.clientWidth <= 560)); + resize.observe(host); + inject(DestroyRef).onDestroy(() => { + clearInterval(timer); + resize.disconnect(); + }); + } + + installed = computed(() => !!this.solution()?.metadata?.installed); + + sections = computed(() => { + const results = this.solution()?.metadata?.installResult?.entityResults; + const items = this.items(); + if (items?.length) { + return this.plannedSections(items, results ?? {}); + } + if (!results) { + return []; + } + return this.grouped(type => aggregateByName(type, results[type]) + .filter(row => !SUPPORTING.includes(type) || row.status !== IssueStatus.OK) + .map(row => this.row(type, row))); + }); + + entityCount = computed(() => this.sections() + .filter(section => section.id !== 'dashboards') + .reduce((count, section) => count + section.rows.length, 0)); + + dashboardCount = computed(() => this.sections().find(section => section.id === 'dashboards')?.rows.length ?? 0); + + hasMain = computed(() => !!this.solution()?.metadata?.installResult?.mainDashboardId); + + private plannedSections(items: SolutionProgressItem[], results: Partial>): InstalledSection[] { + const shown = Math.max(0, this.shown()); + const install = this.stage() === 'INSTALL'; + let index = 0; + return this.grouped(type => { + const created = aggregateByName(type, results[type]); + return items.filter(item => item.type === type).map(item => { + const position = index++; + const result = item.name ? created.find(row => row.primary?.additionalData?.name === item.name) : undefined; + if (position < shown && install && result && item.state === 'DONE') { + return this.row(type, result, item); + } + const name = item.name ?? this.translate.instant('solution-creator.pane.pending-' + type, {profile: item.profile}); + return this.row(type, { + key: item.name ? `${type}:${item.name}` : `${type}:pending:${item.profile}`, + primary: {additionalData: {name}} as EntityResult, + status: IssueStatus.OK, + errors: [], + warnings: [] + }, item, position < shown ? undefined : position === shown ? 'now' : 'wait'); + }); + }); + } + + private grouped(rowsOf: (type: EntityType) => InstalledRow[]): InstalledSection[] { + return GROUPS + .map(group => ({id: group.id, title: group.title, link: group.link, rows: group.types.flatMap(type => rowsOf(type))})) + .filter(section => section.rows.length); + } + + private row(type: EntityType, row: AggregatedEntityResult, item?: SolutionProgressItem, progress?: 'wait' | 'now'): InstalledRow { + const kind = aiEntityKind(type === EntityType.ALARM ? 'ALARM_RULE' : type === EntityType.ROLE ? EntityType.USER : type); + const details = item && !item.name ? {} : this.detailsOf(type, row.primary?.additionalData ?? {}, item); + return {...row, type, icon: kind.icon, palette: kind.palette, details, progress}; + } + + private detailsOf(type: EntityType, data: Record, item?: SolutionProgressItem): RowDetails { + const solution = this.solution()?.data; + const name: string = item?.name ?? data.name; + switch (type) { + case EntityType.DASHBOARD: + return {role: solution?.dashboardsOverview?.find(dashboard => dashboard.name === name)?.assignedTo}; + case EntityType.DEVICE: + case EntityType.ASSET: + case EntityType.CUSTOMER: { + const profile = item?.profile ?? data.type ?? this.entityOf(type, name)?.profile; + const chipKind = aiEntityKind(type === EntityType.DEVICE ? EntityType.DEVICE_PROFILE : type); + return profile ? {chip: {label: profile, icon: chipKind.icon, palette: chipKind.palette}} : {}; + } + case EntityType.USER: { + const user = this.entityOf(type, name); + const customer = item ? item.customer : (data.customer ?? user?.customer); + return {role: item?.profile ?? user?.profile, where: customer || this.translate.instant('tenant.tenant')}; + } + case EntityType.DEVICE_PROFILE: + return {kindLabel: this.translate.instant('entity.type-device')}; + case EntityType.ASSET_PROFILE: + return {kindLabel: this.translate.instant('entity.type-asset')}; + case EntityType.ROLE: { + const permissions = solution?.solutionDescriptor?.iam?.find(role => role.name === name)?.permissions ?? ''; + const operations = roleOperations(permissions); + return {ops: operations.length ? [this.translate.instant('solution-creator.pane.all-resources'), + ...operations.map(operation => this.translate.instant('solution-creator.pane.op-' + operation))] : []}; + } + case EntityType.ALARM: + return {severities: data.severities?.length ? data.severities + : solution?.solutionDescriptor?.alarms?.find(alarm => alarm.alarmName === name)?.severities ?? []}; + default: + return {}; + } + } + + private entityOf(type: EntityType, name: string): Record | undefined { + const entities = this.solution()?.data?.entities; + const list: Array> = type === EntityType.DEVICE ? entities?.devices + : type === EntityType.ASSET ? entities?.assets + : type === EntityType.CUSTOMER ? entities?.customers + : type === EntityType.USER ? entities?.users : null; + return list?.find(entity => type === EntityType.USER + ? [[entity.firstName, entity.lastName].filter(Boolean).join(' '), entity.email].includes(name) + : entity.name === name); + } + + link(type: EntityType, row: AggregatedEntityResult): string | null { + const entity = row.primary; + if (!entity?.id?.id || row.status === IssueStatus.ERROR) { + return null; + } + if (type === EntityType.ENTITY_GROUP) { + const prefix = groupUrlPrefixByEntityType.get(entity.additionalData?.groupType as EntityType); + return prefix ? `${prefix}/${entity.id.id}` : null; + } + const base = baseDetailsPageByEntityType.get(entity.id.entityType as EntityType); + return base ? `${base}/${entity.id.id}` : null; + } + + severityColor(severity: AlarmSeverity): string { + return alarmSeverityColors.get(severity) ?? null; + } + + severityLabel(severity: AlarmSeverity): string { + return alarmSeverityTranslations.get(severity) ?? severity; + } + + statusIcon(row: AggregatedEntityResult): string { + return row.status === IssueStatus.ERROR ? 'close' : row.status === IssueStatus.WARN ? 'priority_high' : 'check'; + } + + statusTone(row: AggregatedEntityResult): string { + return row.status === IssueStatus.ERROR ? 'error' : row.status === IssueStatus.WARN ? 'warn' : 'ok'; + } + + statusTip(row: AggregatedEntityResult): string { + const word = this.translate.instant('solution-creator.pane.status-' + this.statusTone(row)); + const messages = [...row.errors, ...row.warnings].map(entry => entry.error?.message).filter(Boolean); + if (!messages.length) { + return word; + } + return row.status === IssueStatus.WARN ? messages.join('; ') : `${word}: ${messages.join('; ')}`; + } + + severityTone(severity: AlarmSeverity): string { + return (severity ?? '').toLowerCase(); + } + + canViewAs(row: AggregatedEntityResult): boolean { + return !!row.primary?.additionalData?.userId && row.status !== IssueStatus.ERROR; + } + + viewAs(row: AggregatedEntityResult): void { + const entity: EntityResult = row.primary; + const userId = entity.additionalData.userId; + const tenantUser = !this.findUser(userId)?.additionalData?.customer; + this.authService.redirectUrl = tenantUser ? `/dashboards/all/${entity.id.id}` : `/dashboards/${entity.id.id}`; + this.authService.loginAsUser(userId).subscribe(() => {}); + } + + private findUser(userId: string): EntityResult | undefined { + return this.solution()?.metadata?.installResult?.entityResults?.[EntityType.USER]?.find(user => user.id?.id === userId); + } +} diff --git a/ui-ngx/src/app/modules/home/components/ai/solution/pane/solution-json.component.html b/ui-ngx/src/app/modules/home/components/ai/solution/pane/solution-json.component.html new file mode 100644 index 0000000000..b7f9d7f10b --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/ai/solution/pane/solution-json.component.html @@ -0,0 +1,8 @@ + + diff --git a/ui-ngx/src/app/modules/home/components/ai/solution/pane/solution-json.component.scss b/ui-ngx/src/app/modules/home/components/ai/solution/pane/solution-json.component.scss new file mode 100644 index 0000000000..e09b2e6757 --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/ai/solution/pane/solution-json.component.scss @@ -0,0 +1,15 @@ +// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: BUSL-1.1 +:host { + display: flex; + flex-direction: column; + min-height: 0; +} + +tb-ai-file-body { + --art-x: 16px; + flex: 1; + min-height: 0; + display: flex; + flex-direction: column; +} diff --git a/ui-ngx/src/app/modules/home/components/ai/solution/pane/solution-json.component.ts b/ui-ngx/src/app/modules/home/components/ai/solution/pane/solution-json.component.ts new file mode 100644 index 0000000000..10b36b200f --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/ai/solution/pane/solution-json.component.ts @@ -0,0 +1,59 @@ +// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: BUSL-1.1 +import { ChangeDetectionStrategy, Component, computed, EventEmitter, input, Output, viewChild } from '@angular/core'; +import { AiFile, aiFileOf } from '@home/components/ai/ai-file.models'; +import { AiFileBodyComponent, AiFileSaver } from '@home/components/ai/ai-file-body.component'; + +@Component({ + changeDetection: ChangeDetectionStrategy.OnPush, + selector: 'tb-solution-json', + templateUrl: './solution-json.component.html', + styleUrls: ['./solution-json.component.scss'], + standalone: false +}) +export class SolutionJsonComponent { + + value = input(null); + + fileName = input('solution.json'); + + wrap = input(false); + + whitespace = input(false); + + @Output() applied = new EventEmitter(); + + @Output() discarded = new EventEmitter(); + + body = viewChild.required(AiFileBodyComponent); + + file = computed(() => aiFileOf('solution-json::' + this.fileName(), + {name: this.fileName(), content: JSON.stringify(this.value() ?? null, null, 2) + '\n'})); + + error = computed(() => { + const body = this.body(); + if (!body.editing()) { + return ''; + } + try { + JSON.parse(body.draft()); + return ''; + } catch (e) { + return (e as Error).message; + } + }); + + readonly saver: AiFileSaver = content => { + try { + this.applied.emit(JSON.parse(content)); + return Promise.resolve(true); + } catch { + return Promise.resolve(false); + } + }; + + text(): string { + const body = this.body(); + return body.editing() ? body.draft() : this.file().content; + } +} diff --git a/ui-ngx/src/app/modules/home/components/ai/solution/pane/solution-overview.component.html b/ui-ngx/src/app/modules/home/components/ai/solution/pane/solution-overview.component.html new file mode 100644 index 0000000000..871ee4af02 --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/ai/solution/pane/solution-overview.component.html @@ -0,0 +1,287 @@ + +
+
+ @for (section of sections(); track section.id) { + + } +
+
+
+

{{ 'solution-creator.pane.profiles' | translate }}

+
+ + +
+
+ @if (mode() === 'list') { + + + + + + + + + + + @for (profile of profiles; track profile.name + profile.entityType) { + @let key = 'profile:' + profile.entityType + ':' + profile.name; + + + + + + + @if (open() === key) { + + + + } + } + +
{{ 'solution-creator.pane.name' | translate }}{{ 'solution-creator.pane.type' | translate }}{{ 'solution-creator.pane.data' | translate }}
+ + @if (profile.name?.trim()) {{{ profile.name }}} @else {{{ typeLabel(profile) }} {{ $index + 1 }}} + + {{ typeLabel(profile) }}{{ dataOf(profile) }}expand_more
+ +
+ } @else { +
+ + + + + + + + + + {{ cluster.label }} + + + + + + + + + + + @if (link.label) { + +
{{ link.label }}
+
+ } +
+
+
+
+ @if (schemaEntity(); as entity) { +
+
+ {{ entity.name }} +
+ +
+ } + } + +

{{ 'solution-creator.pane.roles' | translate }}

+ @if (descriptor?.iam?.length) { + + + + + + + + + + @for (iam of descriptor.iam; track iam.name) { + + + + + + } + +
{{ 'solution-creator.pane.role' | translate }}{{ 'solution-creator.pane.operations' | translate }}{{ 'solution-creator.pane.on' | translate }}
+ {{ iam.name }} + +
+ @if (operations(iam).length) { + {{ 'solution-creator.pane.all-resources' | translate }} + } + @for (operation of operations(iam); track operation) { + {{ ('solution-creator.pane.op-' + operation) | translate }} + } @empty { + {{ iam.permissions || '—' }} + } +
+
{{ iam.description }}
+ } @else { +

{{ 'solution-creator.pane.no-roles' | translate }}

+ } + +

{{ 'solution-creator.pane.calculated-fields' | translate }}

+ @if (descriptor?.metrics?.length) { + + + + + + + + + @for (metric of descriptor.metrics; track metric.calculatedFieldName) { + + + + + } + +
{{ 'solution-creator.pane.name' | translate }}{{ 'solution-creator.pane.calculates' | translate }}
+ + {{ metric.calculatedFieldName }} + + @if (metric.profileName) { +
+ {{ metric.profileName }} +
+ } +
{{ metric.calculation }}
+ } @else { +

{{ 'solution-creator.pane.no-calculated-fields' | translate }}

+ } + +

{{ 'solution-creator.pane.alarms' | translate }}

+ @if (descriptor?.alarms?.length) { + + + + + + + + + + @for (alarm of descriptor.alarms; track alarm.alarmName) { + @let key = alarmKey(alarm); + + + + + + @if (open() === key) { + + + + } + } + +
{{ 'solution-creator.pane.alarm-rule' | translate }}{{ 'solution-creator.pane.severity' | translate }}
+ + {{ alarm.alarmName }} + + @if (alarm.condition) { +
{{ alarm.condition }}
+ } +
+
+ @for (severity of alarm.severities; track severity) { + + {{ severityLabel(severity) | translate }} + + } +
+
expand_more
+
+
{{ 'solution-creator.pane.profiles' | translate }}
+
+
+ @for (profile of alarm.profileNames ?? []; track profile) { + {{ profile }} + } +
+
+
+ +
+ } @else { +

{{ 'solution-creator.pane.no-alarms' | translate }}

+ } +
+
+ + +
+ @if (profile.scope) { +
{{ 'solution-creator.pane.scope' | translate }}
+
{{ profile.scope }}
+ } + @if (profile.description) { +
{{ 'solution-creator.pane.description' | translate }}
+
{{ profile.description }}
+ } +
+
+ + +
+ @if (keysOf() === 'telemetry') { +
    + @for (item of profile.telemetry ?? []; track item.key) { +
  • + {{ item.key }} + {{ (item.telemetryType === 'ATTRIBUTE' ? 'solution-creator.pane.attribute' : 'solution-creator.pane.time-series') | translate }} + @if (item.calculatedFieldName) { + ƒx + } + {{ item.dataType }}{{ item.units ? ' · ' + item.units : '' }} +
  • + } @empty { +
  • {{ 'solution-creator.pane.no-keys' | translate }}
  • + } +
+ } @else { +
    + @for (relation of relationsOf(profile); track $index) { +
  • + {{ relation.parent }} + {{ relation.type }}{{ relation.cardinality ? ' (' + relation.cardinality + ')' : '' }} + {{ relation.child }} +
  • + } @empty { +
  • {{ 'solution-creator.pane.no-relations' | translate }}
  • + } +
+ } +
diff --git a/ui-ngx/src/app/modules/home/components/ai/solution/pane/solution-overview.component.scss b/ui-ngx/src/app/modules/home/components/ai/solution/pane/solution-overview.component.scss new file mode 100644 index 0000000000..f23f0ea550 --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/ai/solution/pane/solution-overview.component.scss @@ -0,0 +1,104 @@ +// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: BUSL-1.1 +.sol-schema { + height: 380px; + margin: 0 var(--art-x); + overflow: hidden; + + .sol-graph { + display: block; + width: 100%; + height: 100%; + } + + ::ng-deep { + .sol-band rect { + fill: color-mix(in oklab, var(--ai-light-lilac) 34%, var(--tb-surface)); + } + + .sol-band.tenant rect { + fill: color-mix(in oklab, var(--ai-light-peach) 40%, var(--tb-surface)); + } + + .sol-band-title { + font: 400 12px var(--tb-font); + fill: var(--tb-ink-60); + } + + .sol-edge .line { + stroke: var(--tb-ink-38); + fill: none; + } + + .sol-arrow-head { + fill: var(--tb-ink-38); + } + + .sol-edge-label { + width: fit-content; + max-width: 120px; + margin: 0 auto; + padding: 1px 6px; + border: 1px solid var(--tb-line); + border-radius: 4px; + background: var(--tb-surface); + font: 400 12px/18px var(--tb-font); + color: var(--tb-ink-76); + white-space: nowrap; + overflow: hidden; + text-overflow: ellipsis; + text-align: center; + } + + .sol-box { + display: flex; + flex-direction: column; + justify-content: center; + gap: 2px; + padding: 8px 12px; + box-sizing: border-box; + border: 1px solid var(--tb-line); + border-left: 3px solid var(--tb-ink-38); + border-radius: 8px; + background: var(--tb-surface); + box-shadow: 0 1px 2px rgba(16, 24, 40, 0.06); + text-align: left; + cursor: pointer; + font-family: var(--tb-font); + + b { + font: 500 14px/18px var(--tb-font); + color: var(--tb-ink); + overflow: hidden; + white-space: nowrap; + text-overflow: ellipsis; + } + + span { + font: 400 12px/16px var(--tb-font); + color: var(--tb-ink-60); + } + + &[data-pal="device"] { border-left-color: var(--entity-device-fg); } + &[data-pal="people"] { border-left-color: var(--entity-people-fg); } + &[data-pal="solution"] { border-left-color: var(--entity-solution-fg); } + &[data-pal="path"] { border-left-color: var(--entity-path-fg); } + + &:hover, &.on { + border-color: var(--tb-ink-38); + } + + &:focus-visible { + outline: 2px solid var(--ai-focus); + outline-offset: 1px; + } + } + } +} + +.sol-schema-detail { + margin: 12px var(--art-x) 0; + padding: 12px 14px 14px; + border-radius: 8px; + background: color-mix(in srgb, var(--tb-ink) 4%, transparent); +} diff --git a/ui-ngx/src/app/modules/home/components/ai/solution/pane/solution-overview.component.ts b/ui-ngx/src/app/modules/home/components/ai/solution/pane/solution-overview.component.ts new file mode 100644 index 0000000000..0ec3e04fb7 --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/ai/solution/pane/solution-overview.component.ts @@ -0,0 +1,232 @@ +// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: BUSL-1.1 +import { + AfterViewInit, + ChangeDetectionStrategy, + Component, + computed, + ElementRef, + EventEmitter, + inject, + Input, + OnChanges, + OnDestroy, + Output, + signal, + ViewChild +} from '@angular/core'; +import { TranslateService } from '@ngx-translate/core'; +import { ClusterNode, Edge, GraphComponent, Node } from '@swimlane/ngx-graph'; +import { DialogService } from '@core/services/dialog.service'; +import { + SolutionDescriptor, + SolutionDescriptorAlarm, + SolutionDescriptorEntityBase, + SolutionDescriptorEntityBaseRelation, + SolutionDescriptorIam +} from '@shared/models/solution-creator.models'; +import { aiEntityKind } from '@home/components/ai/ai-action.models'; +import { AlarmSeverity, alarmSeverityColors, alarmSeverityTranslations } from '@shared/models/alarm.models'; +import { buildSolutionSchema } from '@home/components/ai/solution/pane/solution-schema'; + +type SectionId = 'profiles' | 'roles' | 'metrics' | 'alarms'; + +interface Section { + id: SectionId; + title: string; +} + +const OPERATIONS: Record = {C: 'create', R: 'read', U: 'update', D: 'delete'}; + +export function roleOperations(permissions: string | undefined): string[] { + const operations = (permissions ?? '').toUpperCase().split('').filter(letter => OPERATIONS[letter]).map(letter => OPERATIONS[letter]); + return operations.length === Object.keys(OPERATIONS).length ? ['all'] : operations; +} + +@Component({ + changeDetection: ChangeDetectionStrategy.OnPush, + selector: 'tb-solution-overview', + templateUrl: './solution-overview.component.html', + styleUrls: ['./solution-pane.scss', './solution-overview.component.scss'], + standalone: false +}) +export class SolutionOverviewComponent implements OnChanges, AfterViewInit, OnDestroy { + + @Input({required: true}) descriptor: SolutionDescriptor; + + @Output() descriptorChange = new EventEmitter(); + + @ViewChild('graphContainer') graphContainer: ElementRef; + @ViewChild(GraphComponent) graphComponent: GraphComponent; + + private translate = inject(TranslateService); + private dialog = inject(DialogService); + private host = inject>(ElementRef); + + mode = signal<'list' | 'schema'>('list'); + open = signal(null); + keysOf = signal<'telemetry' | 'relations'>('telemetry'); + active = signal('profiles'); + wide = signal(false); + + profiles: SolutionDescriptorEntityBase[] = []; + nodes: Node[] = []; + links: Edge[] = []; + clusters: ClusterNode[] = []; + + sections = computed(() => [ + {id: 'profiles', title: 'solution-creator.pane.profiles'}, + {id: 'roles', title: 'solution-creator.pane.roles'}, + {id: 'metrics', title: 'solution-creator.pane.calculated-fields'}, + {id: 'alarms', title: 'solution-creator.pane.alarms'} + ]); + + private resize: ResizeObserver; + private scroller: HTMLElement | null = null; + private scrollListener = () => this.scroller && this.onScroll(this.scroller); + private graphResize: ResizeObserver; + + ngOnChanges(): void { + this.profiles = this.descriptor ? Object.values(this.descriptor.entityProfiles ?? {}).flat() as SolutionDescriptorEntityBase[] : []; + if (this.mode() === 'schema') { + this.buildSchema(); + } + } + + ngAfterViewInit(): void { + this.resize = new ResizeObserver(() => this.wide.set(this.host.nativeElement.clientWidth >= 660)); + this.resize.observe(this.host.nativeElement); + this.scroller = this.host.nativeElement.closest('.art-pane-body') as HTMLElement; + this.scroller?.addEventListener('scroll', this.scrollListener, {passive: true}); + } + + ngOnDestroy(): void { + this.resize?.disconnect(); + this.graphResize?.disconnect(); + this.scroller?.removeEventListener('scroll', this.scrollListener); + } + + severityColor(severity: string): string { + return alarmSeverityColors.get(severity?.toUpperCase() as AlarmSeverity) ?? null; + } + + severityTone(severity: string): string { + return (severity ?? '').toLowerCase(); + } + + severityLabel(severity: string): string { + return alarmSeverityTranslations.get(severity?.toUpperCase() as AlarmSeverity) ?? severity; + } + + setMode(mode: 'list' | 'schema'): void { + this.mode.set(mode); + if (mode === 'schema') { + this.buildSchema(); + requestAnimationFrame(() => this.observeGraph()); + } + } + + toggle(key: string): void { + this.open.set(this.open() === key ? null : key); + this.keysOf.set('telemetry'); + } + + goTo(section: SectionId): void { + this.active.set(section); + const target = this.host.nativeElement.querySelector(`[data-sec="${section}"]`) as HTMLElement; + const scroller = this.host.nativeElement.closest('.art-pane-body') as HTMLElement; + if (target && scroller) { + const tabs = this.wide() ? 0 : (this.host.nativeElement.querySelector('.sol-tabs') as HTMLElement)?.offsetHeight ?? 0; + scroller.scrollTo({top: scroller.scrollTop + target.getBoundingClientRect().top - scroller.getBoundingClientRect().top - tabs, behavior: 'smooth'}); + } + } + + onScroll(scroller: HTMLElement): void { + const top = scroller.getBoundingClientRect().top + (this.wide() ? 8 : 60); + let current: SectionId = 'profiles'; + for (const section of this.sections()) { + const el = this.host.nativeElement.querySelector(`[data-sec="${section.id}"]`) as HTMLElement; + if (el && el.getBoundingClientRect().top <= top) { + current = section.id; + } + } + if (current !== this.active()) { + this.active.set(current); + } + } + + kind(entity: SolutionDescriptorEntityBase): {icon: string; palette: string} { + return aiEntityKind((entity.entityType ?? '').toUpperCase()); + } + + typeLabel(entity: SolutionDescriptorEntityBase): string { + const type = (entity.entityType ?? '').toLowerCase(); + return type ? type.charAt(0).toUpperCase() + type.slice(1) : ''; + } + + relationsOf(entity: SolutionDescriptorEntityBase): SolutionDescriptorEntityBaseRelation[] { + return (this.descriptor?.relations ?? []).filter(relation => relation.parent === entity.name || relation.child === entity.name); + } + + dataOf(entity: SolutionDescriptorEntityBase): string { + const keys = entity.telemetry?.length ?? 0; + const relations = this.relationsOf(entity).length; + const parts = []; + if (keys) { + parts.push(this.translate.instant('solution-creator.pane.keys', {count: keys})); + } + if (relations) { + parts.push(this.translate.instant('solution-creator.pane.relations', {count: relations})); + } + return parts.join(' · ') || '—'; + } + + operations(iam: SolutionDescriptorIam): string[] { + return roleOperations(iam.permissions); + } + + alarmKey(alarm: SolutionDescriptorAlarm): string { + return 'alarm:' + alarm.alarmName; + } + + removeAlarm(alarm: SolutionDescriptorAlarm): void { + this.dialog.confirm( + this.translate.instant('solution-creator.delete-alarm-title'), + this.translate.instant('solution-creator.delete-alarm-text'), + null, + this.translate.instant('action.delete') + ).subscribe(confirmed => { + if (confirmed) { + this.open.set(null); + this.descriptorChange.emit({...this.descriptor, alarms: this.descriptor.alarms.filter(item => item !== alarm)}); + } + }); + } + + openFromSchema(node: Node): void { + const entity = node.data?.entity as SolutionDescriptorEntityBase; + if (entity) { + this.open.set(this.open() === 'schema:' + entity.name ? null : 'schema:' + entity.name); + } + } + + schemaEntity(): SolutionDescriptorEntityBase | undefined { + const key = this.open(); + return key?.startsWith('schema:') ? this.profiles.find(profile => 'schema:' + profile.name === key) : undefined; + } + + private buildSchema(): void { + const schema = buildSolutionSchema(this.descriptor, this.profiles); + this.nodes = schema.nodes; + this.links = schema.links; + this.clusters = schema.clusters; + } + + private observeGraph(): void { + this.graphResize?.disconnect(); + if (this.graphContainer?.nativeElement) { + this.graphResize = new ResizeObserver(() => this.graphComponent?.basicUpdate()); + this.graphResize.observe(this.graphContainer.nativeElement); + } + } +} diff --git a/ui-ngx/src/app/modules/home/components/ai/solution/pane/solution-pane.scss b/ui-ngx/src/app/modules/home/components/ai/solution/pane/solution-pane.scss new file mode 100644 index 0000000000..b3b53e77b8 --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/ai/solution/pane/solution-pane.scss @@ -0,0 +1,560 @@ +// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: BUSL-1.1 +:host { + --art-x: 16px; + display: block; + min-width: 0; + font-family: var(--tb-font); + font-size: var(--chat-line); + line-height: var(--chat-line-lh); + color: var(--tb-ink); +} + +.art-seg { + flex: none; + display: inline-flex; + padding: 3px; + border-radius: 999px; + background: color-mix(in srgb, var(--tb-ink) 6%, transparent); + + button { + height: 26px; + padding: 0 12px; + border: 0; + border-radius: 999px; + background: none; + font: 500 var(--chat-meta)/var(--chat-meta-lh) var(--tb-font); + color: var(--tb-ink-60); + cursor: pointer; + transition: background-color .15s ease, color .15s ease; + + &:hover { + color: var(--tb-ink); + } + + &[aria-pressed="true"] { + background: var(--ai-action); + color: var(--ai-on-action); + } + + &:focus-visible { + outline: 2px solid var(--ai-focus); + outline-offset: 1px; + } + } +} + +:host > .sol-infos, :host > .sol-paged { + width: 100%; + box-sizing: border-box; +} + +.sol-paged { + display: flex; + flex-direction: column; + + &.wide { + display: grid; + grid-template-columns: 168px minmax(0, 1fr); + align-items: start; + + > .sol-tabs { + position: sticky; + top: 0; + flex-direction: column; + align-items: stretch; + gap: 2px; + padding: 12px 8px 12px var(--art-x); + border-bottom: 0; + overflow: visible; + + button { + display: block; + margin: 0; + padding: 6px 10px; + border: 0; + border-left: 2px solid transparent; + border-radius: 0 6px 6px 0; + white-space: normal; + + &[aria-selected="true"] { + border-left-color: var(--ai-action); + background: color-mix(in srgb, var(--tb-ink) 4%, transparent); + } + + &:hover { + background: color-mix(in srgb, var(--tb-ink) 3%, transparent); + } + } + } + } +} + +.sol-tabs { + position: sticky; + top: 0; + z-index: 2; + display: flex; + gap: 2px; + padding: 6px max(0px, calc(var(--art-x) - 6px)) 0; + border-bottom: 1px solid var(--tb-line); + background: var(--tb-surface); + overflow-x: auto; + scrollbar-width: none; + + &::-webkit-scrollbar { + display: none; + } + + button { + flex: none; + padding: 6px 6px 8px; + border: 0; + border-bottom: 2px solid transparent; + margin-bottom: -1px; + background: none; + font: 500 var(--chat-line)/var(--chat-line-lh) var(--tb-font); + color: var(--tb-ink-60); + text-align: left; + cursor: pointer; + white-space: nowrap; + + &:hover { + color: var(--tb-ink); + } + + &[aria-selected="true"] { + color: var(--tb-ink); + border-bottom-color: var(--ai-action); + } + + &:focus-visible { + outline: 2px solid var(--ai-focus); + outline-offset: -2px; + border-radius: 6px; + } + } +} + +.sol-infos { + min-width: 0; + padding: 4px 0 16px; +} + +.sol-sec-head { + display: flex; + align-items: center; + justify-content: space-between; + gap: 12px; + min-height: 32px; + margin: 12px var(--art-x) 0; + box-sizing: border-box; + + h3 { + margin: 0; + font: 500 var(--chat-line)/var(--chat-line-lh) var(--tb-font); + letter-spacing: .25px; + color: var(--tb-ink); + } +} + +.sol-infos > .sol-sec-head:first-child { + margin-top: 4px; +} + +.sol-sec-link { + display: inline-flex; + align-items: center; + gap: 4px; + color: inherit; + font: inherit; + letter-spacing: inherit; + text-decoration: none; + border-bottom: 0 !important; + transition: color .12s ease; + + .mat-icon { + font-size: 16px; + width: 16px; + height: 16px; + line-height: 16px; + color: var(--tb-ink-38); + opacity: 0; + transition: opacity .12s ease; + } + + &:hover, &:focus-visible { + color: var(--ai-link); + text-decoration: underline; + + .mat-icon { + opacity: 1; + } + } +} + +a.sol-ent { + color: inherit; + text-decoration: none; + border-bottom: 0 !important; + + b { + transition: color .12s ease; + } + + &:hover, &:focus-visible { + text-decoration: underline; + } + + &:hover b, &:focus-visible b { + color: var(--ai-link); + } + + &:focus-visible { + outline: 2px solid var(--ai-focus); + outline-offset: 2px; + border-radius: 4px; + } +} + +.sol-empty { + margin: 0; + padding: 4px var(--art-x) 12px; + font-size: var(--chat-line); + line-height: var(--chat-line-lh); + color: var(--k-faint); +} + +table.sol-table { + width: 100%; + border-collapse: collapse; + border-spacing: 0; + + th { + height: 30px; + padding: 0 10px 0 0; + font: 400 var(--chat-caption)/var(--chat-caption-lh) var(--tb-font); + letter-spacing: .2px; + color: var(--k-faint); + text-align: left; + border-bottom: 1px solid var(--tb-line); + } + + td { + min-width: 72px; + height: 40px; + padding: 9px 10px 9px 0; + box-sizing: border-box; + font-size: var(--chat-line); + line-height: var(--chat-line-lh); + letter-spacing: 0; + color: var(--tb-ink); + border-bottom: 1px solid var(--tb-line); + vertical-align: top; + } + + th:first-child, td:first-child { + padding-left: var(--art-x); + } + + th:last-child, td:last-child { + padding-right: var(--art-x); + } + + .secondary { + color: var(--tb-ink-76); + } + + .faint { + color: var(--k-faint); + } + + .wrap { + white-space: normal; + overflow-wrap: break-word; + } + + .nowrap { + white-space: nowrap; + } + + .chev, .stc, .act { + width: 1px; + white-space: nowrap; + text-align: right; + } + + .chev { + width: 18px; + } + + tbody tr.clickable { + cursor: pointer; + + &:hover td { + background: color-mix(in srgb, var(--tb-ink) 2.5%, transparent); + } + } + + tbody tr.on td { + background: color-mix(in srgb, var(--tb-ink) 4%, transparent); + border-bottom-color: transparent; + } + + tr.sol-exp td { + height: auto; + padding: 0 var(--art-x) 14px calc(var(--art-x) + 26px); + background: color-mix(in srgb, var(--tb-ink) 4%, transparent); + } +} + +.sol-chev { + font-size: 18px; + width: 18px; + height: 18px; + line-height: 18px; + margin-top: 1px; + color: var(--tb-ink-38); + transition: transform .15s ease; + + &.open { + transform: rotate(180deg); + } +} + +.sol-name { + display: flex; + align-items: flex-start; + gap: 8px; + min-width: 0; + + > .mat-icon { + flex: none; + font-size: 18px; + width: 18px; + height: 18px; + line-height: 18px; + margin-top: 1px; + color: var(--tb-ink-54); + } + + &[data-pal="device"] > .mat-icon { color: var(--entity-device-fg); } + &[data-pal="people"] > .mat-icon { color: var(--entity-people-fg); } + &[data-pal="path"] > .mat-icon { color: var(--entity-path-fg); } + &[data-pal="rule"] > .mat-icon { color: var(--entity-rule-fg); } + &[data-pal="view"] > .mat-icon { color: var(--entity-view-fg); } + &[data-pal="chain"] > .mat-icon { color: var(--entity-chain-fg); } + &[data-pal="solution"] > .mat-icon { color: var(--entity-solution-fg); } + + b { + font-weight: 500; + min-width: 0; + overflow-wrap: break-word; + } + + small { + display: block; + font-size: var(--chat-meta); + line-height: var(--chat-meta-lh); + color: var(--tb-ink-60); + } + + a { + color: var(--tb-ink); + border-bottom: 0 !important; + text-decoration: underline; + text-decoration-thickness: 1px; + text-underline-offset: 3px; + text-decoration-color: transparent; + transition: text-decoration-color .15s ease; + + &:hover { + text-decoration-color: var(--tb-ink-54); + } + } +} + +.sol-sub { + margin-top: 2px; + padding-left: 26px; +} + +code.sol-cond { + display: inline-block; + max-width: 100%; + box-sizing: border-box; + padding: 2px 7px; + border-radius: 5px; + background: rgba(0, 0, 0, 0.06); + font: 400 14px/18px var(--tb-mono); + color: var(--tb-ink); + white-space: normal; + overflow-wrap: anywhere; +} + +table.sol-table td code.k-ent, table.sol-table td .k-sev, table.sol-table td .sol-op { + vertical-align: baseline; +} + +.sol-chips { + display: flex; + flex-wrap: wrap; + gap: 4px; +} + +.sol-op { + display: inline-block; + margin: 0; + padding: 1px 8px; + border-radius: 10px; + background: rgba(0, 0, 0, 0.06); + font-size: var(--chat-caption); + line-height: var(--chat-caption-lh); + color: var(--tb-ink-76); + white-space: nowrap; +} + +.sol-facts { + padding: 10px 0 0; +} + +.sol-keys-seg { + margin: 12px 0 8px; +} + +.sol-keys { + list-style: none; + margin: 0; + padding: 0; + display: grid; + + li { + display: flex; + align-items: baseline; + gap: 8px; + padding: 4px 0; + font-size: var(--chat-line); + line-height: var(--chat-line-lh); + } + + li + li { + border-top: 1px solid var(--tb-line); + } +} + +.sol-key { + padding: 1px 7px; + border-radius: 5px; + background: rgba(0, 0, 0, 0.06); + font-family: var(--tb-mono); + font-size: var(--chat-code); + line-height: 20px; + color: var(--tb-ink); +} + +.sol-key-type, .sol-key-dt { + color: var(--k-faint); + font-size: var(--chat-meta); + line-height: var(--chat-meta-lh); +} + +.sol-key-fx { + color: var(--entity-path-fg); + font-style: italic; + font-size: var(--chat-meta); +} + +.sol-key-dt { + margin-left: auto; + white-space: nowrap; +} + +.sol-remove { + margin-top: 10px; +} + +@container pane (max-width: 440px) { + table.sol-table, table.sol-table > tbody { + display: block; + } + + table.sol-table > thead { + display: none; + } + + table.sol-table > tbody > tr:not(.sol-exp) { + display: flex; + flex-wrap: wrap; + align-items: center; + gap: 2px 12px; + padding: 9px var(--art-x) 9px calc(var(--art-x) + 26px); + border-bottom: 1px solid var(--tb-line); + + > td { + display: block; + width: auto; + min-width: 0; + height: auto; + padding: 0; + border: 0; + background: none; + } + + > td:first-child { + flex: 1 1 0; + min-width: 0; + padding: 0; + + .sol-name { + position: relative; + + > .mat-icon { + position: absolute; + left: -26px; + top: 0; + } + } + + .sol-sub { + padding-left: 0; + } + } + + > td:is(.stc, .chev) { + order: 1; + flex: none; + } + + > td:not(:first-child):not(.stc):not(.chev) { + order: 2; + } + + &::after { + content: ''; + order: 1; + flex: 0 0 100%; + height: 0; + } + + > td.act { + margin-left: -8px; + } + } + + table.sol-table .act .mdc-button { + margin: 0; + } + + table.sol-table > tbody > tr.clickable:hover { + background: color-mix(in srgb, var(--tb-ink) 2.5%, transparent); + } + + table.sol-table > tbody > tr.on { + background: color-mix(in srgb, var(--tb-ink) 4%, transparent); + border-bottom-color: transparent; + } + + table.sol-table > tbody > tr.sol-exp, table.sol-table > tbody > tr.sol-exp > td { + display: block; + } +} diff --git a/ui-ngx/src/app/modules/home/components/ai/solution/pane/solution-schema.ts b/ui-ngx/src/app/modules/home/components/ai/solution/pane/solution-schema.ts new file mode 100644 index 0000000000..572887a35a --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/ai/solution/pane/solution-schema.ts @@ -0,0 +1,165 @@ +// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: BUSL-1.1 +import { ClusterNode, Edge, Node } from '@swimlane/ngx-graph'; +import { SolutionDescriptor, SolutionDescriptorEntityBase } from '@shared/models/solution-creator.models'; + +export interface SolutionSchema { + nodes: Node[]; + links: Edge[]; + clusters: ClusterNode[]; +} + +export function buildSolutionSchema(descriptor: SolutionDescriptor, profiles: SolutionDescriptorEntityBase[]): SolutionSchema { + const nodes: Node[] = []; + const links: Edge[] = []; + const clusters: ClusterNode[] = []; + if (!descriptor) { + return {nodes, links, clusters}; + } + + const slug = (s: string) => + s.toLowerCase().normalize('NFKD') + .replace(/[\u0300-\u036f]/g, '') + .replace(/\s+/g, '-') + .replace(/[^a-z0-9_-]/g, '-') + .replace(/-+/g, '-') + .replace(/^-+|-+$/g, ''); + + const cssSafeId = (base: string) => { + const v = slug(base); + return v && !/^[a-z_]/.test(v) ? `n-${v}` : (v || 'n'); + }; + + const nodeIdOf = (type: string, name: string) => + `n-${cssSafeId(type)}__${cssSafeId(name)}`; + + const linkIdOf = (sourceNodeId: string, targetNodeId: string, label?: string) => + `e-${sourceNodeId}__to__${targetNodeId}${label ? `__${cssSafeId(label)}` : ''}`; + + const nodeByName = new Map(); + const nodeIdSet = new Set(); + const linkIdSet = new Set(); + const clusterByScope = new Map(); + const ensureCluster = (scope?: string | null) => { + if (!scope) return undefined; + if (!clusterByScope.has(scope)) { + const id = `c-${cssSafeId(scope)}`; + const clusterNode: ClusterNode = { id, label: scope, childNodeIds: [], data: {tone: scope === 'Tenant' ? 'tenant' : 'customer'} }; + clusterByScope.set(scope, clusterNode); + clusters.push(clusterNode); + } + return clusterByScope.get(scope); + }; + + const addNode = (entity: SolutionDescriptorEntityBase) => { + const id = nodeIdOf(entity.entityType || 'Entity', entity.name || 'Unnamed'); + if (nodeIdSet.has(id)) return id; + + const node: Node = { + id, + label: entity.name || 'Unnamed', + dimension: { + width: 200, + height: 56 + }, + data: { + entityType: entity.entityType || 'Entity', + scope: entity.scope, + entity + } + }; + + const scope = entity.entityType === 'Customer' ? entity.name : entity.scope; + const cluster = ensureCluster(scope); + if (cluster) { + cluster.childNodeIds?.push(id); + } + + nodes.push(node); + nodeIdSet.add(id); + nodeByName.set(entity.name, node); + return id; + }; + + const pushLink = (sourceId: string, targetId: string, label?: string) => { + const lbl = (label || '').trim(); + const id = linkIdOf(sourceId, targetId, lbl || undefined); + if (linkIdSet.has(id)) return; + links.push({ id, source: sourceId, target: targetId, label: lbl || undefined }); + linkIdSet.add(id); + }; + + const allProfiles: SolutionDescriptorEntityBase[] = profiles; + + for (const entity of allProfiles) { + addNode(entity); + } + + for (const relation of (descriptor.relations ?? [])) { + const fromNode = nodeByName.get(relation.parent); + const toNode = nodeByName.get(relation.child); + if (fromNode && toNode) { + const label = `${relation.type || ''}${relation.cardinality ? ` (${relation.cardinality})` : ''}`.trim(); + pushLink(fromNode.id, toNode.id, label || undefined); + } + } + + const byType = (t: string) => + allProfiles.filter(x => (x.entityType || '').toLowerCase() === t.toLowerCase()); + const tenantUsers = byType('User').filter(x => x.scope === 'Tenant'); + const customers = byType('Customer'); + const assets = byType('Asset'); + const devices = byType('Device'); + const customerUsers = byType('User').filter(x => x.scope !== 'Tenant'); + + for (const t of tenantUsers) { + const tId = nodeByName.get(t.name)?.id; + if (!tId) continue; + for (const c of customers) { + if (!(descriptor.relations ?? []).some(x => x.child === c.name)) { + const cId = nodeByName.get(c.name)?.id; + if (cId) pushLink(tId, cId, 'Manages'); + } + } + } + + for (const c of customers) { + const cId = nodeByName.get(c.name)?.id; + if (!cId) continue; + for (const a of assets) { + if (a.scope === c.name || a.scope === c.scope) { + if (!(descriptor.relations ?? []).some(x => x.child === a.name)) { + const aId = nodeByName.get(a.name)?.id; + if (aId) pushLink(cId, aId, 'Own'); + } + } + } + } + + for (const c of customers) { + const cId = nodeByName.get(c.name)?.id; + if (!cId) continue; + for (const d of devices) { + if (d.scope === c.name || d.scope === c.scope) { + if (!(descriptor.relations ?? []).some(x => x.child === d.name)) { + const aId = nodeByName.get(d.name)?.id; + if (aId) pushLink(cId, aId, 'Own'); + } + } + } + } + + for (const c of customers) { + const cId = nodeByName.get(c.name)?.id; + if (!cId) continue; + for (const u of customerUsers) { + if (u.scope === c.name || u.scope === c.scope) { + if (!(descriptor.relations ?? []).some(x => x.child === u.name)) { + const uId = nodeByName.get(u.name)?.id; + if (uId) pushLink(cId, uId, 'Manages'); + } + } + } + } + return {nodes, links, clusters}; +} diff --git a/ui-ngx/src/app/modules/home/components/ai/solution/solution-chat.component.html b/ui-ngx/src/app/modules/home/components/ai/solution/solution-chat.component.html new file mode 100644 index 0000000000..fcce6aea3a --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/ai/solution/solution-chat.component.html @@ -0,0 +1,424 @@ + +
+ + +
+ @if (title() || built()) { + + } + +
+
+
+ +@if (opening()) { +
+ + {{ 'solution-creator.opening' | translate }} +
+} @else if (isInitialEmpty()) { +
+
+
+ +

{{ 'solution-creator.what-should-it-do' | translate }}

+

{{ 'solution-creator.what-it-becomes' | translate }}

+ @if (creditsOut(); as limitType) { + + } @else if (notice(); as current) { +
+ {{ current.text }} +
+ } + + +
+ @for (ex of solutionExamples; track ex.key) { + + } +
+

{{ 'solution-creator.limits' | translate }}

+ +
+
+
+
+
+ {{ 'solution-creator.about-title' | translate }} + +
+
+ @for (feature of aboutFeatures; track feature.icon) { +
+ +
{{ feature.title | translate }}{{ feature.line | translate }}
+
+ } +
+
+
+
+} @else if (creatorStep()) { +
+
+
+ +
+
+
+ @if (pill(); as current) { + + } + @if (showPane() && !paneOpen()) { + + } + @if (creditsOut(); as limitType) { + + } @else if (notice(); as current) { +
+ {{ current.text }} +
+ } + + +
+
+ @if (showPane() && paneOpen()) { + +
+ @for (view of views(); track view.id) { + + } +
+ @if (json() && jsonView) { +
+
+ @if (!jsonView.body().editing()) { + + } + + +
+
+ + {{ jsonCopied() ? ('ai-assistant.copied' | translate) : '' }} + +
+
+ } + @if (jsonAvailable()) { + + } + @if (making() === 'solution' && currentView() === 'solution' && progressInfo(); as progress) { + + } @else if (making() && currentView() === making()) { +
+ + + + + +

{{ estimateOf(making()) }}

+
+ } @else if (json()) { + + } @else { + @switch (currentView()) { + @case ('overview') { + + } + @case ('dashboards') { + + } + @case ('solution') { + + } + } + } + @if (!making()) { +
+ @if (json() && jsonView; as view) { + + @if (view.body().editing()) { + @if (view.error(); as message) { + {{ 'solution-creator.pane.json-invalid' | translate: {message} }} + } @else if (view.body().dirty()) { + {{ 'ai-assistant.file.unsaved' | translate }} + } @else { + {{ 'ai-assistant.file.editing' | translate }} + } + @if (view.body().caret(); as caret) { + + {{ 'ai-assistant.file.position' | translate: {line: caret.line, col: caret.col} }} + } + } @else if (view.body().saved()) { + {{ 'solution-creator.pane.json-applied' | translate }} + } @else { + {{ view.fileName() }} + + {{ 'ai-assistant.file.lines' | translate: {count: view.file().lines} }} + + {{ view.file().size }} + } + + + @if (view.body().editing()) { + @if (view.body().dirty()) { + + + } @else { + + } + } @else { + + } + + } @else if (currentView() === 'solution' || creatorStep() === 'result') { + @if (installed()) { + + } + + + @if (installed()) { + @if (mainUser()) { + + } @else if (solutionMetadata.installResult?.mainDashboardId) { + + } + } @else { + + } + } @else if (currentView() === 'overview') { + {{ estimateOf('dashboards') }} + + } @else { + {{ estimateOf('solution') }} + + + + } +
+ } +
+ } +
+} + + + + @if (built() && creatorStep() === 'result') { + + } + @if (creatorStep() === 'result') { + + } + @if (installed()) { + + } + + + + + @if (!jsonView?.body()?.editing()) { + + } +
+ + {{ 'ai-assistant.file.theme' | translate }} +
+ + +
+
+
diff --git a/ui-ngx/src/app/modules/home/components/ai/solution/solution-chat.component.scss b/ui-ngx/src/app/modules/home/components/ai/solution/solution-chat.component.scss new file mode 100644 index 0000000000..8f55892ffe --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/ai/solution/solution-chat.component.scss @@ -0,0 +1,829 @@ +// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: BUSL-1.1 +@use '../ai-icon-button' as *; +:host { + position: relative; + width: 100%; + height: 100%; + min-width: 0; + min-height: 0; + display: flex; + flex-direction: column; + overflow: hidden; + background: var(--tb-surface); + font-family: var(--tb-font); + font-size: var(--chat-line); + line-height: var(--chat-line-lh); + color: var(--tb-ink); +} + +:host(.tb-fullscreen) { + margin: 0 !important; + border-radius: 0 !important; + box-shadow: none !important; +} + +.sol-head { + position: relative; + z-index: 2; + flex: none; + display: flex; + align-items: center; + gap: 8px; + height: 48px; + box-sizing: border-box; + padding: 0 8px 0 16px; + border-bottom: 1px solid rgba(0, 0, 0, 0.06); + background: var(--tb-surface); +} + +.sol-head-mark { + flex: none; + font-size: 18px; + width: 18px; + height: 18px; + color: var(--tb-ink-54); +} + +.sol-head-actions { + flex: none; + margin-left: auto; + display: flex; + align-items: center; + gap: 2px; +} + +tb-ai-chat-title:has(.ai-chat-status) + .sol-head-actions { + margin-left: 0; +} + +.sol-ib { + @include ai-icon-button($icon: 20px, $tap: false, $relative: false); +} + +.sol-toast { + position: absolute; + inset: 48px 0 auto; + pointer-events: none; +} + +.sol-hero { + --sol-dot: color-mix(in srgb, var(--tb-ink) 9%, transparent); + position: relative; + isolation: isolate; + flex: 1; + min-height: 0; + display: flex; + overflow: hidden; + contain: paint; + background: var(--ai-field-wash); + + &::after { + content: ''; + position: absolute; + left: -20vw; + top: -20vh; + width: 140vw; + height: 140vh; + z-index: -1; + pointer-events: none; + background: var(--ai-field-wash); + opacity: .9; + filter: blur(16px); + will-change: transform; + animation: sol-drift 16s ease-in-out infinite alternate; + } + + &::before { + content: ''; + position: absolute; + inset: -8px; + z-index: 0; + pointer-events: none; + mix-blend-mode: multiply; + will-change: transform; + animation: sol-dots 26s ease-in-out infinite alternate; + background: radial-gradient(circle, var(--sol-dot) 1px, transparent 1.4px) 0 0 / 16px 16px; + mask-image: radial-gradient(ellipse 56% 52% at 50% 44%, transparent 0%, rgba(0, 0, 0, .3) 55%, #000 100%), linear-gradient(180deg, #000 50%, transparent 100%); + mask-composite: intersect; + } + + @media (prefers-reduced-motion: reduce) { + &::before, &::after { + animation: none; + } + } +} + +@keyframes sol-drift { + 0% { transform: translate(-3%, -2%); } + 50% { transform: translate(3%, 2%); } + 100% { transform: translate(-1%, 3%); } +} + +@keyframes sol-dots { + from { transform: translate(-5px, -3px); } + to { transform: translate(5px, 4px); } +} + +.sol-hero-scroll { + position: relative; + z-index: 1; + flex: 1; + min-width: 0; + display: flex; + justify-content: center; + padding: 48px 24px 56px; + box-sizing: border-box; + overflow-y: auto; + overflow-x: hidden; +} + +.sol-hero-in { + position: relative; + z-index: 1; + width: 100%; + max-width: 720px; + margin: auto 0; + text-align: center; +} + +.sol-mark { + --ai-mark-fill: radial-gradient(80% 80% at 16% 10%, color-mix(in srgb, var(--tb-surface) 16%, transparent), transparent 62%), + linear-gradient(135deg in oklab, + color-mix(in oklab, var(--ai-light-teal) 34%, var(--tb-ink)) 0%, + color-mix(in oklab, var(--ai-light-aqua) 32%, var(--tb-ink)) 36%, + color-mix(in oklab, var(--ai-light-lilac) 36%, var(--tb-ink)) 68%, + color-mix(in oklab, var(--ai-light-peach) 34%, var(--tb-ink)) 100%); + --ai-mark-edge: 0 10px 28px color-mix(in oklab, var(--tb-ink) 24%, transparent); + --ai-mark-ink: var(--ai-on-action); + --ai-mark-ink-fill: linear-gradient(var(--ai-on-action), var(--ai-on-action)); + display: flex; + margin: 0 auto 14px; +} + +.sol-title { + margin: 0; + font: 500 var(--chat-title)/var(--chat-title-lh) var(--tb-font); + letter-spacing: -0.2px; + color: var(--tb-ink); +} + +.sol-lead { + margin: 8px auto 0; + max-width: 540px; + font-size: var(--chat-text); + line-height: var(--chat-text-lh); + letter-spacing: var(--chat-text-ls); + color: var(--tb-ink-76); + text-wrap: balance; +} + +.sol-hero-input { + display: block; + margin-top: 24px; + text-align: left; +} + +.sol-hero-credits { + margin-top: 24px; + text-align: left; + + + .sol-hero-input { + margin-top: 0; + } +} + +.sol-hero-notice { + align-self: stretch; + margin: 24px 0 8px; + text-align: left; + + + .sol-hero-input { + margin-top: 0; + } +} + +.sol-examples { + display: flex; + flex-wrap: wrap; + justify-content: center; + gap: 6px; + max-width: 600px; + margin: 22px auto 0; + + .ob-chip { + gap: 8px; + padding: 0 16px 0 12px; + + .mat-icon { + font-size: 20px; + width: 20px; + height: 20px; + line-height: 20px; + color: var(--tb-ink-76); + } + } +} + +.sol-hero-foot { + margin: 20px 0 0; + letter-spacing: var(--chat-text-ls); + font-size: var(--chat-meta); + line-height: var(--chat-meta-lh); + color: var(--k-faint); +} + +.sol-cols { + flex: 1; + min-height: 0; + display: flex; +} + +.sol-chat { + position: relative; + flex: 1 1 0; + min-width: 0; + display: flex; + flex-direction: column; +} + +.sol-head::after, .sol-cols.with-pane .sol-chat::before { + content: ''; + position: absolute; + left: 0; + right: 0; + z-index: 3; + height: 12px; + background: linear-gradient(to bottom, color-mix(in srgb, var(--tb-ink) 9%, transparent), transparent); + opacity: 0; + transition: opacity .15s ease; + pointer-events: none; +} + +.sol-head::after { + top: 100%; +} + +.sol-cols.with-pane .sol-chat::before { + top: 0; +} + +.sol-head.scrolled::after, .sol-cols.with-pane .sol-chat.scrolled::before { + opacity: 1; +} + +.sol-cols.with-pane .sol-chat { + min-width: var(--chat-col-min, 340px); +} + +.sol-log { + flex: 1; + min-height: 0; + overflow-y: auto; + overscroll-behavior: contain; + padding: 20px 20px 0; + container: k-chat / inline-size; +} + +.sol-log-in { + width: 100%; + max-width: 760px; + margin: 0 auto; + padding-bottom: 24px; +} + +.sol-chips { + margin-top: 14px; +} + +.sol-closing { + margin-top: var(--chat-turn-gap, 28px); + font-size: var(--chat-text); + line-height: var(--chat-text-lh); + letter-spacing: var(--chat-text-ls); + color: var(--tb-ink); + + p { + margin: 0; + font-size: var(--chat-text); + line-height: var(--chat-text-lh); + letter-spacing: var(--chat-text-ls); + } +} + +.sol-hint { + margin-top: 14px; +} + +.sol-closing .sol-chips { + margin-top: 14px; +} + +.sol-closing > .sol-hint { + margin-top: 12px; + + + .sol-chips { + margin-top: 36px; + } +} + +.sol-work { + margin-top: var(--chat-turn-gap, 28px); +} + +.sol-composer { + position: relative; + flex: none; + width: 100%; + max-width: 760px; + margin: 0 auto; + padding: 0 20px 14px; + box-sizing: border-box; +} + +.sol-toast-chat { + position: absolute; + inset: auto 0 100%; + pointer-events: none; +} + +.sol-views { + flex: 1; + min-width: 0; + display: flex; + align-items: center; + gap: 2px; + + button { + display: inline-flex; + align-items: center; + gap: 7px; + height: 32px; + padding: 0 14px 0 10px; + border: 0; + border-radius: 999px; + background: none; + font: 500 var(--chat-line)/var(--chat-line-lh) var(--tb-font); + color: var(--tb-ink-60); + cursor: pointer; + white-space: nowrap; + transition: background-color .18s ease, color .18s ease; + + > .mat-icon { + font-size: 18px; + width: 18px; + height: 18px; + color: var(--tb-ink-54); + } + + &:not([aria-pressed="true"]):not([disabled]):hover { + background: color-mix(in srgb, var(--tb-ink) 5%, transparent); + color: var(--tb-ink); + } + + &[aria-pressed="true"] { + background: var(--ai-action); + color: var(--ai-on-action); + + > .mat-icon { + color: var(--ai-on-action); + } + } + + &[disabled] { + color: var(--tb-ink-38); + cursor: default; + + > .mat-icon { + color: var(--tb-ink-24, rgba(0, 0, 0, 0.24)); + } + } + + &:focus-visible { + outline: 2px solid var(--ai-focus); + outline-offset: 1px; + } + } +} + +.sol-views button.working { + padding-left: 9px; +} + +@container pane (min-width: 660px) { + .sol-views button tb-ai-spin { + --spin: 24px; + } + + .sol-views button.working { + padding-left: 10px; + } + + .sol-views button { + height: 34px; + padding: 0 16px 0 12px; + gap: 8px; + + > .mat-icon { + font-size: 20px; + width: 20px; + height: 20px; + } + } +} + +@container pane (max-width: 470px) { + .sol-views button:not([aria-pressed="true"]) { + padding: 0 9px; + + .sol-views-l { + display: none; + } + } +} + +.sol-tool { + flex: none; + display: inline-flex; + align-items: center; + gap: 4px; + height: 32px; + padding: 0 12px 0 8px; + border: 0; + border-radius: 8px; + background: transparent; + font: 500 var(--chat-meta)/var(--chat-meta-lh) var(--tb-font); + color: var(--tb-ink-60); + cursor: pointer; + transition: background-color .12s ease, color .12s ease; + + .mat-icon { + font-size: 18px; + width: 18px; + height: 18px; + color: var(--tb-ink-54); + } + + &:hover { + color: var(--tb-ink); + background: color-mix(in srgb, var(--tb-ink) 6%, transparent); + } + + &.on { + background: var(--ai-action); + color: var(--ai-on-action); + + .mat-icon { + color: var(--ai-on-action); + } + } + + &:focus-visible { + outline: 2px solid var(--ai-focus); + outline-offset: 1px; + } +} + +.sol-loading, .sol-json { + flex: 1; +} + +.sol-loading { + --art-x: 16px; +} + +.sol-json { + width: 100%; + min-height: 0; +} + + +.art-pane-foot { + .warn { + --mat-button-text-label-text-color: var(--tb-crit); + } + + .sol-foot-stroked.mat-mdc-outlined-button { + padding: 0 15px; + background: var(--tb-surface); + --mat-button-outlined-label-text-color: var(--tb-ink-76); + --mat-button-outlined-outline-color: rgba(0, 0, 0, 0.1); + } +} + +.sol-foot-note { + flex: 1; + min-width: 0; + white-space: nowrap; + overflow: hidden; + text-overflow: ellipsis; + font-size: var(--chat-caption); + line-height: var(--chat-caption-lh); + color: var(--k-faint); +} + +.sol-spacer { + flex: 1; +} + +.sol-failure { + display: flex; + align-items: flex-start; + gap: 8px; + margin-top: 14px; + font-size: var(--chat-line); + line-height: var(--chat-line-lh); + color: var(--tb-crit); + + .mat-icon { + flex: none; + font-size: 18px; + width: 18px; + height: 18px; + line-height: 18px; + margin-top: 1px; + } +} + +.sol-issues { + ul { + margin: 8px 0 0; + padding-left: 20px; + font-size: var(--chat-line); + line-height: var(--chat-line-lh); + color: var(--tb-ink-76); + } + + b { + font-weight: 500; + color: var(--tb-ink); + } +} + +.sol-learn { + display: inline-flex; + align-items: center; + gap: 6px; + margin: 6px auto 0; + padding: 4px 10px 4px 8px; + border: 0; + border-radius: 8px; + background: none; + font: inherit; + font-size: var(--chat-line); + line-height: var(--chat-line-lh); + font-weight: 500; + color: var(--tb-ink-60); + cursor: pointer; + + .mat-icon { + font-size: 18px; + width: 18px; + height: 18px; + line-height: 18px; + } + + &:hover { + color: var(--tb-ink); + background: rgba(0, 0, 0, 0.05); + } + + &:focus-visible { + outline: 2px solid var(--ai-focus); + outline-offset: 1px; + } +} + +.sol-about { + position: absolute; + left: 0; + right: 0; + bottom: 0; + z-index: 2; + padding: 12px 24px 18px; + background: var(--tb-surface); + border-top: 1px solid var(--k-stroke, rgba(0, 0, 0, 0.1)); + transform: translateY(100%); + opacity: 0; + visibility: hidden; + will-change: transform; + transition: transform .26s cubic-bezier(.2, 0, 0, 1), opacity .2s ease, visibility 0s linear .26s; + + &::before { + content: ''; + position: absolute; + left: 0; + right: 0; + bottom: 100%; + height: 18px; + background: linear-gradient(to top, color-mix(in srgb, var(--tb-ink) 5%, transparent), transparent); + pointer-events: none; + } + + &.open { + transform: none; + opacity: 1; + visibility: visible; + transition-delay: 0s, 0s, 0s; + } + + @media (prefers-reduced-motion: reduce) { + transition: none; + } +} + +.sol-about-in { + max-width: 860px; + margin: 0 auto; + text-align: left; +} + +.sol-about-head { + display: flex; + align-items: center; + gap: 8px; + margin-bottom: 8px; + + b { + flex: 1; + display: inline-flex; + align-items: center; + gap: 8px; + font-size: var(--chat-line); + line-height: var(--chat-line-lh); + font-weight: 500; + color: var(--ai-action); + + .mat-icon { + font-size: 18px; + width: 18px; + height: 18px; + line-height: 18px; + } + } + + .sol-ib { + width: 32px; + height: 32px; + margin: -4px -8px -4px 0; + border-radius: 50%; + font-size: 14px; + line-height: 20px; + color: var(--tb-ink-60); + } +} + +.sol-feats { + display: grid; + grid-template-columns: repeat(2, minmax(0, 1fr)); + gap: 16px 32px; + align-items: start; + + @media (max-width: 480px) { + grid-template-columns: minmax(0, 1fr); + } +} + +.sol-feat { + display: grid; + grid-template-columns: auto minmax(0, 1fr); + column-gap: 12px; + align-items: start; + min-width: 0; + + > .mat-icon { + box-sizing: content-box; + font-size: 20px; + width: 20px; + height: 20px; + line-height: 20px; + margin-top: -6px; + padding: 6px; + border-radius: 8px; + background: color-mix(in oklab, var(--tb-ink) 5%, transparent); + color: var(--tb-ink-76); + } + + > div { + display: grid; + gap: 4px; + align-content: start; + min-width: 0; + } + + b { + font-size: var(--chat-line); + line-height: var(--chat-line-lh); + font-weight: 500; + color: var(--tb-ink); + } + + span { + font-size: var(--chat-meta); + line-height: var(--chat-meta-lh); + color: var(--k-grey); + } +} + +.sol-ask { + display: block; + margin-top: var(--chat-turn-gap, 28px); +} + +@media (min-width: 1100px) { + .sol-cols.with-pane { + .sol-log-in, .sol-composer { + max-width: none; + } + } +} + +.sol-views tb-ai-spin { + --spin: 20px; + --spin-color: var(--ai-action); +} + +.sol-views button[aria-pressed="true"] tb-ai-spin { + --spin-color: var(--ai-on-action); +} + +.sol-composer:has(.art-tray) .k-pill { + bottom: calc(100% + 44px); +} + +@media (max-width: 1099px) { + .sol-cols.with-pane .sol-chat { + min-width: 0; + } +} + +@container pane (max-width: 900px) { + .sol-json-on .sol-views button:not([aria-pressed="true"]) { + padding: 0 9px; + + .sol-views-l { + display: none; + } + } +} + +@container pane (max-width: 560px) { + .sol-json-on .sol-views button[aria-pressed="true"] { + padding: 0 9px; + + .sol-views-l { + display: none; + } + } + + .sol-json-on .sol-tool > span { + display: none; + } +} + +.art-dark { + .sol-views button { + color: rgba(255, 255, 255, 0.72); + + > .mat-icon { + color: rgba(255, 255, 255, 0.6); + } + + &:not([aria-pressed="true"]):not([disabled]):hover { + background: rgba(255, 255, 255, 0.08); + color: #fff; + } + + &[aria-pressed="true"] { + background: rgba(143, 227, 211, 0.14); + color: var(--ai-dark-accent); + + > .mat-icon { + color: var(--ai-dark-accent); + } + } + } + + .sol-tool { + color: rgba(255, 255, 255, 0.72); + + .mat-icon { + color: rgba(255, 255, 255, 0.6); + } + + &:hover { + background: rgba(255, 255, 255, 0.08); + color: #fff; + } + + &.on { + background: rgba(143, 227, 211, 0.14); + color: var(--ai-dark-accent); + + .mat-icon { + color: var(--ai-dark-accent); + } + } + } +} diff --git a/ui-ngx/src/app/modules/home/components/ai/solution/solution-chat.component.ts b/ui-ngx/src/app/modules/home/components/ai/solution/solution-chat.component.ts new file mode 100644 index 0000000000..de3b8151f5 --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/ai/solution/solution-chat.component.ts @@ -0,0 +1,1945 @@ +// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: BUSL-1.1 +import { AI_TOOLTIP_PROVIDERS } from '@home/components/ai/ai-tooltip'; +import { aiCreditsLimitOf, AiCreditsLimitType } from '@home/components/ai/ai-credits.models'; +import { AiCardAction } from '@home/components/ai/ai-card-actions.component'; +import { AiNotice } from '@shared/models/ai-chat.models'; +import { AiArtifactPaneComponent } from '@home/components/ai/ai-artifact-pane.component'; +import { + ChangeDetectionStrategy, + Component, + computed, + DestroyRef, + effect, + ElementRef, + EventEmitter, + HostListener, + inject, + OnDestroy, + OnInit, + Output, + signal, + untracked, + viewChild, + ViewChild +} from '@angular/core'; +import { + AiChatMessagesComponent, + AnswerRatingEvent, + AnswerReportEvent +} from '@home/components/ai/ai-chat-messages.component'; +import { PageComponent } from '@shared/components/page.component'; +import { DomSanitizer } from '@angular/platform-browser'; +import { ActivatedRoute, Router } from '@angular/router'; +import { + AiQuestion, + AiQuestionAnswer, + ChatMessage, + EntityResult, + DashboardsOverview, + GeneralChatMessage, + SolutionEstimate, + SolutionInstallProgress, + NEW_SOLUTION_ID, + SolutionCreatorInfo, + SolutionDescriptor, + SolutionInstallResult, + SolutionMetadata, + SolutionStep, + SolutionStepStatus +} from '@shared/models/solution-creator.models'; +import { AiPromptInputComponent } from '@home/components/ai/ai-prompt-input.component'; +import { AiPromptMessage, AiResourceInfo } from '@shared/models/ai-chat.models'; +import { SolutionsCreatorService } from '@core/http/solutions-creator.service'; +import { + catchError, + defaultIfEmpty, + filter, + finalize, + map, + switchMap, + take, + takeUntil, + tap +} from 'rxjs/operators'; +import { ActionNotificationShow } from '@core/notification/notification.actions'; +import { ClipboardService } from 'ngx-clipboard'; +import { downloadAiFile } from '@home/components/ai/ai-file.models'; +import { EMPTY, forkJoin, Observable, of, Subject, timer } from 'rxjs'; +import { takeUntilDestroyed, toObservable } from '@angular/core/rxjs-interop'; +import { DialogService } from '@core/services/dialog.service'; +import { TranslateService } from '@ngx-translate/core'; +import { AiSolutionsService } from '@core/services/ai-solutions.service'; +import { AuthService } from '@core/auth/auth.service'; +import { + SolutionInfoDialogComponent, + SolutionInfoDialogData +} from '@home/components/ai/solution/solution-info/solution-info-dialog.component'; +import { baseDetailsPageByEntityType, EntityType } from '@shared/models/entity-type.models'; +import { isNotEmptyStr, parseHttpErrorMessage } from '@core/utils'; +import { aggregateByName, IssueStatus } from '@home/components/ai/solution/solution-info/issues-aggregation'; +import { SolutionJsonComponent } from '@home/components/ai/solution/pane/solution-json.component'; +import { AiChatTitleComponent } from '@home/components/ai/ai-chat-title.component'; +import { AiSpinKind } from '@home/components/ai/ai-action.models'; +import { aiAnswersOf, aiAnswersText } from '@home/components/ai/ai-question.component'; +import { readStored, writeStored } from '@core/local-storage/stored'; +import { AiAnswerFeedback, aiRateAnswer, aiReportAnswer, aiTrackLogScroll } from '@home/components/ai/ai-chat-session'; +import { EntityId } from '@shared/models/id/entity-id'; + +export type SolutionView = 'overview' | 'dashboards' | 'solution'; + +function formatCredits(credits: number): string { + if (credits >= 1000) { + const thousands = credits / 1000; + return (thousands >= 10 ? Math.round(thousands) : Math.round(thousands * 10) / 10) + 'k'; + } + return String(credits); +} + +const isVisibleMessage = (msg: ChatMessage): boolean => + msg.from === 'AI' || (msg.from === 'USER' && !/^<[a-z-]+\/>$/.test(((msg as GeneralChatMessage).content ?? '').trim())); + +@Component({ + changeDetection: ChangeDetectionStrategy.OnPush, + selector: 'tb-solution-chat', + templateUrl: './solution-chat.component.html', + styleUrls: ['./solution-chat.component.scss'], + standalone: false, + providers: AI_TOOLTIP_PROVIDERS +}) +export class SolutionChatComponent extends PageComponent implements OnInit, OnDestroy { + + private static readonly NARROW_WIDTH = 1100; + + private static readonly CREDITS_PIN_MS = 1500; + private static readonly CONNECTIVITY_GUIDE = 'https://thingsboard.io/docs/getting-started-guides/connectivity/'; + + @ViewChild(AiPromptInputComponent) promptInput: AiPromptInputComponent; + @ViewChild(AiChatMessagesComponent) chatMessages: AiChatMessagesComponent; + @ViewChild(AiChatTitleComponent) titleRef: AiChatTitleComponent; + @ViewChild(AiArtifactPaneComponent) pane: AiArtifactPaneComponent; + @Output() loaded = new EventEmitter(); + + get hostElement(): HTMLElement { + return this.elementRef.nativeElement; + } + + isReadyStep = signal(false); + private static readonly DESIGN_POLL_MS = 4000; + + private static readonly DESIGN_POLL_LIMIT = 150; + + skipInterviewAllowed = signal(false); + solutionStep = signal(SolutionStep.INITIAL_CONFIGURATION); + creatorStep = signal<'chat' | 'result' | null>('chat'); + + messages = signal([]); + + loading = signal(false); + isGenerating = signal(false); + + work = signal<{words: string; kind: 'think' | 'gen' | 'install'; since: number; lines?: string[]} | null>(null); + + paneTalks = computed(() => this.showPane() && this.paneOpen() && !!this.making() && this.currentView() === this.making() + && !(this.making() === 'solution' && !!this.progressInfo())); + + fullscreen = signal(false); + + title = signal(''); + shownTitle = computed(() => this.title() || this.aiSolutions.find(this.info()?.id)?.solutionTitle || ''); + + built = signal(false); + + installed = signal(false); + + mainDashboard = signal([]); + + logScrolled = signal(false); + private atEnd = signal(true); + + private chatArea = viewChild>('chatArea'); + + private composer = viewChild>('composer'); + + private pinToEndUntil = 0; + + private creditsOutEffect = effect(() => { + if (this.creditsOut()) { + this.pinToEndUntil = Date.now() + SolutionChatComponent.CREDITS_PIN_MS; + setTimeout(() => this.scrollLogToEnd()); + } + }); + + private composerSizeEffect = effect(onCleanup => { + const area = this.chatArea()?.nativeElement; + const composer = this.composer()?.nativeElement; + if (!area || !composer) { + return; + } + let composerHeight = composer.offsetHeight; + const observer = new ResizeObserver(() => { + const height = composer.offsetHeight; + if (Date.now() < this.pinToEndUntil || (height > composerHeight && untracked(this.atEnd))) { + area.scrollTop = area.scrollHeight; + } + composerHeight = height; + }); + observer.observe(composer); + if (area.firstElementChild) { + observer.observe(area.firstElementChild); + } + onCleanup(() => observer.disconnect()); + }); + private newTurns = signal(0); + private seenTurns = 0; + + pill = computed<{mode: 'work' | 'new'; kind: AiSpinKind; label: string; count: number} | null>(() => { + if (this.atEnd()) { + return null; + } + const work = this.work(); + if (work && (this.loading() || this.isGenerating())) { + return {mode: 'work', kind: work.kind, label: work.words, count: 0}; + } + const count = this.newTurns(); + return count ? {mode: 'new', kind: 'think', label: this.translate.instant('ai-assistant.new-count', {count}), count} : null; + }); + + private newTurnsEffect = effect(() => { + const total = this.viewMessages().length; + untracked(() => { + if (this.atEnd() || total <= this.seenTurns) { + this.seenTurns = total; + return; + } + this.newTurns.update(count => count + total - this.seenTurns); + this.seenTurns = total; + }); + }); + + onLogScroll(area: HTMLElement): void { + aiTrackLogScroll(area, {scrolled: this.logScrolled, atEnd: this.atEnd, newTurns: this.newTurns}, () => this.seenTurns = this.viewMessages().length); + } + + goToEnd(area: HTMLElement): void { + const reduce = matchMedia('(prefers-reduced-motion: reduce)').matches; + area.scrollTo({top: area.scrollHeight, behavior: reduce ? 'auto' : 'smooth'}); + } + + statusTip = computed(() => { + const level = this.level(); + if (!level) { + return ''; + } + return level === 'error' && this.failure() ? this.failure() : this.translate.instant('ai-assistant.status-tip-' + level); + }); + + level = computed<'running' | 'needs' | 'error' | null>(() => this.loading() || this.isGenerating() + ? 'running' + : this.failure() ? 'error' + : this.pendingQuestions().length || (this.isReadyStep() && this.creatorStep() === 'chat' && !this.built()) ? 'needs' : null); + + info = signal(null); + + making = signal(null); + + pickedView = signal<{view: SolutionView; phase: string} | null>(null); + + json = signal(false); + + opening = signal(false); + + jsonWrap = signal(SolutionChatComponent.stored('tbAiFileWrap') === 'true'); + + jsonWhitespace = signal(SolutionChatComponent.stored('tbAiFileWhitespace') === 'true'); + + jsonDark = signal(SolutionChatComponent.stored('tbAiFileTheme') !== 'light'); + + jsonCopied = signal(false); + + private jsonCopiedTimer: ReturnType; + + private clipboardService = inject(ClipboardService); + + toggleJsonWrap(): void { + this.jsonWrap.update(wrap => !wrap); + SolutionChatComponent.store('tbAiFileWrap', String(this.jsonWrap())); + } + + toggleJsonWhitespace(): void { + this.jsonWhitespace.update(value => !value); + SolutionChatComponent.store('tbAiFileWhitespace', String(this.jsonWhitespace())); + } + + setJsonTheme(theme: 'dark' | 'light'): void { + this.jsonDark.set(theme === 'dark'); + SolutionChatComponent.store('tbAiFileTheme', theme); + } + + copyJson(): void { + if (this.jsonView && this.clipboardService.copyFromContent(this.jsonView.text())) { + this.jsonCopied.set(true); + clearTimeout(this.jsonCopiedTimer); + this.jsonCopiedTimer = setTimeout(() => this.jsonCopied.set(false), 1500); + } + } + + downloadJson(): void { + if (this.jsonView) { + downloadAiFile({...this.jsonView.file(), content: this.jsonView.text()}); + } + } + + onJsonDiscarded(): void { + this.store.dispatch(new ActionNotificationShow({ + message: this.translate.instant('solution-creator.pane.json-discarded'), + type: 'success', + modern: true, + verticalPosition: 'bottom', + horizontalPosition: 'center' + })); + } + + private static stored(key: string): string | null { + return readStored(key); + } + + private static store(key: string, value: string): void { + writeStored(key, value); + } + + uninstalledAt = signal(null); + + failure = signal(null); + failedAt = signal<'install' | 'step'>('step'); + installProgress = signal(null); + makeStartedAt = signal(0); + private installOnly = signal(false); + private messageSteps: SolutionStep[] = []; + + stopping = signal(false); + private readonly stopEnded = effect(() => { + if (!this.loading() && !this.isGenerating()) { + untracked(() => this.stopping.set(false)); + } + }); + + notice = signal(null); + + creditsOut = signal(null); + + private freshSolutionId: string | null = null; + + private stoppedAction: (() => void) | null = null; + + progressInfo = computed(() => { + const progress = this.installProgress(); + const info = this.info(); + if (!progress || !info || (!progress.items?.length && !Object.values(progress.entityResults ?? {}).some(results => results?.length))) { + return null; + } + return {...info, metadata: {built: true, installed: false, installResult: {createdEntities: [], entityResults: progress.entityResults as any}}}; + }); + + createShare = computed(() => { + if (this.installOnly()) { + return 0; + } + const estimates = this.info()?.estimates; + const create = estimates?.CREATE?.seconds; + const install = estimates?.INSTALL?.seconds; + return create > 0 && install > 0 ? Math.min(.95, Math.max(.5, create / (create + install))) : .85; + }); + + makeSeconds = computed(() => { + const estimates = this.info()?.estimates; + if (this.installOnly()) { + return Math.max(5, estimates?.INSTALL?.seconds ?? 15); + } + const seconds = (estimates?.CREATE?.seconds ?? 0) + (estimates?.INSTALL?.seconds ?? 0); + return estimates?.CREATE && estimates?.INSTALL ? Math.max(20, seconds) : 90; + }); + + private closingPatch = signal>({}); + + private stepActions(): ChatMessage[] { + const info = this.info(); + const result = info?.metadata?.installResult; + const metadata = info?.metadata; + const actions: ChatMessage[] = [{from: 'ACTION', data: {executionId: 'solution-create', tool: 'create_solution', status: 'SUCCESS', + startedAt: metadata?.builtTime ?? 0, durationMs: metadata?.createDurationMs}}]; + if (this.installed() && result) { + const entities = Object.entries(result.entityResults ?? {}) + .filter(([type]) => type !== EntityType.ENTITY_GROUP && type !== EntityType.RULE_CHAIN) + .flatMap(([, entries]) => (entries ?? []).filter(entry => entry?.id && entry.status !== 'ERROR').map(entry => entry.id)); + actions.push({from: 'ACTION', data: {executionId: 'solution-install', tool: 'install_solution', status: 'SUCCESS', + startedAt: result.installedTime ?? 0, durationMs: result.durationMs, affectedEntities: entities}}); + } + return actions; + } + + closing = computed(() => { + const info = this.info(); + if (this.creatorStep() !== 'result' || !this.built() || !info) { + return null; + } + const installed = this.installed(); + const result = info.metadata?.installResult; + const user = this.mainUser(); + const chips: GeneralChatMessage['chips'] = []; + if (installed && user) { + chips.push({id: 'view-as', icon: 'person', label: this.translate.instant('solution-creator.view-as-name', {name: user.name})}); + } + chips.push({id: 'edit', icon: 'edit', label: this.translate.instant('ai-assistant.edit-design')}); + if (installed) { + chips.push({id: 'connect', icon: 'memory', label: this.translate.instant('solution-creator.connect-devices')}); + chips.push({id: 'uninstall', icon: 'delete_sweep', label: this.translate.instant('solution-creator.uninstall-solution')}); + } + return { + from: 'AI', + content: installed ? this.installedSummary(result?.entityResults) : this.translate.instant('solution-creator.closing-created'), + time: installed ? result?.installedTime : undefined, + entities: installed && this.mainDashboard().length ? this.mainDashboard() : undefined, + entitiesMeta: installed ? this.mainDashboardMeta() : undefined, + hint: installed ? { + lead: this.translate.instant('solution-creator.closing-simulated-lead'), + text: this.translate.instant('solution-creator.closing-simulated') + } : undefined, + chips, + ...this.closingPatch() + }; + }); + + viewMessages = computed(() => { + const messages = this.messages(); + const lastAi = messages.map(message => message.from).lastIndexOf('AI'); + const waiting = this.isReadyStep() && this.creatorStep() === 'chat' && !this.built() && !this.loading() && !this.isGenerating(); + return messages.map((message, index) => { + if (message.from === 'AI') { + const general = message as GeneralChatMessage; + const patch: Partial = {}; + if (/^\s*(✅|🛠️|🛠)/u.test(general.content ?? '')) { + patch.done = true; + } else if (/^\s*(🤔|💡|🛑)/u.test(general.content ?? '')) { + patch.done = false; + } + if (general.questions?.length) { + patch.lead = this.translate.instant('solution-creator.assumptions'); + } + if (waiting && index === lastAi) { + patch.note = this.translate.instant(this.solutionStep() === SolutionStep.DASHBOARDS_CONFIGURATION + ? 'solution-creator.next-create' : 'solution-creator.next-dashboards-note'); + } + return Object.keys(patch).length ? {...general, ...patch} : message; + } + if (message.from === 'USER') { + const previous = messages[index - 1] as GeneralChatMessage; + const answers = previous?.from === 'AI' ? aiAnswersOf((message as GeneralChatMessage).content, previous.questions) : null; + return answers ? {...message, answers} as GeneralChatMessage : message; + } + return message; + }).concat(this.closing() ? [...this.stepActions(), this.closing()] : []); + }); + + onChip(id: string): void { + switch (id) { + case 'resume': + this.resume(); + break; + case 'view-as': + this.viewAsMainUser(); + break; + case 'edit': + this.editDesign(); + break; + case 'connect': + this.connectDevices(); + break; + case 'uninstall': + this.uninstallSolution(); + break; + } + } + + private installedSummary(results: Partial> | undefined): string { + const count = (...types: EntityType[]) => types.reduce((sum, type) => + sum + aggregateByName(type, results?.[type]).filter(row => row.status !== IssueStatus.ERROR).length, 0); + const parts = [ + ['device', count(EntityType.DEVICE)], + ['asset', count(EntityType.ASSET)], + ['profile', count(EntityType.DEVICE_PROFILE, EntityType.ASSET_PROFILE)], + ['calculated-field', count(EntityType.CALCULATED_FIELD)], + ['alarm-rule', count(EntityType.ALARM)], + ['role', count(EntityType.ROLE)], + ['user', count(EntityType.USER)], + ['dashboard', count(EntityType.DASHBOARD)] + ].filter(([, n]) => (n as number) > 0) + .map(([key, n]) => this.translate.instant('solution-creator.installed-made.' + key, {count: n})); + if (!parts.length) { + return this.translate.instant('solution-creator.closing-installed'); + } + const items = parts.length === 1 ? parts[0] + : parts.slice(0, -1).join(', ') + ' ' + this.translate.instant('solution-creator.installed-and') + ' ' + parts[parts.length - 1]; + return this.translate.instant('solution-creator.installed-summary', {items}); + } + + private mainDashboardMeta(): string | undefined { + const result = this.info()?.metadata?.installResult; + const main = result?.mainDashboardId?.id; + const dashboard = main ? result?.entityResults?.[EntityType.DASHBOARD]?.find(entry => entry.id?.id === main) : undefined; + if (!dashboard) { + return undefined; + } + const role = this.info()?.data?.dashboardsOverview?.find(overview => overview.name === dashboard.additionalData?.name)?.assignedTo; + const user = this.mainUser(); + return [ + this.translate.instant('entity.type-dashboard'), + role, + user ? this.translate.instant('solution-creator.shared-with', {name: user.name}) : null + ].filter(Boolean).join(' · '); + } + + pendingQuestions = computed(() => { + const last = this.messages()[this.messages().length - 1] as GeneralChatMessage; + if (!last || last.from !== 'AI' || !last.questions?.length || this.loading() || this.isGenerating() || this.isReadyStep() + || this.solutionStep() !== SolutionStep.INITIAL_CONFIGURATION) { + return []; + } + return last.questions; + }); + + readonly aboutFeatures = [ + {icon: 'account_tree', title: 'solution-creator.about-design-title', line: 'solution-creator.about-design'}, + {icon: 'fact_check', title: 'solution-creator.about-approve-title', line: 'solution-creator.about-approve'}, + {icon: 'dashboard', title: 'solution-creator.about-dashboards-title', line: 'solution-creator.about-dashboards'}, + {icon: 'layers', title: 'solution-creator.about-installed-title', line: 'solution-creator.about-installed'} + ]; + + aboutOpen = signal(false); + + issues = computed>(() => { + const results = this.info()?.metadata?.installResult?.entityResults; + if (!results || !this.info()?.metadata?.installed) { + return []; + } + return Object.values(results).flat() + .filter(entry => entry?.status === 'ERROR' || entry?.status === 'WARN') + .map(entry => ({name: entry.additionalData?.name ?? '', status: entry.status, message: entry.error?.message})); + }); + + private paneEdgeEffect = effect(() => { + this.currentView(); + this.json(); + this.paneOpen(); + untracked(() => setTimeout(() => this.pane?.refreshEdges(), 50)); + }); + + private failureEffect = effect(() => { + const id = this.info()?.id; + const failure = this.failure(); + untracked(() => this.aiSolutions.setFailed(id, failure)); + }); + + private runningEffect = effect(() => { + const id = this.info()?.id; + const running = this.loading() || this.isGenerating(); + untracked(() => this.aiSolutions.setRunning(id, running)); + }); + + private needsEffect = effect(onCleanup => { + const id = this.info()?.id; + const needs = this.level() === 'needs'; + untracked(() => this.aiSolutions.setNeeds(id, needs)); + onCleanup(() => untracked(() => this.aiSolutions.setNeeds(id, false))); + }); + + mainUser = computed<{id: string; name: string} | null>(() => { + const result = this.info()?.metadata?.installResult; + const main = result?.mainDashboardId?.id; + const dashboard = main ? result?.entityResults?.[EntityType.DASHBOARD]?.find(entry => entry.id?.id === main) : undefined; + const userId = dashboard?.additionalData?.userId; + if (!userId) { + return null; + } + const user = result.entityResults?.[EntityType.USER]?.find(entry => entry.id?.id === userId); + return {id: userId, name: user?.additionalData?.name ?? ''}; + }); + + jsonValue = computed(() => this.currentView() === 'dashboards' + ? this.info()?.data?.dashboardsOverview + : this.info()?.data?.solutionDescriptor); + + @ViewChild('jsonView') jsonView: SolutionJsonComponent; + + paneOpen = signal(typeof window === 'undefined' || window.innerWidth >= SolutionChatComponent.NARROW_WIDTH); + + phase = computed(() => `${this.creatorStep()}:${this.solutionStep()}`); + + views = computed>(() => { + const info = this.info(); + const states = info?.states; + const have: Record = { + overview: !!info?.data?.solutionDescriptor && states?.[SolutionStep.INITIAL_CONFIGURATION]?.status === SolutionStepStatus.READY, + dashboards: !!info?.data?.dashboardsOverview?.length, + solution: !!info?.metadata?.built + }; + const icons: Record = {overview: 'account_tree', dashboards: 'dashboard', solution: 'layers'}; + return (['overview', 'dashboards', 'solution'] as SolutionView[]).map(id => ({ + id, + icon: icons[id], + state: this.making() === id ? 'working' : have[id] ? 'have' : 'next' + })); + }); + + currentView = computed(() => { + const views = this.views(); + const usable = (view: SolutionView) => views.find(item => item.id === view)?.state !== 'next'; + const picked = this.pickedView(); + if (picked && picked.phase === this.phase() && usable(picked.view)) { + return picked.view; + } + if (this.making()) { + return this.making(); + } + const preferred: SolutionView = this.creatorStep() === 'result' ? 'solution' + : this.solutionStep() === SolutionStep.DASHBOARDS_CONFIGURATION ? 'dashboards' : 'overview'; + if (usable(preferred)) { + return preferred; + } + return [...views].reverse().find(item => item.state !== 'next')?.id ?? null; + }); + + showPane = computed(() => !!this.currentView()); + + jsonAvailable = computed(() => !this.making() && (this.currentView() === 'overview' || this.currentView() === 'dashboards')); + + trayNote = computed(() => { + const making = this.making(); + if (making) { + return this.translate.instant(making === 'solution' ? 'solution-creator.pane.creating' : 'solution-creator.pane.designing'); + } + if (this.failure()) { + return this.translate.instant(this.failedAt() === 'install' ? 'solution-creator.pane.install-failed' : 'solution-creator.pane.step-failed'); + } + return this.translate.instant('solution-creator.pane.view-' + this.currentView()); + }); + + showMoreExamples = signal(false); + + isInitialEmpty = computed(() => + this.creatorStep() === 'chat' && + this.solutionStep() === SolutionStep.INITIAL_CONFIGURATION && + !this.messages().length && + !this.loading() + ); + + activePlaceholder = computed(() => this.isInitialEmpty() + || (this.creatorStep() === 'chat' && this.solutionStep() === SolutionStep.INITIAL_CONFIGURATION && !this.isReadyStep() && !this.pendingQuestions().length) + ? 'solution-creator.describe-solution-you-want' + : this.pendingQuestions().length ? 'solution-creator.type-the-answer' + : this.creatorStep() === 'result' ? 'solution-creator.ask-about-solution' : 'solution-creator.say-what-to-change'); + + solutionExamples: Array<{ key: string; labelKey: string; icon: string; message: string }> = [ + { + key: 'coffeeMonitor', + labelKey: 'solution-creator.coffee-machine-monitoring', + icon: 'coffee', + message: 'I want to monitor my coffee machine. It brews espresso, cappuccino, latte, and americano.\n\n' + + 'I need to track stock levels (beans, milk, water, cups), waste fullness, and temperatures. ' + + 'I also want to calculate daily totals for each drink type and daily revenue.\n\n' + + 'Alert me when stock runs low, waste is nearly full, or temperatures are out of range.' + }, + { + key: 'lorawanTracker', + labelKey: 'solution-creator.lorawan-tracking', + icon: 'cell_tower', + message: 'I need a simple device management dashboard for monitoring my LoRaWAN tracker devices and connectivity.\n' + + 'I want to assign a label to device and see them on the map.\n' + + 'I also want to browse the device telemetry related to signal strength and raise alerts when device is offline, low battery or low signal strength.' + }, + { + key: 'waterMetering', + labelKey: 'solution-creator.water-metering', + icon: 'water_drop', + message: 'I\'m building a water metering solution for a utility company. We deploy pulse-based water meters at residential and commercial properties to monitor consumption and track water costs.\n\n' + + 'The meter reports a cumulative pulse counter; consumption in liters is derived from the delta between readings.\n\n' + + 'Residential and commercial properties are billed at different rates. The price per liter is fixed per property type and set by the utility — not configurable per individual property.\n\n' + + 'Each property owner should see only their own consumption and cost data. Alert when consumption is abnormally high or a possible leak is detected. Alert thresholds should be configurable per property.' + }, + { + key: 'smartParking', + labelKey: 'solution-creator.smart-parking', + icon: 'local_parking', + message: 'I would like to create a simple smart parking solution to monitor single level indoor parking lots with magnetic sensors.\n\n' + + 'There will be three roles:\n' + + ' * Solution Administrator will provision customers, sensors and users. He needs to see the alarms from devices.\n' + + ' * Technician will oversee all sensor statuses. He is interested to track the alarms.\n' + + ' * Parking attendant view parking status.\n\n' + + 'Parking lots are relatively small, no need to create Zones or support parking spaces types.\n\n' + + 'Alarms:\n' + + 'An alarm must be generated for a sensor offline, a low battery, or if a vehicle overstays a designated time limit.\n' + + 'The low battery and max stay duration must be configured on the customer level.' + }, + { + key: 'weatherMonitoring', + labelKey: 'solution-creator.weather-monitoring', + icon: 'thermostat', + message: 'I want to monitor outdoor weather conditions across multiple locations using weather stations. ' + + 'Each station reports standard atmospheric data — temperature, humidity, pressure, wind speed and direction, and rainfall.\n\n' + + 'Show all stations on a map. Alert when conditions reach extreme levels such as frost, strong wind, or heavy rainfall.' + }, + { + key: 'fleetGeofencing', + labelKey: 'solution-creator.fleet-geofencing', + icon: 'local_shipping', + message: 'I want to build a fleet tracking solution for transport companies. Vehicles are tracked by GPS in real time and must operate within designated allowed zones while avoiding restricted areas.\n\n' + + 'Raise an alarm when a vehicle enters a restricted zone or leaves an allowed zone.' + }, + ]; + + SolutionStep = SolutionStep; + + private solutionId: string; + private _solutionInfo: SolutionCreatorInfo; + + private get solutionInfo(): SolutionCreatorInfo { + return this._solutionInfo; + } + + private set solutionInfo(value: SolutionCreatorInfo) { + this._solutionInfo = value; + this.info.set(value ? {...value} : null); + this.title.set(value?.data?.solutionTitle || value?.data?.aiSolutionTitle || ''); + this.built.set(!!value?.metadata?.built); + this.installed.set(!!value?.metadata?.installed); + const main = value?.metadata?.installResult?.mainDashboardId; + this.mainDashboard.set(value?.metadata?.installed && main ? [main] : []); + } + private messages$ = toObservable(this.messages); + private forceScroll = false; + + private cancelPending$ = new Subject(); + private workTimers: NodeJS.Timeout[] = []; + + constructor(private route: ActivatedRoute, + private solutionCreator: SolutionsCreatorService, + private router: Router, + private destroyRef: DestroyRef, + private elementRef: ElementRef, + private dialogService: DialogService, + private translate: TranslateService, + private sanitizer: DomSanitizer, + private aiSolutions: AiSolutionsService, + private authService: AuthService) { + super(); + + this.messages$.pipe( + takeUntilDestroyed(), + ).subscribe(value => { + const lastMsg = value[value.length - 1]; + if (this.forceScroll) { + setTimeout(() => { + const animationPanel: Element = this.elementRef.nativeElement.querySelector('.overview'); + if (animationPanel) { + animationPanel.addEventListener('animationend', () => { + this.scrollLogToEnd(); + }, { once: true }); + } else { + this.scrollLogToEnd(); + } + }, 0); + this.forceScroll = false; + } else if (lastMsg?.from === 'USER') { + setTimeout(() => this.scrollLogToEnd(true), 0); + } else if (lastMsg?.from === 'AI') { + setTimeout(() => this.scrollLastQuestionToTop(), 0); + } + }) + } + + ngOnInit() { + SolutionChatComponent.watchUnload(); + this.route.queryParams.pipe( + filter(data => this.solutionId !== data.solutionId), + tap(() => this.resetSolution()), + switchMap(data => { + if (data.solutionId && data.solutionId !== NEW_SOLUTION_ID) { + this.opening.set(true); + const listed$ = this.aiSolutions.loaded() ? of(null) : this.aiSolutions.load().pipe(catchError(() => of(null))); + return forkJoin([this.solutionCreator.getSolutionById(data.solutionId, {ignoreLoading: true, ignoreErrors: true}), listed$]).pipe( + map(([solution]) => solution), + catchError(err => { + this.opening.set(false); + this.creatorStep.set('chat'); + if (err?.status === 400 || err?.status === 404) { + this.router.navigate([], { + relativeTo: this.route, + queryParams: {solutionId: NEW_SOLUTION_ID}, + queryParamsHandling: 'merge', + replaceUrl: true + }); + } else { + this.showErrorMessage(err); + } + return EMPTY; + }) + ); + } else { + this.opening.set(false); + this.creatorStep.set('chat'); + return EMPTY; + } + }), + takeUntilDestroyed(this.destroyRef) + ).subscribe(solution => { + this.opening.set(false); + this.solutionId = solution.id; + this.solutionInfo = solution; + this.forceScroll = true; + this.initPredefinedSolution(); + this.loaded.emit(solution.id); + setTimeout(() => this.scrollLogToEnd(), 300); + }); + } + + ngOnDestroy(): void { + this.keepRunningListed(); + this.clearWork(); + this.cancelPending$.next(); + this.cancelPending$.complete(); + } + + toggleFullscreen(): void { + this.fullscreen.update(value => !value); + } + + renameTo(title: string): void { + if (!this.solutionId || title === this.title()) { + return; + } + this.aiSolutions.rename(this.aiSolutions.find(this.solutionId) ?? {id: this.solutionId}, title).subscribe({ + next: value => this.updatedSolution(value), + error: err => this.showErrorMessage(err) + }); + } + + deleteSolution(): void { + if (!this.solutionId) { + return; + } + this.aiSolutions.confirmAndDelete(this.aiSolutions.find(this.solutionId) ?? {id: this.solutionId, solutionTitle: this.title()}).subscribe({ + next: deleted => { + if (deleted) { + this.router.navigate([], {relativeTo: this.route, queryParams: {solutionId: NEW_SOLUTION_ID}, queryParamsHandling: 'merge'}); + } + }, + error: err => this.showErrorMessage(err) + }); + } + + @HostListener('keydown.escape') + closeAbout(): void { + this.aboutOpen.set(false); + } + + stop(): void { + if (!this.solutionId || this.stopping()) { + return; + } + this.stopping.set(true); + this.solutionCreator.stopSolution(this.solutionId, {ignoreLoading: true, ignoreErrors: true}).subscribe({ + next: stopped => { + if (!stopped) { + this.stopping.set(false); + } + }, + error: () => this.stopping.set(false) + }); + } + + resume(): void { + const action = this.stoppedAction; + this.stoppedAction = null; + this.messages.update(list => list.filter(message => (message as GeneralChatMessage).status !== 'STOPPED')); + action?.(); + } + + private creditsLimitOf(err: any, message?: string): AiCreditsLimitType | null { + const limitType = aiCreditsLimitOf(err); + if (limitType) { + return limitType; + } + const text = message ?? (parseHttpErrorMessage(err, this.translate, isNotEmptyStr(err?.error) ? 'text' : undefined, this.sanitizer).message ?? '').toString(); + return /out of ai credits|ai_credits limit exceeded/i.test(text) ? 'POOL' : null; + } + + private restorePrompt(msg: string): void { + const messages = this.messages(); + const last = messages.map(message => message.from).lastIndexOf('USER'); + let resources: AiResourceInfo[] = []; + if (last >= 0 && (messages[last] as GeneralChatMessage).content === msg) { + resources = (messages[last] as GeneralChatMessage).resources ?? []; + this.messages.set([...messages.slice(0, last), ...messages.slice(last + 1)]); + this.messageSteps = this.messageSteps.slice(0, -1); + } + setTimeout(() => { + this.promptInput?.setValue(msg); + this.promptInput?.restoreAttachments(resources); + }); + } + + private discardFreshSolution(msg: string): boolean { + const solutionId = this.freshSolutionId; + this.freshSolutionId = null; + if (!solutionId || solutionId !== this.solutionId) { + return false; + } + this.aiSolutions.discard(solutionId).subscribe(); + this.router.navigate([], {relativeTo: this.route, queryParams: {solutionId: NEW_SOLUTION_ID}, queryParamsHandling: 'merge', replaceUrl: true}) + .then(() => setTimeout(() => this.promptInput?.setValue(msg))); + return true; + } + + private noticeFor(err: any): boolean { + const status = err?.status; + const message = (parseHttpErrorMessage(err, this.translate, isNotEmptyStr(err?.error) ? 'text' : undefined, this.sanitizer).message ?? '').toString(); + const limitType = this.creditsLimitOf(err, message); + if (status === 0) { + this.setNotice('warn', 'wifi_off', 'connection-failed'); + } else if (limitType) { + this.creditsOut.set(limitType); + } else if (status === 429) { + this.setNotice('warn', 'hourglass_top', 'rate-limited'); + } else { + return false; + } + return true; + } + + private setNotice(kind: AiNotice['kind'], icon: string, key: string): void { + this.notice.set({kind, icon, text: this.translate.instant('ai-assistant.notice.' + key)}); + } + + private wasStopped(err: any, again: () => void, phase: 'chat' | 'build' | 'install' = 'chat'): boolean { + if (!this.stopping() || err?.status !== 409) { + return false; + } + this.stopping.set(false); + this.stoppedAction = again; + this.messageSteps = [...this.messageSteps, this.solutionStep()]; + const chips = phase === 'chat' ? undefined : [ + {id: 'resume', icon: 'play_arrow', label: this.translate.instant(phase === 'install' ? 'solution-creator.create-solution' : 'ai-assistant.resume')}, + {id: 'edit', icon: 'edit', label: this.translate.instant('solution-creator.change-design')} + ]; + this.messages.update(list => [...list, {from: 'AI', content: this.translate.instant('solution-creator.stopped' + (phase === 'chat' ? '' : '-' + phase)), + status: 'STOPPED', time: Date.now(), ...(chips ? {chips} : {})}]); + setTimeout(() => this.scrollLogToEnd(true)); + return true; + } + + private reportFailure(err: any, at?: 'install' | 'step'): void { + this.failedAt.set(at ?? (this.creatorStep() === 'result' ? 'install' : 'step')); + const responseType = isNotEmptyStr(err?.error) ? 'text' : undefined; + this.failure.set(parseHttpErrorMessage(err, this.translate, responseType, this.sanitizer).message); + this.paneOpen.set(true); + setTimeout(() => this.scrollLogToEnd(true)); + } + + private openPaneForStep(): void { + if (window.innerWidth >= SolutionChatComponent.NARROW_WIDTH) { + this.paneOpen.set(true); + } + } + + viewAsMainUser(): void { + const user = this.mainUser(); + const main = this.info()?.metadata?.installResult?.mainDashboardId?.id; + if (!user || !main) { + return; + } + const tenantUser = !this.info()?.metadata?.installResult?.entityResults?.[EntityType.USER] + ?.find(entry => entry.id?.id === user.id)?.additionalData?.customer; + this.authService.redirectUrl = tenantUser ? `/dashboards/all/${main}` : `/dashboards/${main}`; + this.authService.loginAsUser(user.id).subscribe(() => {}); + } + + connectDevices(): void { + window.open(SolutionChatComponent.CONNECTIVITY_GUIDE, '_blank', 'noopener'); + } + + fillExample(key: string): void { + const example = this.solutionExamples.find(ex => ex.key === key); + if (example) { + this.promptInput?.setValue(example.message, true); + } + } + + nextStep() { + const toDashboards = this.solutionStep() === SolutionStep.INITIAL_CONFIGURATION || this.currentView() === 'overview'; + if (toDashboards && this.solutionInfo.states[SolutionStep.INITIAL_CONFIGURATION]?.status !== SolutionStepStatus.READY) { + return; + } + if (!toDashboards && this.solutionInfo.states[SolutionStep.DASHBOARDS_CONFIGURATION]?.status !== SolutionStepStatus.READY) { + if (this.solutionInfo.states[SolutionStep.DASHBOARDS_CONFIGURATION]?.pendingChanges?.length) { + this.sendDashboardConfigurationMsg(''); + } + return; + } + this.pickedView.set(null); + if (toDashboards) { + const dashboardState = this.solutionInfo.states[SolutionStep.DASHBOARDS_CONFIGURATION]; + const notStarted = !dashboardState || (!dashboardState.messages?.length && dashboardState.status !== SolutionStepStatus.READY); + if (notStarted) { + this.solutionInfo.states[SolutionStep.DASHBOARDS_CONFIGURATION] = { + messages: [], + status: SolutionStepStatus.IN_PROGRESS, + chatId: dashboardState?.chatId ?? null + } + this.solutionStep.set(SolutionStep.DASHBOARDS_CONFIGURATION); + this.updatedCurrentMsg(); + this.sendDashboardConfigurationMsg(''); + } else if (dashboardState.pendingChanges?.length) { + this.solutionStep.set(SolutionStep.DASHBOARDS_CONFIGURATION); + this.updatedCurrentMsg(); + this.sendDashboardConfigurationMsg(''); + } else { + this.solutionStep.set(SolutionStep.DASHBOARDS_CONFIGURATION); + this.updatedCurrentMsg(); + } + } else { + if (this.solutionInfo.metadata?.built) { + this.creatorStep.set('result'); + } else { + this.installProgress.set(null); + this.makeStartedAt.set(Date.now()); + this.installOnly.set(false); + SolutionChatComponent.markMaking(this.solutionId, true); + const dialogRef = this.initGenerateState('create'); + const uninstallOrContinue$ = !this.solutionInfo.metadata?.installed + ? of(null) + : this.solutionCreator.uninstallSolution(this.solutionId, {ignoreLoading: true, ignoreErrors: true}); + uninstallOrContinue$.pipe( + switchMap(() => this.withProgress(this.solutionCreator.createSolution(this.solutionId, { + ignoreLoading: true, + ignoreErrors: true + }))), + tap(() => this.creatorStep.set('result')), + switchMap((solution) => + this.installWithProgress() + .pipe(map((installData) => { + if (!solution.metadata) { + solution.metadata = {} as SolutionMetadata; + } + solution.metadata.installed = true; + if (!solution.metadata.installResult) { + solution.metadata.installResult = {} as SolutionInstallResult; + } + Object.assign(solution.metadata.installResult, installData); + return solution; + })) + ), + takeUntil(this.cancelPending$), + finalize(() => { + this.isGenerating.set(false); + dialogRef.close(); + }) + ) + .subscribe({ + next: (value) => { + SolutionChatComponent.markMaking(value.id, false); + this.solutionInfo = value; + this.aiSolutions.upsert(value); + this.showInstalled(); + }, + error: (err) => { + if (err?.status !== 0 && !SolutionChatComponent.unloading) { + SolutionChatComponent.markMaking(this.solutionId, false); + } + if (!this.wasStopped(err, () => this.nextStep(), 'build') && !this.noticeFor(err)) { + this.reportFailure(err); + } + } + }); + } + } + } + + installSolution() { + this.failure.set(null); + this.installProgress.set(null); + this.makeStartedAt.set(Date.now()); + this.installOnly.set(true); + if (window.innerWidth >= SolutionChatComponent.NARROW_WIDTH) { + this.paneOpen.set(true); + } + const work = this.startWork([{text: 'solution-creator.step-loading-creating-entities', delay: 0}], 'install'); + this.making.set('solution'); + this.installWithProgress().pipe( + takeUntil(this.cancelPending$), + finalize(() => work.close()) + ).subscribe({ + next: (value) => { + SolutionChatComponent.markMaking(this.solutionId, false); + if (!this.solutionInfo.metadata) { + this.solutionInfo.metadata = {} as SolutionMetadata; + } + if (!this.solutionInfo.metadata.installResult) { + this.solutionInfo.metadata.installResult = {} as SolutionInstallResult; + } + Object.assign(this.solutionInfo.metadata.installResult, value); + this.solutionInfo.metadata.installed = true; + this.solutionInfo = {...this.solutionInfo}; + this.aiSolutions.update(this.solutionId, {installed: true}); + this.showInstalled(); + }, + error: (err) => { + if (err?.status !== 0 && !SolutionChatComponent.unloading) { + SolutionChatComponent.markMaking(this.solutionId, false); + } + if (!this.wasStopped(err, () => this.installSolution(), 'install') && !this.noticeFor(err)) { + this.reportFailure(err, 'install'); + } + } + }); + } + + private installWithProgress(): Observable { + return this.withProgress(this.solutionCreator.installSolution(this.solutionId, {ignoreLoading: true, ignoreErrors: true})); + } + + private withProgress(operation: Observable): Observable { + const solutionId = this.solutionId; + const finished$ = new Subject(); + timer(800, 1200).pipe( + switchMap(() => this.aiSolutions.installProgress(solutionId).pipe(catchError(() => of(null)))), + takeUntil(finished$), + takeUntil(this.cancelPending$) + ).subscribe(progress => { + if (progress?.running) { + this.installProgress.set(progress); + } + }); + return operation.pipe( + finalize(() => { + finished$.next(); + finished$.complete(); + }) + ); + } + + estimateOf(view: SolutionView): string { + const estimates = this.info()?.estimates; + const operations: Record>> = { + overview: ['INITIAL_CONFIGURATION'], + dashboards: ['DASHBOARDS_CONFIGURATION'], + solution: ['CREATE', 'INSTALL'] + }; + const known = operations[view].map(operation => estimates?.[operation]).filter((estimate): estimate is SolutionEstimate => !!estimate); + if (!known.length || known.length < operations[view].length) { + return this.translate.instant('solution-creator.pane.estimate-' + view); + } + const seconds = known.reduce((sum, estimate) => sum + estimate.seconds, 0); + const credits = known.reduce((sum, estimate) => sum + estimate.credits, 0); + const time = seconds < 50 + ? this.translate.instant('solution-creator.pane.about-seconds', {count: Math.max(10, Math.round(seconds / 10) * 10)}) + : seconds < 90 + ? this.translate.instant('solution-creator.pane.estimate-solution') + : this.translate.instant('solution-creator.pane.about-minutes', {count: Math.round(seconds / 60)}); + return credits > 0 ? time + ' · ' + this.translate.instant('solution-creator.pane.credits', {credits: formatCredits(credits), count: credits}) : time; + } + + answerQuestions(answers: AiQuestionAnswer[]): void { + this.sendMsgFromUser({message: aiAnswersText(answers), resources: []}); + } + + skipQuestions(answers: AiQuestionAnswer[]): void { + if (this.skipInterviewAllowed()) { + this.skipInterview(); + } else { + this.answerQuestions(answers); + } + } + + onRate(event: AnswerRatingEvent): void { + const target = this.answerAt(event.index); + if (target) { + aiRateAnswer(event, target.answer.rating, this.answerFeedback(event.index, target)); + } + } + + onReport(event: AnswerReportEvent): void { + const target = this.answerAt(event.index); + if (target) { + aiReportAnswer(event, this.answerFeedback(event.index, target), () => this.store.dispatch(new ActionNotificationShow({ + message: this.translate.instant('ai-assistant.feedback.thanks'), type: 'success', modern: true, + target: 'solution-creator-chat', verticalPosition: 'bottom', horizontalPosition: 'center' + }))); + } + } + + private answerFeedback(index: number, target: {answer: GeneralChatMessage; step: SolutionStep}): AiAnswerFeedback { + return { + patch: patch => this.patchAnswer(index, patch), + send: feedback => this.aiSolutions.sendFeedback(this.solutionId, target.step, {answer: target.answer.content, ...feedback}), + failed: () => this.showErrorMessage(this.translate.instant('ai-assistant.feedback.failed')) + }; + } + + private answerAt(index: number): {answer: GeneralChatMessage; step: SolutionStep} | null { + const message = this.viewMessages()[index] as GeneralChatMessage; + if (!this.solutionId || message?.from !== 'AI' || !message.content) { + return null; + } + return {answer: message, step: this.messageSteps[index] ?? this.solutionStep()}; + } + + private patchAnswer(index: number, patch: Partial): void { + if (index >= this.messages().length) { + this.closingPatch.update(current => ({...current, ...patch})); + return; + } + this.messages.update(list => list.map((message, at) => at === index ? {...message, ...patch} as GeneralChatMessage : message)); + } + + uninstallSolution() { + this.dialogService.confirm( + this.translate.instant('solution-creator.uninstall-solution-dialog-title', {name: this.solutionInfo.data.solutionTitle}), + this.translate.instant('solution-creator.uninstall-solution-dialog-text'), + this.translate.instant('action.no'), + this.translate.instant('solution-creator.uninstall-solution-dialog-confirm') + ).subscribe((value) => { + if (value) { + this.solutionCreator.uninstallSolution(this.solutionId, {ignoreErrors: true}).pipe( + takeUntil(this.cancelPending$) + ).subscribe((value) => { + this.solutionInfo = value; + this.aiSolutions.update(this.solutionId, {installed: false}); + this.uninstalledAt.set(Date.now()); + if (this.creatorStep() === 'result') { + this.pickedView.set({view: 'solution', phase: this.phase()}); + } + }); + } + }) + } + + startOver() { + this.initLoadingState(); + this.solutionCreator.clearStep(this.solutionId, this.solutionStep(), {ignoreLoading: true, ignoreErrors: true}).pipe( + takeUntil(this.cancelPending$) + ).subscribe({ + next: () => { + this.messages.set([]); + this.messageSteps = []; + this.isReadyStep.set(false); + if (this.solutionStep() === SolutionStep.DASHBOARDS_CONFIGURATION) { + this.sendDashboardConfigurationMsg(''); + } else { + this.stopLoadingState(); + } + }, + error: (err) => { + this.showErrorMessage(err); + this.stopLoadingState(); + }, + complete: () => { + this.stopLoadingState(); + } + }) + } + + editDesign(): void { + if (this.creatorStep() === 'result') { + this.back(); + } + } + + back(): void { + this.forceScroll = true; + if (this.creatorStep() === 'result') { + this.solutionStep.set(SolutionStep.DASHBOARDS_CONFIGURATION); + this.creatorStep.set('chat'); + } else if(this.solutionStep() === SolutionStep.DASHBOARDS_CONFIGURATION) { + this.solutionStep.set(SolutionStep.INITIAL_CONFIGURATION); + } + this.updatedCurrentMsg(); + } + + updatedSolutionDescriptor(descriptor: SolutionDescriptor) { + this.solutionCreator.updateSolutionData(this.solutionId, 'solutionDescriptor', descriptor, {ignoreLoading: true}).pipe( + takeUntil(this.cancelPending$) + ).subscribe(value => { + this.solutionInfo = value; + this.aiSolutions.upsert(value); + this.updatedCurrentMsg(); + }); + } + + updatedDashboardOverview(dashboards: DashboardsOverview[]) { + this.solutionCreator.updateSolutionData(this.solutionId, 'dashboardsOverview', dashboards, {ignoreLoading: true}).pipe( + takeUntil(this.cancelPending$) + ).subscribe(value => { + this.solutionInfo = value; + this.aiSolutions.upsert(value); + this.updatedCurrentMsg(); + }); + } + + get solutionMetadata(): Partial { + return this.solutionInfo?.metadata ?? {}; + } + + get nextButtonLabel(): string { + if (this.solutionStep() === SolutionStep.INITIAL_CONFIGURATION) { + return 'solution-creator.go-dashboard-manager'; + } else { + if (this.solutionInfo.metadata?.built) { + return 'solution-creator.finish-edit'; + } + if (this.solutionInfo.data.entities || this.solutionInfo.data.dashboards) { + return 'solution-creator.update-solution'; + } + return 'solution-creator.create-solution'; + } + } + + updatedSolution($event: SolutionCreatorInfo) { + if ($event.id === this.solutionId) { + this.solutionInfo = $event; + } + } + + onInstalledChanged($event: {solutionId: string, installed: boolean}) { + if ($event.solutionId === this.solutionId && this.solutionInfo) { + if (!this.solutionInfo.metadata) { + this.solutionInfo.metadata = {} as SolutionMetadata; + } + this.solutionInfo.metadata.installed = $event.installed; + } + } + + startCreateSolution(key: string) { + const example = this.solutionExamples.find(ex => ex.key === key); + if (example) { + this.sendMsgFromUser({message: example.message, resources: []}); + } + } + + private showInstalled(): void { + this.creatorStep.set('result'); + this.json.set(false); + this.pickedView.set({view: 'solution', phase: this.phase()}); + if (window.innerWidth >= SolutionChatComponent.NARROW_WIDTH) { + this.paneOpen.set(true); + } + } + + gotoMainDashboard(openInfoDialog = false): void { + this.router.navigateByUrl( + this.router.createUrlTree([baseDetailsPageByEntityType.get(EntityType.DASHBOARD), this.solutionMetadata.installResult.mainDashboardId.id]) + ).then(()=> { + if (openInfoDialog) { + this.openInfo(); + } + }); + } + + openInfo(): void { + this.dialogService.dialog.open(SolutionInfoDialogComponent, { + disableClose: true, + panelClass: ['tb-dialog', 'tb-fullscreen-dialog'], + data: { + solution: this.solutionInfo + } + }).afterClosed().subscribe(() => {}); + } + + private sendMessage(msg: string, resources: string[] = []): Observable { + this.initLoadingState(); + + const startOrContinue$ = this.solutionId + ? of(null) + : this.solutionCreator.startSolution({ignoreLoading: true, ignoreErrors: true}).pipe( + tap(solution => { + this.freshSolutionId = solution.id; + this.solutionId = solution.id; + this.solutionInfo = solution; + this.rememberSolution(); + this.router.navigate([], { + relativeTo: this.route, + queryParams: { solutionId: this.solutionId }, + queryParamsHandling: 'merge', + }).then(() => {}); + }) + ); + + return startOrContinue$.pipe( + switchMap(() => + this.solutionCreator.chatSolution(this.solutionId, this.solutionStep(), msg, {ignoreLoading: true, ignoreErrors: true}, resources) + ), + tap(solution => { + this.freshSolutionId = null; + this.solutionInfo = solution; + this.rememberSolution(); + this.updatedCurrentMsg(); + if (this.isReadyStep()) { + this.openPaneForStep(); + } + }), + catchError(err => { + if (this.creditsLimitOf(err)) { + this.restorePrompt(msg); + if (this.discardFreshSolution(msg)) { + this.noticeFor(err); + return EMPTY; + } + } + this.freshSolutionId = null; + if (err?.status === 0 && this.solutionId && this.solutionId !== NEW_SOLUTION_ID) { + this.setNotice('warn', 'wifi_off', 'connection-lost'); + this.recoverDroppedMessage(msg); + return EMPTY; + } + if (!this.wasStopped(err, () => this.sendMessage(msg, resources).subscribe(() => {})) && !this.noticeFor(err)) { + this.showErrorMessage(err); + } + this.rememberSolution(); + return EMPTY; + }), + takeUntil(this.cancelPending$), + finalize(() => this.stopLoadingState()) + ); + } + + private scrollLogToEnd(smooth = false): void { + const log = this.elementRef.nativeElement.querySelector('.sol-log') as HTMLElement; + log?.scrollTo({top: log.scrollHeight, behavior: smooth ? 'smooth' : 'auto'}); + } + + private scrollLastQuestionToTop(): void { + const log = this.elementRef.nativeElement.querySelector('.sol-log') as HTMLElement; + const questions = log?.querySelectorAll('tb-ai-chat-messages .user'); + const last = questions?.length ? questions[questions.length - 1] : null; + if (log && last) { + const top = log.scrollTop + last.getBoundingClientRect().top - log.getBoundingClientRect().top - 12; + log.scrollTo({top, behavior: 'smooth'}); + } + } + + private rememberSolution(): void { + if (this.solutionInfo) { + this.aiSolutions.upsert(this.solutionInfo); + } + } + + private sendDashboardConfigurationMsg(message: string): void { + const dialogRef = this.initGenerateState(message === '' ? 'sync' : 'design'); + this.sendMessage(message).pipe( + finalize(() => { + this.isGenerating.set(false); + dialogRef.close(); + }), + ).subscribe(() => {}); + } + + private updatedCurrentMsg() { + const steps = this.solutionStep() === SolutionStep.DASHBOARDS_CONFIGURATION + ? [SolutionStep.INITIAL_CONFIGURATION, SolutionStep.DASHBOARDS_CONFIGURATION] + : [SolutionStep.INITIAL_CONFIGURATION]; + const tagged = steps.flatMap(step => (this.solutionInfo.states[step]?.messages ?? []).filter(isVisibleMessage).map(message => ({message, step}))); + this.messageSteps = tagged.map(item => item.step); + this.messages.set(tagged.map(item => item.message)); + const stepState = this.solutionInfo.states[this.solutionStep()]; + if (stepState?.status === SolutionStepStatus.READY) { + if (this.solutionStep() === SolutionStep.INITIAL_CONFIGURATION) { + } + if (this.solutionStep() === SolutionStep.DASHBOARDS_CONFIGURATION) { + } + this.isReadyStep.set(true); + this.skipInterviewAllowed.set(false); + } else { + this.isReadyStep.set(false); + this.skipInterviewAllowed.set(!!stepState?.skipInterviewAllowed); + } + } + + showErrorMessage(error: any): void { + const responseType = isNotEmptyStr(error?.error) ? 'text' : undefined; + const message = parseHttpErrorMessage(error, this.translate, responseType, this.sanitizer).message; + const showOnTop = this.creatorStep() === 'result' || this.isInitialEmpty(); + this.store.dispatch(new ActionNotificationShow({ + message, + modern: true, + type: 'error', + target: showOnTop ? 'solution-creator' : 'solution-creator-chat', + verticalPosition: showOnTop ? 'top' : 'bottom', + horizontalPosition: 'center', + panelClass: showOnTop ? ( this.isInitialEmpty() ? 'mt-4' : 'mt-12') : '' + })); + } + + private keepRunningListed(): void { + if (this.solutionId && this.solutionId !== NEW_SOLUTION_ID && (this.loading() || this.isGenerating())) { + this.aiSolutions.keepRunning(this.solutionId); + } + } + + private resetSolution(): void { + this.keepRunningListed(); + this.clearWork(); + this.pickedView.set(null); + this.json.set(false); + this.installProgress.set(null); + this.failedAt.set('step'); + this.uninstalledAt.set(null); + this.cancelPending$.next(); + this.isReadyStep.set(false); + this.skipInterviewAllowed.set(false); + this.solutionStep.set(SolutionStep.INITIAL_CONFIGURATION); + this.messages.set([]); + this.messageSteps = []; + this.closingPatch.set({}); + this.stopping.set(false); + this.stopLoadingState(); + this.creatorStep.set(null); + this.promptInput?.reset(); + this.showMoreExamples.set(false); + this.solutionId = undefined; + this.solutionInfo = undefined; + } + + private initPredefinedSolution(): void { + const listed = this.aiSolutions.find(this.solutionInfo?.id); + this.failure.set(listed?.status === 'FAILED' ? listed.statusReason ?? null : null); + if (this.solutionInfo.metadata?.built) { + if (this.solutionInfo.states[SolutionStep.DASHBOARDS_CONFIGURATION]) { + this.solutionStep.set(SolutionStep.DASHBOARDS_CONFIGURATION); + } + this.updatedCurrentMsg(); + this.creatorStep.set('result'); + if (!this.solutionInfo.metadata?.installed) { + this.resumeMaking(); + } + return; + } + this.creatorStep.set('chat'); + const initialStatus = this.solutionInfo.states[SolutionStep.INITIAL_CONFIGURATION]?.status; + const dashboardState = this.solutionInfo.states[SolutionStep.DASHBOARDS_CONFIGURATION]; + const dashboardsStarted = !!dashboardState && (!!dashboardState.messages?.length || dashboardState.status === SolutionStepStatus.READY + || !this.aiSolutions.loaded() || this.aiSolutions.find(this.solutionInfo.id)?.status === 'RUNNING'); + this.solutionStep.set(initialStatus === SolutionStepStatus.READY && dashboardsStarted + ? SolutionStep.DASHBOARDS_CONFIGURATION : SolutionStep.INITIAL_CONFIGURATION); + this.updatedCurrentMsg(); + if (this.isReadyStep()) { + this.paneOpen.set(true); + } + if (this.solutionStep() === SolutionStep.DASHBOARDS_CONFIGURATION && dashboardState?.pendingChanges?.length) { + this.sendDashboardConfigurationMsg(''); + } + if (this.designStillRunning()) { + this.waitForDesign(); + } else if (this.solutionStep() === SolutionStep.DASHBOARDS_CONFIGURATION && this.isReadyStep()) { + this.resumeMaking(); + } + } + + private static unloading = false; + + private static watchUnload(): void { + window.addEventListener('pagehide', () => SolutionChatComponent.unloading = true, {once: true}); + } + + private static makingKey(solutionId: string): string { + return 'tb-ai-solution-making-' + solutionId; + } + + private static markMaking(solutionId: string | undefined, making: boolean): void { + if (!solutionId) { + return; + } + try { + if (making) { + sessionStorage.setItem(SolutionChatComponent.makingKey(solutionId), '1'); + } else { + sessionStorage.removeItem(SolutionChatComponent.makingKey(solutionId)); + } + } catch { + return; + } + } + + private static wasMaking(solutionId: string): boolean { + try { + return sessionStorage.getItem(SolutionChatComponent.makingKey(solutionId)) === '1'; + } catch { + return false; + } + } + + private resumeMaking(): void { + const solutionId = this.solutionId; + const pending = SolutionChatComponent.wasMaking(solutionId); + forkJoin([ + this.aiSolutions.load().pipe(catchError(() => of([]))), + this.aiSolutions.installProgress(solutionId).pipe(catchError(() => of(null))), + this.solutionCreator.getSolutionById(solutionId, {ignoreLoading: true, ignoreErrors: true}).pipe(catchError(() => of(null))) + ]).pipe(takeUntil(this.cancelPending$), takeUntilDestroyed(this.destroyRef)).subscribe(([, progress, fresh]) => { + if (this.solutionId !== solutionId || this.isGenerating()) { + return; + } + if (fresh) { + this.solutionInfo = fresh; + if (fresh.metadata?.built && this.creatorStep() !== 'result') { + this.creatorStep.set('result'); + } + if (fresh.metadata?.installed) { + SolutionChatComponent.markMaking(solutionId, false); + return; + } + } + const running = this.aiSolutions.find(solutionId)?.status === 'RUNNING' || !!progress?.running; + const built = !!this.solutionInfo?.metadata?.built; + if (!built && running) { + this.followCreate(); + } else if (built && running) { + this.followInstall(); + } else if (built && pending) { + this.installSolution(); + } + }); + } + + private followCreate(): void { + const solutionId = this.solutionId; + this.installProgress.set(null); + this.makeStartedAt.set(Date.now() - this.makeSeconds() * 1000); + this.installOnly.set(false); + SolutionChatComponent.markMaking(solutionId, true); + const dialogRef = this.initGenerateState('create'); + this.withProgress(timer(SolutionChatComponent.DESIGN_POLL_MS, SolutionChatComponent.DESIGN_POLL_MS).pipe( + take(SolutionChatComponent.DESIGN_POLL_LIMIT), + switchMap(() => this.solutionCreator.getSolutionById(solutionId, {ignoreLoading: true, ignoreErrors: true}).pipe(catchError(() => EMPTY))), + filter(solution => !!solution.metadata?.built), + take(1) + )).pipe( + takeUntil(this.cancelPending$), + finalize(() => { + this.isGenerating.set(false); + dialogRef.close(); + }), + takeUntilDestroyed(this.destroyRef) + ).subscribe(solution => { + if (this.solutionId !== solutionId) { + return; + } + this.solutionInfo = solution; + this.aiSolutions.upsert(solution); + this.creatorStep.set('result'); + if (!solution.metadata?.installed) { + setTimeout(() => this.installSolution(), 0); + } + }); + } + + private followInstall(): void { + const solutionId = this.solutionId; + this.installProgress.set(null); + this.makeStartedAt.set(Date.now() - this.makeSeconds() * 1000); + this.installOnly.set(true); + this.creatorStep.set('result'); + if (window.innerWidth >= SolutionChatComponent.NARROW_WIDTH) { + this.paneOpen.set(true); + } + const work = this.startWork([{text: 'solution-creator.step-loading-creating-entities', delay: 0}], 'install'); + this.making.set('solution'); + timer(800, 1200).pipe( + switchMap(() => this.aiSolutions.installProgress(solutionId).pipe(catchError(() => of(null)))), + tap(progress => { + if (progress?.running) { + this.installProgress.set(progress); + } + }), + filter(progress => !progress?.running), + take(1), + switchMap(() => this.solutionCreator.getSolutionById(solutionId, {ignoreLoading: true, ignoreErrors: true}).pipe(catchError(() => EMPTY))), + takeUntil(this.cancelPending$), + finalize(() => work.close()), + takeUntilDestroyed(this.destroyRef) + ).subscribe(solution => { + if (this.solutionId !== solutionId) { + return; + } + this.solutionInfo = solution; + this.aiSolutions.upsert(solution); + if (solution.metadata?.installed) { + SolutionChatComponent.markMaking(solutionId, false); + this.showInstalled(); + } + }); + } + + private recoverDroppedMessage(msg: string): void { + const solutionId = this.solutionId; + const step = this.solutionStep(); + const sent = this.messages().filter((message, at) => message.from === 'USER' && this.messageSteps[at] === step).length; + timer(0, SolutionChatComponent.DESIGN_POLL_MS).pipe( + take(SolutionChatComponent.DESIGN_POLL_LIMIT), + switchMap(() => forkJoin([ + this.solutionCreator.getSolutionById(solutionId, {ignoreLoading: true, ignoreErrors: true}), + this.aiSolutions.load() + ]).pipe(catchError(() => EMPTY))), + take(1), + defaultIfEmpty(null), + takeUntil(this.cancelPending$), + takeUntilDestroyed(this.destroyRef) + ).subscribe(result => { + if (this.solutionId !== solutionId) { + return; + } + this.notice.set(null); + const solution = result?.[0]; + const received = !!solution && (solution.states?.[step]?.messages ?? []) + .filter(message => message.from === 'USER' && isVisibleMessage(message)).length >= sent; + if (!received) { + this.restorePrompt(msg); + this.setNotice('warn', 'wifi_off', 'connection-failed'); + return; + } + this.solutionInfo = solution; + this.aiSolutions.upsert(solution); + this.initPredefinedSolution(); + }); + } + + private designStillRunning(): boolean { + return this.stepAwaitingReply(this.solutionInfo, this.solutionStep()); + } + + private stepAwaitingReply(solution: SolutionCreatorInfo | undefined, step: SolutionStep): boolean { + const state = solution?.states?.[step]; + const last = state?.messages?.at(-1) as GeneralChatMessage | undefined; + if (state && state.status !== SolutionStepStatus.READY && this.aiSolutions.find(solution.id)?.status === 'RUNNING') { + return true; + } + if (state && !last && state.status !== SolutionStepStatus.READY) { + return !this.aiSolutions.loaded() || this.aiSolutions.find(solution.id)?.status === 'RUNNING'; + } + if (last?.from === 'USER') { + return this.awaitingReply(solution.id, last); + } + return state?.status !== SolutionStepStatus.READY && this.awaitingReply(solution?.id, last); + } + + private awaitingReply(solutionId: string, last: GeneralChatMessage | undefined): boolean { + if (last?.from === 'USER') { + return !this.aiSolutions.loaded() || this.aiSolutions.find(solutionId)?.status === 'RUNNING'; + } + return last?.from === 'AI' && /^\s*(✅|🛠️|🛠)/u.test(last.content ?? ''); + } + + private waitForDesign(): void { + const solutionId = this.solutionId; + const step = this.solutionStep(); + this.skipInterviewAllowed.set(false); + const since = this.workSince(step); + if (step === SolutionStep.DASHBOARDS_CONFIGURATION) { + this.initGenerateState('design', since); + } else { + if ((this.messages().at(-1) as GeneralChatMessage | undefined)?.from === 'AI') { + this.messages.set(this.messages().slice(0, -1)); + this.messageSteps = this.messageSteps.slice(0, -1); + } + this.isGenerating.set(true); + this.startWork([{text: 'solution-creator.work-thinking', delay: 0}], 'think', since); + } + timer(SolutionChatComponent.DESIGN_POLL_MS, SolutionChatComponent.DESIGN_POLL_MS).pipe( + take(SolutionChatComponent.DESIGN_POLL_LIMIT), + switchMap(() => this.solutionCreator.getSolutionById(solutionId, {ignoreLoading: true, ignoreErrors: true}).pipe(catchError(() => EMPTY))), + filter(solution => !this.stepAwaitingReply(solution, step)), + take(1), + takeUntil(this.cancelPending$), + finalize(() => { + if (this.solutionId === solutionId) { + this.isGenerating.set(false); + this.clearWork(); + } + }), + takeUntilDestroyed(this.destroyRef) + ).subscribe(solution => { + if (this.solutionId !== solutionId) { + return; + } + this.isGenerating.set(false); + this.clearWork(); + this.solutionInfo = solution; + this.aiSolutions.upsert(solution); + this.initPredefinedSolution(); + }); + } + + private initGenerateState(kind: 'design' | 'sync' | 'create', since = Date.now()) { + this.failure.set(null); + this.isGenerating.set(true); + let messages: Array<{text: string; delay: number}>; + if (this.solutionStep() === SolutionStep.INITIAL_CONFIGURATION) { + messages = [ + { text: 'solution-creator.step-loading-updating-entities', delay: 0 }, + { text: 'solution-creator.step-loading-restructuring-roles', delay: 10000 }, + { text: 'solution-creator.step-loading-rebuilding-alarm-rules', delay: 10000 }, + { text: 'solution-creator.step-loading-reassembling-dashboards', delay: 10000 }, + { text: 'solution-creator.step-loading-updating-solution', delay: 10000 }, + ]; + } else if (this.solutionStep() === SolutionStep.DASHBOARDS_CONFIGURATION) { + if (kind === 'design') { + messages = [ + { text: 'solution-creator.step-loading-designing-dashboards-structure', delay: 0 }, + { text: 'solution-creator.step-loading-designing-dashboards-states', delay: 10000 }, + { text: 'solution-creator.step-loading-designing-widgets', delay: 10000 }, + { text: 'solution-creator.step-loading-adding-finishing-touches', delay: 10000 }, + ]; + } else if (kind === 'sync') { + messages = [ + { text: 'solution-creator.step-loading-evaluating-solution-changes', delay: 0 }, + { text: 'solution-creator.step-loading-reevaluating-use-cases', delay: 5000 }, + { text: 'solution-creator.step-loading-finalizing', delay: 15000 }, + ]; + } else { + messages = [ + { text: 'solution-creator.step-loading-creating-entities', delay: 0 }, + { text: 'solution-creator.step-loading-configuring-devices', delay: 10000 }, + { text: 'solution-creator.step-loading-setting-up-relations', delay: 10000 }, + { text: 'solution-creator.step-loading-structuring-access-controls', delay: 10000 }, + { text: 'solution-creator.step-loading-building-calculated-fields', delay: 10000 }, + { text: 'solution-creator.step-loading-building-alarm-rules', delay: 10000 }, + { text: 'solution-creator.step-loading-assembling-dashboards', delay: 10000 }, + { text: 'solution-creator.step-loading-preparing-states', delay: 10000 }, + { text: 'solution-creator.step-loading-initializing-solution', delay: 10000 }, + ]; + } + } + + const creating = messages[0]?.text === 'solution-creator.step-loading-creating-entities'; + this.making.set(creating ? 'solution' : this.solutionStep() === SolutionStep.DASHBOARDS_CONFIGURATION ? 'dashboards' : 'overview'); + this.json.set(false); + if (window.innerWidth >= SolutionChatComponent.NARROW_WIDTH) { + this.paneOpen.set(true); + } + return this.startWork(messages, creating ? 'install' : 'gen', since); + } + + private static storeWork(solutionId: string, value: string): void { + try { + sessionStorage.setItem(SolutionChatComponent.workKey(solutionId), value); + } catch { + return; + } + } + + private static workKey(solutionId: string): string { + return `tb-ai-solution-work-${solutionId}`; + } + + private workSince(step: SolutionStep): number { + let since = 0; + try { + const [storedStep, storedSince] = (sessionStorage.getItem(SolutionChatComponent.workKey(this.solutionId)) ?? '').split(':'); + if (storedStep === step) { + since = Number(storedSince) || 0; + } + } catch { + since = 0; + } + const asked = (this.messages() as GeneralChatMessage[]).filter(message => message.from === 'USER' && message.time).at(-1)?.time ?? 0; + const start = Math.max(since, asked); + return start > 0 && start <= Date.now() ? start : Date.now(); + } + + private startWork(messages: Array<{text: string; delay: number}>, kind: 'think' | 'gen' | 'install', + since = Date.now()): {close: () => void} { + const making = this.making(); + this.clearWork(); + this.making.set(making); + if (kind !== 'install' && this.solutionId && this.solutionId !== NEW_SOLUTION_ID) { + SolutionChatComponent.storeWork(this.solutionId, `${this.solutionStep()}:${since}`); + } + const lines = messages.map(message => this.translate.instant(message.text) as string); + let at = 0; + messages.forEach((message, index) => { + at += message.delay; + this.workTimers.push(setTimeout(() => this.work.set({words: lines[index], kind, since, lines}), at)); + }); + return {close: () => this.clearWork()}; + } + + private clearWork(): void { + this.workTimers.forEach(timer => clearTimeout(timer)); + this.workTimers = []; + this.work.set(null); + this.making.set(null); + } + + pickView(view: SolutionView): void { + this.pickedView.set({view, phase: this.phase()}); + this.json.set(false); + } + + toggleJson(): void { + this.json.set(!this.json()); + } + + applyJson(value: unknown): void { + if (this.currentView() === 'dashboards') { + this.updatedDashboardOverview(value as DashboardsOverview[]); + } else { + this.updatedSolutionDescriptor(value as SolutionDescriptor); + } + } + + openPane(): void { + this.paneOpen.set(true); + } + + closePane(): void { + this.paneOpen.set(false); + this.json.set(false); + } + + toggleMoreExamples(): void { + this.showMoreExamples.update(v => !v); + } + + skipActions(): AiCardAction[] { + return [{id: 'skip', icon: 'fast_forward', label: this.translate.instant('solution-creator.skip-interview')}]; + } + + skipInterview(): void { + this.sendMessage('').subscribe(() => {}); + } + + sendMsgFromUser(prompt: AiPromptMessage): void { + const time = Date.now(); + this.messageSteps = [...this.messageSteps, this.solutionStep()]; + this.messages.update(list => [...list, prompt.resources.length + ? {from: 'USER', content: prompt.message, resources: prompt.resources, time} + : {from: 'USER', content: prompt.message, time}]); + this.sendMessage(prompt.message, prompt.resources.map(resource => resource.id)).subscribe(() => {}); + } + + private initLoadingState(): void { + this.failure.set(null); + if (this.notice()?.kind !== 'block') { + this.notice.set(null); + } + this.loading.set(true); + if (!this.workTimers.length) { + this.startWork([{text: this.messages().length ? 'solution-creator.work-thinking' : 'solution-creator.work-reading', delay: 0}], 'think'); + } + } + + private stopLoadingState(): void { + this.loading.set(false); + if (!this.isGenerating()) { + this.clearWork(); + } + } +} diff --git a/ui-ngx/src/app/modules/home/components/ai/solution/solution-chat.module.ts b/ui-ngx/src/app/modules/home/components/ai/solution/solution-chat.module.ts new file mode 100644 index 0000000000..20cf12a4f9 --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/ai/solution/solution-chat.module.ts @@ -0,0 +1,42 @@ +// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: BUSL-1.1 +import { CommonModule } from '@angular/common'; +import { SharedModule } from '@shared/shared.module'; +import { HomeComponentsModule } from '@home/components/home-components.module'; +import { NgModule } from '@angular/core'; +import { SolutionChatComponent } from '@home/components/ai/solution/solution-chat.component'; +import { + SolutionInfoDialogComponent +} from '@home/components/ai/solution/solution-info/solution-info-dialog.component'; +import { + IssuesPopoverComponent +} from '@home/components/ai/solution/solution-info/issues-popover.component'; +import { NgxGraphModule } from '@swimlane/ngx-graph'; +import { SolutionOverviewComponent } from '@home/components/ai/solution/pane/solution-overview.component'; +import { SolutionDashboardsComponent } from '@home/components/ai/solution/pane/solution-dashboards.component'; +import { SolutionInstalledComponent } from '@home/components/ai/solution/pane/solution-installed.component'; +import { SolutionJsonComponent } from '@home/components/ai/solution/pane/solution-json.component'; +import { AiModule } from '@home/components/ai/ai.module'; + +@NgModule({ + declarations: [ + SolutionChatComponent, + SolutionOverviewComponent, + SolutionDashboardsComponent, + SolutionInstalledComponent, + SolutionJsonComponent, + SolutionInfoDialogComponent, + IssuesPopoverComponent + ], + imports: [ + CommonModule, + SharedModule, + HomeComponentsModule, + NgxGraphModule, + AiModule + ], + exports: [ + SolutionChatComponent + ] +}) +export class SolutionChatModule { } diff --git a/ui-ngx/src/app/modules/home/pages/ai-solution-creator/solution-info/issues-aggregation.ts b/ui-ngx/src/app/modules/home/components/ai/solution/solution-info/issues-aggregation.ts similarity index 100% rename from ui-ngx/src/app/modules/home/pages/ai-solution-creator/solution-info/issues-aggregation.ts rename to ui-ngx/src/app/modules/home/components/ai/solution/solution-info/issues-aggregation.ts diff --git a/ui-ngx/src/app/modules/home/pages/ai-solution-creator/solution-info/issues-popover.component.html b/ui-ngx/src/app/modules/home/components/ai/solution/solution-info/issues-popover.component.html similarity index 100% rename from ui-ngx/src/app/modules/home/pages/ai-solution-creator/solution-info/issues-popover.component.html rename to ui-ngx/src/app/modules/home/components/ai/solution/solution-info/issues-popover.component.html diff --git a/ui-ngx/src/app/modules/home/pages/ai-solution-creator/solution-info/issues-popover.component.scss b/ui-ngx/src/app/modules/home/components/ai/solution/solution-info/issues-popover.component.scss similarity index 100% rename from ui-ngx/src/app/modules/home/pages/ai-solution-creator/solution-info/issues-popover.component.scss rename to ui-ngx/src/app/modules/home/components/ai/solution/solution-info/issues-popover.component.scss diff --git a/ui-ngx/src/app/modules/home/pages/ai-solution-creator/solution-info/issues-popover.component.ts b/ui-ngx/src/app/modules/home/components/ai/solution/solution-info/issues-popover.component.ts similarity index 95% rename from ui-ngx/src/app/modules/home/pages/ai-solution-creator/solution-info/issues-popover.component.ts rename to ui-ngx/src/app/modules/home/components/ai/solution/solution-info/issues-popover.component.ts index 9e01a9776d..5066957104 100644 --- a/ui-ngx/src/app/modules/home/pages/ai-solution-creator/solution-info/issues-popover.component.ts +++ b/ui-ngx/src/app/modules/home/components/ai/solution/solution-info/issues-popover.component.ts @@ -1,7 +1,7 @@ // SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. // SPDX-License-Identifier: BUSL-1.1 import { Component, Input } from '@angular/core'; -import { AggregatedEntityResult, issuesCountSummary } from '@home/pages/ai-solution-creator/solution-info/issues-aggregation'; +import { AggregatedEntityResult, issuesCountSummary } from '@home/components/ai/solution/solution-info/issues-aggregation'; import { EntityResult } from '@shared/models/solution-creator.models'; import { TranslateService } from '@ngx-translate/core'; diff --git a/ui-ngx/src/app/modules/home/pages/ai-solution-creator/solution-info/solution-info-dialog.component.html b/ui-ngx/src/app/modules/home/components/ai/solution/solution-info/solution-info-dialog.component.html similarity index 99% rename from ui-ngx/src/app/modules/home/pages/ai-solution-creator/solution-info/solution-info-dialog.component.html rename to ui-ngx/src/app/modules/home/components/ai/solution/solution-info/solution-info-dialog.component.html index b2ce060ca6..fb24ae192e 100644 --- a/ui-ngx/src/app/modules/home/pages/ai-solution-creator/solution-info/solution-info-dialog.component.html +++ b/ui-ngx/src/app/modules/home/components/ai/solution/solution-info/solution-info-dialog.component.html @@ -13,7 +13,7 @@
- +
@let dashboardEntries = aggregatedFor(EntityType.DASHBOARD); @if (dashboardEntries.length > 0) { diff --git a/ui-ngx/src/app/modules/home/pages/ai-solution-creator/solution-info/solution-info-dialog.component.scss b/ui-ngx/src/app/modules/home/components/ai/solution/solution-info/solution-info-dialog.component.scss similarity index 100% rename from ui-ngx/src/app/modules/home/pages/ai-solution-creator/solution-info/solution-info-dialog.component.scss rename to ui-ngx/src/app/modules/home/components/ai/solution/solution-info/solution-info-dialog.component.scss diff --git a/ui-ngx/src/app/modules/home/pages/ai-solution-creator/solution-info/solution-info-dialog.component.ts b/ui-ngx/src/app/modules/home/components/ai/solution/solution-info/solution-info-dialog.component.ts similarity index 94% rename from ui-ngx/src/app/modules/home/pages/ai-solution-creator/solution-info/solution-info-dialog.component.ts rename to ui-ngx/src/app/modules/home/components/ai/solution/solution-info/solution-info-dialog.component.ts index 991222e665..a903f4745f 100644 --- a/ui-ngx/src/app/modules/home/pages/ai-solution-creator/solution-info/solution-info-dialog.component.ts +++ b/ui-ngx/src/app/modules/home/components/ai/solution/solution-info/solution-info-dialog.component.ts @@ -17,9 +17,9 @@ import { AggregatedEntityResult, issuesCountSummary, IssueStatus -} from '@home/pages/ai-solution-creator/solution-info/issues-aggregation'; +} from '@home/components/ai/solution/solution-info/issues-aggregation'; import { TbPopoverService } from '@shared/components/popover.service'; -import { IssuesPopoverComponent } from '@home/pages/ai-solution-creator/solution-info/issues-popover.component'; +import { IssuesPopoverComponent } from '@home/components/ai/solution/solution-info/issues-popover.component'; export interface SolutionInfoDialogData { solution: SolutionCreatorInfo; @@ -28,7 +28,7 @@ export interface SolutionInfoDialogData { @Component({ selector: 'tb-solution-info-dialog', templateUrl: './solution-info-dialog.component.html', - styleUrls: ['../../../../../shared/components/markdown.component.scss', './solution-info-dialog.component.scss'], + styleUrls: ['../../../../../../shared/components/markdown.component.scss', './solution-info-dialog.component.scss'], standalone: false }) export class SolutionInfoDialogComponent extends DialogComponent { diff --git a/ui-ngx/src/app/modules/home/components/alarm-rules/alarm-rules-table-config.ts b/ui-ngx/src/app/modules/home/components/alarm-rules/alarm-rules-table-config.ts index 36ce683376..c2c801f634 100644 --- a/ui-ngx/src/app/modules/home/components/alarm-rules/alarm-rules-table-config.ts +++ b/ui-ngx/src/app/modules/home/components/alarm-rules/alarm-rules-table-config.ts @@ -124,7 +124,7 @@ export class AlarmRulesTableConfig extends EntityTableConfig -@if (show()) { -
- - -
-} diff --git a/ui-ngx/src/app/modules/home/components/alarm/ai-assistant-alarm-button.component.ts b/ui-ngx/src/app/modules/home/components/alarm/ai-assistant-alarm-button.component.ts deleted file mode 100644 index 731caf5423..0000000000 --- a/ui-ngx/src/app/modules/home/components/alarm/ai-assistant-alarm-button.component.ts +++ /dev/null @@ -1,43 +0,0 @@ -// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. -// SPDX-License-Identifier: BUSL-1.1 -import { Component, OnInit } from '@angular/core'; -import { Store } from '@ngrx/store'; -import { AppState } from '@core/core.state'; -import { getCurrentAuthState, getCurrentAuthUser } from '@core/auth/auth.selectors'; -import { AuthUser } from '@shared/models/user.model'; -import { AiAssistantPanelService } from '@core/services/ai-assistant-panel.service'; -import { Operation, Resource } from '@shared/models/security.models'; -import { UserPermissionsService } from '@core/http/user-permissions.service'; -import { alarmRuleEntityTypeList } from '@shared/models/alarm-rule.models'; - -@Component({ - selector: 'tb-ai-assistant-alarm-button', - templateUrl: './ai-assistant-alarm-button.component.html', - standalone: false -}) -export class AiAssistantAlarmButtonComponent implements OnInit { - - private authUser: AuthUser = getCurrentAuthUser(this.store); - private hasPermission: boolean; - - constructor(private store: Store, - private panelService: AiAssistantPanelService, - private userPermissionsService: UserPermissionsService) { - } - - ngOnInit(): void { - this.hasPermission = getCurrentAuthState(this.store).aiEnabled && - this.userPermissionsService.hasGenericPermission(Resource.AI, Operation.ALL) && - alarmRuleEntityTypeList.some(entityType => - this.userPermissionsService.hasGenericPermissionByEntityGroupType(Operation.READ_CALCULATED_FIELD, entityType)); - } - - show(): boolean { - return this.hasPermission && !this.panelService.open(); - } - - toggleAiAssistant($event: Event): void { - $event?.stopPropagation(); - this.panelService.toggle(); - } -} diff --git a/ui-ngx/src/app/modules/home/components/alarm/alarm-comment.component.scss b/ui-ngx/src/app/modules/home/components/alarm/alarm-comment.component.scss index 91f07bce91..8c482949f4 100644 --- a/ui-ngx/src/app/modules/home/components/alarm/alarm-comment.component.scss +++ b/ui-ngx/src/app/modules/home/components/alarm/alarm-comment.component.scss @@ -2,7 +2,7 @@ // SPDX-FileCopyrightText: Modifications Copyright ThingsBoard, Inc. // SPDX-License-Identifier: Apache-2.0 AND BUSL-1.1 @use '@angular/material' as mat; -@import "../theme/app-theme.scss"; +@import "../theme/app-theme-palette"; @import '../../../../../scss/constants'; $primary-color: mat.m2-get-color-from-palette($tb-primary); diff --git a/ui-ngx/src/app/modules/home/components/alarm/alarm-details-dialog.component.ts b/ui-ngx/src/app/modules/home/components/alarm/alarm-details-dialog.component.ts index 3115a38684..aae7ebe3da 100644 --- a/ui-ngx/src/app/modules/home/components/alarm/alarm-details-dialog.component.ts +++ b/ui-ngx/src/app/modules/home/components/alarm/alarm-details-dialog.component.ts @@ -31,6 +31,7 @@ export interface AlarmDetailsDialogData { allowClear: boolean; displayDetails: boolean; allowAssign: boolean; + displayOriginatorName?: boolean; } @Component({ @@ -108,8 +109,10 @@ export class AlarmDetailsDialogComponent extends DialogComponent filter_list{{buttonDisplayValue}} diff --git a/ui-ngx/src/app/modules/home/components/alarm/alarm-table-config.ts b/ui-ngx/src/app/modules/home/components/alarm/alarm-table-config.ts index 2f846be65b..66b727ce14 100644 --- a/ui-ngx/src/app/modules/home/components/alarm/alarm-table-config.ts +++ b/ui-ngx/src/app/modules/home/components/alarm/alarm-table-config.ts @@ -1,6 +1,8 @@ // SPDX-FileCopyrightText: Copyright The ThingsBoard Authors // SPDX-FileCopyrightText: Modifications Copyright ThingsBoard, Inc. // SPDX-License-Identifier: Apache-2.0 AND BUSL-1.1 +import { aiSevMarkElement } from '@home/components/ai/ai-sev-mark.component'; +import { AiAssistantPanelService } from '@core/services/ai-assistant-panel.service'; import { CellActionDescriptorType, DateEntityTableColumn, @@ -23,7 +25,6 @@ import { AlarmInfo, AlarmQueryV2, AlarmSearchStatus, - alarmSeverityColors, alarmSeverityTranslations, AlarmsMode, alarmStatusTranslations, @@ -44,7 +45,6 @@ import { Store } from '@ngrx/store'; import { AppState } from '@core/core.state'; import { getCurrentAuthUser } from '@core/auth/auth.selectors'; import { getEntityDetailsPageURL, isDefinedAndNotNull, isNotEmptyStr, isUndefinedOrNull } from '@core/utils'; -import { Authority } from '@shared/models/authority.enum'; import { ChangeDetectorRef, Injector, StaticProvider, ViewContainerRef } from '@angular/core'; import { ConnectedPosition, Overlay, OverlayConfig, OverlayRef } from '@angular/cdk/overlay'; import { @@ -106,8 +106,7 @@ export class AlarmTableConfig extends EntityTableConfig this.defaultSortOrder = {property: 'createdTime', direction: Direction.DESC}; - if (this.pageMode && this.authUser.authority === Authority.TENANT_ADMIN && - this.userPermissionsService.hasGenericPermission(Resource.AI, Operation.ALL)) { + if (this.pageMode && this.userPermissionsService.isAiAvailable()) { this.aiAssistantConfig = { view: { listView: AiAssistantViewType.ALARM_LIST @@ -138,11 +137,9 @@ export class AlarmTableConfig extends EntityTableConfig entity => this.utilsService.customTranslation(entity.type, entity.type))); this.columns.push( new EntityTableColumn('severity', 'alarm.severity', '25%', - (entity) => this.translate.instant(alarmSeverityTranslations.get(entity.severity)), - entity => ({ - fontWeight: 'bold', - color: alarmSeverityColors.get(entity.severity) - }))); + (entity) => '' + + aiSevMarkElement(entity.severity).outerHTML + + `${this.translate.instant(alarmSeverityTranslations.get(entity.severity))}`)); this.columns.push( new EntityTableColumn('assignee', 'alarm.assignee', '240px', (entity) => this.getAssigneeTemplate(entity), () => ({}), false, () => ({}), () => undefined, false, @@ -209,7 +206,7 @@ export class AlarmTableConfig extends EntityTableConfig } showAlarmDetails(entity: AlarmInfo) { - this.dialog.open + const dialog$ = this.dialog.open (AlarmDetailsDialogComponent, { disableClose: true, @@ -220,9 +217,15 @@ export class AlarmTableConfig extends EntityTableConfig allowAcknowledgment: this.writeEnabled, allowClear: this.writeEnabled, displayDetails: true, - allowAssign: true + allowAssign: true, + displayOriginatorName: true } - }).afterClosed().subscribe( + }).afterClosed(); + const closed$ = this.aiAssistantConfig + ? this.viewContainerRef.injector.get(AiAssistantPanelService).focusWhile( + {type: AiAssistantViewType.ALARM, entityId: entity.id}, entity.type, dialog$) + : dialog$; + closed$.subscribe( (res) => { if (res) { this.updateData(); diff --git a/ui-ngx/src/app/modules/home/components/attribute/attribute-table.component.ts b/ui-ngx/src/app/modules/home/components/attribute/attribute-table.component.ts index ffdd1c1bb1..4e79c100ad 100644 --- a/ui-ngx/src/app/modules/home/components/attribute/attribute-table.component.ts +++ b/ui-ngx/src/app/modules/home/components/attribute/attribute-table.component.ts @@ -6,7 +6,6 @@ import { ChangeDetectionStrategy, ChangeDetectorRef, Component, - DestroyRef, ElementRef, Injector, Input, @@ -216,7 +215,6 @@ export class AttributeTableComponent extends PageComponent implements AfterViewI private elementRef: ElementRef, private fb: FormBuilder, private timeService: TimeService, - private destroyRef: DestroyRef, private aiDashboardGenerationService: AiDashboardGenerationService) { super(store); this.isSysAdmin = getCurrentAuthUser(this.store).authority === Authority.SYS_ADMIN; @@ -677,8 +675,11 @@ export class AttributeTableComponent extends PageComponent implements AfterViewI generateDashboard($event: Event) { $event.stopPropagation(); - const selectedTimeseries = this.dataSource.selection.selected.map(telemetry => telemetry.key); - this.aiDashboardGenerationService.generate(this.entityIdValue.id, this.destroyRef, selectedTimeseries); + this.aiDashboardGenerationService.askInChat({ + deviceId: this.entityIdValue.id, + keys: this.dataSource.selection.selected.map(telemetry => telemetry.key), + checkTelemetry: false + }); } isAllowedDashboardGenerate(): boolean { diff --git a/ui-ngx/src/app/modules/home/components/calculated-fields/calculated-fields-table-config.ts b/ui-ngx/src/app/modules/home/components/calculated-fields/calculated-fields-table-config.ts index 54e71516cb..969c80b50a 100644 --- a/ui-ngx/src/app/modules/home/components/calculated-fields/calculated-fields-table-config.ts +++ b/ui-ngx/src/app/modules/home/components/calculated-fields/calculated-fields-table-config.ts @@ -120,7 +120,7 @@ export class CalculatedFieldsTableConfig extends EntityTableConfig
+ [class.!hidden]="simpleConfiguration.get('output').value?.type !== OutputType.Timeseries">
calculated-fields.use-latest-timestamp diff --git a/ui-ngx/src/app/modules/home/components/dashboard-page/add-widget-dialog.component.html b/ui-ngx/src/app/modules/home/components/dashboard-page/add-widget-dialog.component.html index 3d331ae634..4b4e81f569 100644 --- a/ui-ngx/src/app/modules/home/components/dashboard-page/add-widget-dialog.component.html +++ b/ui-ngx/src/app/modules/home/components/dashboard-page/add-widget-dialog.component.html @@ -6,6 +6,8 @@ -->
+ +

{{'widget.add' | translate}}:

@@ -52,6 +54,7 @@ [previewHeight]="widgetConfig.typeParameters.previewHeight">
} } - @if (showConfigureWithAi) { - - - } @if (isEdit) {
@if (previewMode) { } - @if (aiEnabled && entitiesTableConfig.aiAssistantConfig) { - - } @for (buttonDescriptor of entitiesTableConfig.headerButtonDescriptors; track buttonDescriptor.name) { } diff --git a/ui-ngx/src/app/modules/home/components/entity/entities-table.component.ts b/ui-ngx/src/app/modules/home/components/entity/entities-table.component.ts index 383c1747c2..20f6d5fe8b 100644 --- a/ui-ngx/src/app/modules/home/components/entity/entities-table.component.ts +++ b/ui-ngx/src/app/modules/home/components/entity/entities-table.component.ts @@ -110,10 +110,8 @@ export class EntitiesTableComponent extends PageComponent implements IEntitiesTa isDetailsOpen = false; detailsPanelOpened = new EventEmitter(); - get isAiAssistantOpen() { return this.panelService.open(); } aiEnabled = getCurrentAuthState(this.store).aiEnabled; - configureWithAiButton: HeaderActionDescriptor; replaceComponent: Type; @@ -228,23 +226,24 @@ export class EntitiesTableComponent extends PageComponent implements IEntitiesTa if (aiConfig) { this.panelService.setEnabled(true); this.panelService.setConfig(aiConfig); - this.configureWithAiButton = { - name: this.translate.instant('ai-assistant.configure-with-ai'), - icon: 'mdi:creation', - isEnabled: () => this.aiEnabled && aiConfig.showButton !== false && !this.isAiAssistantOpen, - onAction: ($event) => this.toggleAiAssistant($event) - }; this.updateAiClientContext(); - this.aiUpdatedData$?.unsubscribe(); - if (entitiesTableConfig.entityType) { - this.aiUpdatedData$ = this.panelService.updatedData$.pipe( - filter(affectedEntities => - affectedEntities.some(entityId => entityId.entityType === entitiesTableConfig.entityType)), - takeUntil(this.destroy$) - ).subscribe(() => { - this.updateData(); - }); - } + } + this.aiUpdatedData$?.unsubscribe(); + if (entitiesTableConfig.entityType) { + this.aiUpdatedData$ = this.panelService.updatedData$.pipe( + filter(affectedEntities => + affectedEntities.some(entityId => entityId.entityType === (entitiesTableConfig.aiReloadEntityType ?? entitiesTableConfig.entityType))), + takeUntil(this.destroy$) + ).subscribe(() => { + if (this.isDetailsOpen && this.entityDetailsPanel?.isEdit) { + this.panelService.keepEdits('entity', () => { + this.entityDetailsPanel.isEdit = false; + this.updateData(false, true); + }); + } else { + this.updateData(false); + } + }); } this.pageMode = this.entitiesTableConfig.pageMode; @@ -567,6 +566,7 @@ export class EntitiesTableComponent extends PageComponent implements IEntitiesTa ? {type: viewConfig.entityView, entityId: entity.id as EntityId} : {type: viewConfig.listView, entityId: viewConfig.listEntityId}; this.panelService.setClientContextForView(view); + this.panelService.setViewName(viewConfig.entityView && entity ? this.entitiesTableConfig.entityTitle(entity) : null); } toggleAiAssistant($event: Event) { diff --git a/ui-ngx/src/app/modules/home/components/entity/entity-details-page.component.ts b/ui-ngx/src/app/modules/home/components/entity/entity-details-page.component.ts index 0bbdb4a1ef..538ec3dfc2 100644 --- a/ui-ngx/src/app/modules/home/components/entity/entity-details-page.component.ts +++ b/ui-ngx/src/app/modules/home/components/entity/entity-details-page.component.ts @@ -1,6 +1,8 @@ // SPDX-FileCopyrightText: Copyright The ThingsBoard Authors // SPDX-FileCopyrightText: Modifications Copyright ThingsBoard, Inc. // SPDX-License-Identifier: Apache-2.0 AND BUSL-1.1 +import { AiAssistantPanelService } from '@core/services/ai-assistant-panel.service'; +import { EntityId } from '@shared/models/id/entity-id'; import { ChangeDetectionStrategy, ChangeDetectorRef, @@ -71,6 +73,7 @@ export class EntityDetailsPageComponent extends EntityDetailsPanelComponent impl private broadcast: BroadcastService, private translate: TranslateService, private dialogService: DialogService, + private panelService: AiAssistantPanelService, protected store: Store) { super(store, injector, cd); if (isDefinedAndNotNull(this.route.snapshot.data.entityGroup) && isUndefinedOrNull(this.route.snapshot.data.entitiesTableConfig)) { @@ -94,6 +97,20 @@ export class EntityDetailsPageComponent extends EntityDetailsPanelComponent impl this.reload(); } })); + this.subscriptions.push(this.panelService.updatedData$.subscribe(affected => { + const id = this.currentEntityId?.id; + if (!id || !affected.some(entityId => entityId.id === id)) { + return; + } + if (this.isEdit) { + this.panelService.keepEdits('entity', () => { + this.onToggleDetailsEditMode(); + this.reload(); + }); + } else { + this.reload(); + } + })); this.subscriptions.push(this.route.paramMap.subscribe( paramMap => { if (this.entitiesTableConfig) { const entityType = this.entitiesTableConfig.entityType; @@ -123,6 +140,9 @@ export class EntityDetailsPageComponent extends EntityDetailsPanelComponent impl } ngOnDestroy() { + if (this.entitiesTableConfig?.aiAssistantConfig?.view?.entityView) { + this.panelService.teardown(); + } super.ngOnDestroy(); } @@ -173,6 +193,18 @@ export class EntityDetailsPageComponent extends EntityDetailsPanelComponent impl this.broadcast.broadcast('updateBreadcrumb'); this.isReadOnly = this.entitiesTableConfig.detailsReadonly(this.entity); this.headerTitle = this.entitiesTableConfig.entityTitle(this.entity); + this.updateAiAssistant(); + } + + private updateAiAssistant(): void { + const config = this.entitiesTableConfig?.aiAssistantConfig; + if (!config?.view?.entityView || !this.entity?.id) { + return; + } + this.panelService.setEnabled(true); + this.panelService.setConfig(config); + this.panelService.setClientContextForView({type: config.view.entityView, entityId: this.entity.id as EntityId}); + this.panelService.setViewName(this.headerTitle); } private deleteEntity($event: Event, entity: BaseData) { diff --git a/ui-ngx/src/app/modules/home/components/entity/entity-details-panel.component.ts b/ui-ngx/src/app/modules/home/components/entity/entity-details-panel.component.ts index 393a4b8503..e71bf6405d 100644 --- a/ui-ngx/src/app/modules/home/components/entity/entity-details-panel.component.ts +++ b/ui-ngx/src/app/modules/home/components/entity/entity-details-panel.component.ts @@ -1,5 +1,7 @@ // SPDX-FileCopyrightText: Copyright The ThingsBoard Authors -// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Modifications Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: Apache-2.0 AND BUSL-1.1 +import { AiAssistantPanelService } from '@core/services/ai-assistant-panel.service'; import { AfterViewInit, ChangeDetectionStrategy, @@ -7,6 +9,7 @@ import { Component, ComponentRef, EventEmitter, + inject, Injector, Input, OnDestroy, @@ -59,6 +62,8 @@ export class EntityDetailsPanelComponent extends PageComponent implements AfterV entitiesTableConfigValue: EntityTableConfig>; isEditValue = false; + + private aiPanelService = inject(AiAssistantPanelService); selectedTab = 0; entityTypes = EntityType; @@ -93,6 +98,8 @@ export class EntityDetailsPanelComponent extends PageComponent implements AfterV this.currentEntityId = entityId; if (this.currentEntityId) { this.reloadEntity(); + } else { + this.isEdit = false; } } } @@ -115,6 +122,9 @@ export class EntityDetailsPanelComponent extends PageComponent implements AfterV } set isEdit(val: boolean) { + if (this.isEditValue && !val) { + this.aiPanelService.clearKeptEdits('entity'); + } this.isEditValue = val; if (this.entityComponent) { this.entityComponent.isEdit = val; diff --git a/ui-ngx/src/app/modules/home/components/group/entity-groups-table-config.resolver.ts b/ui-ngx/src/app/modules/home/components/group/entity-groups-table-config.resolver.ts index 132cfff504..d534be7c9b 100644 --- a/ui-ngx/src/app/modules/home/components/group/entity-groups-table-config.resolver.ts +++ b/ui-ngx/src/app/modules/home/components/group/entity-groups-table-config.resolver.ts @@ -1,6 +1,6 @@ // SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. // SPDX-License-Identifier: BUSL-1.1 -import { Injectable } from '@angular/core'; +import { inject, Injectable } from '@angular/core'; import { ActivatedRouteSnapshot, Router } from '@angular/router'; import { TranslateService } from '@ngx-translate/core'; @@ -22,12 +22,27 @@ import { AppState } from '@core/core.state'; import { EntityType } from '@shared/models/entity-type.models'; import { Operation, Resource } from '@shared/models/security.models'; import { deviceAiAssistantConfig } from '@shared/models/device.models'; +import { AiAssistantConfigService } from '@core/services/ai-assistant-config.service'; import { AiAssistantViewType } from '@shared/models/ai-chat.models'; +import { CustomerId } from '@shared/models/id/customer-id'; import { getCurrentAuthUser } from '@core/auth/auth.selectors'; +import { EdgeId } from '@shared/models/id/edge-id'; + +const GROUP_LIST_VIEWS = new Map([ + [EntityType.ASSET, [AiAssistantViewType.ASSET_GROUP_LIST, AiAssistantViewType.ASSET_GROUP]], + [EntityType.ENTITY_VIEW, [AiAssistantViewType.ENTITY_VIEW_GROUP_LIST, AiAssistantViewType.ENTITY_VIEW_GROUP]], + [EntityType.DASHBOARD, [AiAssistantViewType.DASHBOARD_GROUP_LIST, AiAssistantViewType.DASHBOARD_GROUP]], + [EntityType.CUSTOMER, [AiAssistantViewType.CUSTOMER_GROUP_LIST, AiAssistantViewType.CUSTOMER_GROUP]], + [EntityType.USER, [AiAssistantViewType.USER_GROUP_LIST, AiAssistantViewType.USER_GROUP]], + [EntityType.EDGE, [AiAssistantViewType.EDGE_GROUP_LIST, AiAssistantViewType.EDGE_GROUP]], + [EntityType.AGENT, [AiAssistantViewType.AGENT_GROUP_LIST, AiAssistantViewType.AGENT_GROUP]] +]); @Injectable() export class EntityGroupsTableConfigResolver { + private aiAssistantConfigService = inject(AiAssistantConfigService); + constructor(private entityGroupService: EntityGroupService, private customerService: CustomerService, private edgeService: EdgeService, @@ -63,10 +78,15 @@ export class EntityGroupsTableConfigResolver { params ); + const owner = config.edgeId ? new EdgeId(config.edgeId) : config.customerId ? new CustomerId(config.customerId) : undefined; if (config.groupType === EntityType.DEVICE) { config.aiAssistantConfig = deviceAiAssistantConfig(this.store, this.userPermissionsService, this.translate, this.userPermissionsService.hasGenericPermission(Resource.DEVICE, Operation.WRITE), - AiAssistantViewType.DEVICE_GROUP, AiAssistantViewType.DEVICE_GROUP_LIST); + AiAssistantViewType.DEVICE_GROUP, AiAssistantViewType.DEVICE_GROUP_LIST, owner); + } + const groupViews = GROUP_LIST_VIEWS.get(config.groupType); + if (groupViews) { + config.aiAssistantConfig = this.aiAssistantConfigService.tableConfig(groupViews[0], groupViews[1], owner); } if (config.customerId && resolveCustomer) { @@ -94,6 +114,7 @@ export class EntityGroupsTableConfigResolver { return this.edgeService.getEdge(config.edgeId).pipe( map((info) => { config.tableTitle = info.name + ': ' + this.translate.instant(entityGroupsTitle(config.groupType)); + config.edgeOwnerId = info.ownerId; return config; }) ); diff --git a/ui-ngx/src/app/modules/home/components/group/entity-groups-table-config.ts b/ui-ngx/src/app/modules/home/components/group/entity-groups-table-config.ts index be3ffd2313..53b369e99b 100644 --- a/ui-ngx/src/app/modules/home/components/group/entity-groups-table-config.ts +++ b/ui-ngx/src/app/modules/home/components/group/entity-groups-table-config.ts @@ -30,10 +30,12 @@ import { EntityId } from '@shared/models/id/entity-id'; import { CustomTranslatePipe } from '@shared/pipe/custom-translate.pipe'; import { AuthUser } from '@shared/models/user.model'; import { edgeCreationAllowed } from '@shared/models/edge.models'; +import { Authority } from '@shared/models/authority.enum'; export class EntityGroupsTableConfig extends EntityTableConfig { edgeId: string; + edgeOwnerId: EntityId; groupType: EntityType; shared: boolean; @@ -288,7 +290,13 @@ export class EntityGroupsTableConfig extends EntityTableConfig $event.stopPropagation(); } let ownerId = this.userPermissionsService.getUserOwnerId(); - if (this.params.customerId) { + if (this.edgeOwnerId && this.authUser.authority === Authority.TENANT_ADMIN) { + // List groups of the edge owner and its parent owners, so the groups of the customer that owns the edge are + // available no matter which page the edge was opened from (Edge management or Customers). + // Tenant admin only: for a customer user the edge owner may be outside their owner chain (an edge shared + // from the tenant or a parent customer), and the hierarchy request is then denied + ownerId = this.edgeOwnerId; + } else if (this.params.customerId) { ownerId = { id: this.params.customerId, entityType: EntityType.CUSTOMER diff --git a/ui-ngx/src/app/modules/home/components/home-components.module.ts b/ui-ngx/src/app/modules/home/components/home-components.module.ts index d0aed9acce..39a74353e4 100644 --- a/ui-ngx/src/app/modules/home/components/home-components.module.ts +++ b/ui-ngx/src/app/modules/home/components/home-components.module.ts @@ -225,7 +225,6 @@ import { AlarmAssigneePanelComponent } from '@home/components/alarm/alarm-assign import { RouterTabsComponent } from '@home/components/router-tabs.component'; import { AllEntitiesTableConfigService } from '@home/components/entity/all-entities-table-config.service'; import { SendNotificationButtonComponent } from '@home/components/notification/send-notification-button.component'; -import { AiAssistantAlarmButtonComponent } from '@home/components/alarm/ai-assistant-alarm-button.component'; import { GroupEntityInfoComponent } from '@home/components/group/group-entity-info.component'; import { ManageOwnerAndGroupsDialogComponent } from '@home/components/group/manage-owner-and-groups-dialog.component'; import { OwnerAndGroupsComponent } from '@home/components/group/owner-and-groups.component'; @@ -272,12 +271,14 @@ import { import { ConverterLibraryModelAutocompleteComponent } from '@home/components/converter/converter-library-model-autocomplete.component'; -import { AiModule } from '@home/components/ai/ai.module'; +import { AiCoreModule } from '@home/components/ai/ai-core.module'; import { RequestPePackComponent } from '@home/components/pe-pack/request-pe-pack.component'; +import { LicenseHandOffDialogComponent } from '@home/components/license/license-hand-off-dialog.component'; @NgModule({ declarations: [ + LicenseHandOffDialogComponent, RouterTabsComponent, EntitiesTableComponent, AddEntityDialogComponent, @@ -447,7 +448,6 @@ import { RequestPePackComponent } from '@home/components/pe-pack/request-pe-pack ConverterTestDialogComponent, UpdatedPayloadPanelComponent, SendNotificationButtonComponent, - AiAssistantAlarmButtonComponent, EntityChipsComponent, DashboardViewComponent, ConverterLibraryComponent, @@ -487,9 +487,10 @@ import { RequestPePackComponent } from '@home/components/pe-pack/request-pe-pack EntityDebugSettingsButtonComponent, NotificationBellModule, GithubBadgeModule, - AiModule, + AiCoreModule, ], exports: [ + LicenseHandOffDialogComponent, SharedHomeComponentsModule, RouterTabsComponent, EntitiesTableComponent, @@ -639,7 +640,6 @@ import { RequestPePackComponent } from '@home/components/pe-pack/request-pe-pack RateLimitsTextComponent, IntegrationWizardDialogComponent, SendNotificationButtonComponent, - AiAssistantAlarmButtonComponent, EntityChipsComponent, DashboardViewComponent, CancelTaskDialogComponent, diff --git a/ui-ngx/src/app/modules/home/components/integration/configuration/azure-event-hub-integration-form/azure-event-hub-integration-form.component.html b/ui-ngx/src/app/modules/home/components/integration/configuration/azure-event-hub-integration-form/azure-event-hub-integration-form.component.html index 1bcad7d9c1..bd66080687 100644 --- a/ui-ngx/src/app/modules/home/components/integration/configuration/azure-event-hub-integration-form/azure-event-hub-integration-form.component.html +++ b/ui-ngx/src/app/modules/home/components/integration/configuration/azure-event-hub-integration-form/azure-event-hub-integration-form.component.html @@ -12,15 +12,17 @@ label="{{ 'integration.connection-string' | translate }}" requiredText="{{ 'integration.connection-string-required' | translate }}"> - - integration.iot-hub-name - - @if (azureEventHubIntegrationConfigForm.get('iotHubName').hasError('required')) { - - integration.event-iot-hub-name-required - - } - + @if (isSetDownLink) { + + integration.iot-hub-name + + @if (azureEventHubIntegrationConfigForm.get('iotHubName').hasError('required')) { + + integration.event-iot-hub-name-required + + } + + } diff --git a/ui-ngx/src/app/modules/home/components/integration/configuration/azure-services-bus-integration-form/azure-services-bus-integration-form.component.html b/ui-ngx/src/app/modules/home/components/integration/configuration/azure-services-bus-integration-form/azure-services-bus-integration-form.component.html index 6e3cde027c..d48883be07 100644 --- a/ui-ngx/src/app/modules/home/components/integration/configuration/azure-services-bus-integration-form/azure-services-bus-integration-form.component.html +++ b/ui-ngx/src/app/modules/home/components/integration/configuration/azure-services-bus-integration-form/azure-services-bus-integration-form.component.html @@ -29,6 +29,21 @@ }
+ @if (isSetDownLink) { + + + + integration.downlink-topic-name + + @if (azureServicesBusIntegrationConfigForm.get('downlinkTopicName').hasError('required')) { + integration.downlink-topic-name-required + } + + } @@ -40,22 +55,6 @@ - - - - - integration.downlink-topic-name - - @if (azureServicesBusIntegrationConfigForm.get('downlinkTopicName').hasError('required')) { - - integration.downlink-topic-name-required - - } - - diff --git a/ui-ngx/src/app/modules/home/components/integration/configuration/http-integration-form/http-integration-form.component.html b/ui-ngx/src/app/modules/home/components/integration/configuration/http-integration-form/http-integration-form.component.html index f031d8c99e..6fb90a6a99 100644 --- a/ui-ngx/src/app/modules/home/components/integration/configuration/http-integration-form/http-integration-form.component.html +++ b/ui-ngx/src/app/modules/home/components/integration/configuration/http-integration-form/http-integration-form.component.html @@ -50,6 +50,7 @@ noDataText="integration.no-headers-filter" keyPlaceholderText="integration.header" isStrokedButton="true" + showRequiredErrors appearance="outline" secretValues formControlName="headersFilter"> diff --git a/ui-ngx/src/app/modules/home/components/integration/configuration/kafka-integration-form/kafka-integration-form.component.html b/ui-ngx/src/app/modules/home/components/integration/configuration/kafka-integration-form/kafka-integration-form.component.html index 131bea0d4f..4b09f41dab 100644 --- a/ui-ngx/src/app/modules/home/components/integration/configuration/kafka-integration-form/kafka-integration-form.component.html +++ b/ui-ngx/src/app/modules/home/components/integration/configuration/kafka-integration-form/kafka-integration-form.component.html @@ -73,7 +73,7 @@
integration.other-properties - +
diff --git a/ui-ngx/src/app/modules/home/components/integration/configuration/kpn-integration-form/kpn-integration-form.component.html b/ui-ngx/src/app/modules/home/components/integration/configuration/kpn-integration-form/kpn-integration-form.component.html index 74c7e2eb42..50f4d721be 100644 --- a/ui-ngx/src/app/modules/home/components/integration/configuration/kpn-integration-form/kpn-integration-form.component.html +++ b/ui-ngx/src/app/modules/home/components/integration/configuration/kpn-integration-form/kpn-integration-form.component.html @@ -62,6 +62,7 @@ noDataText="integration.no-headers-filter" keyPlaceholderText="integration.header" isStrokedButton="true" + showRequiredErrors appearance="outline" secretValues formControlName="additionalHeadersFilter"> diff --git a/ui-ngx/src/app/modules/home/components/integration/configuration/loriot-integration-form/loriot-integration-form.component.html b/ui-ngx/src/app/modules/home/components/integration/configuration/loriot-integration-form/loriot-integration-form.component.html index 954503bfec..1d30ca3ef9 100644 --- a/ui-ngx/src/app/modules/home/components/integration/configuration/loriot-integration-form/loriot-integration-form.component.html +++ b/ui-ngx/src/app/modules/home/components/integration/configuration/loriot-integration-form/loriot-integration-form.component.html @@ -122,6 +122,7 @@ noDataText="integration.no-headers-filter" keyPlaceholderText="integration.header" isStrokedButton="true" + showRequiredErrors appearance="outline" secretValues formControlName="headersFilter"> diff --git a/ui-ngx/src/app/modules/home/components/integration/configuration/particle-integration-form/particle-integration-form.component.html b/ui-ngx/src/app/modules/home/components/integration/configuration/particle-integration-form/particle-integration-form.component.html index fe9f587091..caf8189be6 100644 --- a/ui-ngx/src/app/modules/home/components/integration/configuration/particle-integration-form/particle-integration-form.component.html +++ b/ui-ngx/src/app/modules/home/components/integration/configuration/particle-integration-form/particle-integration-form.component.html @@ -67,6 +67,7 @@ noDataText="integration.no-headers-filter" keyPlaceholderText="integration.header" isStrokedButton="true" + showRequiredErrors appearance="outline" secretValues formControlName="headersFilter"> diff --git a/ui-ngx/src/app/modules/home/components/integration/mqtt-topic-filters/mqtt-topic-filters.component.html b/ui-ngx/src/app/modules/home/components/integration/mqtt-topic-filters/mqtt-topic-filters.component.html index 7dc4ab6015..2f5ddbe7a6 100644 --- a/ui-ngx/src/app/modules/home/components/integration/mqtt-topic-filters/mqtt-topic-filters.component.html +++ b/ui-ngx/src/app/modules/home/components/integration/mqtt-topic-filters/mqtt-topic-filters.component.html @@ -10,17 +10,22 @@ @for (topicFilter of mqttFiltersFromArray.controls; track topicFilter; let i = $index) {
- + @if (i === 0) { {{"integration.topic" | translate }} } - + + @if (topicFilter.get('filter').hasError('required')) { + integration.topics-required + } @if (i === 0) { {{"integration.mqtt-qos" | translate }} } - + @for (mqttQoS of mqttQosTypes; track mqttQoS) { {{ mqttQoS }} - {{ getMqttQosTranslation(mqttQoS) | translate}} diff --git a/ui-ngx/src/app/modules/home/components/iot-hub/device-install-dialog/device-install-dialog.component.ts b/ui-ngx/src/app/modules/home/components/iot-hub/device-install-dialog/device-install-dialog.component.ts index 7c91316a4b..a59a9a185d 100644 --- a/ui-ngx/src/app/modules/home/components/iot-hub/device-install-dialog/device-install-dialog.component.ts +++ b/ui-ngx/src/app/modules/home/components/iot-hub/device-install-dialog/device-install-dialog.component.ts @@ -1,7 +1,7 @@ // SPDX-FileCopyrightText: Copyright The ThingsBoard Authors // SPDX-FileCopyrightText: Modifications Copyright ThingsBoard, Inc. // SPDX-License-Identifier: Apache-2.0 AND BUSL-1.1 -import { ChangeDetectorRef, Component, DestroyRef, Inject, OnDestroy, OnInit, ViewChild } from '@angular/core'; +import { ChangeDetectorRef, Component, Inject, OnDestroy, OnInit, ViewChild } from '@angular/core'; import { Router } from '@angular/router'; import { MAT_DIALOG_DATA, MatDialogRef } from '@angular/material/dialog'; import { Store } from '@ngrx/store'; @@ -429,7 +429,6 @@ export class TbDeviceInstallDialogComponent extends DialogComponent, @Inject(MAT_DIALOG_DATA) public data: DeviceInstallDialogData, - private destroyRef: DestroyRef, private cdr: ChangeDetectorRef, private deviceProfileService: DeviceProfileService, private deviceService: DeviceService, @@ -832,10 +831,10 @@ export class TbDeviceInstallDialogComponent extends DialogComponent this.done() }); } diff --git a/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-actions.service.ts b/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-actions.service.ts index 1c7d17c87f..f533084f73 100644 --- a/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-actions.service.ts +++ b/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-actions.service.ts @@ -29,7 +29,9 @@ import { isBuiltInItem } from './iot-hub-utils'; */ export type IotHubBuiltInAction = 'handled' | 'install-requested'; -@Injectable() +@Injectable({ + providedIn: 'root' +}) export class IotHubActionsService { constructor( diff --git a/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-components.module.ts b/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-components.module.ts index ea754e42f9..56c4720fa7 100644 --- a/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-components.module.ts +++ b/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-components.module.ts @@ -22,7 +22,6 @@ import { TbIotHubSelectCfEntityDialogComponent } from './iot-hub-select-cf-entit import { TbIotHubUpgradeRequiredDialogComponent } from './iot-hub-upgrade-required-dialog.component'; import { TbIotHubMarkdownComponent } from './iot-hub-markdown.component'; import { SolutionInstallDialogComponent } from './solution-install-dialog.component'; -import { IotHubActionsService } from './iot-hub-actions.service'; import { IotHubItemLinkModule } from './iot-hub-item-link-card/iot-hub-item-link.module'; @NgModule({ @@ -51,9 +50,6 @@ import { IotHubItemLinkModule } from './iot-hub-item-link-card/iot-hub-item-link SharedModule, IotHubItemLinkModule ], - providers: [ - IotHubActionsService - ], exports: [ TbIotHubItemDetailDialogComponent, TbIotHubBrowseComponent, diff --git a/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-markdown.utils.ts b/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-markdown.utils.ts index 4eae1f8533..b3f366dc7f 100644 --- a/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-markdown.utils.ts +++ b/ui-ngx/src/app/modules/home/components/iot-hub/iot-hub-markdown.utils.ts @@ -1,5 +1,10 @@ // SPDX-FileCopyrightText: Copyright The ThingsBoard Authors -// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Modifications Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: Apache-2.0 AND BUSL-1.1 +import { escapeHtml, escapeHtmlAttr } from '@core/utils'; + +export { escapeHtml, escapeHtmlAttr }; + export const ITEM_LINK_PLACEHOLDER_REGEX = /\$\{item-link:([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})}/g; @@ -44,22 +49,6 @@ function buildDocLinkButton(url: string, text: string, icon: string): string { `${icon}${safeText}`; } -export function escapeHtml(value: string): string { - return value.replace(/[&<>]/g, ch => ch === '&' ? '&' : ch === '<' ? '<' : '>'); -} - -export function escapeHtmlAttr(value: string): string { - return value.replace(/[&<>"']/g, ch => { - switch (ch) { - case '&': return '&'; - case '<': return '<'; - case '>': return '>'; - case '"': return '"'; - default: return '''; - } - }); -} - // Inline-only tags + a small attribute whitelist that are safe to keep // in caption strings (or other small bits of user-authored HTML inside // generated markdown). Anything else is dropped — disallowed tags are diff --git a/ui-ngx/src/app/modules/home/components/license/license-actions.service.ts b/ui-ngx/src/app/modules/home/components/license/license-actions.service.ts new file mode 100644 index 0000000000..df22b413c5 --- /dev/null +++ b/ui-ngx/src/app/modules/home/components/license/license-actions.service.ts @@ -0,0 +1,117 @@ +// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: BUSL-1.1 +import { inject, Injectable } from '@angular/core'; +import { MatDialog } from '@angular/material/dialog'; +import { select, Store } from '@ngrx/store'; +import { take } from 'rxjs/operators'; +import { AppState } from '@core/core.state'; +import { selectUserSettingsProperty } from '@core/auth/auth.selectors'; +import { AddonType, createManageSubscriptionUrl, PlanUiType, SubscriptionInfo, UsageItemType } from '@shared/models/subscription.models'; +import { + LicenseHandOffCase, + LicenseHandOffDialogComponent, + LicenseHandOffDialogData +} from '@home/components/license/license-hand-off-dialog.component'; + +const LIMIT_WARN = 0.85; + +const ADD_ITEMS: Partial>> = { + [UsageItemType.DEVICES]: {extraDeviceCount: 100}, + [UsageItemType.EDGES]: {extraEdgeCount: 1}, + [UsageItemType.PROD_INSTANCES]: {extraInstanceCount: 1}, + [UsageItemType.AI_CREDITS]: {extraAiCreditsCount: 5}, + [UsageItemType.AGENTS]: {extraAgentCount: 1} +}; + +const ADD_ADDONS: Partial>> = { + [AddonType.EDGE]: {edgeEnabled: true}, + [AddonType.TRENDZ]: {trendzEnabled: true}, + [AddonType.PROFESSIONAL_UPGRADE]: {professionalUpgradeEnabled: true} +}; + +export const licenseLimitWarn = (count: number, max: number): boolean => !!count && !!max && count / max >= LIMIT_WARN; + +export const licenseLimitCritical = (count: number, max: number): boolean => !!count && !!max && count >= max; + +export const licenseMeterWidth = (count: number, max: number): number => count > 0 && max > 0 ? Math.min(count / max, 1) * 100 : 0; + +@Injectable({ + providedIn: 'root' +}) +export class LicenseActionsService { + + private store = inject(Store); + private dialog = inject(MatDialog); + + manageLicense(info: SubscriptionInfo): void { + this.openPortal(info, LicenseHandOffCase.MANAGE_LICENSE, null, null, createManageSubscriptionUrl(info)); + } + + addItems(info: SubscriptionInfo, itemType: UsageItemType): void { + const items = ADD_ITEMS[itemType]; + if (items) { + this.openPortal(info, LicenseHandOffCase.ADD_ITEMS, itemType, null, createManageSubscriptionUrl(info, items)); + } + } + + addAddOn(info: SubscriptionInfo, addonType: AddonType): void { + const items = ADD_ADDONS[addonType]; + if (items) { + this.openPortal(info, LicenseHandOffCase.ADD_ADDON, null, addonType, createManageSubscriptionUrl(info, items)); + } + } + + upgradePlanForItems(info: SubscriptionInfo, itemType: UsageItemType): void { + let targetPlan = PlanUiType.TbPilot; + if (itemType === UsageItemType.DEVICES) { + switch (info.planUiType) { + case PlanUiType.TbCommercialSmall: + targetPlan = PlanUiType.TbPilot; + break; + case PlanUiType.TbPilot: + targetPlan = PlanUiType.TbStartup; + break; + default: + targetPlan = PlanUiType.TbBusiness; + } + } + this.upgradePlan(info, itemType, null, targetPlan); + } + + upgradePlanForAddon(info: SubscriptionInfo, addonType: AddonType): void { + this.upgradePlan(info, null, addonType, PlanUiType.TbPilot); + } + + private upgradePlan(info: SubscriptionInfo, itemType: UsageItemType, addonType: AddonType, targetPlan: PlanUiType): void { + const url = `${info.licenseServerEndpoint}/?changeSubscriptionPlan=true&subscriptionId=${info.subscriptionId}&planUiType=${targetPlan}`; + this.openPortal(info, itemType ? LicenseHandOffCase.UPGRADE_PLAN_FOR_ITEMS : LicenseHandOffCase.UPGRADE_PLAN_FOR_ADDON, + itemType, addonType, url); + } + + private openPortal(info: SubscriptionInfo, handOffCase: LicenseHandOffCase, itemType: UsageItemType, addonType: AddonType, + url: string): void { + this.store.pipe(select(selectUserSettingsProperty('notDisplayLicenseHandOff')), take(1)).subscribe((skipDialog: boolean) => { + if (skipDialog) { + window.open(url, '_blank'); + return; + } + this.dialog.open(LicenseHandOffDialogComponent, { + disableClose: true, + autoFocus: false, + panelClass: ['tb-dialog', 'tb-fullscreen-dialog'], + data: { + case: handOffCase, + isPerpetual: info.perpetual, + isCeGrant: info.communityGrantLicense, + itemType, + addonType, + planName: info.subscriptionPlanName + } + }).afterClosed().subscribe(result => { + if (result) { + window.open(url, '_blank'); + } + }); + }); + } +} diff --git a/ui-ngx/src/app/modules/home/pages/admin/license-hand-off-dialog.component.html b/ui-ngx/src/app/modules/home/components/license/license-hand-off-dialog.component.html similarity index 100% rename from ui-ngx/src/app/modules/home/pages/admin/license-hand-off-dialog.component.html rename to ui-ngx/src/app/modules/home/components/license/license-hand-off-dialog.component.html diff --git a/ui-ngx/src/app/modules/home/pages/admin/license-hand-off-dialog.component.scss b/ui-ngx/src/app/modules/home/components/license/license-hand-off-dialog.component.scss similarity index 100% rename from ui-ngx/src/app/modules/home/pages/admin/license-hand-off-dialog.component.scss rename to ui-ngx/src/app/modules/home/components/license/license-hand-off-dialog.component.scss diff --git a/ui-ngx/src/app/modules/home/pages/admin/license-hand-off-dialog.component.ts b/ui-ngx/src/app/modules/home/components/license/license-hand-off-dialog.component.ts similarity index 100% rename from ui-ngx/src/app/modules/home/pages/admin/license-hand-off-dialog.component.ts rename to ui-ngx/src/app/modules/home/components/license/license-hand-off-dialog.component.ts diff --git a/ui-ngx/src/app/modules/home/components/notification/send-notification-button.component.html b/ui-ngx/src/app/modules/home/components/notification/send-notification-button.component.html index 1614b4a7e8..8e685ff34e 100644 --- a/ui-ngx/src/app/modules/home/components/notification/send-notification-button.component.html +++ b/ui-ngx/src/app/modules/home/components/notification/send-notification-button.component.html @@ -5,27 +5,14 @@ SPDX-License-Identifier: Apache-2.0 AND BUSL-1.1 --> -@if (showAiAssistant() || show()) { +@if (show()) {
- @if (showAiAssistant()) { - - - } - @if (show()) { - - - } + +
} diff --git a/ui-ngx/src/app/modules/home/components/notification/send-notification-button.component.ts b/ui-ngx/src/app/modules/home/components/notification/send-notification-button.component.ts index ea0b547cdf..33a76e0e8a 100644 --- a/ui-ngx/src/app/modules/home/components/notification/send-notification-button.component.ts +++ b/ui-ngx/src/app/modules/home/components/notification/send-notification-button.component.ts @@ -15,10 +15,9 @@ import { Store } from '@ngrx/store'; import { AppState } from '@core/core.state'; import { UserPermissionsService } from '@core/http/user-permissions.service'; import { Operation, Resource } from '@shared/models/security.models'; -import { getCurrentAuthState, getCurrentAuthUser } from '@core/auth/auth.selectors'; +import { getCurrentAuthUser } from '@core/auth/auth.selectors'; import { AuthUser } from '@shared/models/user.model'; import { Authority } from '@shared/models/authority.enum'; -import { AiAssistantPanelService } from '@core/services/ai-assistant-panel.service'; @Component({ selector: 'tb-send-notification-button', @@ -29,24 +28,10 @@ export class SendNotificationButtonComponent { private authUser: AuthUser = getCurrentAuthUser(this.store); - private hasAiPermission: boolean = getCurrentAuthState(this.store).aiEnabled && - this.userPermissionsService.hasGenericPermission(Resource.AI, Operation.ALL) && - this.userPermissionsService.hasGenericPermission(Resource.NOTIFICATION, Operation.WRITE); - constructor(private dialog: MatDialog, private store: Store, private activeComponentService: ActiveComponentService, - private userPermissionsService: UserPermissionsService, - private panelService: AiAssistantPanelService) { - } - - showAiAssistant(): boolean { - return this.hasAiPermission && !this.panelService.open(); - } - - toggleAiAssistant($event: Event): void { - $event?.stopPropagation(); - this.panelService.toggle(); + private userPermissionsService: UserPermissionsService) { } sendNotification($event: Event) { diff --git a/ui-ngx/src/app/modules/home/components/router-tabs.component.scss b/ui-ngx/src/app/modules/home/components/router-tabs.component.scss index 6bec0637c1..d2ec215b0d 100644 --- a/ui-ngx/src/app/modules/home/components/router-tabs.component.scss +++ b/ui-ngx/src/app/modules/home/components/router-tabs.component.scss @@ -13,13 +13,6 @@ } } - :host-context(.openAiAssistant) { - .tb-router-tabs-container { - margin-right: 16px; - border-right: solid 1px rgba(0, 0, 0, 0.12); - } - } - .mat-mdc-tab-nav-bar.tb-router-tabs { --mat-tab-container-height: 48px; a.mat-mdc-tab-link { diff --git a/ui-ngx/src/app/modules/home/components/scheduler/scheduler-events.component.ts b/ui-ngx/src/app/modules/home/components/scheduler/scheduler-events.component.ts index 39ffeb560c..117dd2f34e 100644 --- a/ui-ngx/src/app/modules/home/components/scheduler/scheduler-events.component.ts +++ b/ui-ngx/src/app/modules/home/components/scheduler/scheduler-events.component.ts @@ -88,6 +88,7 @@ import { takeUntilDestroyed } from '@angular/core/rxjs-interop'; import { CustomTranslatePipe } from '@shared/pipe/custom-translate.pipe'; import { DomSanitizer } from "@angular/platform-browser"; import { TbAnchorComponent } from '@shared/components/tb-anchor.component'; +import { AiAssistantPanelService } from '@core/services/ai-assistant-panel.service'; @Component({ selector: 'tb-scheduler-events', @@ -181,9 +182,14 @@ export class SchedulerEventsComponent extends PageComponent implements OnInit, A private popoverService: TbPopoverService, private viewContainerRef: ViewContainerRef, private destroyRef: DestroyRef, - private sanitizer: DomSanitizer + private sanitizer: DomSanitizer, + private aiAssistantPanelService: AiAssistantPanelService ) { super(); + this.aiAssistantPanelService.updatedData$.pipe( + filter(entities => entities.some(entityId => entityId.entityType === EntityType.SCHEDULER_EVENT)), + takeUntilDestroyed() + ).subscribe(() => this.reloadSchedulerEvents()); } ngOnInit(): void { @@ -406,7 +412,7 @@ export class SchedulerEventsComponent extends PageComponent implements OnInit, A reloadSchedulerEvents(): void { if (this.mode === 'calendar') { - this.calendarApi.refetchEvents(); + this.calendarApi?.refetchEvents(); } else { this.updateData(); } diff --git a/ui-ngx/src/app/modules/home/components/widget/config/basic/alarm/alarm-count-basic-config.component.html b/ui-ngx/src/app/modules/home/components/widget/config/basic/alarm/alarm-count-basic-config.component.html index 47c8f67ea9..30121d1640 100644 --- a/ui-ngx/src/app/modules/home/components/widget/config/basic/alarm/alarm-count-basic-config.component.html +++ b/ui-ngx/src/app/modules/home/components/widget/config/basic/alarm/alarm-count-basic-config.component.html @@ -18,7 +18,7 @@
alarm.filter
- diff --git a/ui-ngx/src/app/modules/home/components/widget/config/basic/alarm/alarm-count-basic-config.component.ts b/ui-ngx/src/app/modules/home/components/widget/config/basic/alarm/alarm-count-basic-config.component.ts index 794d8a7f4b..c71ec48586 100644 --- a/ui-ngx/src/app/modules/home/components/widget/config/basic/alarm/alarm-count-basic-config.component.ts +++ b/ui-ngx/src/app/modules/home/components/widget/config/basic/alarm/alarm-count-basic-config.component.ts @@ -2,21 +2,21 @@ // SPDX-FileCopyrightText: Modifications Copyright ThingsBoard, Inc. // SPDX-License-Identifier: Apache-2.0 AND BUSL-1.1 import { Component } from '@angular/core'; -import { UntypedFormBuilder, UntypedFormGroup, Validators } from '@angular/forms'; +import { UntypedFormBuilder, UntypedFormGroup } from '@angular/forms'; import { Store } from '@ngrx/store'; import { AppState } from '@core/core.state'; import { BasicWidgetConfigComponent } from '@home/components/widget/config/widget-config.component.models'; import { WidgetConfigComponentData } from '@home/models/widget-component.models'; -import { DatasourceType, WidgetConfig, widgetType, } from '@shared/models/widget.models'; +import { DatasourceType, WidgetConfig } from '@shared/models/widget.models'; import { WidgetConfigComponent } from '@home/components/widget/widget-config.component'; -import { DataKeyType } from '@shared/models/telemetry/telemetry.models'; import { isUndefined } from '@core/utils'; import { getAlarmFilterConfig, setAlarmFilterConfig } from '@shared/models/widget-settings.models'; import { UtilsService } from '@core/services/utils.service'; import { AlarmSearchStatus } from '@shared/models/alarm.models'; import { countDefaultSettings, - CountWidgetSettings + CountWidgetSettings, + normalizeCountWidgetDatasource } from '@home/components/widget/lib/count/count-widget.models'; @Component({ @@ -43,17 +43,11 @@ export class AlarmCountBasicConfigComponent extends BasicWidgetConfigComponent { } protected setupDefaults(configData: WidgetConfigComponentData) { - let datasources = configData.config.datasources; - if (!datasources || !datasources.length) { - datasources = [{}]; - configData.config.datasources = datasources; - } - datasources[0].type = DatasourceType.alarmCount; - datasources[0].alarmFilterConfig = {statusList: [AlarmSearchStatus.ACTIVE]}; - datasources[0].dataKeys = [this.utils.createKey({name: 'count'}, DataKeyType.count)]; + normalizeCountWidgetDatasource(configData, DatasourceType.alarmCount, this.utils, true); } protected onConfigSet(configData: WidgetConfigComponentData) { + const normalized = !this.widgetEditMode && normalizeCountWidgetDatasource(configData, DatasourceType.alarmCount, this.utils); const settings: CountWidgetSettings = {...countDefaultSettings(true), ...(configData.config.settings || {})}; this.alarmCountWidgetConfigForm = this.fb.group({ alarmFilterConfig: [getAlarmFilterConfig(configData.config.datasources), []], @@ -67,6 +61,9 @@ export class AlarmCountBasicConfigComponent extends BasicWidgetConfigComponent { actions: [configData.config.actions || {}, []] }); + if (normalized) { + this.emitConfigChangedDeferred(); + } } protected prepareOutputConfig(config: any): WidgetConfigComponentData { diff --git a/ui-ngx/src/app/modules/home/components/widget/config/basic/alarm/alarms-table-basic-config.component.html b/ui-ngx/src/app/modules/home/components/widget/config/basic/alarm/alarms-table-basic-config.component.html index 271530d2f0..7a4657108e 100644 --- a/ui-ngx/src/app/modules/home/components/widget/config/basic/alarm/alarms-table-basic-config.component.html +++ b/ui-ngx/src/app/modules/home/components/widget/config/basic/alarm/alarms-table-basic-config.component.html @@ -16,7 +16,7 @@
alarm.filter
- diff --git a/ui-ngx/src/app/modules/home/components/widget/config/basic/common/widget-actions-panel.component.html b/ui-ngx/src/app/modules/home/components/widget/config/basic/common/widget-actions-panel.component.html index ef2a677822..4e915acb6f 100644 --- a/ui-ngx/src/app/modules/home/components/widget/config/basic/common/widget-actions-panel.component.html +++ b/ui-ngx/src/app/modules/home/components/widget/config/basic/common/widget-actions-panel.component.html @@ -1,7 +1,8 @@
@@ -18,12 +19,12 @@ } @if (!hasWidgetActions) { - } @if (hasWidgetActions) { - } diff --git a/ui-ngx/src/app/modules/home/components/widget/config/basic/entity/entity-count-basic-config.component.ts b/ui-ngx/src/app/modules/home/components/widget/config/basic/entity/entity-count-basic-config.component.ts index 72ad9375ae..62ccf6c3e2 100644 --- a/ui-ngx/src/app/modules/home/components/widget/config/basic/entity/entity-count-basic-config.component.ts +++ b/ui-ngx/src/app/modules/home/components/widget/config/basic/entity/entity-count-basic-config.component.ts @@ -9,10 +9,13 @@ import { BasicWidgetConfigComponent } from '@home/components/widget/config/widge import { WidgetConfigComponentData } from '@home/models/widget-component.models'; import { DatasourceType, WidgetConfig, widgetTitleAutocompleteValues, } from '@shared/models/widget.models'; import { WidgetConfigComponent } from '@home/components/widget/widget-config.component'; -import { DataKeyType } from '@shared/models/telemetry/telemetry.models'; import { isUndefined } from '@core/utils'; import { UtilsService } from '@core/services/utils.service'; -import { countDefaultSettings, CountWidgetSettings } from '@home/components/widget/lib/count/count-widget.models'; +import { + countDefaultSettings, + CountWidgetSettings, + normalizeCountWidgetDatasource +} from '@home/components/widget/lib/count/count-widget.models'; @Component({ selector: 'tb-entity-count-basic-config', @@ -38,16 +41,11 @@ export class EntityCountBasicConfigComponent extends BasicWidgetConfigComponent } protected setupDefaults(configData: WidgetConfigComponentData) { - let datasources = configData.config.datasources; - if (!datasources || !datasources.length) { - datasources = [{}]; - configData.config.datasources = datasources; - } - datasources[0].type = DatasourceType.entityCount; - datasources[0].dataKeys = [this.utils.createKey({name: 'count'}, DataKeyType.count)]; + normalizeCountWidgetDatasource(configData, DatasourceType.entityCount, this.utils, true); } protected onConfigSet(configData: WidgetConfigComponentData) { + const normalized = !this.widgetEditMode && normalizeCountWidgetDatasource(configData, DatasourceType.entityCount, this.utils); const settings: CountWidgetSettings = {...countDefaultSettings(false), ...(configData.config.settings || {})}; this.entityCountWidgetConfigForm = this.fb.group({ datasources: [configData.config.datasources, []], @@ -59,6 +57,9 @@ export class EntityCountBasicConfigComponent extends BasicWidgetConfigComponent actions: [configData.config.actions || {}, []] }); + if (normalized) { + this.emitConfigChangedDeferred(); + } } protected prepareOutputConfig(config: any): WidgetConfigComponentData { diff --git a/ui-ngx/src/app/modules/home/components/widget/config/widget-config.component.models.ts b/ui-ngx/src/app/modules/home/components/widget/config/widget-config.component.models.ts index 8cbe1b7e95..c1fa19e678 100644 --- a/ui-ngx/src/app/modules/home/components/widget/config/widget-config.component.models.ts +++ b/ui-ngx/src/app/modules/home/components/widget/config/widget-config.component.models.ts @@ -1,5 +1,6 @@ // SPDX-FileCopyrightText: Copyright The ThingsBoard Authors -// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Modifications Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: Apache-2.0 AND BUSL-1.1 import { WidgetActionCallbacks } from '@home/components/widget/action/manage-widget-actions.component.models'; import { DatasourceCallbacks } from '@home/components/widget/config/datasource.component.models'; import { WidgetConfigComponentData } from '@home/models/widget-component.models'; @@ -91,12 +92,16 @@ export abstract class BasicWidgetConfigComponent extends PageComponent implement ngAfterViewInit(): void { if (!this.validateConfig()) { - setTimeout(() => { - this.onConfigChanged(this.prepareOutputConfig(this.configForm().getRawValue())); - }, 0); + this.emitConfigChangedDeferred(); } } + protected emitConfigChangedDeferred() { + setTimeout(() => { + this.onConfigChanged(this.prepareOutputConfig(this.configForm().getRawValue())); + }, 0); + } + protected setupConfig(widgetConfig: WidgetConfigComponentData) { if (this.isAdd) { this.setupDefaults(widgetConfig); diff --git a/ui-ngx/src/app/modules/home/components/widget/lib/count/count-widget.models.ts b/ui-ngx/src/app/modules/home/components/widget/lib/count/count-widget.models.ts index 7c531a6b30..86b034559a 100644 --- a/ui-ngx/src/app/modules/home/components/widget/lib/count/count-widget.models.ts +++ b/ui-ngx/src/app/modules/home/components/widget/lib/count/count-widget.models.ts @@ -1,5 +1,6 @@ // SPDX-FileCopyrightText: Copyright The ThingsBoard Authors -// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: Modifications Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: Apache-2.0 AND BUSL-1.1 import { ColorSettings, ColorType, @@ -8,6 +9,11 @@ import { defaultColorFunction, Font } from '@shared/models/widget-settings.models'; +import { WidgetConfigComponentData } from '@home/models/widget-component.models'; +import { DatasourceType } from '@shared/models/widget.models'; +import { AlarmSearchStatus } from '@shared/models/alarm.models'; +import { DataKeyType } from '@shared/models/telemetry/telemetry.models'; +import { UtilsService } from '@core/services/utils.service'; export enum CountCardLayout { column = 'column', @@ -110,3 +116,23 @@ export const countDefaultSettings = (alarmElseEntity: boolean): CountWidgetSetti chevronSizeUnit: 'px', chevronColor: 'rgba(0, 0, 0, 0.38)' }); + +export const normalizeCountWidgetDatasource = (configData: WidgetConfigComponentData, type: DatasourceType.alarmCount | DatasourceType.entityCount, + utils: UtilsService, force = false): boolean => { + let datasources = configData.config.datasources; + if (!datasources || !datasources.length) { + datasources = [{}]; + configData.config.datasources = datasources; + } + const datasource = datasources[0]; + if (!force && datasource.type === type) { + return false; + } + datasource.type = type; + delete datasource.name; + datasource.dataKeys = [utils.createKey({name: 'count'}, DataKeyType.count)]; + if (type === DatasourceType.alarmCount) { + datasource.alarmFilterConfig = {statusList: [AlarmSearchStatus.ACTIVE]}; + } + return true; +}; diff --git a/ui-ngx/src/app/modules/home/components/widget/lib/home-page/cluster-info-table.component.html b/ui-ngx/src/app/modules/home/components/widget/lib/home-page/cluster-info-table.component.html deleted file mode 100644 index 878b6be563..0000000000 --- a/ui-ngx/src/app/modules/home/components/widget/lib/home-page/cluster-info-table.component.html +++ /dev/null @@ -1,65 +0,0 @@ - - - - - {{ 'widgets.cluster-info.service-id' | translate }} - - - {{ serviceData.serviceId }} - - - - - {{ 'widgets.cluster-info.service-type' | translate }} - - - {{ serviceData.serviceType }} - - - - - {{ 'widgets.system-info.cpu' | translate }} - - - {{ serviceData.cpuUsage }}% - - - - - {{ 'widgets.system-info.ram' | translate }} - - - {{ serviceData.memoryUsage }}% - - - - - {{ 'widgets.system-info.disk' | translate }} - - - {{ serviceData.discUsage }}% - - - - -
-widgets.cluster-info.no-data diff --git a/ui-ngx/src/app/modules/home/components/widget/lib/home-page/cluster-info-table.component.scss b/ui-ngx/src/app/modules/home/components/widget/lib/home-page/cluster-info-table.component.scss deleted file mode 100644 index c0ec6dcd57..0000000000 --- a/ui-ngx/src/app/modules/home/components/widget/lib/home-page/cluster-info-table.component.scss +++ /dev/null @@ -1,59 +0,0 @@ -// SPDX-FileCopyrightText: Copyright The ThingsBoard Authors -// SPDX-FileCopyrightText: Modifications Copyright ThingsBoard, Inc. -// SPDX-License-Identifier: Apache-2.0 AND BUSL-1.1 -:host { - span.no-data-found { - font-weight: 400; - font-size: 14px; - line-height: 20px; - letter-spacing: 0.2px; - color: rgba(0, 0, 0, 0.76); - } - - .tb-resource-usage { - cursor: default; - &.tb-status-warn, &.tb-status-critical { - position: relative; - overflow: visible; - &:before { - position: absolute; - top: 15px; - left: -24px; - font-family: 'Material Icons Round'; - font-size: 20px; - line-height: 1; - } - } - &.tb-status-warn { - color: var(--tb-warning); - &:before { - content: "warning"; - color: var(--tb-warning); - } - } - &.tb-status-critical { - color: var(--tb-crit); - &:before { - content: "warning"; - color: var(--tb-crit); - } - } - } -} - -:host ::ng-deep { - .mdc-data-table__header-cell { - font-weight: 500; - font-size: 11px; - line-height: 20px; - letter-spacing: 0.25px; - color: rgba(0, 0, 0, 0.54); - } - .mdc-data-table__cell { - font-weight: 400; - font-size: 14px; - line-height: 20px; - letter-spacing: 0.2px; - color: rgba(0, 0, 0, 0.76); - } -} diff --git a/ui-ngx/src/app/modules/home/components/widget/lib/home-page/cluster-info-table.component.ts b/ui-ngx/src/app/modules/home/components/widget/lib/home-page/cluster-info-table.component.ts deleted file mode 100644 index 6ec9483f6e..0000000000 --- a/ui-ngx/src/app/modules/home/components/widget/lib/home-page/cluster-info-table.component.ts +++ /dev/null @@ -1,224 +0,0 @@ -// SPDX-FileCopyrightText: Copyright The ThingsBoard Authors -// SPDX-License-Identifier: Apache-2.0 -import { AfterViewInit, Component, NgZone, OnInit, ViewChild } from '@angular/core'; -import { PageComponent } from '@shared/components/page.component'; -import { Store } from '@ngrx/store'; -import { AppState } from '@core/core.state'; -import { CollectionViewer, DataSource } from '@angular/cdk/collections'; -import { BehaviorSubject, Observable, of } from 'rxjs'; -import { emptyPageData, PageData } from '@shared/models/page/page-data'; -import { MAX_SAFE_PAGE_SIZE, PageLink } from '@shared/models/page/page-link'; -import { catchError, map, publishReplay, refCount, share } from 'rxjs/operators'; -import { MatSort } from '@angular/material/sort'; -import { Direction, SortOrder } from '@shared/models/page/sort-order'; -import { TelemetryWebsocketService } from '@core/ws/telemetry-websocket.service'; -import { EntityDataUpdate, TelemetrySubscriber } from '@shared/models/telemetry/telemetry.models'; -import { AliasFilterType } from '@shared/models/alias.models'; -import { EntityKeyType } from '@shared/models/query/query.models'; -import { TranslateService } from '@ngx-translate/core'; - -export interface SystemInfoData { - serviceId: string; - serviceType: string; - cpuUsage: number; - cpuCount: number; - memoryUsage: number; - totalMemory: number; - discUsage: number; - totalDiscSpace: number; -} - -@Component({ - selector: 'tb-cluster-info-table', - templateUrl: './cluster-info-table.component.html', - styleUrls: ['./cluster-info-table.component.scss'], - standalone: false -}) -export class ClusterInfoTableComponent extends PageComponent implements OnInit, AfterViewInit { - - @ViewChild(MatSort) sort: MatSort; - - displayedColumns = ['serviceId', 'serviceType', 'cpuUsage', 'memoryUsage', 'discUsage']; - - dataSource: SystemInfoDataSource; - - pageLink: PageLink; - - constructor(protected store: Store, - private telemetryWsService: TelemetryWebsocketService, - private translate: TranslateService, - private zone: NgZone) { - super(store); - } - - ngOnInit() { - this.dataSource = new SystemInfoDataSource(this.telemetryWsService, this.zone); - const sortOrder: SortOrder = { - property: 'serviceId', - direction: Direction.ASC - }; - this.pageLink = new PageLink(MAX_SAFE_PAGE_SIZE, 0, null, sortOrder); - this.dataSource.loadData(this.pageLink); - } - - ngAfterViewInit() { - this.sort.sortChange.subscribe(() => this.updateData()); - } - - updateData() { - this.pageLink.sortOrder.property = this.sort.active; - this.pageLink.sortOrder.direction = Direction[this.sort.direction.toUpperCase()]; - this.dataSource.loadData(this.pageLink); - } - - statusClass(value: number): string { - let status = ''; - if (value > 85) { - status = 'tb-status-critical'; - } else if (value > 75) { - status = 'tb-status-warn'; - } - return status; - } - - infoTooltip(serviceData: SystemInfoData, type: 'cpu' | 'ram' | 'disc'): string { - let tooltip = ''; - let value: number; - switch (type) { - case 'cpu': - value = serviceData.cpuUsage; - tooltip += value + ' / 100 %'; - break; - case 'ram': - value = serviceData.memoryUsage; - const memoryUsage = serviceData.memoryUsage; - const totalMemory = serviceData.totalMemory / 1073741824; - const usedMemory = (totalMemory * (memoryUsage / 100)).toFixed(0); - tooltip += usedMemory + ' / ' + totalMemory.toFixed(0) + ' Gb'; - break; - case 'disc': - value = serviceData.discUsage; - const discUsage = serviceData.discUsage; - const totalDiscSpace = serviceData.totalDiscSpace / 1073741824; - const usedDisc = (totalDiscSpace * (discUsage / 100)).toFixed(0); - tooltip += usedDisc + ' / ' + totalDiscSpace.toFixed(0) + ' Gb'; - break; - } - if (value > 85) { - switch (type) { - case 'cpu': - tooltip += '\n\n' + this.translate.instant('widgets.system-info.cpu-critical-text'); - break; - case 'ram': - tooltip += '\n\n' + this.translate.instant('widgets.system-info.ram-critical-text'); - break; - case 'disc': - tooltip += '\n\n' + this.translate.instant('widgets.system-info.disk-critical-text'); - break; - } - } else if (value > 75) { - switch (type) { - case 'cpu': - tooltip += '\n\n' + this.translate.instant('widgets.system-info.cpu-warning-text'); - break; - case 'ram': - tooltip += '\n\n' + this.translate.instant('widgets.system-info.ram-warning-text'); - break; - case 'disc': - tooltip += '\n\n' + this.translate.instant('widgets.system-info.disk-warning-text'); - break; - } - } - return tooltip; - } -} - -export class SystemInfoDataSource implements DataSource { - - private systemDataSubject = new BehaviorSubject([]); - private pageDataSubject = new BehaviorSubject>(emptyPageData()); - - public pageData$ = this.pageDataSubject.asObservable(); - - private allSystemData: Observable>; - - private telemetrySubscriber: TelemetrySubscriber; - - constructor(private telemetryWsService: TelemetryWebsocketService, - private zone: NgZone) { - } - - connect(collectionViewer: CollectionViewer): Observable> { - return this.systemDataSubject.asObservable(); - } - - disconnect(collectionViewer: CollectionViewer): void { - this.systemDataSubject.complete(); - this.pageDataSubject.complete(); - if (this.telemetrySubscriber) { - this.telemetrySubscriber.unsubscribe(); - this.telemetrySubscriber = null; - } - } - - loadData(pageLink: PageLink): void { - this.getAllSystemData().pipe( - map((data) => pageLink.filterData(data)), - catchError(() => of(emptyPageData())), - ).subscribe( - (pageData) => { - this.onSystemData(pageData.data); - this.pageDataSubject.next(pageData); - } - ); - } - - getAllSystemData(): Observable> { - if (!this.allSystemData) { - this.telemetrySubscriber = TelemetrySubscriber.createEntityFilterLatestSubscription( - this.telemetryWsService, { type: AliasFilterType.apiUsageState }, this.zone, - [ { key: 'clusterSystemData', type: EntityKeyType.TIME_SERIES } ]); - this.telemetrySubscriber.subscribe(); - this.allSystemData = this.telemetrySubscriber.entityData$.pipe( - map((update) => this.toSystemInfoData(update)), - publishReplay(1), - refCount() - ); - } - return this.allSystemData; - } - - private toSystemInfoData(entityDataUpdate: EntityDataUpdate): Array { - const entityData = entityDataUpdate.data?.data ? entityDataUpdate.data?.data : entityDataUpdate.update; - if (entityData && entityData.length) { - const latest = entityData[0].latest; - if (latest && latest[EntityKeyType.TIME_SERIES]) { - const latestTs = latest[EntityKeyType.TIME_SERIES]; - const tsValue = latestTs.clusterSystemData; - if (tsValue && tsValue.value) { - return JSON.parse(tsValue.value); - } - } - } - return []; - } - - protected onSystemData(data: SystemInfoData[]) { - this.systemDataSubject.next(data); - } - - isEmpty(): Observable { - return this.systemDataSubject.pipe( - map((entities) => !entities.length), - share() - ); - } - - total(): Observable { - return this.pageDataSubject.pipe( - map((pageData) => pageData.totalElements), - share() - ); - } - -} diff --git a/ui-ngx/src/app/modules/home/components/widget/lib/home-page/configured-features.component.html b/ui-ngx/src/app/modules/home/components/widget/lib/home-page/configured-features.component.html deleted file mode 100644 index 33345de243..0000000000 --- a/ui-ngx/src/app/modules/home/components/widget/lib/home-page/configured-features.component.html +++ /dev/null @@ -1,71 +0,0 @@ - - diff --git a/ui-ngx/src/app/modules/home/components/widget/lib/home-page/configured-features.component.scss b/ui-ngx/src/app/modules/home/components/widget/lib/home-page/configured-features.component.scss deleted file mode 100644 index 168d3aaf4c..0000000000 --- a/ui-ngx/src/app/modules/home/components/widget/lib/home-page/configured-features.component.scss +++ /dev/null @@ -1,102 +0,0 @@ -// SPDX-FileCopyrightText: Copyright The ThingsBoard Authors -// SPDX-FileCopyrightText: Modifications Copyright ThingsBoard, Inc. -// SPDX-License-Identifier: Apache-2.0 AND BUSL-1.1 -@import "../../../../../../../scss/constants"; - -:host { - - .tb-title { - margin-top: 8px; - } - - .tb-info-icon { - color: rgba(0, 0, 0, 0.12); - font-size: 16px; - width: 16px; - height: 16px; - line-height: 15px; - vertical-align: middle; - } - - .tb-features-list { - overflow: auto; - } - - .mat-grid-tile.tb-feature-tile { - overflow: visible; - } - - .tb-feature-button { - height: 50px; - display: flex; - overflow: hidden; - flex-direction: column; - justify-content: center; - padding: 12px; - background: #FFFFFF; - border: 1px solid rgba(0, 0, 0, 0.05); - box-shadow: 0 5px 16px rgba(0, 0, 0, 0.04); - border-radius: 10px; - @media #{$mat-md-lg} { - height: 22px; - padding: 0 8px; - } - &:hover { - border: 1px solid rgba(0, 0, 0, 0.12); - box-shadow: 0 4px 10px rgba(23, 33, 90, 0.08); - } - .tb-feature-text { - font-weight: 400; - font-size: 14px; - line-height: 20px; - color: rgba(0, 0, 0, 0.87); - white-space: nowrap; - overflow: hidden; - text-overflow: ellipsis; - @media #{$mat-md-lg} { - font-size: 11px; - line-height: 16px; - } - } - .tb-feature-status { - display: inline-block; - font-family: 'Material Icons Round'; - font-size: 20px; - line-height: 20px; - color: rgba(0, 0, 0, 0.12); - font-weight: 600; - position: relative; - background: #F4F4F4; - border-radius: 4px; - width: 24px; - height: 24px; - padding: 2px; - margin-right: 8px; - vertical-align: middle; - @media #{$mat-md-lg} { - font-size: 14px; - line-height: 14px; - width: 18px; - height: 18px; - margin-right: 4px; - } - } - &.configured { - .tb-feature-status { - color: #198038; - background: transparent; - &:before { - content: ""; - position: absolute; - top: 0; - bottom: 0; - left: 0; - right: 0; - border-radius: 4px; - background: var(--tb-primary-500); - opacity: 0.04; - } - } - } - } -} diff --git a/ui-ngx/src/app/modules/home/components/widget/lib/home-page/configured-features.component.ts b/ui-ngx/src/app/modules/home/components/widget/lib/home-page/configured-features.component.ts deleted file mode 100644 index f521e95201..0000000000 --- a/ui-ngx/src/app/modules/home/components/widget/lib/home-page/configured-features.component.ts +++ /dev/null @@ -1,88 +0,0 @@ -// SPDX-FileCopyrightText: Copyright The ThingsBoard Authors -// SPDX-FileCopyrightText: Modifications Copyright ThingsBoard, Inc. -// SPDX-License-Identifier: Apache-2.0 AND BUSL-1.1 -import { ChangeDetectorRef, Component, OnDestroy, OnInit } from '@angular/core'; -import { PageComponent } from '@shared/components/page.component'; -import { Store } from '@ngrx/store'; -import { AppState } from '@core/core.state'; -import { AdminService } from '@core/http/admin.service'; -import { FeaturesInfo } from '@shared/models/settings.models'; -import { getCurrentAuthUser } from '@core/auth/auth.selectors'; -import { Authority } from '@shared/models/authority.enum'; -import { of, Subscription } from 'rxjs'; -import { BreakpointObserver, BreakpointState } from '@angular/cdk/layout'; -import { TranslateService } from '@ngx-translate/core'; -import { MediaBreakpoints } from '@shared/models/constants'; - -@Component({ - selector: 'tb-configured-features', - templateUrl: './configured-features.component.html', - styleUrls: ['./home-page-widget.scss', './configured-features.component.scss'], - standalone: false -}) -export class ConfiguredFeaturesComponent extends PageComponent implements OnInit, OnDestroy { - - authUser = getCurrentAuthUser(this.store); - featuresInfo: FeaturesInfo; - rowHeight = '50px'; - gutterSize = '12px'; - colspan = 2; - - private observeBreakpointSubscription: Subscription; - - constructor(protected store: Store, - private cd: ChangeDetectorRef, - private adminService: AdminService, - private translate: TranslateService, - private breakpointObserver: BreakpointObserver) { - super(store); - } - - ngOnInit() { - const isMdLg = this.breakpointObserver.isMatched(MediaBreakpoints['md-lg']); - const isLtMd = this.breakpointObserver.isMatched(MediaBreakpoints['lt-md']); - this.rowHeight = isMdLg ? '22px' : '50px'; - this.gutterSize = isMdLg ? '8px' : '12px'; - this.colspan = isLtMd ? 3 : 2; - this.observeBreakpointSubscription = this.breakpointObserver - .observe([MediaBreakpoints['md-lg'], MediaBreakpoints['lt-md']]) - .subscribe((state: BreakpointState) => { - if (state.breakpoints[MediaBreakpoints['md-lg']]) { - this.rowHeight = '22px'; - this.gutterSize = '8px'; - } else { - this.rowHeight = '50px'; - this.gutterSize = '12px'; - } - if (state.breakpoints[MediaBreakpoints['lt-md']]) { - this.colspan = 3; - } else { - this.colspan = 2; - } - this.cd.markForCheck(); - } - ); - (this.authUser.authority === Authority.SYS_ADMIN ? - this.adminService.getFeaturesInfo() : of(null)).subscribe( - (featuresInfo) => { - this.featuresInfo = featuresInfo; - this.cd.markForCheck(); - } - ); - } - - ngOnDestroy() { - if (this.observeBreakpointSubscription) { - this.observeBreakpointSubscription.unsubscribe(); - } - super.ngOnDestroy(); - } - - featureTooltip(configured: boolean): string { - if (configured) { - return this.translate.instant('widgets.configured-features.feature-configured'); - } else { - return this.translate.instant('widgets.configured-features.feature-not-configured'); - } - } -} diff --git a/ui-ngx/src/app/modules/home/components/widget/lib/home-page/home-page-widgets.module.ts b/ui-ngx/src/app/modules/home/components/widget/lib/home-page/home-page-widgets.module.ts index 55ea62bb7d..b44d03a596 100644 --- a/ui-ngx/src/app/modules/home/components/widget/lib/home-page/home-page-widgets.module.ts +++ b/ui-ngx/src/app/modules/home/components/widget/lib/home-page/home-page-widgets.module.ts @@ -4,9 +4,6 @@ import { NgModule } from '@angular/core'; import { CommonModule } from '@angular/common'; import { SharedModule } from '@app/shared/shared.module'; -import { ClusterInfoTableComponent } from '@home/components/widget/lib/home-page/cluster-info-table.component'; -import { ConfiguredFeaturesComponent } from '@home/components/widget/lib/home-page/configured-features.component'; -import { VersionInfoComponent } from '@home/components/widget/lib/home-page/version-info.component'; import { DocLinksWidgetComponent } from '@home/components/widget/lib/home-page/doc-links-widget.component'; import { DocLinkComponent } from '@home/components/widget/lib/home-page/doc-link.component'; import { AddDocLinkDialogComponent } from '@home/components/widget/lib/home-page/add-doc-link-dialog.component'; @@ -15,7 +12,6 @@ import { GettingStartedWidgetComponent } from '@home/components/widget/lib/home- import { GettingStartedCompletedDialogComponent } from '@home/components/widget/lib/home-page/getting-started-completed-dialog.component'; -import { LicenseUsageInfoComponent } from '@home/components/widget/lib/home-page/license-usage-info.component'; import { UsageInfoWidgetComponent } from '@home/components/widget/lib/home-page/usage-info-widget.component'; import { QuickLinksWidgetComponent } from '@home/components/widget/lib/home-page/quick-links-widget.component'; import { QuickLinkComponent } from '@home/components/widget/lib/home-page/quick-link.component'; @@ -29,16 +25,12 @@ import { IotHubComponentsModule } from '@home/components/iot-hub/iot-hub-compone @NgModule({ declarations: [ - ClusterInfoTableComponent, - ConfiguredFeaturesComponent, - VersionInfoComponent, DocLinksWidgetComponent, DocLinkComponent, AddDocLinkDialogComponent, EditLinksDialogComponent, GettingStartedWidgetComponent, GettingStartedCompletedDialogComponent, - LicenseUsageInfoComponent, UsageInfoWidgetComponent, QuickLinksWidgetComponent, QuickLinkComponent, @@ -52,16 +44,12 @@ import { IotHubComponentsModule } from '@home/components/iot-hub/iot-hub-compone IotHubComponentsModule ], exports: [ - ClusterInfoTableComponent, - ConfiguredFeaturesComponent, - VersionInfoComponent, DocLinksWidgetComponent, DocLinkComponent, AddDocLinkDialogComponent, EditLinksDialogComponent, GettingStartedWidgetComponent, GettingStartedCompletedDialogComponent, - LicenseUsageInfoComponent, UsageInfoWidgetComponent, QuickLinksWidgetComponent, QuickLinkComponent, diff --git a/ui-ngx/src/app/modules/home/components/widget/lib/home-page/iot-hub-widget.component.ts b/ui-ngx/src/app/modules/home/components/widget/lib/home-page/iot-hub-widget.component.ts index 5311eae1bb..2ffe865485 100644 --- a/ui-ngx/src/app/modules/home/components/widget/lib/home-page/iot-hub-widget.component.ts +++ b/ui-ngx/src/app/modules/home/components/widget/lib/home-page/iot-hub-widget.component.ts @@ -16,7 +16,7 @@ import { IotHubInstalledItem } from '@shared/models/iot-hub/iot-hub-installed-it import { PageLink } from '@shared/models/page/page-link'; import { Direction, SortOrder } from '@shared/models/page/sort-order'; import { UserPermissionsService } from '@core/http/user-permissions.service'; -import { Operation, Resource } from '@shared/models/security.models'; +import { Operation } from '@shared/models/security.models'; const WIDGET_CARD_COUNT = 3; @@ -51,7 +51,7 @@ export class IotHubWidgetComponent extends PageComponent implements OnInit { ngOnInit() { this.ctx.overflowVisible = true; this.hasIotHubAccess = [Authority.TENANT_ADMIN].includes(this.authUser.authority) && - this.userPermissionsService.hasGenericPermission(Resource.ALL, Operation.ALL); + this.userPermissionsService.hasGenericPermissionExceptAi(Operation.ALL); if (this.hasIotHubAccess) { this.load(); } diff --git a/ui-ngx/src/app/modules/home/components/widget/lib/home-page/license-usage-info.component.html b/ui-ngx/src/app/modules/home/components/widget/lib/home-page/license-usage-info.component.html deleted file mode 100644 index 809294b972..0000000000 --- a/ui-ngx/src/app/modules/home/components/widget/lib/home-page/license-usage-info.component.html +++ /dev/null @@ -1,80 +0,0 @@ - -
-
-
-
widgets.license-info.title
-
- {{ 'widgets.license-info.view-all' | translate }} -
-
- -
-
-
- - {{ statusIcon(licenseUsageInfo?.devicesCount, licenseUsageInfo?.maxDevices) }} - {{ 'widgets.license-info.devices-info' | translate: { count: licenseUsageInfo?.devicesCount, max: licenseUsageInfo?.maxDevices} }} -
-
- - {{ statusIcon(licenseUsageInfo?.assetsCount, licenseUsageInfo?.maxAssets) }} - {{ 'widgets.license-info.assets-info' | translate: { count: licenseUsageInfo?.assetsCount, max: licenseUsageInfo?.maxAssets} }} -
- @if (showEdges) { -
- - {{ statusIcon(licenseUsageInfo?.edgesCount, licenseUsageInfo?.maxEdges) }} - {{ 'widgets.license-info.edges-info' | translate: { count: licenseUsageInfo?.edgesCount, max: licenseUsageInfo?.maxEdges} }} -
- } - @if (!isMdLg) { -
- - check - {{ 'widgets.license-info.dashboards-info' | translate: { count: licenseUsageInfo?.dashboardsCount, max: 0} }} -
- } - @if (!isMdLg) { -
- - check - {{ 'widgets.license-info.integrations-info' | translate: { count: licenseUsageInfo?.integrationsCount, max: 0} }} -
- } -
- @if (!isMdLg) { -
-
- - check - {{ 'widgets.license-info.community-support' | translate }} -
-
- - {{ licenseUsageInfo?.whiteLabelingEnabled ? 'check' : 'close' }} - {{ 'widgets.license-info.white-labeling' | translate }} -
-
- - check - {{ 'widgets.license-info.unlimited-datapoints-and-messages' | translate }} -
-
- - check - {{ 'widgets.license-info.unlimited-api-calls' | translate }} -
-
- } -
-
-
diff --git a/ui-ngx/src/app/modules/home/components/widget/lib/home-page/license-usage-info.component.scss b/ui-ngx/src/app/modules/home/components/widget/lib/home-page/license-usage-info.component.scss deleted file mode 100644 index b9ef44a550..0000000000 --- a/ui-ngx/src/app/modules/home/components/widget/lib/home-page/license-usage-info.component.scss +++ /dev/null @@ -1,162 +0,0 @@ -// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. -// SPDX-License-Identifier: BUSL-1.1 -@import "../../../../../../../scss/constants"; - -:host { - .tb-card-content { - width: 100%; - height: 100%; - } - - .tb-card-header { - display: flex; - flex-direction: row; - justify-content: space-between; - align-items: center; - @media #{$mat-md-lg} { - margin-bottom: 4px; - } - } - - .tb-title { - font-style: normal; - font-weight: 500; - font-size: 14px; - line-height: 20px; - letter-spacing: 0.25px; - color: rgba(0, 0, 0, 0.54); - @media #{$mat-md-lg} { - font-size: 12px; - line-height: 16px; - } - } - - .tb-view-all, .tb-license-portal { - @media #{$mat-md-lg} { - height: 24px; - font-size: 12px; - } - } - - .tb-license-info-container { - border: 1px solid rgba(0, 0, 0, 0.05); - box-shadow: 0 5px 16px rgba(0, 0, 0, 0.04); - border-radius: 10px; - padding: 8px 16px 4px 16px; - display: flex; - flex-direction: column; - @media #{$mat-md-lg} { - padding: 4px; - } - } - - .tb-plan-link { - font-weight: 500; - font-size: 16px; - line-height: 24px; - letter-spacing: 0.25px; - color: rgba(0, 0, 0, 0.76); - position: relative; - border-bottom: none; - @media #{$mat-md-lg} { - font-size: 12px; - line-height: 16px; - color: rgba(0, 0, 0, 0.54); - } - &:hover, &:focus { - border-bottom: none; - } - &::after { - content: 'arrow_forward'; - display: inline-block; - transform: rotate(315deg); - font-family: 'Material Icons'; - font-weight: normal; - font-style: normal; - font-size: 18px; - color: rgba(0, 0, 0, 0.12); - vertical-align: bottom; - margin-left: 6px; - } - &:hover::after { - color: inherit; - } - } - .tb-feature-text { - font-weight: 400; - font-size: 14px; - color: rgba(0, 0, 0, 0.87); - white-space: nowrap; - overflow: hidden; - text-overflow: ellipsis; - @media #{$mat-md-lg} { - font-size: 11px; - line-height: 16px; - } - .tb-feature-status { - display: inline-block; - font-family: 'Material Icons Round'; - position: relative; - border-radius: 4px; - width: 22px; - height: 22px; - margin-right: 8px; - @media #{$mat-md-lg} { - width: 18px; - height: 18px; - margin-right: 4px; - } - } - &.ok, &.disabled { - .tb-feature-status { - font-size: 20px; - line-height: 20px; - font-weight: 600; - padding: 1px; - vertical-align: sub; - @media #{$mat-md-lg} { - font-size: 14px; - line-height: 14px; - padding: 2px; - } - } - } - &.ok { - .tb-feature-status { - color: #198038; - background: transparent; - &:before { - content: ""; - position: absolute; - top: 0; - bottom: 0; - left: 0; - right: 0; - border-radius: 4px; - background: var(--tb-primary-500); - opacity: 0.04; - } - } - } - &.disabled { - .tb-feature-status { - color: rgba(0, 0, 0, 0.12); - background: #F4F4F4; - } - } - &.critical { - color: var(--tb-crit); - .tb-feature-status { - line-height: 24px; - font-size: 24px; - font-weight: normal; - padding: 0; - vertical-align: bottom; - @media #{$mat-md-lg} { - font-size: 18px; - line-height: 18px; - } - } - } - } -} diff --git a/ui-ngx/src/app/modules/home/components/widget/lib/home-page/license-usage-info.component.ts b/ui-ngx/src/app/modules/home/components/widget/lib/home-page/license-usage-info.component.ts deleted file mode 100644 index 176cac3229..0000000000 --- a/ui-ngx/src/app/modules/home/components/widget/lib/home-page/license-usage-info.component.ts +++ /dev/null @@ -1,86 +0,0 @@ -// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. -// SPDX-License-Identifier: BUSL-1.1 -import { ChangeDetectionStrategy, ChangeDetectorRef, Component, OnDestroy, OnInit } from '@angular/core'; -import { PageComponent } from '@shared/components/page.component'; -import { Store } from '@ngrx/store'; -import { AppState } from '@core/core.state'; -import { AdminService } from '@core/http/admin.service'; -import { LicenseUsageInfo } from '@shared/models/settings.models'; -import { getCurrentAuthState, getCurrentAuthUser } from '@core/auth/auth.selectors'; -import { Authority } from '@shared/models/authority.enum'; -import { of, Subscription } from 'rxjs'; -import { BreakpointObserver, BreakpointState } from '@angular/cdk/layout'; -import { TranslateService } from '@ngx-translate/core'; -import { MediaBreakpoints } from '@shared/models/constants'; - -@Component({ - selector: 'tb-license-usage-info', - templateUrl: './license-usage-info.component.html', - styleUrls: ['./license-usage-info.component.scss'], - changeDetection: ChangeDetectionStrategy.OnPush, - standalone: false -}) -export class LicenseUsageInfoComponent extends PageComponent implements OnInit, OnDestroy { - - authUser = getCurrentAuthUser(this.store); - licenseUsageInfo: LicenseUsageInfo; - isMdLg = false; - authState = getCurrentAuthState(this.store); - showEdges = this.authState.licenseVersion > 1 && this.authState.edgesSupportEnabled && this.authState.edgeEnabled; - - private observeBreakpointSubscription: Subscription; - - constructor(protected store: Store, - private cd: ChangeDetectorRef, - private adminService: AdminService, - private translate: TranslateService, - private breakpointObserver: BreakpointObserver) { - super(store); - } - - ngOnInit() { - this.isMdLg = this.breakpointObserver.isMatched(MediaBreakpoints['md-lg']); - this.observeBreakpointSubscription = this.breakpointObserver - .observe(MediaBreakpoints['md-lg']) - .subscribe((state: BreakpointState) => { - this.isMdLg = state.matches; - this.cd.markForCheck(); - }); - (this.authUser.authority === Authority.SYS_ADMIN ? - this.adminService.getLicenseUsageInfo() : of(null)).subscribe( - (licenseUsageInfo) => { - this.licenseUsageInfo = licenseUsageInfo; - this.cd.markForCheck(); - } - ); - } - - ngOnDestroy() { - if (this.observeBreakpointSubscription) { - this.observeBreakpointSubscription.unsubscribe(); - } - super.ngOnDestroy(); - } - - statusIcon(count?: number, max?: number): string { - let icon = 'check'; - if (count && max) { - const percent = (count / max) * 100; - if (percent > 85) { - icon = 'warning'; - } - } - return icon; - } - - statusClass(count?: number, max?: number): string { - let className = 'ok'; - if (count && max) { - const percent = (count / max) * 100; - if (percent > 85) { - className = 'critical'; - } - } - return className; - } -} diff --git a/ui-ngx/src/app/modules/home/components/widget/lib/home-page/usage-info-widget.component.ts b/ui-ngx/src/app/modules/home/components/widget/lib/home-page/usage-info-widget.component.ts index 8174ec5794..5916598612 100644 --- a/ui-ngx/src/app/modules/home/components/widget/lib/home-page/usage-info-widget.component.ts +++ b/ui-ngx/src/app/modules/home/components/widget/lib/home-page/usage-info-widget.component.ts @@ -13,7 +13,7 @@ import { UsageInfo } from '@shared/models/usage.models'; import { UsageInfoService } from '@core/http/usage-info.service'; import { ShortNumberPipe } from '@shared/pipe/short-number.pipe'; import { UserPermissionsService } from '@core/http/user-permissions.service'; -import { Operation, Resource } from '@shared/models/security.models'; +import { Operation } from '@shared/models/security.models'; @Component({ selector: 'tb-usage-info-widget', @@ -48,7 +48,7 @@ export class UsageInfoWidgetComponent extends PageComponent implements OnInit, O ngOnInit() { this.hasUsageInfoAccess = this.authUser.authority === Authority.TENANT_ADMIN && - this.userPermissionsService.hasGenericPermission(Resource.ALL, Operation.READ); + this.userPermissionsService.hasGenericPermissionExceptAi(Operation.READ); if (this.hasUsageInfoAccess) { this.usageInfoService.getUsageInfo().subscribe( (usageInfo) => { diff --git a/ui-ngx/src/app/modules/home/components/widget/lib/home-page/version-info.component.html b/ui-ngx/src/app/modules/home/components/widget/lib/home-page/version-info.component.html deleted file mode 100644 index b222ea9477..0000000000 --- a/ui-ngx/src/app/modules/home/components/widget/lib/home-page/version-info.component.html +++ /dev/null @@ -1,53 +0,0 @@ - -
-
-
-
widgets.version-info.title
-
- {{ 'widgets.version-info.contact-us' | translate }} -
-
-
-
- -
{{ updateMessage?.currentVersion }}
-
-
-
-
- @if (updateMessage?.updateAvailable) { - - } @else { -
-
check
-
widgets.version-info.version-is-up-to-date
-
- } -
-
diff --git a/ui-ngx/src/app/modules/home/components/widget/lib/home-page/version-info.component.scss b/ui-ngx/src/app/modules/home/components/widget/lib/home-page/version-info.component.scss deleted file mode 100644 index c3e815d550..0000000000 --- a/ui-ngx/src/app/modules/home/components/widget/lib/home-page/version-info.component.scss +++ /dev/null @@ -1,130 +0,0 @@ -// SPDX-FileCopyrightText: Copyright The ThingsBoard Authors -// SPDX-FileCopyrightText: Modifications Copyright ThingsBoard, Inc. -// SPDX-License-Identifier: Apache-2.0 AND BUSL-1.1 -@import "../../../../../../../scss/constants"; - -:host { - .tb-card-header { - display: flex; - flex-direction: row; - justify-content: space-between; - align-items: center; - margin-bottom: 8px; - @media #{$mat-md-lg} { - margin-bottom: 4px; - } - } - - .tb-contact-us { - @media #{$mat-md-lg} { - height: 24px; - font-size: 12px; - } - } - - .tb-version-info-container { - border: 1px solid rgba(0, 0, 0, 0.05); - box-shadow: 0 5px 16px rgba(0, 0, 0, 0.04); - border-radius: 10px; - padding: 8px 16px 4px 16px; - overflow: hidden; - white-space: nowrap; - @media #{$mat-lt-md} { - padding: 16px; - } - @media #{$mat-md-lg} { - padding: 4px; - } - &.up-to-date { - position: relative; - box-shadow: none; - border: none; - white-space: initial; - text-align: center; - &:before { - content: ""; - position: absolute; - top: 0; - bottom: 0; - left: 0; - right: 0; - border-radius: 10px; - background: var(--tb-primary-500); - opacity: 0.04; - } - } - } - - .tb-version-link { - font-weight: 400; - font-size: 14px; - line-height: 20px; - letter-spacing: 0.2px; - color: rgba(0, 0, 0, 0.76); - position: relative; - border-bottom: none; - @media #{$mat-md-lg} { - font-size: 11px; - line-height: 16px; - } - &:hover, &:focus { - border-bottom: none; - } - &::after { - content: 'arrow_forward'; - display: inline-block; - transform: rotate(315deg); - font-family: 'Material Icons'; - font-weight: normal; - font-style: normal; - font-size: 18px; - color: rgba(0, 0, 0, 0.12); - vertical-align: bottom; - margin-left: 6px; - } - &:hover::after { - color: inherit; - } - } - - .tb-version { - font-weight: 500; - font-size: 18px; - line-height: 24px; - letter-spacing: 0.15px; - color: rgba(0, 0, 0, 0.87); - @media #{$mat-md-lg} { - font-size: 12px; - line-height: 14px; - } - } - - .tb-upgrade { - @media #{$mat-md-lg} { - height: 24px; - font-size: 12px; - padding: 0; - overflow: hidden; - } - } - - .check-icon { - color: #198038; - font-weight: 600; - @media #{$mat-md-lg} { - font-size: 16px; - } - } - - .up-to-date-text { - font-weight: 400; - font-size: 14px; - line-height: 20px; - letter-spacing: 0.2px; - color: rgba(0, 0, 0, 0.76); - @media #{$mat-md-lg} { - font-size: 11px; - line-height: 16px; - } - } -} diff --git a/ui-ngx/src/app/modules/home/components/widget/lib/home-page/version-info.component.ts b/ui-ngx/src/app/modules/home/components/widget/lib/home-page/version-info.component.ts deleted file mode 100644 index 921a6ba0a3..0000000000 --- a/ui-ngx/src/app/modules/home/components/widget/lib/home-page/version-info.component.ts +++ /dev/null @@ -1,39 +0,0 @@ -// SPDX-FileCopyrightText: Copyright The ThingsBoard Authors -// SPDX-License-Identifier: Apache-2.0 -import { ChangeDetectorRef, Component, OnInit } from '@angular/core'; -import { PageComponent } from '@shared/components/page.component'; -import { Store } from '@ngrx/store'; -import { AppState } from '@core/core.state'; -import { AdminService } from '@core/http/admin.service'; -import { UpdateMessage } from '@shared/models/settings.models'; -import { getCurrentAuthUser } from '@core/auth/auth.selectors'; -import { Authority } from '@shared/models/authority.enum'; -import { of } from 'rxjs'; - -@Component({ - selector: 'tb-version-info', - templateUrl: './version-info.component.html', - styleUrls: ['./home-page-widget.scss', './version-info.component.scss'], - standalone: false -}) -export class VersionInfoComponent extends PageComponent implements OnInit { - - authUser = getCurrentAuthUser(this.store); - updateMessage: UpdateMessage; - - constructor(protected store: Store, - private cd: ChangeDetectorRef, - private adminService: AdminService) { - super(store); - } - - ngOnInit() { - (this.authUser.authority === Authority.SYS_ADMIN ? - this.adminService.checkUpdates() : of(null)).subscribe( - (updateMessage) => { - this.updateMessage = updateMessage; - this.cd.markForCheck(); - } - ); - } -} diff --git a/ui-ngx/src/app/modules/home/components/widget/lib/settings/common/action/custom-action-pretty-editor.component.html b/ui-ngx/src/app/modules/home/components/widget/lib/settings/common/action/custom-action-pretty-editor.component.html index 5c85012257..479c35124f 100644 --- a/ui-ngx/src/app/modules/home/components/widget/lib/settings/common/action/custom-action-pretty-editor.component.html +++ b/ui-ngx/src/app/modules/home/components/widget/lib/settings/common/action/custom-action-pretty-editor.component.html @@ -1,13 +1,14 @@
@if (!fullscreen) { -
-
-
- diff --git a/ui-ngx/src/app/modules/home/components/widget/lib/settings/common/date-format-select.component.html b/ui-ngx/src/app/modules/home/components/widget/lib/settings/common/date-format-select.component.html index 93a1f33612..27d92696b8 100644 --- a/ui-ngx/src/app/modules/home/components/widget/lib/settings/common/date-format-select.component.html +++ b/ui-ngx/src/app/modules/home/components/widget/lib/settings/common/date-format-select.component.html @@ -1,7 +1,8 @@ @@ -11,13 +12,13 @@ } @if (dateFormatFormControl.value?.custom) { - } @if (dateFormatFormControl.value?.auto && !dateFormatFormControl.value?.custom) { - diff --git a/ui-ngx/src/app/modules/home/components/widget/lib/settings/common/gradient.component.html b/ui-ngx/src/app/modules/home/components/widget/lib/settings/common/gradient.component.html index 4b251eda4d..f2ff5c4499 100644 --- a/ui-ngx/src/app/modules/home/components/widget/lib/settings/common/gradient.component.html +++ b/ui-ngx/src/app/modules/home/components/widget/lib/settings/common/gradient.component.html @@ -1,7 +1,8 @@ @@ -83,7 +84,7 @@
} -
} -
-
diff --git a/ui-ngx/src/app/modules/home/components/widget/widget-config.component.html b/ui-ngx/src/app/modules/home/components/widget/widget-config.component.html index 4c8b9dede5..3849a99b52 100644 --- a/ui-ngx/src/app/modules/home/components/widget/widget-config.component.html +++ b/ui-ngx/src/app/modules/home/components/widget/widget-config.component.html @@ -272,7 +272,7 @@
alarm.filter
- diff --git a/ui-ngx/src/app/modules/home/components/wizard/integration-wizard-dialog.component.html b/ui-ngx/src/app/modules/home/components/wizard/integration-wizard-dialog.component.html index c3047766af..f74ab22105 100644 --- a/ui-ngx/src/app/modules/home/components/wizard/integration-wizard-dialog.component.html +++ b/ui-ngx/src/app/modules/home/components/wizard/integration-wizard-dialog.component.html @@ -163,7 +163,7 @@ [genericAdditionalInfoTemplate]="genericAdditionalInfo" [executeRemotelyTemplate]="executeRemotely" [integrationType]="integrationWizardForm.get('type').value" - [isSetDownlink]="!!downlinkConverterForm.get('downlinkConverterId').value || downlinkConverterForm.get('converterType').value === 'new'" + [isSetDownlink]="isDownlinkConverterSet" [isEdgeTemplate]="isEdgeTemplate" > @@ -177,7 +177,7 @@
integration.metadata - +
diff --git a/ui-ngx/src/app/modules/home/components/wizard/integration-wizard-dialog.component.ts b/ui-ngx/src/app/modules/home/components/wizard/integration-wizard-dialog.component.ts index fc73da1626..bd1e829cdf 100644 --- a/ui-ngx/src/app/modules/home/components/wizard/integration-wizard-dialog.component.ts +++ b/ui-ngx/src/app/modules/home/components/wizard/integration-wizard-dialog.component.ts @@ -283,6 +283,17 @@ export class IntegrationWizardDialogComponent extends } } + get isDownlinkConverterSet(): boolean { + switch (this.downlinkConverterForm.get('converterType').value) { + case ConverterSourceType.EXISTING: + return !!this.downlinkConverterForm.get('downlinkConverterId').value; + case ConverterSourceType.SKIP: + return false; + default: + return true; + } + } + private createDownlinkConverter(): Observable { const converterType = this.downlinkConverterForm.get('converterType').value; if (converterType === ConverterSourceType.SKIP) { diff --git a/ui-ngx/src/app/modules/home/home.component.html b/ui-ngx/src/app/modules/home/home.component.html index 852d1c4742..c7626e2a10 100644 --- a/ui-ngx/src/app/modules/home/home.component.html +++ b/ui-ngx/src/app/modules/home/home.component.html @@ -58,7 +58,7 @@ -
+
@if ((homeService.hideMainToolbar$ | async) === false) { -
- -
+ +

@@ -63,13 +63,13 @@

-